【发布时间】:2014-10-08 00:22:37
【问题描述】:
我正在试验我的新 arduino UNO Rev 3 和一个简单的 python 套接字服务器。服务器代码是:
##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 double parens are to create a tuple with one element”那行不通。元组由 逗号 创建。有时您碰巧需要括号来消除歧义,但它们不是元组的一部分。
((ADDR,))将一个元素的元组作为参数传递;((ADDR))刚刚通过ADDR。 -
下一步:
data = str没有将data声明为字符串,而是将字符串类型(不是字符串值,表示类型本身的对象)设置为data的默认值.使用recieve.data并不完全是非法的,但它很奇怪;当您真正想要的只是一个局部变量data时,您将属性附加到函数recieve.data。 (另外,你拼错了“receive”。)另外,leave()应该做什么? -
另外,为什么这个标签是C?您有 Python 代码和 Arduino/接线代码,但我在任何地方都看不到任何 C 代码。
-
最重要的是:您的 Arduino 代码中的
client是什么类型?它是如何连接的?我敢打赌你正在使用某种非阻塞流,其read方法返回 -1(在一个字节中,它与 255 相同,这是ÿ的拉丁语 1)还没有什么可读的。但是在不知道你在使用什么的情况下,我无法告诉你如何修复它。