gpt4 book ai didi

python - 通过TCP从arduino发送数据到python

转载 作者:可可西里 更新时间:2023-11-01 02:56:51 25 4
gpt4 key购买 nike

我已经为此苦苦挣扎了几个小时,真的不知道从这里该何去何从。我有一个带有连接到网络的 wifi shield 的 arduino uno,以及连接到同一网络的带有 Ubuntu 的笔记本电脑。我正在使用 arduino Wifi Library连接到网络。

我可以将数据从 arduino 发送到我的笔记本电脑并使用以下命令成功打印:sudo nc -l 25565

我还尝试使用以下 python 代码来执行与 nc 相同的操作,它也作为 sudo 运行,以防万一:

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 25565
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)

(conn,addr) = s.accept()
print 'Connection address: ',addr
while True:
data = conn.recv(BUFFER_SIZE)
if not data: break
print 'received data: ',data
conn.send('ECHO')
conn.close()
s.close()

但它只是卡在 (conn,addr) = s.accept() 处。在同一台笔记本电脑上使用客户端 python 脚本,我可以连接到上述服务器,我可以向它发送数据,然后服务器打印数据。

我只是不知道为什么 nc 会从 arduino 打印但 python 服务器脚本不会,即使它会从 python 客户端打印。 arduino 库是否无法遵循 python 期望的某些标准?提前致谢。

最佳答案

不,arduino 库不是“未能遵循某些标准”。

您的程序绑定(bind)到 localhost接口(interface),IP地址127.0.0.1 .这意味着只有在同一台 PC 上运行的程序才能连接到您的 Python 服务器。

试试这个:

s.bind(('',TCP_PORT))

引用:

https://docs.python.org/2/library/socket.html :

For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '<broadcast>' represents INADDR_BROADCAST. The behavior is not available for IPv6 for backward compatibility, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

https://docs.python.org/2/howto/sockets.html#creating-a-socket :

A couple things to notice: we used socket.gethostname() so that the socket would be visible to the outside world. If we had used s.bind(('localhost', 80)) or s.bind(('127.0.0.1', 80)) we would still have a “server” socket, but one that was only visible within the same machine. s.bind(('', 80)) specifies that the socket is reachable by any address the machine happens to have.

关于python - 通过TCP从arduino发送数据到python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com