Python serial примеры windows

pySerial¶

Overview¶

This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend.

It is released under a free software license, see LICENSE for more details.

Copyright (C) 2001-2016 Chris Liechti

Other pages (online)

Features¶

  • Same class based interface on all supported platforms.
  • Access to the port settings through Python properties.
  • Support for different byte sizes, stop bits, 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.
  • 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.
  • Compatible with io library
  • RFC 2217 client (experimental), server provided in the examples.

Requirements¶

  • Python 2.7 or Python 3.4 and newer
  • If running on Windows: Windows 7 or newer
  • If running on Jython: “Java Communications” (JavaComm) or compatible extension for Java

For older installations (older Python versions or older operating systems), see older versions below.

Installation¶

This installs a package that can be used from Python ( import serial ).

To install for all users on the system, administrator rights (root) may be required.

From PyPI¶

pySerial can be installed from PyPI:

Using the python / python3 executable of the desired version (2.7/3.x).

Developers also may be interested to get the source archive, because it contains examples, tests and the this documentation.

From Conda¶

pySerial can be installed from Conda:

Currently the default conda channel will provide version 3.4 whereas the conda-forge channel provides the current 3.x version.

From source (zip/tar.gz or checkout)¶

Download the archive from http://pypi.python.org/pypi/pyserial or https://github.com/pyserial/pyserial/releases. Unpack the archive, enter the pyserial-x.y directory and run:

Using the python / python3 executable of the desired version (2.7/3.x).

Packages¶

There are also packaged versions for some Linux distributions:

  • Debian/Ubuntu: “python-serial”, “python3-serial”
  • Fedora / RHEL / CentOS / EPEL: “pyserial”
  • Arch Linux: “python-pyserial”
  • Gentoo: “dev-python/pyserial”

Note that some distributions may package an older version of pySerial. These packages are created and maintained by developers working on these distributions.

Читайте также:  Загрузочный dvd windows 10 uefi

References¶

Older Versions¶

Older versions are still available on the current download page or the old download page. The last version of pySerial’s 2.x series was 2.7, compatible with Python 2.3 and newer and partially with early Python 3.x versions.

pySerial 1.21 is compatible with Python 2.0 on Windows, Linux and several un*x like systems, MacOSX and Jython.

On Windows, releases older than 2.5 will depend on pywin32 (previously known as win32all). WinXP is supported up to 3.0.1.

© Copyright 2001-2017, Chris Liechti. Revision a27715f3 .

Библиотека pyserial

Введение

Примеры

Инициализировать последовательное устройство

Читать из последовательного порта

Инициализировать последовательное устройство

читать один байт с последовательного устройства

читать заданное количество байтов из последовательного устройства

прочитать одну строку из последовательного устройства.

читать данные с последовательного устройства, пока что-то записывается поверх него.

Проверьте, какие последовательные порты доступны на вашем компьютере

Чтобы получить список доступных последовательных портов, используйте

в командной строке или

из оболочки Python.

Синтаксис

Параметры

Примечания

Научим основам Python и Data Science на практике

Это не обычный теоритический курс, а онлайн-тренажер, с практикой на примерах рабочих задач, в котором вы можете учиться в любое удобное время 24/7. Вы получите реальный опыт, разрабатывая качественный код и анализируя реальные данные.

Модуль heapq

Введение Примеры Самые большие и маленькие предметы в коллекции Для того, чтобы найти самые большие предметы в коллекции, heapq модуль имеет функцию под названием nlargest , мы передаем его два аргумента, то первый из

Short introduction¶

Opening serial ports¶

Open port at “9600,8,N,1”, no timeout:

Open named port at “19200,8,N,1”, 1s timeout:

Open port at “38400,8,E,1”, non blocking HW handshaking:

Configuring ports later¶

Get a Serial instance and configure/open it later:

Readline¶

Be careful 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.

The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.

To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:

Testing ports¶

Listing ports¶

python -m serial.tools.list_ports will print a list of available ports. It is also possible to add a regexp as first argument and the list will only include entries that matched.

The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or may lack detailed descriptions of the ports.

Accessing ports¶

pySerial includes a small console based terminal program called serial.tools.miniterm . It can be started with python -m serial.tools.miniterm

(use option -h to get a listing of all options).

© Copyright 2001-2017, Chris Liechti. Revision a27715f3 .

Читайте также:  Pac the mac os

Petri Mäki

Blogi tietokoneista, ohjelmista ja minusta

Reading Arduino serial ports in Windows 7 with Python + Pyserial

Here i am going to show you 3 working examples on how to read Arduino serial ports with windows. You are going to need following programs / tools:

Installing Python + Pyserial to Windows

First you have ton install Python on your computer. This is just typical install with no big deal. When you have installed Python you may want to restart your computer. If you are not sure if your install was succesfull you can open your command prompt and type python or go to location where you installed python and run Python.exe. If everything works correctly your command prompt should look something like this:

After installing Python you can download Pyserial. Unzip pyserial to folder where you installed python and says lib. For me example to location was:

c:\Python27\Lib\pyserial-2.6\

After you have unzipped pyserial, you should start command prompt and go to location above. In there you can find setup.py named file, which you cn run by typing:

python setup.py install

Now you have installed Python + Pyserial

Reading Arduino serial ports with Pyserial

First code is basic ”Hello world” with arduino and python
Code for Arduino:

Hello world with serial ports

Next code for python: (Note that WordPress might break Pythons code blocks)

Arduino read data from Python

Arduino read data when user type something and prints it out byte by byte.

Arduino control led

Controlling 1 led light with arduino and pyserial by typing 0 or 1 to turn led on and off

Code for arduino:

Code for python:

Reading data from sensor and printing that to computer

In this code we are going to use unknown light sensor for arduino. You can basically use any type of sensor you want since the principle is the same.

Examples¶

Miniterm¶

Miniterm is now available as module instead of example. see serial.tools.miniterm for details.

miniterm.py The miniterm program. setup-miniterm-py2exe.py This is a py2exe setup script for Windows. It can be used to create a standalone miniterm.exe .

TCP/IP — serial bridge¶

This program opens a TCP/IP port. When a connection is made to that port (e.g. with telnet) it forwards all data to the serial port and vice versa.

This example only exports a raw socket connection. The next example below gives the client much more control over the remote serial port.

  • The serial port settings are set on the command line when starting the program.
  • There is no possibility to change settings from remote.
  • All data is passed through as-is.

Single-port TCP/IP — serial bridge (RFC 2217)¶

Simple cross platform RFC 2217 serial port server. It uses threads and is portable (runs on POSIX, Windows, etc).

  • The port settings and control lines (RTS/DTR) can be changed at any time using RFC 2217 requests. The status lines (DSR/CTS/RI/CD) are polled every second and notifications are sent to the client.
  • Telnet character IAC (0xff) needs to be doubled in data stream. IAC followed by another value is interpreted as Telnet command sequence.
  • Telnet negotiation commands are sent when connecting to the server.
  • RTS/DTR are activated on client connect and deactivated on disconnect.
  • Default port settings are set again when client disconnects.
Читайте также:  Набор системных библиотек для windows

New in version 2.5.

Multi-port TCP/IP — serial bridge (RFC 2217)¶

This example implements a TCP/IP to serial port service that works with multiple ports at once. It uses select, no threads, for the serial ports and the network sockets and therefore runs on POSIX systems only.

  • Full control over the serial port with RFC 2217.
  • Check existence of /tty/USB0. 8 . This is done every 5 seconds using os.path.exists .
  • Send zeroconf announcements when port appears or disappears (uses python-avahi and dbus). Service name: _serial_port._tcp .
  • Each serial port becomes available as one TCP/IP server. e.g. /dev/ttyUSB0 is reachable at :7000 .
  • Single process for all ports and sockets (not per port).
  • The script can be started as daemon.
  • Logging to stdout or when run as daemon to syslog.
  • Default port settings are set again when client disconnects.
  • modem status lines (CTS/DSR/RI/CD) are not polled periodically and the server therefore does not send NOTIFY_MODEMSTATE on its own. However it responds to request from the client (i.e. use the poll_modem option in the URL when using a pySerial client.)

Installation as daemon:

  • Copy the script port_publisher.py to /usr/local/bin .
  • Copy the script port_publisher.sh to /etc/init.d .
  • Add links to the runlevels using update-rc.d port_publisher.sh defaults 99
  • That’s it 🙂 the service will be started on next reboot. Alternatively run invoke-rc.d port_publisher.sh start as root.

New in version 2.5: new example

wxPython examples¶

A simple terminal application for wxPython and a flexible serial port configuration dialog are shown here.

wxTerminal.py A simple terminal application. Note that the length of the buffer is limited by wx and it may suddenly stop displaying new input. wxTerminal.wxg A wxGlade design file for the terminal application. wxSerialConfigDialog.py A flexible serial port configuration dialog. wxSerialConfigDialog.wxg The wxGlade design file for the configuration dialog. setup-wxTerminal-py2exe.py A py2exe setup script to package the terminal application.

Unit tests¶

The project uses a number of unit test to verify the functionality. They all need a loop back connector. The scripts itself contain more information. All test scripts are contained in the directory test .

The unit tests are performed on port loop:// unless a different device name or URL is given on the command line ( sys.argv[1] ). e.g. to run the test on an attached USB-serial converter hwgrep://USB could be used or the actual name such as /dev/ttyUSB0 or COM1 (depending on platform).

run_all_tests.py Collect all tests from all test* files and run them. By default, the loop:// device is used. test.py Basic tests (binary capabilities, timeout, control lines). test_advanced.py Test more advanced features (properties). test_high_load.py Tests involving sending a lot of data. test_readline.py Tests involving readline . test_iolib.py Tests involving the io library. Only available for Python 2.6 and newer. test_url.py Tests involving the URL feature.

© Copyright 2001-2017, Chris Liechti. Revision a27715f3 .

Оцените статью