Hi All, I've literally taught myself to program the Arduino so I'm still relatively new, so apologies if this is a stupid question.
I have this code set up so when my int "val = serial.Read() - '0'" receives a "1" it will go ahead and run my while loop which turns a relay on and off. In Addition to this, I have 3 buttons that will Serial.println 3 different messages when they pushed and also break the while loop. As it stands, this code works as it should except that it is only breaking a loop once it gets to the part of the loop that it reads the button, which means I need to hold the button 1 - 2 seconds until the code recognizes the change in button state. Basically I want to end the loop straight away but I can't seem to figure out a logical way how to do this.
Here is my code. I am using it in conjunction with some python code i stole from somewhere that reads the serial println and posts it to twitter for me whilst reading if I get any mentions, to which the arduino registers and triggers my relay to turn some pretty christmas lights on and off!
int relayPin = 3; int redPin = 8; int greenPin = 7; int switchPinHappy = 12; int switchPinOk = 11; int switchPinNotOk = 10;
void setup() { Serial.begin(9600);
pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT);
pinMode(relayPin, OUTPUT);
pinMode(switchPinOk, INPUT); pinMode(switchPinNotOk, INPUT); pinMode(switchPinHappy, INPUT); }
void loop() { //define val to read serial int val = Serial.read() - '0'; // if val is picked up, let's turn the relay on and off while (val == 1) { digitalWrite(relayPin, HIGH); delay (500); digitalWrite(relayPin, LOW); delay (500); //if the switch is pressed, println and break the while loop. if (digitalRead(switchPinOk) == LOW) { Serial.println("I have acknowledged your tweet and I am OK :|"); break; } //if the switch is pressed, println and break the while loop. if (digitalRead(switchPinNotOk) == LOW) { Serial.println("I have acknowledged your tweet and I not OK :("); break; } //if the switch is pressed, println and break the while loop. if (digitalRead(switchPinHappy) == LOW) { Serial.println("I have acknowledged your tweet and I am Super! :)"); break; } } //run when nothing is happening standByFlash(); }
void standByFlash() { digitalWrite(redPin, HIGH); delay (200); digitalWrite(redPin, LOW); delay (200); digitalWrite(greenPin, HIGH); delay (200); digitalWrite(greenPin, LOW); delay (200); }
Thanks heaps and now that I read the topic, maybe it should be titled "Help James code more effectively!" ^^
James