Convert UDP packet script to TCP packet

Hey
im very new at programming arduinos but i have made the script downunder and thought about if it possible to make something similar by using TCP packets instead of udp?
If it is could someone please tell me i can read about it? i have tryed to google and look at this forum without luck.. Hope someone can help me out here :slight_smile:

#include <SPI.h>         // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008

int led = 4;
int laser = 6;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {  
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 5, 107);

unsigned int localPort = 7;      // local port to listen on
unsigned int remotePort = 9;
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char  ReplyBuffer[] = "The power is on";  // a string to send back
char  ReplyBuffer1[] = "The power is off";

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // start the Ethernet and UDP:
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);

  Serial.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(laser, INPUT);
}

void loop() {
  int val = digitalRead(laser);
  // if there's data available, read a packet
  int packetSize = Udp.parsePacket();
    if(packetSize)
  {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i =0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    // send a reply, to the IP address and port that sent us the packet we received
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  
  delay(10);
  }
    
 
 
    if((packetSize > 1) && (packetSize < 3))
  {
    if (val == HIGH)
    {
    digitalWrite(led, LOW);
    }
    else
    {
     digitalWrite(led, HIGH);
    }
  }
      if((packetSize > 5) && (packetSize < 7))
  {
    if (val == HIGH)
    {
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer);
    Udp.endPacket();
    
  delay(10);
    }
    else
    {
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer1);
    Udp.endPacket();
    
  delay(10);
    }
  }
}

The answer it's the same Ethernet library you are already using (there's no specific "EthernetTcp" library, just Ethernet).
The main difference is that TCP requires the establishment of a connection, so there are two different behaviors: the client requests the connection, while the server waits for incoming connection requests. From your code I think that the Arduino will work in the role of the server (EthernetServer). It will wait until some data (a request from the outside) is available(), then a Client will be created on the spot to read the incoming message, and finally the server will send the response to the outside client and close the connection.

Hope someone can help me out here

Perhaps a description of what your code is intended to do will help.

spatula:
The answer it's the same Ethernet library you are already using (there's no specific "EthernetTcp" library, just Ethernet).
The main difference is that TCP requires the establishment of a connection, so there are two different behaviors: the client requests the connection, while the server waits for incoming connection requests. From your code I think that the Arduino will work in the role of the server (EthernetServer). It will wait until some data (a request from the outside) is available(), then a Client will be created on the spot to read the incoming message, and finally the server will send the response to the outside client and close the connection.

im not quite sure if i understand this right? because when i send a tcp packet to the arduino i cant get it to do anything..

zoomkat:

Hope someone can help me out here

Perhaps a description of what your code is intended to do will help.

Yeah im sorry i forgot that..
The code should switch a LED on and off and be able to tell me the status on the LED(whether its on or off)

Malibux:
... when i send a tcp packet to the arduino i cant get it to do anything..

This is because you need to establish a tcp connection before sending any packet.
Look at the EthernetServer class, there are useful examples of how you can have the Arduino wait for a connection request, get the client data, send a reply, close the connection.

spatula:

Malibux:
... when i send a tcp packet to the arduino i cant get it to do anything..

This is because you need to establish a tcp connection before sending any packet.
Look at the EthernetServer class, there are useful examples of how you can have the Arduino wait for a connection request, get the client data, send a reply, close the connection.

I have now tryed to get it to work but i cant get the functions from the UDP transferred to the TCP script.
so can anybody help me with that?
The function should be like this:
When i send a certain packet/data( ex. on) the LED shall switch on and when i send another packet the LED shall turn off?

thank you in advance

simple tcp/ip based web server control code.

//zoomkat 4-1-12
//simple button GET for servo and pin 5
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//use the \ slash to escape the " in the html, or use ' instead of " 
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h> 
Servo myservo;  // create servo object to control a servo 

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 102 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port

String readString; 

//////////////////////

void setup(){

  pinMode(5, OUTPUT); //pin selected to control
  //start Ethernet
  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  server.begin();

  myservo.write(90); //set initial servo position if desired
  myservo.attach(7);  //the pin for the servo control
  //enable serial data print 
  Serial.begin(9600); 
  Serial.println("server servo/pin 5 test 1.0"); // so I can keep track of what is loaded
}

void loop(){
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {

          //store characters to string 
          readString += c; 
          //Serial.print(c);
        } 

        //if HTTP request has ended
        if (c == '\n') {

          ///////////////
          Serial.println(readString); //print to serial monitor for debuging 

          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<TITLE>Arduino GET test page</TITLE>");
          client.println("</HEAD>");
          client.println("<BODY>");

          client.println("<H1>Zoomkat's simple Arduino button</H1>");
          
          client.println("<a href=\"/?on\">ON</a>"); 
          client.println("<a href=\"/?off\">OFF</a>"); 

          client.println("</BODY>");
          client.println("</HTML>");
 
          delay(1);
          //stopping client
          client.stop();

          ///////////////////// control arduino pin
          if(readString.indexOf("on") >0)//checks for on
          {
            myservo.write(40);
            digitalWrite(5, HIGH);    // set pin 5 high
            Serial.println("Led On");
          }
          if(readString.indexOf("off") >0)//checks for off
          {
            myservo.write(140);
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("Led Off");
          }
          //clearing string for next read
          readString="";

        }
      }
    }
  }
}

If you just need to read a single byte and do something depending on its value the basic sequence is this:

loop()
{
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char ch = client.read();
// examine ch
        switch(ch)
        {
        case '0':  // for example
// switch LED off
          break;
// add other cases
        }
// send the response and close the connection
        client.println("OK");
        delay(1);
        client.stop();
      }
    }
  } 
}

You'll notice this is the same sequence of zoomkat's example. If you want to send and read commands as strings, zoomkat's is the solution you are looking for.

spatula:
If you just need to read a single byte and do something depending on its value the basic sequence is this:

loop()

{
 EthernetClient client = server.available();
 if (client) {
   while (client.connected()) {
     if (client.available()) {
       char ch = client.read();
// examine ch
       switch(ch)
       {
       case '0':  // for example
// switch LED off
         break;
// add other cases
       }
// send the response and close the connection
       client.println("OK");
       delay(1);
       client.stop();
     }
   }
 }
}




You'll notice this is the same sequence of zoomkat's example. If you want to send and read commands as strings, zoomkat's is the solution you are looking for.

Thank you very much. that was just what I needed :slight_smile: