Python 插座编程和 LED 接口

Python socket programming and LED interfacing

我正尝试在 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 位,因为我没有它们。

您正在比较字符串 "10" 和数字 10。将您的服务器代码更改为:

msg1 = "10"