c - Sketch that responds to certain commands, how is it done? -
alright have half complete arduino sketch @ moment. sketch below blink led on kegboard-mini shield if string of chars equals *{blink_flow_a}* led blinks once current sketch loaded on arduino. arduino blink repeatedly until "stop" command sent arduino. open valve, keep open until valve receives close command close valve. sketch looks following,
/* * kegboard-serial-simple-blink07 * code public domain * * sketch sends receives multibyte string iphone * , performs functions on it. * * examples: * http://arduino.cc/en/tutorial/serialevent * http://arduino.cc/en/serial/read */ // global variables should identified _ // flow_a led int led = 4; // relay_a const int relay_a = a0; // variables sketch example string inputstring = ""; // string hold incoming data boolean stringcomplete = false; // whether string complete void setup() { serial.begin(2400); // open serial port, sets data rate 2400bps serial.println("power on test"); inputstring.reserve(200); pinmode(relay_a, output); } void open_valve() { digitalwrite(relay_a, high); // turn relay_a on } void close_valve() { digitalwrite(relay_a, low); // turn relay_a off } void flow_a_blink() { digitalwrite(led, high); // turn led on (high voltage level) delay(1000); // wait 1 second digitalwrite(led, low); // turn led off making voltage low delay(1000); // wait second } void flow_a_blink_stop() { digitalwrite(led, low); } void loop() { // print string when newline arrives: if (stringcomplete) { serial.println(inputstring); // clear string: inputstring = ""; stringcomplete = false; } if (inputstring == "{blink_flow_a}") { flow_a_blink(); } } //serialevent occurs whenever new data comes in //hardware serial rx. routine run between each //time loop() runs, using delay inside loop can delay //response. multiple bytes of data may available. void serialevent() { while(serial.available()) { // new byte: char inchar = (char)serial.read(); // add inputstring: inputstring += inchar; // if incoming character newline, set flag // main loop can it: if (inchar == '\n') { stringcomplete = true; } } }
if makes difference on irc told me research state machines scratches head
a state machine (at it's simplest - can lots more complicated) can set of conditional statements (if/else or switch/case) behaviors based on state of variable, , change variable state. can thought of way of handling or progressing through series of conditions.
so have state of led/valve - either blinking (open) or not blinking (closed). in pseudo code here:
boolean led_state = false; //init false/closed void loop(){ if (checkforcorrectcommand() == true){ // if (led_state == false){ open_valve(); led_state = true; } else { close_valve(); led_state = false; } } }
the blinking led part should easy implement if gist of code above. checkforcorrectcommand()
bit function write checking whatever input - key, serial, button, etc. should return boolean.
Comments
Post a Comment