Send command via TCP error

I’m writing a sketch to send a TCP command when a button connected to the Arduino Uno is pressed. The sketch will also respond to a message received via TCP to turn on an LED connected to the Uno. So far, I’m able to send the command from the other device to turn on the LED. However, when push the button on the Uno, the command is not sent.

I was able to set up a TCP server software and send the required command to my device, and it received the command. So I know that’s working. Also, in the sketch on line 125, a text string is sent to my device. It is received correctly. My issue is in lines 130-141. When the button is pushed, the command on line 134 works turning on the LED. I also get the serial message on line 136. Line 135 however does not work.

I’m new to this and a lot of the sketch is copy paste stuff. Any suggestions will be helpful.

Wiring: Three buttons connected to pins 2,3,5
Three LEDs connected to pins 7,8,9
Ethernet Shield 2 used for network connection
Arduino Uno

/*
  Button

  Turns on and off a light emitting diode(LED) connected to digital pin 13,
  when pressing a pushbutton attached to pin 2.

  The circuit:
  - LED attached from pin 13 to ground
  - pushbutton attached to pin 2 from +5V
  - 10K resistor attached to pin 2 from ground

  - Note: on most Arduinos there is already an LED on the board
    attached to pin 13.

  created 2005
  by DojoDave <http://www.0j0.org>
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Button
*/

// constants won't change. They're used here to set pin numbers:
const int button1Pin = 2;     // the number of the pushbutton pin
const int button2Pin = 3;     // the number of the pushbutton pin
const int button3Pin = 5;     // the number of the pushbutton pin
const int led1Pin =  7;      // the number of the LED pin
const int led2Pin =  8;      // the number of the LED pin
const int led3Pin =  9;      // the number of the LED pin
#include <SPI.h>
#include <Ethernet.h>




// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0xA8, 0x61, 0x0A, 0xAE, 0x64, 0x52 };
IPAddress ip(10, 200, 1, 199);
IPAddress myDns(10, 100, 10, 10);
IPAddress gateway(10, 200, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(1234);
bool alreadyConnected = false; // whether or not the client was connected previously
String commandStr;

// variables will change:
int button1State = 0;         // variable for reading the pushbutton status
int button2State = 0;         // variable for reading the pushbutton status
int button3State = 0;         // variable for reading the pushbutton status
int lastbutton1State = 0;
int lastbutton2State = 0;
int lastbutton3State = 0;



void setup() {
  // initialize the LED pin as an output:
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);  
  pinMode(led3Pin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(button3Pin, INPUT);
    // You can use Ethernet.init(pin) to configure the CS pin
    Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet
  // initialize the ethernet device
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only 
      }


  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }
  // start listening for clients
  server.begin();
  Serial.print("Server address:");
  Serial.println(Ethernet.localIP());   
}



void loop() {
  ButtonState();
  TCPRead();
}



void ButtonState(){  
  // read the state of the pushbutton value:
  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);
  button3State = digitalRead(button3Pin);
   // wait for a new client:
 EthernetClient client = server.available();
  // when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clear out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }
  }

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (button1State != lastbutton1State) {
      if (button1State == HIGH) {
      // turn LED on:
      digitalWrite(led1Pin, HIGH);
      client.println("Button1_High\r\n");
      Serial.write("Button1_High\r\n");
    } else {
      // turn LED off:
      digitalWrite(led1Pin, LOW);
      client.println("Button1_Low\r\n");
      Serial.write("Button1_Low\r\n");
    }
    lastbutton1State = button1State;
  }
  if (button2State != lastbutton2State) {
      if (button2State == HIGH) {
      // turn LED on:
      digitalWrite(led2Pin, HIGH);
      client.println("Button2_High\r\n");
      Serial.write("Button2_High\r\n");
    } else {
      // turn LED off:
      digitalWrite(led2Pin, LOW);
      client.println("Button2_Low\r\n");
      Serial.write("Button2_Low\r\n");
    }
    lastbutton2State = button2State;
  }
  if (button3State != lastbutton3State) {
      if (button3State == HIGH) {
      // turn LED on:
      digitalWrite(led3Pin, HIGH);
      client.println("Button3_High\r\n");
      Serial.write("Button3_High\r\n");
    } else {
      // turn LED off:
      digitalWrite(led3Pin, LOW);
      client.println("Button3_Low\r\n");
      Serial.write("Button3_Low\r\n");
    }
    lastbutton3State = button3State;
  }
}


void TCPRead(){
   EthernetClient client = server.available();
    if (client.available()) {
        // Read char until linefeed
        char c = client.read();
        if (c != '\n') {
            // Add received char to string variable
            commandStr += c;
            //Serial.println("Command: " + commandStr);
        } else {
            // Print received command to serial monitor
            Serial.println("Command: " + commandStr);

            // Process the received command
            processCommand(commandStr);
    
            // Clear variable for receive next command
            commandStr = "";
        }
    }
}

void processCommand(String cmd) {
    if (cmd == "LED1_HIGH") {
        // Turn on LED
        digitalWrite(led1Pin, HIGH);
    } else if (cmd == "LED1_LOW") {
        // Turn off LED
        digitalWrite(led1Pin, LOW);
    } else if (cmd == "LED2_HIGH") {
        // Turn on LED
        digitalWrite(led2Pin, HIGH);
    } else if (cmd == "LED2_LOW") {
        // Turn off LED
        digitalWrite(led2Pin, LOW); 
    } else if (cmd == "LED3_HIGH") {
        // Turn on LED
        digitalWrite(led3Pin, HIGH);
    } else if (cmd == "LED3_LOW") {
        // Turn off LED
        digitalWrite(led3Pin, LOW);      
    }

    // end of script
    }

The line 125 is only executed if you got a new connection, after that you set a boolean variable of your own to remember that state although it isn't correct anymore in the next run of your loop (as you ask again for new connections in server.available()). Most probably you didn't get another new connection exactly at that time, so "client" isn't an active connection anymore. The previous connection was closed when "client" went out of it's validity range (at the end of loop()).

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.