树莓派socket c语言,PC和树莓派socket通信 控制LED

本文详细介绍了如何使用Python在PC和树莓派(RPi)之间通过socket通信,PC作为客户端发送指令控制LED灯的开闭。通过SSH远程连接Raspberry Pi,Server端等待连接并处理指令,而Client端不断尝试连接并发送'1'或'0'操作LED。
摘要由CSDN通过智能技术生成

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

首先元器件:

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

2.电阻一个

3.发光二极管

4.杜邦线若干

连线(很简单):

a4c26d1e5885305701be709a3d33442f.png

树莓派我是通过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)

最后运行测试:

​首先运行server.py;

a4c26d1e5885305701be709a3d33442f.png运行server端

​然后运行client.py;

a4c26d1e5885305701be709a3d33442f.png运行client端

​在客户端输入1或者0回车,输入1发现led点亮,输入0,led熄灭;

a4c26d1e5885305701be709a3d33442f.png

效果图:

a4c26d1e5885305701be709a3d33442f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值