gpt4 book ai didi

Python 套接字编程和 LED 接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:59 25 4
gpt4 key购买 nike

我正在尝试用 python 编写套接字编程。每当客户端向服务器发送消息时,LED 应该开始闪烁。我在 Raspberry pi 上运行服务器程序,在 PC 上运行客户端。

这是在我的 Pi 上运行的服务器代码。

#!/usr/bin/python             # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off

def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()

s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()

这是在我的电脑上运行的客户端代码。

#!/usr/bin/python           # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port

s.connect((host, port))
s.send('10')
s.close

我能够从客户端接收消息,但无法使 LED 闪烁。对不起,我是编码新手。我对硬件有很好的了解,但对软件却一无所知。请帮助我。

最佳答案

在您的 PC 或 Raspberry 上尝试此操作,然后进行相应的编辑:

#!/usr/bin/python             # This is server.py file
import socket # Import socket module

def led_blink(msg):
print "got msg", msg # Debug msg

s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "Listening"
c, addr = s.accept() # Establish connection with client.
while True:
msg = c.recv(1024)
print 'Got connection from', addr
if msg == "Exit":
break
led_blink(msg)
c.close()

和:

#!/usr/bin/python           # This is client.py file
import socket, time # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # port
s.connect((host, port))
x=0
for x in range(10):
s.send('Message_'+str(x))
print x
time.sleep(2)
s.send('Exit')
s.close

请注意,我在同一台机器 127.0.0.1 上同时使用服务器和客户端,并删除了 GPIO 位,因为我没有它们可用。

关于Python 套接字编程和 LED 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39973653/

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