I already succeeded in making the sender send hello to the receiver arduino. But now I want to make a code where I press a button on the sender arduino and it then sends a signal to the receiver arduino to light up an LED lamp.
For this project I'm using arduino UNO for both.
With these codes.
Code of sender arduino:
char mystr[5] = "Hello"; //String data
void setup() {
// Begin the Serial at 9600 Baud
Serial.begin(9600);
}
void loop() {
Serial.write(mystr,5); //Write the serial data
delay(1000);
}
Code of receiver arduino:
char mystr[10]; //Initialized variable to store recieved data
void setup() {
// Begin the Serial at 9600 Baud
Serial.begin(9600);
}
void loop() {
Serial.readBytes(mystr,5); //Read the serial data and store in var
Serial.println(mystr); //Print data on Serial Monitor
delay(1000);
}
1. You add the following codes at the appropriate place of the Sender Sketch:
pinMode(2, INPUT_PULLUP); //connect a Switch across DPin-2 and GND
while(digitalRead(2) != LOW)
{
;//wait until Swicth is pressed
}
Serial.write(mystr, 5);
2. You add the following codes at the appropriate place of the Receiver Sketch:
#define LED 2
pinMode(LED, OUTPUT);
byte n = Serial.available();
if(n != 0)
{
Serial.readBytes(mystr, 5);
mystr[5] ='\0';
if(strcmp(mystr, "Hello") == 0)
{
digitalWrite(LED, HIGH); //LED is turned On
}
}
The string actually has 6 characters in it including the trailing '\0' that the compiler will add to mark the end of the string. By declaring teh array as having 5 elements it means that the '\0' is written to memory that does not belong to the array
char mystr[] = "Hello"; //String data
would be better as it allows the compiler to work out teh size of the array