Hey there! I've been working on a project following this tutorial on communication between 2 Arduino using TCP & the ethernet shield.
In this tutorial, one has a switch and the other has the LED. Following the code exactly, I've got Arduino #1 as the switch that's sending data, and Arduino #2 as the LED receiving data. I'd like to add a button on the receiver with the LED that kills the LED, and sends a message back to the sender unit that the light has been turned off.
I've got the kill switch working on the receiver side, but I can't seem to figure out how to get it to send data back to Arduino #1. I've researched a lot on the forums here, and other tutorials, but I'm having trouble finding out exactly what to add to each side's code for that functionality. Can anyone point me in the right direction?
Hi @chesshoyle ,
Welcome to the forum..
hmm.. on the receiver side you're going to need to try to keep your client connected, so you can send back to it..
maybe something like this..
void loop() {
// Wait for a TCP client from Arduino #1:
EthernetClient client = TCPserver.available();
if (client) {
//keep looping while our client is connected..
while (client.connected()) {
//anything ready to read??
if (client.available()) {
// Read the command from the TCP client:
char command = client.read();
//process command recvd..
if (command == '1') {
Serial.print("- Received command: ");
Serial.println(command);
digitalWrite(LED_PIN, HIGH); // Turn LED on
} else if (command == '0') {
Serial.print("- Received command: ");
Serial.println(command);
digitalWrite(LED_PIN, LOW); // Turn LED off
}
} //done reading..
//add code to check button, send to client while connected..
//end of where your code goes..
} // while we are connected..
} // if we connect..
//maintains dhcp renewal if used..
Ethernet.maintain();
}
going to need a if available() check on the other side added to the loop..
something like..
if (TCPclient.available()){
char command = TCPclient.read();
//process command recvd..
if (command == '1') {
Serial.print("- Received command: ");
Serial.println(command);
} else if (command == '0') {
Serial.print("- Received command: ");
Serial.println(command);
}
}
good luck.. ~q
Thank you so much for this! I didn't realize I could have TCPclient on both sides; I thought one had to be client and one had to be server. This got me where I needed to go. Thanks again!