我想在python中编写套接字编程。每当客户端发送消息到服务器,LED应该开始闪烁。 我在PC上运行Raspberry Pi和客户端上的服务器程序。Python套接字编程和LED接口
这是在我的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闪烁。 对不起,我是编码新手。我在硬件方面有很好的知识,但在软件方面没有。 请帮帮我。
您正在比较字符串和数字。用'msg1 =“10”'替换你的服务器代码。如果这不起作用,您是否看到控制台中的“msg”? – Goufalite
在你的'led_blink()'函数中是'while 1'循环。这是你的目的吗? – rocksteady
是啊!用字符串替换后,我可以使LED闪烁。谢谢 – Arunkrishna