Go Down

Topic: Am I doing this right? (Read 321 times) previous topic - next topic

aerialtarget

I have a scenario where I have 2 arudino uno boards, both with XPORTs atatched to them for Serial over IP communication. I have a push-button on one side which is turning an LED on/off on the opposite side. If the button is pressed, the LED turns ON. If released, the LED goes off.

Here's the code for the push button side.

Code: [Select]

const int buttonPin = 12;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);     
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
Serial.begin(9600); 
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:   
    digitalWrite(ledPin, HIGH); 
    Serial.println("on");
    delay(1000);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
    Serial.println("off");
    delay(1000);
   
  }
}




Here's the code for the opposite side:

Code: [Select]
#define LED 13

int input = 0;       // variable to keep the data from the serial port

void setup() {
  pinMode(LED,OUTPUT);    // declare the LED's pin as output
  Serial.begin(9600);        // connect to the serial port
}

void loop () {
  input = Serial.read();      // read the serial port

  // if the input is 'on' turn the LED ON, if 'off' turn it OFF
  if (input == 'on' ) {
    digitalWrite(LED,HIGH);
    Serial.println("LED13 is ON");
  }
  if (input == 'off'){
      digitalWrite(LED, LOW);
      Serial.println("LED13 is OFF");
  }
}


I think it'll work this way but I'm wondering if there is a better more efficient way of doing it rather than just delay it. What would be more ideal is simply sending a string whenever the button is pressed, then if the LED is on, then turn it off, if it is on, turn it on.

Any ideas?

Thanx

Udo Klein

Just remove the delay. This may send the string several times. But this does not matter as you just keep the LED in the same state.

If you do not want to send strings endlessly then you might want to implement a state machine
http://en.wikipedia.org/wiki/Finite-state_machine
http://www.arduino.cc/playground/Code/FiniteStateMachine

Since your machine will have only two states this can be implemented easily without the library as well.

Check out my experiments http://blog.blinkenlight.net

Go Up