1.控制LED的七彩闪烁
服务段server代码如下:
import socket
import time
import RPi.GPIO as GPIO
from threading import Thread
# set code regular
GPIO.setmode(GPIO.BOARD)
# define pin
BLUE = 11
GREEN = 13
RED = 15
# set the corresponding pin to output mode and initialize it to a low level
GPIO.setup(RED, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(GREEN, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(BLUE, GPIO.OUT, initial=GPIO.LOW)
flag = False
index = 0.1
def lamp():
global flag
if not flag:
flag = True
while True:
# 给指定的引用一个高电平
if not flag:
break
GPIO.output(RED, GPIO.HIGH) # 红
time.sleep(index)
GPIO.output(GREEN, GPIO.HIGH) # 红绿
time.sleep(index)
GPIO.output(GREEN, GPIO.LOW)
GPIO.output(BLUE, GPIO.HIGH) # 红蓝
time.sleep(index)
GPIO.output(RED, GPIO.LOW) # 蓝
time.sleep(index)
GPIO.output(GREEN, GPIO.HIGH) # 绿蓝
time.sleep(index)
GPIO.output(BLUE, GPIO.LOW) # 绿
time.sleep(index)
GPIO.output(RED, GPIO.HIGH)
GPIO.output(BLUE, GPIO.HIGH) # 红绿蓝
time.sleep(index)
GPIO.output(RED, GPIO.LOW)
GPIO.output(BLUE, GPIO.LOW)
GPIO.output(GREEN, GPIO.LOW)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind(('', 6969))
sock.listen(5)
while True:
conn, addr = sock.accept()
with conn:
print('Connected by:', addr)
while True:
try:
recv_data = conn.recv(1024)
conn.sendall(recv_data.upper())
data = recv_data.decode()
print('accept msg:', data)
if not recv_data:
continue
elif 'on' == data:
Thread(target=lamp, ).start()
elif 'off' == data:
flag = False
except ConnectionResetError as e:
print('close using connection!')
break
conn.close()
sock.close()
本博客介绍了一个使用Raspberry Pi实现远程控制LED七彩闪烁的项目。通过Python编程,结合网络套接字(socket)通信,实现了从客户端发送指令到服务器,控制LED灯的开关与颜色变化。服务器端代码详细展示了如何设置GPIO接口,控制RGB LED灯的亮灭,以及如何接收并响应客户端的控制指令。

1万+

被折叠的 条评论
为什么被折叠?



