Go Down

Topic: Serial communication between two arduino (Read 2689 times) previous topic - next topic

Vincent19

Dear all,

Transmitter code :
Code: [Select]
void setup(){
  Serial.begin(9600);
}

void loop(){
 

{
   if (digitalRead(8)==LOW)
   {
   Serial.write(1);
   }
  }
}


Receiver code:
Code: [Select]
void setup()
{
 
  Serial.begin(9600);
}
void loop()
{
  int incoming;
 
  if (Serial.available()) {
    delay(1);
   
    while (Serial.available() > 0){
    incoming=Serial.read();
    if(incoming==1)
    {
      Serial.print(incoming);
      digitalWrite(13, HIGH);
      delay(100);
      digitalWrite(13,LOW);
      delay(100);
    }
    }
  }

}
 


I realised that when I press the button, it will not just send 'a' 1, but instead it shows like around 20++ 1 in the serial monitor.

Why ? I thought only will serialprint only one 1 ? Instead of so many ?

Thanks

wildbill

The serial.write does indeed only send one byte, but on the next iteration of loop, if the input is still low, it will print another, then another ad nauseum. The arduino is fast, so if that input is low for even a short time, you'll get lots of transmissions.

Arrch

If you want it to only send once, you need to detect the transition, rather than the state. The transition occurs when the switch goes from HIGH to LOW, or LOW to HIGH. Keep track of the last value you read and compare it to the current value. If they are not the same, a transition occurred.

Vincent19


Arrch


How can I progam in that way ?


Look at the StateChangeDetection example.

Vincent19

Where is that example ? I cant locate it ><

Jimmy60


Vincent19

Thanks alot. I will try it again and get back to all of you :0

Vincent19

Cool ! I get it !

However, just wonder, for the below coding :
Code: [Select]
if (buttonPushCounter % 4 == 0) {
    digitalWrite(ledPin, HIGH);
    Serial.println("The LED is ON");
  } else {
   digitalWrite(ledPin, LOW);
  }


the %4 is just example is it ? to show us that the chip knows when to light up the led ? which is the press which is multiple of 4

Go Up