2016-10-11 94 views
2

我想在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閃爍。 對不起,我是編碼新手。我在硬件方面有很好的知識,但在軟件方面沒有。 請幫幫我。

+0

您正在比較字符串和數字。用'msg1 =「10」'替換你的服務器代碼。如果這不起作用,您是否看到控制檯中的「msg」? – Goufalite

+1

在你的'led_blink()'函數中是'while 1'循環。這是你的目的嗎? – rocksteady

+0

是啊!用字符串替換後,我可以使LED閃爍。謝謝 – Arunkrishna

回答

0

您正在比較字符串"10"和數字10。將您的服務器代碼更改爲:

msg1 = "10" 
1

試試這個您的PC或覆盆子,然後相應地編輯:

#!/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位。

+0

這個答案解決了'led_blink()'函數中的無限循環:在出口可以調用'GPIO.cleanup()'! – Goufalite