python使用socket库的TCP协议控制小车的各种操作

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()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值