- Библиотека pyserial
- Введение
- Примеры
- Инициализировать последовательное устройство
- Читать из последовательного порта
- Проверьте, какие последовательные порты доступны на вашем компьютере
- Синтаксис
- Параметры
- Примечания
- Модуль heapq
- Short introduction¶
- Opening serial ports¶
- Configuring ports later¶
- Readline¶
- Testing ports¶
- Listing ports¶
- Accessing ports¶
- pySerial¶
- Overview¶
- Features¶
- Requirements¶
- Installation¶
- From PyPI¶
- From Conda¶
- From source (zip/tar.gz or checkout)¶
- Packages¶
- References¶
- Older Versions¶
- Petri Mäki
- Blogi tietokoneista, ohjelmista ja minusta
- Reading Arduino serial ports in Windows 7 with Python + Pyserial
- Reading Arduino serial ports with Pyserial
- Hello world with serial ports
- Arduino read data from Python
- Arduino control led
- Reading data from sensor and printing that to computer
- Python & Arduino. Просто, быстро и красиво
- Оборудование
- Скетч для Arduino
- Код для компьютера
- Установка
- Интерфейс
- Исходный код
Библиотека 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 .
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.
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 .
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.
Python & Arduino. Просто, быстро и красиво
Оборудование
Недавно я заполучил очень интересную плату: Arduino SS Micro. Эта плата, внешне напоминающая Digispark Attiny 85, тем не менее является китайской версией Arduino Micro, с выведенным выходом USB.
Подробно рассказывать о ней я не буду, ведь это уже сделал пользователь YouTube с ником iomoio, и его обзор можно посмотреть здесь.
Как мне кажется — это довольно крутое и удобное устройство для небольших домашних проектов, ведь у проводов есть супер-свойство: теряться в самый неподходящий момент.
В качестве управляющего компьютера был использован MacBook Pro с операционной системой macOS Mojave, но не надо закрывать статью, если вы используете Windows или Linux — всё описанное в статье будет работать без изменений на любой операционной системе.
Скетч для Arduino
В качестве примера будет использоваться скетч, включающий и выключающий светодиод, по команде из Serial-порта.
Светодиод в Arduino SS Micro висит на порте SS, и поэтому он автоматически выключается. Не смотря на это, стандартный пример Blink — мигающий светодиод работает.
Если вы будете использовать другую Arduino — не забудьте сменить пин светодиода.
Код для компьютера
Одним из достоинств Python, кроме его кроссплатформенности — наличие гигантского числа библиотек. Нам понадобятся:
- PySerial — библиотека для работы с Serial-портом
- PyQT5 — библиотека для создания графического интерфейса
Установка
Для установки, воспользуемся встроенным менеджером пакетов — pip.
Для удобства создания GUI можно установить программу QTDesigner.
Интерфейс
Поскольку данная программа предназначена скорее, для демонстрации возможностей, пользователь может выбрать порт из предложенных, а так же скорость, с которой будет происходить общение.
Исходный код
Вся работа с устройством происходит благодаря библиотеке PySerial. Но есть несколько нюансов. Например, как узнать, в какой из портов подключено устройство?
На всем прекрасно известном сайте stackoverflow, пользователь с ником Thomas предложил уже готовое решение, которое я и использовал.
Кроме этого необходимо хранить список доступных скоростей:
А теперь соберём вместе дизайн(созданный в QtDesigner и сконвертированный с помощью утилиты pyuic5 в .py файл), функции для сканирования портов и основной код программы.
Основной класс, содержащий в себе всю логику программы
Переменные self.Port и self.Speed — это выпадающие списки, содержащие в себе значения доступных портов и скоростей.
При нажатии на кнопку self.ConnectButton вызывается функция connect, в которой производится попытка подключения к заданному порту с заданной скоростью. Если подключение успешно, то кнопка окрашивается в зелёный цвет, и меняется надпись.
Функция send отправляет в наш порт байтовую строку — заставляющую включить режим мигания.
Таким образом можно управлять различными устройствами, подключёнными к USB.
Данная статья является вводной и обзорной, более полную информацию можно найти например тут:
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.