我想在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