python下的串口操作

python和串口用得都很广,学习了一下python下的串口操作

ls /dev/ttyS*

发现0、1、2、3一共四个串口

dmesg | grep ttyS*

看一下日志,一一对应,查看资料http://wiki.friendlyarm.com/wiki/index.php/NanoPi_NEO/zh
neo.png

0号是debug口,3号没有引出,就剩1号(8T/10R)和2号(11T/22R),和以前的GPS测试比较吻合http://www.ickey.cc/community/thread-67030-1-13.html
串口测试的python例子

import serial  
t = serial.Serial('/dev/ttyS2',9600)  
n = t.write('you are my world')  
print t.portstr  
print n  
str = t.read(n)  
print str

需要短接11和22脚,同时需要pyserial的支持,安装方法如下

sudo apt-get install python-pip
pip install pyserial

关于pyserial
https://pyserial.readthedocs.io/en/latest/
https://github.com/pyserial/pyserial
https://sourceforge.net/projects/pyserial/
http://pythonhosted.org/pyserial/
http://www.runoob.com/python/python-tutorial.html

读取GPS数据
import serial
import time
t = serial.Serial('COM70',9600)
c=0
while True:
str = t.readline()
print str[:-2]

等待法(已弃用)

n=t.in_waiting;
if n>0:
    time.sleep(0.3)
    c+=1 
    n=t.in_waiting;
    print "The length of %d is %d" % (c,n)
    str = t.read(n)  
    print str

显示十六进制串print '-'.join('0x{:02X}'.format(ord(x)) for x in str)

相关关键字$GPRMC、$GPVTG、$GPGGA、$GPGSA、$GPGSV、$GPGLL、$GPTXT,python中没有switch,插播一个栗子

def jia(x,y):  
    print x+y  
def jian(x,y):  
    print x-y  
def cheng(x,y):  
    print x*y  
def chu(x,y):  
    print x/y  
operator = {'+':jia,'-':jian,'*':cheng,'/':chu}  
def f(x,o,y):  
    operator.get(o)(x,y)  
f(3,'+',2)

仿写

operator = {'$GPGSA':gpgsa,'$GPTXT':gptxt}
x=operator.get(str[0])
if x:
    x(str)
else:
    gpelse(str)  

划简operator.get(str[

标签: none

添加新评论