PC和树莓派socket通信 控制LED

小白一只,今天来实现让PC和RPi通过socket进行通信,然后通过PC端发指令给PI控制LED的开关。此时RPi作为服务器端Server一直等待客户端的连接并且等待客户端给它发指令;而PC端作为客户端Client不断的去尝试连接服务器,连上之后负责给server发指令。下面:

首先元器件:

1. 树莓派(本人二代B)

2. 电阻一个

3. 发光二极管

4. 杜邦线若干

连线(很简单):

PC和树莓派socket通信 控制LED_第1张图片

树莓派我是通过SSH远程的,server和client都是用Python编写,下面首先是树莓派上的Server.py :

#import necessary package
import socket
import time
import sys
import RPi.GPIO as GPIO
#define host ip: Rpi's IP
HOST_IP = "192.168.1.106"
HOST_PORT = 8888
print("Starting socket: TCP...")
#1.create socket object:socket=socket.socket(family,type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
#2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)
#3.listen connection request:socket.listen(backlog)
socket_tcp.listen(1)
#4.waite for client:connection,address=socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip)
socket_con.send("Welcome to RPi TCP server!")
#5.handle
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
print("Receiving package...")
while True:
    try:
        data=socket_con.recv(512)
        if len(data)>0:
            print("Received:%s"%data)
            if data=='1':
                GPIO.output(11,GPIO.HIGH)
            elif data=='0':
                GPIO.output(11,GPIO.LOW)
            socket_con.send(data)
            time.sleep(1)
            continue
    except Exception:
            socket_tcp.close()
            sys.exit(1)

下面是PC上的Client.py:

import socket
import time
import sys
#RPi's IP
SERVER_IP = "192.168.1.106"
SERVER_PORT = 8888

print("Starting socket: TCP...")
server_addr = (SERVER_IP, SERVER_PORT)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

while True:
    try:
        print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT))
        socket_tcp.connect(server_addr)
        break
    except Exception:
        print("Can't connect to server,try it latter!")
        time.sleep(1)
        continue
print("Please input 1 or 0 to turn on/off the led!")
while True:
    try:
        data = socket_tcp.recv(512)
        if len(data)>0:
            print("Received: %s" % data)
            command=raw_input()
            socket_tcp.send(command)
            time.sleep(1)
            continue
    except Exception:
        socket_tcp.close()
        socket_tcp=None
        sys.exit(1)

最后运行测试:

​首先用python server.py运行server.py:
PC和树莓派socket通信 控制LED_第2张图片

​然后运行client.py;
PC和树莓派socket通信 控制LED_第3张图片

​在客户端输入1或者0回车,输入1发现led点亮,输入0,led熄灭;
PC和树莓派socket通信 控制LED_第4张图片

效果图:

你可能感兴趣的:(RPi,socket,python,RPi)