Arduino timed void draw() loops

1.2k Views Asked by At

I have an Arduino Uno set up to sense the light level and draw to a text file via Processing when it gets dark. I'd like to modify the Processing code to interrupt the draw loop for five seconds and then restart the draw loop. This will continuously write and overwrite the .txt file but that's not important right now.

The purpose of this excercise is to understand how to insert a break into the endless draw loop. I'm still very much a newbie to programming and am trying to wrap my head around how commands interact with eath other. Can anyone help me understand how to make this work? Eample code would be great but I'd also be happy with a conceptual description of how it's supposed to work...learn by doing and all.

I've tried putting the void draw() loop within a void loop() but it erred out. Am I on the right path?

<setup...mySerial and createWriter to path/file.txt>{
}

void draw() { //this is what needs to terminate & restart
if (mySerial.available() > 0 ) {
String value = mySerial.readString();
if ( value != null ) {
output.println( value );
}
}
}

void keyPressed and end
2

There are 2 best solutions below

0
On BEST ANSWER

I believe what you're looking for is called a "state machine".

Make a variable that you can use to store a time value, then compare that to the current time to see if 5s have passed.

uint32_t last_trigger = 0; // millis() returns an unsigned, 32-bit integer

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    if (millis() - last_trigger > 5000) { // 5000 milliseconds
        last_trigger = millis(); // update last_trigger
        Serial.print("last triggered at "); // report findings
        Serial.print(last_trigger);
        Serial.println(" milliseconds");    
    }
}

http://www.arduino.cc/en/Reference/Millis

7
On

If you aren't worried about really tight timing, the easy solution is to use the delay function. http://www.arduino.cc/en/Reference/Delay

The following might be a simple sketch that would do what you want. Adjust it as needed.

void setup()
{
  Serial.begin(9600); // initialize serial routines
}

void loop()
{
int a = analogRead(0);  // read the value of lightness
  Serial.println(a);      // tell processing what the value is
  delay(5000);          // wait for a 5 seconds
}