Electronic – arduino – Passing data from Python to Arduino over ethernet

arduinopython

I have an Arduino with Ethernet shield handshaking with my machine over Ethernet, and now I want to send data between them. My problem seems to be correctly parsing the different data types.

For example, after connecting to my Arduino server, my Python script runs this

msg = "255"
print "Sending %s" % msg
data = s.send(msg)
s.close()

and all I'm looking to do right now is print it to serial on Arduino (I'll eventually do different things based on the input).

Here is my run loop on the Arduino.

void loop() {
     Client client = server.available();

     if (client == true) {
          int recv = client.read();    
          if (recv == 255)
               Serial.print("Received ");
          Serial.println(recv, DEC);
     }
}

For some reason it's only printing a single blank character and I don't get any "received" message.

Best Answer

In Python, msg = "255" will make msg a string type using those quotes around 255.

Your Arduino code is making this comparison: if(recv == 255)

This is going to do an integer comparison. A string "255" is not going to equal the integer 255 and I'm not sure how the data is going to be received and formatted on the Arduino using client.read(), it's probably returning the first byte out of that string.

In any case, you'll have to keep things consistent byte for byte in your python code and your arduino code.

EDIT:

After some further reading:

client.read() Returns The next byte (or character), or -1 if none is available. So you either need to house that function in a loop and terminate on -1 (which is a bad idea in my opinion - in the case that you do want to send the value -1 in your data stream) or you can do what Joby Taffey suggested, build a basic protocol and state the number of bytes of content that will follow.