# Timing Problem xxx

**URL:** <https://discourse.processing.org/t/timing-problem-xxx/22180>\
**Category:** Electronics (Arduino, etc.)\
**Created:** [June 26, 2020, 3:29pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180 "2020-06-26T15:29:34Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![mike\_z](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mike\_z](https://discourse.processing.org/u/mike_z)\
**Post date:** [June 26, 2020, 3:29pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/1 "2020-06-26T15:29:34Z")

</div>

I have made an G4P image button as an ON/OFF switch for an Arduino program. I’m having some timing problems. Seems that when the image button is turned on the Arduino comes on with no noticeable delay, but when the image button is turned off the Arduino takes nearly 2 seconds to turn off. As an experiment I used the Arduino Serial Monitor to turn on the Arduino instead of the image button. I type a ‘O’ for OFF and ‘1’ for ON. The same the image button sends. The serial monitor does not have any noticeable time delay, as soon as the enter button is pressed the Arduino either turns on or off. I need to better understand how the serial communications works and maybe how the G4P event handlers work. Can anyone steer me in a direction to some information about this, Thanks, Mike

---

<div class="post-metadata">

**Author:** ![kfrajer](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kfrajer/32/196_2.png) [@kfrajer](https://discourse.processing.org/u/kfrajer)\
**Post date:** [June 26, 2020, 9:02pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/2 "2020-06-26T21:02:43Z")

</div>

For this case, the best way forward is to provide a [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) so you can show your approach and to provide suggestions to tackle this issue.

One suggestion is to remove G4P to narrow down if the issue is in this library.

Kf

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [June 26, 2020, 10:12pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/3 "2020-06-26T22:12:16Z")

</div>

An example of an issue I had and how I resolved it:

> [@Processing to Arduino Serial Library Example](https://discourse.processing.org/t/processing-to-arduino-serial-library-example/11143):
>
> The SimpleWrite example in the Processing examples was not working on PCs I had available to me. The Arduino resets when establishing a serial connection. I added a delay(1000) to allow the Arduino to reset after serial connection to Processing and it now works. I modified the Processing setup() as follows: void setup() { size(200, 200); printArray(Serial.list()); //Added! List all the available serial ports String portName = Serial.list()[0]; myPort = new Serial(this, portNa…

It may help.

`:)`

---

<div class="post-metadata">

**Author:** ![mike\_z](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mike\_z](https://discourse.processing.org/u/mike_z)\
**Post date:** [June 26, 2020, 10:28pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/4 "2020-06-26T22:28:31Z")

</div>

Here is my Arduino code;

```auto

/*
Igntion tester
*/

int ledPin = 13; // select the pin for the igntion pulse
char SwStatus = '0'; //Sw is the ON/OFF switch

void setup() {
  pinMode(ledPin, OUTPUT); // declare the ledPin for the igntion pulse output
  Serial.begin(38400); // Start serial communication at 38400 bps
  digitalWrite(ledPin, HIGH); // start with igntion pulse high
}

void loop() {
   if (Serial.available()) { // If data is available to read,
     SwStatus = Serial.read(); // read it and store it in SwStatus
     delay(10);
      }
   if (SwStatus == '0') { // If 0 was received
    digitalWrite(ledPin, HIGH); // make the igntion pulse high
   } 
   else if (SwStatus == '1') {
    digitalWrite(ledPin, HIGH); // make the igntion pulse high
    delay(20); // This is the frequency control
    digitalWrite(ledPin, LOW); // make the igntion pulse low
    delay(10); // This is the dwell control, wait until next pulse
   }
  }

```

Basically, this program generates a pulse of varying frequency and duration. The ON/OFF is waiting for Serial.Available and then checking for a ‘0’ (OFF) or ‘1’ (ON).

Here again if I use the Arduino Serial Monitor the code works fine, which is to say there is no noticable delay in the on or off action.

---

<div class="post-metadata">

**Author:** ![mike\_z](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mike\_z](https://discourse.processing.org/u/mike_z)\
**Post date:** [June 26, 2020, 10:51pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/5 "2020-06-26T22:51:08Z")

</div>

Here is the Processing Code;

```auto
import g4p_controls.*;

import processing.serial.*;
Serial myPort; // Create object from Serial class

GImageToggleButton btnToggle0;
 
boolean SwState = false;

public void setup() {
  String portName = Serial.list()[1]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 38400);
  
  size(480, 220, JAVA2D);
  G4P.setGlobalColorScheme(GCScheme.ORANGE_SCHEME);
  G4P.setCursor(ARROW);

  // ##########################################################################
  // Create default 2 state switch button
  btnToggle0 = new GImageToggleButton(this, 50, 100);
  background(250, 225, 200);
  fill(#000000);
  textSize(16);
  text("ON", 58, 90);
  text("OFF", 56, 175);
}

public void draw() {

  if (SwState == false){
    fill( #84FF03);
    myPort.write('0');
  }
  else if(SwState == true) {
    fill (#FA030B);
    myPort.write('1');  
}
    circle(70, 50, 25);
}

// Event handler for image toggle buttons
public void handleToggleButtonEvents(GImageToggleButton button, GEvent event) { 
  //println(button + " State: " + button.getState());
  if (button.getState() == 0){
      println("OFF");
      SwState = false;
  }
  else {println("ON");
      SwState = true;
  }
}

```

All this is, is the image toggle button. I set the SwState in the event handler, then send the character zero or one over the serial port to the Arduino. Mike

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [June 26, 2020, 11:17pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/7 "2020-06-26T23:17:14Z")

</div>

I followed my example and modified your code and it worked:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/9/93c9e31c7ebcbfe99a66ca87a41cfc8b98ef83f7.png)

`:)`

---

<div class="post-metadata">

**Author:** ![mike\_z](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mike\_z](https://discourse.processing.org/u/mike_z)\
**Post date:** [June 27, 2020, 3:51pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/8 "2020-06-27T15:51:14Z")

</div>

GLV, I was optimistic about your change. It is interesting that the Arduino ‘resets’ after the serial connection is established. How do you know that fact and what exactly is meant by reset? Does that mean the Arduino literally starts over?

Anyway I gave your changes a try and on my equipment there was no change. I’m using an Arduino Nano and my host computer is a Windows 32bit XP model. The G4P image button seems to work on the XP, but maybe the problem lays in the event handler? Could there be a problem in how the XP handles a mouse click? I’m thinking that that direction because the Arduino works correctly when I use the Serial Monitor to start and stop the program and the Processing code seems to work if you look at the println command, the ON and OFF are printed immediately. I think the next thing I will try is to look at when the Arduino code gets the notification of the mouse click. Thanks for you efforts, Mike

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [June 27, 2020, 4:22pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/9 "2020-06-27T16:22:52Z")

</div>

> [@mike\_z](#):
>
> It is interesting that the Arduino ‘resets’ after the serial connection is established. How do you know that fact and what exactly is meant by reset? Does that mean the Arduino literally starts over?

The link in my referenced post is no longer valid…

I came across this:

> **[Soft reset on arduino through starting serial comm](https://forum.arduino.cc/t/soft-reset-on-arduino-through-starting-serial-comm/26755/1)**
>
> Hi everyone, I have made my first serial comm program on arduino last weekend. I realized that each time I establish link on the USB serial port by opening serial port file and activating the transmission lines, the arduino resets itself. I know...

I also watch the status LEDs on the Arduino to observe this.

My hardware is a W10 PC and a USB connection (serial over USB) to to an Arduino MEGA 2560 R3.

Just adding this at end of setup worked on my end:  
`delay(1000);`

Your code is sending serial data 60 fps:

> **[draw() / Reference](https://processing.org/reference/draw_.html)**
>
> Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called. draw()…

> **[frameRate() / Reference](https://processing.org/reference/frameRate_.html)**
>
> Specifies the number of frames to be displayed every second. For example, the function call frameRate(30) will attempt to refresh 30 times a second. If the processor is not fast enough to maint…

With your code the Rx LED is ON **all the time**.

Try this on the Processing side:

> [@Processing to Arduino Serial Library Example](https://discourse.processing.org/t/processing-to-arduino-serial-library-example/11143/5):
>
> I modified the existing “SimpleWrite” example to: save and check for the state of mouseOverRect() print state to console only writes serial data once a delay() to wait for Arduino to reset once connected to it; in my case, it is an Arduino Mega 2560 R3. I kept the spirit of the original example intact and left it as a “Simple Write” program. My edit of “SimpleWrite” example so it only sends data once: /\*\* \* Simple Write. \* \* Check if the mouse is over a rectangle and writes the status …

Processing only Tx when there is a state change (see code) and I see the RX light turn on and off only during this change.

`:)`

---

<div class="post-metadata">

**Author:** ![RichardDL](https://avatars.discourse-cdn.com/v4/letter/r/f475e1/32.png) [@RichardDL](https://discourse.processing.org/u/RichardDL)\
**Post date:** [June 27, 2020, 9:41pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/10 "2020-06-27T21:41:57Z")

</div>

@mike_z When the PC connects to the serial port the Arduino is reset. Yes, it ‘starts over’ and runs setup etc. If you print out millis() you’ll see it restart from zero. Just before the ‘start over’ there’s a pause so the IDE can get in and load the program if required.

---

<div class="post-metadata">

**Author:** ![mike\_z](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mike\_z](https://discourse.processing.org/u/mike_z)\
**Post date:** [June 27, 2020, 10:11pm UTC](https://discourse.processing.org/t/timing-problem-xxx/22180/11 "2020-06-27T22:11:50Z")

</div>

Richard, I find it interesting that the Arduino does this, not surprised. What I’d really like to know is where does a guy find out things like this? I’m sure that in the future I will run into another item such as this. It would be nice to find a book that helps a guy out. Back in the 80’s there were many books regarding Quick Basic and Visual Basic, which I ate up. Most everything now is on the computer and doesn’t seem to cover items as well.  
GLV, read your last comment and you are correct, the Arduino was constantly receiving data. I changed my code to something similar to yours and now the test set switches on and off as fast as I can click the switch. I’m betting that there must be a serial buffer that fills with all the characters my previous code generated. The Arduino had to (?) run through the buffered characters before it got to the correct one. Again this is a guess. Having some real documentation on stuff like this would be a great help. Well… it’s works. I want to thank you for the help. The next step is to add a couple of sliders to make the dwell and frequency numbers controllable. And then to arrange it so it looks good and is intuitive. Thanks a million, Mike
