python 树莓派tcp与串口通讯

#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''
树莓派串口设置

打开mini UART串口

交换映射关系
sudo vim /boot/config.txt
在末尾添加一行代码:
dtoverlay=pi3-miniuart-bit


python字符串章节的官方文档:
https://docs.python.org/3/library/stdtypes.html?highlight=encode#string-methods

str3    = u.encode('utf-8')     # 以utf-8编码对u进行编码,获得bytes类型对象
u1      = str1.decode('gb2312') # 以gb2312编码对字符串str进行解码,获得字符串类型对象
'''

import serial
import time
import socket               # 导入 socket 模块
import RPi.GPIO as GPIO
import threading
import string

sensori = 13	#中间传感器
sensorr	= 12	#右边传感器
sensorl	= 11	#左边传感器
sock,ser = -1 , -1
#host = "127.0.1.1"
host = "192.168.137.236"
port = 12306    # 设置端口号
n = 0
key = 0

class myThread1 (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开启线程: " + self.name)
        # 获取锁,用于线程同步
        #threadLock.acquire()
        while True:  
            number,sum = 0 ,0  
            if  GPIO.input(sensori)==1 or GPIO.input(sensorl)==1 or GPIO.input(sensorr)==1    :            
                time.sleep(0.01)
                if GPIO.input(sensorl) == 1:
                    number = 1
                if GPIO.input(sensori) == 1:
                    number += 2
                if GPIO.input(sensorr)==1:
                    number += 5   
           
            if key == 0:
                if number == 1:
                    angle ="\xcc\x01\x01\x2d\xcc"
                    sum = 45
                elif number == 2:
                    angle ="\xcc\x01\x01\x5a\xcc"
                    sum = 90
                elif number == 5:
                    angle ="\xcc\x01\x01\x87\xcc"
                    sum = 135
           
                
                try:  
                    if number > 0:
                        ser.write(angle)
                        fsangle = str(sum)
                        sock.send(fsangle.encode('utf-8'))   #以utf-8编码对fsangle进行编码,获得bytes类型对象
                        print ("fs angle:",number)   
                except socket.error :
                    doConnect(host,port)  
                    try:           
                        sock.send(fsangle.encode('utf-8'))   
                    except Exception :
                        print ("key",key)             
            elif key == 1:
               
                if sock < 0 :
                    try :
                        doConnect(host,port)
                    except Exception:
                        print "connicet false"  
            try :
                count = ser.inWaiting()  #获取缓存区字符
                if count > 0:
                    print count
                    # 读取内容并发送    
                    date = ser.read(count)
                    ser.write(date)
                    sock.send(date)
                # 清空接收缓冲区
                ser.flushInput()
            except Exception :
                print("ser.read")
              
        
            # 必要的软件延时
            time.sleep(0.1)
            try :
                if sock.recv(1024) < 0:
                    doConnect(host,port)
            except Exception:
                pass
        # 释放锁,开启下一个线程
        #threadLock.release()
     
class myThread2 (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开启线程: " + self.name)
        # 获取锁,用于线程同步
        #threadLock.acquire()
        
        while True:  
            global key
            try:
                date = sock.recv(15)  #读取
                if date > 0 :
                    
                    #lock.acquire()
                    if date[1]  == '\x03':    #状态控制手动
                        key = 1
                    elif date[1]    ==  '\x02':
                        key = 0
                    #lock.release()
                    
                    ser.write(date)
                    print ("key:",key)
                    #ser.write(key.encode('utf-8'))
                    print ("%r" % date)
                      
            except Exception :
                pass
                    
            # 必要的软件延时
            time.sleep(0.1)
        # 释放锁,开启下一个线程
        #threadLock.release()
        
def init():
    
    GPIO.setmode(GPIO.BOARD)    #采用实际的物理管脚给GPIO口
    GPIO.setwarnings(False)     #去除GPIO口警告
    GPIO.setup(sensori,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) #设置为输入模式、引脚电压为0
    GPIO.setup(sensorr,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(sensorl,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
 
def serinit(): 
    global ser 
    
    try :
        ser = serial.Serial("/dev/ttyS0", 9600)  #打开串口 
        print (ser)
        ser.flushInput()  # 清空缓存区 count = ser.inWaiting()  #获取缓存区字符
        #ser.write("begin !".encode("utf-8"))  # 写入信息
        str ="\xcc\x00\x01\x00\xcc" 
        ser.write(str) 
    except :
        pass
    
    
def doConnect(host,port): 
    global sock
    print "连接服务器"
    
    try :
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#声明socket类型,同时生成链接对象
        sock.settimeout(3)  #连接超时
        sock.connect((host,port))
        global n
        n = n + 1
        print (n,"connect")
    except :
        pass
 
def doset():
    global ser
    
 
def stop():
    ser.close()
    sock.close()
    GPIO.cleanup()

if __name__ == '__main__':
         
    print ("begin !")
    init() 
    while ser < 0:
        try :
            serinit()
        except:
            pass
        
    try :
        doConnect(host,port)
        sock.send("hell world".encode('utf-8')) 
    except Exception:
        print "connicet false"   
    
    #线程锁
    #threadLock = threading.Lock()
    #threads = []

    # 创建新线程
    thread1 = myThread1(1, "Thread-1", 1)
    thread2 = myThread2(1, "Thread-2", 1)

    # 开启新线程
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    
    '''
    # 添加线程到线程列表
    threads.append(thread1)
    threads.append(thread2)

    # 等待所有线程完成
    for t in threads:
        t.join()
    print ("退出主线程")
    '''
        
    stop()
    

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值