设为首页 收藏本站
查看: 1039|回复: 0

[经验分享] 树莓派RaspberryPi串口Python操作指南

[复制链接]

尚未签到

发表于 2015-4-26 11:36:19 | 显示全部楼层 |阅读模式
Python的串口操作库:PySerial
  下载

  http://sourceforge.net/projects/pyserial/files/pyserial/2.5/

  或者

  easy_install pyserial

  英文文档:


Overview
  This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono). The module named "serial" automatically selects the appropriate backend.
It is released under a free software license, see LICENSE.txt
for more details.
(C) 2001-2008 Chris Liechti cliechti@gmx.net

The project page on SourceForge
and here is the SVN repository
and the Download Page
.
The homepage is on http://pyserial.sf.net/


Features


  • same class based interface on all supported platforms
  • access to the port settings through Python 2.2+ properties
  • port numbering starts at zero, no need to know the port name in the user program
  • port string (device name) can be specified if access through numbering is inappropriate
  • support for different bytesizes, stopbits, parity and flow control with RTS/CTS and/or Xon/Xoff
  • working with or without receive timeout
  • file like API with "read" and "write" ("readline" etc. also supported)
  • The files in this package are 100% pure Python. They depend on
    non standard but common packages on Windows (pywin32) and Jython
    (JavaComm). POSIX (Linux, BSD) uses only modules from the standard
    Python distribution)
  • The port is set up for binary transmission. No NULL byte
    stripping, CR-LF translation etc. (which are many times enabled for
    POSIX.) This makes this module universally useful.
  

Requirements


  • Python 2.2 or newer
  • pywin32 extensions on Windows
  • "Java Communications" (JavaComm) or compatible extension for Java/Jython
  

Installation
  

from source
  
Extract files from the archive, open a shell/console in that directory and let Distutils do the rest:
python setup.py install

The files get installed in the "Lib/site-packages" directory.

easy_install
  
An EGG is available from the Python Package Index: http://pypi.python.org/pypi/pyserial
easy_install pyserial


windows installer
  
There is also a Windows installer for end users. It is located in the Download Page
Developers may be interested to get the source archive, because it contains examples and the readme.

Short introduction
  
Open port 0 at "9600,8,N,1", no timeout


.text .imp { font-weight: bold; color: red; }
>>> import serial
>>> ser = serial.Serial(0)  # open first serial port
>>> print ser.portstr       # check which port was really used
>>> ser.write("hello")      # write a string
>>> ser.close()             # close port
Open named port at "19200,8,N,1", 1s timeout
.text .imp { font-weight: bold; color: red; }
>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
>>> x = ser.read()          # read one byte
>>> s = ser.read(10)        # read up to ten bytes (timeout)
>>> line = ser.readline()   # read a '/n' terminated line
>>> ser.close()
Open second port at "38400,8,E,1", non blocking HW handshaking
.text .imp { font-weight: bold; color: red; }
>>> ser = serial.Serial(1, 38400, timeout=0,
...                     parity=serial.PARITY_EVEN, rtscts=1)
>>> s = ser.read(100)       # read up to one hundred bytes
...                         # or as much is in the buffer
Get a Serial instance and configure/open it later
.text .imp { font-weight: bold; color: red; }
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False
Be carefully when using "readline". Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that "readlines" only works with a timeout. "readlines" depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.
Do also have a look at the example files in the examples directory in the source distribution or online.
Examples

Please look in the SVN Repository. There is an example directory where you can find a simple terminal and more.
http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/

Parameters for the Serial class

.text .imp { font-weight: bold; color: red; }
ser = serial.Serial(
port=None,              # number of device, numbering starts at
# zero. if everything fails, the user
# can specify a device string, note
# that this isn't portable anymore
# if no port is specified an unconfigured
# an closed serial port object is created
baudrate=9600,          # baud rate
bytesize=EIGHTBITS,     # number of databits
parity=PARITY_NONE,     # enable parity checking
stopbits=STOPBITS_ONE,  # number of stopbits
timeout=None,           # set a timeout value, None for waiting forever
xonxoff=0,              # enable software flow control
rtscts=0,               # enable RTS/CTS flow control
interCharTimeout=None   # Inter-character timeout, None to disable
)
The port is immediately opened on object creation, if a port is given. It is not opened if port is None.
Options for read timeout:
.text .imp { font-weight: bold; color: red; }
timeout=None            # wait forever
timeout=0               # non-blocking mode (return immediately on read)
timeout=x               # set timeout to x seconds (float allowed)
Methods of Serial instances

.text .imp { font-weight: bold; color: red; }
open()                  # open port
close()                 # close port immediately
setBaudrate(baudrate)   # change baud rate on an open port
inWaiting()             # return the number of chars in the receive buffer
read(size=1)            # read "size" characters
write(s)                # write the string s to the port
flushInput()            # flush input buffer, discarding all it's contents
flushOutput()           # flush output buffer, abort output
sendBreak()             # send break condition
setRTS(level=1)         # set RTS line to specified logic level
setDTR(level=1)         # set DTR line to specified logic level
getCTS()                # return the state of the CTS line
getDSR()                # return the state of the DSR line
getRI()                 # return the state of the RI line
getCD()                 # return the state of the CD line
Attributes of Serial instances

Read Only:
.text .imp { font-weight: bold; color: red; }
portstr                 # device name
BAUDRATES               # list of valid baudrates
BYTESIZES               # list of valid byte sizes
PARITIES                # list of valid parities
STOPBITS                # list of valid stop bit widths
New values can be assigned to the following attributes, the port will be reconfigured, even if it's opened at that time:
.text .imp { font-weight: bold; color: red; }
port                    # port name/number as set by the user
baudrate                # current baud rate setting
bytesize                # byte size in bits
parity                  # parity setting
stopbits                # stop bit with (1,2)
timeout                 # timeout setting
xonxoff                 # if Xon/Xoff flow control is enabled
rtscts                  # if hardware flow control is enabled
Exceptions

.text .imp { font-weight: bold; color: red; }
serial.SerialException
Constants

parity:
.text .imp { font-weight: bold; color: red; }
    serial.PARITY_NONE
serial.PARITY_EVEN
serial.PARITY_ODD
stopbits:
.text .imp { font-weight: bold; color: red; }
    serial.STOPBITS_ONE
serial.STOPBITS_TWO
bytesize:
.text .imp { font-weight: bold; color: red; }




serial.FIVEBITS
serial.SIXBITS
serial.SEVENBITS
serial.EIGHTBITS

PySerial使用实例



#!/usr/bin/env python
import serial
import sys
class Control():
def __init__(self,device='/dev/ttyUSB0',BAUD=4800):
self.client = serial.Serial(device,BAUD,timeout=1)
def command(self,CMD):
try:
self.client.write(CMD)
#self.client.close()
except:
pass
if __name__ == '__main__':
c = Control()
while True:
cmd = raw_input("控制命令:")
if cmd == 'exit': #输入exit退出程序
sys.exit()
else:
c.command(cmd)

  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60852-1-1.html 上篇帖子: 【Python】:用python做下百度2014笔试题 下篇帖子: python数组的使用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表