我正在尝试使用新的arduino UNO Rev 3和一个简单的python套接字服务器。服务器代码是:Arduino上的TCP问题。从Python TCP套接字服务器读取字符串
##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()
我想要做的就是确认我可以与Arduino通信并从那里建立。下面是相关的Arduino代码:
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();
}
我不断收到这样的输出:
连接
Arduino的收稿日期:ÿÿÿÿÿÿÿÿÿÿHELLOCLIENT%
断开。
为什么我收到所有这些填充字符?我研究了不同的编码方法,尝试了ASCII和UTF-32,但它一直在做,我错过了什么?
华富首评:“#the你继续读书,直到你得到一个
%
,然后断开连接,你可以先继续读,直到你得到,比如说,一个$
字符,扔掉一切到这一点,以同样的方式双parens将创建一个元素与一个元素“这是行不通的。元组由_commas_创建。有时你碰巧需要parens来消除歧义,但它们不是元组的一部分。 '((ADDR,))'传递一个元素的元组作为参数; '((ADDR))'只是传递'ADDR'。 – abarnert 2014-10-08 00:40:07Next:'data = str'不会将'data'声明为一个字符串,它会将字符串类型(不是字符串值,表示类型本身的对象)设置为'data'的默认值。使用'recieve.data'并不完全违法,但这很奇怪;当你真正需要的是一个局部变量'data'时,你正在为函数附加一个属性'recieve.data'。 (另外,你拼写“接收”错误。)另外,'leave()'应该做什么? – abarnert 2014-10-08 00:44:07
另外,为什么这个标签C?你有Python代码和Arduino/Wiring代码,但是我没有看到任何C代码。 – abarnert 2014-10-08 00:45:23