I am experimenting with my new arduino UNO Rev 3 and a simple python socket server. The server code is:
##server.py
from socket import * #import the socket library
#MY FUNCTIONS
def send(data = str):
conn.send(data.encode())
def recieve():
recieve.data = conn.recv(BUFSIZE)
recieve.data = recieve.data.decode()
return recieve.data
##let's set up some constants
HOST = '' #we are the host
PORT = 29876 #arbitrary port not currently in use
ADDR = (HOST,PORT) #we need a tuple for the address
BUFSIZE = 4096 #reasonably sized buffer for data
## now we create a new socket object (serv)
## see the python docs for more information on the socket types/flags
serv = socket( AF_INET,SOCK_STREAM)
##bind our socket to the address
serv.bind((ADDR)) #the double parens are to create a tuple with one element
serv.listen(5) #5 is the maximum number of queued connections we'll allow
print(" ")
print("Listening")
print(" ")
conn,addr = serv.accept() #accept the connection
print("Connection Established")
send('HELLOCLIENT')
send('%')
leave()
All I'm trying to do is confirm I can communicate with the Arduino and build from there. Here is the relevant Arduino code:
void loop()
{
int n =-1;
while (client.connected())
{
n++;
char recieved = client.read();
inData[n] = recieved;
// Process message when new line character is recieved
if (recieved == '%')
{
Serial.print("Arduino Received: ");
Serial.print(inData);
n = -1;
}
}
Serial.println();
Serial.println("Disconnecting.");
client.stop();
}
I keep getting this output:
Connected
Arduino Received: ÿÿÿÿÿÿÿÿÿÿHELLOCLIENT%
disconnecting.
Why am I receiving all those padded characters? I've researched different encoding methods and tried ASCII and UTF-32 but it keeps doing it, what am I missing?
((ADDR,))is passing a tuple of one element as the argument;((ADDR))is just passingADDR.data = strdoesn't declaredataas a string, it sets the string type (not a string value, the object representing the type itself) as a default value fordata. Usingrecieve.dataisn't exactly illegal, but it's very weird; you're attaching an attribute to the function,recieve.datawhen all you really want is a local variable,data. (Also, you spelled "receive" wrong.) Also, what isleave()supposed to do?clientin your Arduino code? How is it being connected? I'm willing to bet you're using some kind of non-blocking stream whosereadmethod returns -1 (which, in a byte, is the same as 255, which is Latin-1 forÿ) when there's nothing to read yet. But without knowing what you're using, I can't tell you how to fix it.