11.07.2015 Views

arduino state machine code examples - Making Things Interactive

arduino state machine code examples - Making Things Interactive

arduino state machine code examples - Making Things Interactive

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}// if we didn't set the initial <strong>state</strong> when we created the variable,// we'd do it here. The initial <strong>state</strong> is "off" or "start" in most// <strong>state</strong> <strong>machine</strong>s, but if you only hvae active/on <strong>state</strong>s, pick an// appropriate starting <strong>state</strong>.//// currentState = sOff;Serial.begin(9600);void loop(){BlinkStatusLed();// Every time through the loop we check the <strong>state</strong> we're in with a// series of if/else if <strong>state</strong>ments. the first thing we do is check// to see if we should be in a different <strong>state</strong>. If not, then we go// ahead and do whatever this <strong>state</strong> says we should do// There probably shouldn't be anything outside of your <strong>state</strong>// <strong>machine</strong> if() <strong>state</strong>ments other than a status marker like// BlinkStatusLed(). If there's something you think should happen// that isn't in the <strong>state</strong> <strong>machine</strong>, re-think your <strong>state</strong> <strong>machine</strong>!// and yes, we could have done this with a switch <strong>state</strong>ment, but we// haven't learned those yet.// STATE OFFif (currentState == sOff) {Serial.println("off"); // from off, the only place we can go is calibrate, and that's // only if the switch is turned on if (digitalRead(switchPin) == HIGH) { currentState = sCalibrate; }}// STATE CALIBRATEif (currentState == sCalibrate) {Serial.println("calibrate"); // first, have we been turned off? if (digitalRead(switchPin) == LOW) { currentState = sOff; } else { // if we're on, calibrate our photosensor // in calibrate, we take one reading every second for a // set number of seconds, then average them and use that // as our starting value to compare against. int val = 0; int numReads = 5;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!