Python serial install windows

Библиотека pyserial

Введение

Примеры

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

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

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

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

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

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

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

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

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

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

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

Синтаксис

Параметры

Примечания

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

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

Модуль heapq

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

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.

Читайте также:  Приложение apple для windows phone

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 .

Использование языка программирования Python вместе с Arduino

В настоящее время Arduino является одной из самых мощных и простых в использовании платформ с открытым исходным кодом. Однако тенденции современного мира таковы, что часто электронными платформами необходимо управлять с помощью высокоуровневого общецелевого языка программирования чтобы сделать их более эффективными и дружественными. Одним из таких языков является Python, который представляет собой интерпретируемый, объектно-ориентированный, высокоуровневый язык программирования с динамической семантикой и высокоуровневыми встроенными структурами данных, что делает его весьма привлекательным для быстрой разработки приложений.

Объединение возможностей Arduino и Python открывает двери для множества новых возможностей, поскольку Python имеет повышенную производительность и умеет взаимодействовать с другими платформами, такими как openCV, Matlab и т. д.

В этой статье мы изучим как установить Python на компьютер и как его использовать вместе с Arduino для включения/выключения встроенного в плату Arduino светодиода.

Установка Python на ваш компьютер

В данном разделе статьи будет рассмотрена установка языка программирования на компьютер с 32 или 64-битной windows. Установка Python на компьютеры под управлением MAC и Linux будет отличаться.
Для установки Python выполните следующую последовательность шагов:

1. Установите 32-битную версию Python 2.7.9 IDLE на ваш компьютер. Не скачивайте 64-битную версию Python или его более свежую версию поскольку они могут быть не совместимы с используемыми нами библиотеками Arduino. Даже если ваш компьютер работает на 64-битной операционной системе, то вы все равно можете использовать на нем 32-битную версию Python.

Примечание : оригинал данной статьи был написан в 2017 году, поэтому, возможно, сейчас Arduino IDE уже поддерживает совместимость с более свежими версиями Python (этот вопрос будет уточняться в дальнейшем).

2. Запустите на выполнение скачанный установочный файл и установите эту версию языка Python на ваш компьютер. Не изменяйте каталог для установки Python, оставьте его по умолчанию — C:\Python27.

3. Возможно, во время установки Python на него будет “ругаться” антивирус – не обращайте на это внимание.

После установки Python вы можете проверить действительно ли он установлен на ваш компьютер введя в строке поиска Windows строку “Python IDLE”.

После его запуска вы должны увидеть на экране компьютера “Python shell” (оболочка Python) как показано на следующем рисунке.

Читайте также:  Безопасность камеры windows 10

Вы можете непосредственно писать программу в этой оболочке или же создать новый файл и писать и проверять программу в нем. Теперь давайте удостоверимся в том, что Python работает. Для этого напечатайте “print (1+1)” и нажмите enter. Вы должны после этого увидеть в оболочке напечатанный результат вычислений – 2.

Установка PySerial в Python

Следующим шагом необходимо установить программу PySerial, которая представляет собой Python API module (модуль прикладного программного интерфейса Python’а), с помощью которого можно считывать и записывать данные в последовательном виде в плату Arduino или любой другой микроконтроллер.

Кликните на Pyserial Windows чтобы скачать PySerial. По приведенной ссылке вы можете скачать установочный файл этого приложения и установить его. Не изменяйте настройки (в том числе и каталог для установки) во время установки приложения – оставьте их по умолчанию.

Теперь давайте убедимся в том, что PySerial корректно установлена и работает. Для этого снова откройте Python Shell и напечатайте в нем “import serial”. Если библиотека успешно установлена, то после этого вы не увидите никаких сообщений об ошибке как показано на следующем рисунке.

Дальнейший материал статьи предполагает что вы хотя бы немного знакомы с платформой Arduino и умеете загружать в нее программы. Если это не так, то советуем ознакомиться с руководством по Arduino для начинающих.

Наша первая совместная программа на Arduino и Python

Как отмечалось ранее, в этой программе мы будем управлять встроенным в плату Arduino светодиодом.

Программа для Arduino

Полный текст программы для платы Arduino приведен в конце статьи, здесь же обсудим наиболее важные его фрагменты.

Внутри функции setup мы инициализируем последовательную связь со скоростью 9600 бод/с и зададим режим работы для контакта, с которого будем управлять светодиодом. Также мы передадим приветственное сообщение в Python при помощи последовательной связи.

Pyserial install for Python 3.X (64bit windows)

Attempt to install via pip failed:

C:\Users\User>python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type «help», «copyright», «credits» or «license» for more information.

pip install pyserial File «», line 1 pip install pyserial ^ SyntaxError: invalid syntax

Not sure why there is an error (perhaps this mode only work with LINUX / OSX?). Very curious.

Fairly certain from other postings that Win-32 bit pyserial installer will not work on Win64. Ideally, someone who has successfully installed pyserial on Win64 can weigh in and provide link / CLI install instructions. Spent hours Googling, but have not resolved this install.

2 Answers 2

Try installing PySerial from the command line in Windows. Just make sure ‘pip’ is in your PATH.

By the way, newer versions of PySerial have some bugs that might affect you on Windows (they did to me). If that happens simply install an earlier version of PySerial. I found that for me 2.7 works just fine.

The flag -I tells pip to ignore other versions and installs (or reinstalls) the defined one.

I am curious as to how many readers have successfully used the install process below. If your are successful please INDICATE by voting-up this response. PLEASE do not vote-up if you were not successful with the install procedure.

1) Downloaded and unzipped (WinRAR): pyserial3.0.1.gz to C:\Apps\pyserial

Читайте также:  Устранение неполадок windows 10 при запуске как исправить

2) At DOS CLI: cd C:\Apps\pyserial

3) At DOS CLI: python setup.py install

C:\Apps\pyserial>python setup.py install

running install running bdist_egg running egg_info writing top-level names to pyserial.egg-info\top_level.txt writing dependency_links to pyserial.egg-info\dependency_links.txt writing pyserial.egg-info\PKG-INFO reading manifest file ‘pyserial.egg-info\SOURCES.txt’ reading manifest template ‘MANIFEST.in’ writing manifest file ‘pyserial.egg-info\SOURCES.txt’ installing library code to build\bdist.win-amd64\egg running install_lib running build_py creating build creating build\lib creating build\lib\serial copying serial\aio.py -> build\lib\serial copying serial\rfc2217.py -> build\lib\serial copying serial\rs485.py -> build\lib\serial copying serial\serialcli.py -> build\lib\serial copying serial\serialjava.py -> build\lib\serial copying serial\serialposix.py -> build\lib\serial copying serial\serialutil.py -> build\lib\serial copying serial\serialwin32.py -> build\lib\serial copying serial\win32.py -> build\lib\serial copying serial__init__.py -> build\lib\serial creating build\lib\serial\tools copying serial\tools\hexlify_codec.py -> build\lib\serial\tools copying serial\tools\list_ports.py -> build\lib\serial\tools copying serial\tools\list_ports_common.py -> build\lib\serial\tools copying serial\tools\list_ports_linux.py -> build\lib\serial\tools copying serial\tools\list_ports_osx.py -> build\lib\serial\tools copying serial\tools\list_ports_posix.py -> build\lib\serial\tools copying serial\tools\list_ports_windows.py -> build\lib\serial\tools copying serial\tools\miniterm.py -> build\lib\serial\tools copying serial\tools__init__.py -> build\lib\serial\tools creating build\lib\serial\urlhandler copying serial\urlhandler\protocol_alt.py -> build\lib\serial\urlhandler copying serial\urlhandler\protocol_hwgrep.py -> build\lib\serial\urlhandler copying serial\urlhandler\protocol_loop.py -> build\lib\serial\urlhandler copying serial\urlhandler\protocol_rfc2217.py -> build\lib\serial\urlhandler copying serial\urlhandler\protocol_socket.py -> build\lib\serial\urlhandler copying serial\urlhandler\protocol_spy.py -> build\lib\serial\urlhandler copying serial\urlhandler__init__.py -> build\lib\serial\urlhandler creating build\lib\serial\threaded copying serial\threaded__init__.py -> build\lib\serial\threaded creating build\bdist.win-amd64 creating build\bdist.win-amd64\egg creating build\bdist.win-amd64\egg\serial copying build\lib\serial\aio.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\rfc2217.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\rs485.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\serialcli.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\serialjava.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\serialposix.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\serialutil.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial\serialwin32.py -> build\bdist.win-amd64\egg\serial creating build\bdist.win-amd64\egg\serial\threaded copying build\lib\serial\threaded__init__.py -> build\bdist.win-amd64\egg\serial\threaded creating build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\hexlify_codec.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports_common.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports_linux.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports_osx.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports_posix.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\list_ports_windows.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools\miniterm.py -> build\bdist.win-amd64\egg\serial\tools copying build\lib\serial\tools__init__.py -> build\bdist.win-amd64\egg\serial\tools creating build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_alt.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_hwgrep.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_loop.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_rfc2217.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_socket.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler\protocol_spy.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\urlhandler__init__.py -> build\bdist.win-amd64\egg\serial\urlhandler copying build\lib\serial\win32.py -> build\bdist.win-amd64\egg\serial copying build\lib\serial__init__.py -> build\bdist.win-amd64\egg\serial byte-compiling build\bdist.win-amd64\egg\serial\aio.py to aio.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\rfc2217.py to rfc2217.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\rs485.py to rs485.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\serialcli.py to serialcli.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\serialjava.py to serialjava.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\serialposix.py to serialposix.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\serialutil.py to serialutil.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\serialwin32.py to serialwin32.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\threaded__init__.py to init.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\hexlify_codec.py to hexlify_codec.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports.py to list_ports.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports_common.py to list_ports_common.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports_linux.py to list_ports_linux.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports_osx.py to list_ports_osx.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports_posix.py to list_ports_posix.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\list_ports_windows.py to list_ports_windows.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools\miniterm.py to miniterm.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\tools__init__.py to init.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_alt.py to protocol_alt.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_hwgrep.py to protocol_hwgrep.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_loop.py to protocol_loop.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_rfc2217.py to protocol_rfc2217.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_socket.py to protocol_socket.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler\protocol_spy.py to protocol_spy.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\urlhandler__init__.py to init.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial\win32.py to win32.cpython-35.pyc byte-compiling build\bdist.win-amd64\egg\serial__init__.py to init.cpython-35.pyc creating build\bdist.win-amd64\egg\EGG-INFO installing scripts to build\bdist.win-amd64\egg\EGG-INFO\scripts running install_scripts running build_scripts creating build\scripts-3.5 copying and adjusting serial\tools\miniterm.py -> build\scripts-3.5 creating build\bdist.win-amd64\egg\EGG-INFO\scripts copying build\scripts-3.5\miniterm.py -> build\bdist.win-amd64\egg\EGG-INFO\scripts copying pyserial.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO copying pyserial.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO copying pyserial.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG-INFO copying pyserial.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO zip_safe flag not set; analyzing archive contents. creating dist creating ‘dist\pyserial-3.0.1-py3.5.egg’ and adding ‘build\bdist.win-amd64\egg’ to it removing ‘build\bdist.win-amd64\egg’ (and everything under it) Processing pyserial-3.0.1-py3.5.egg Copying pyserial-3.0.1-py3.5.egg to c:\users\user\appdata\local\programs\python\python35\lib\site-packages Adding pyserial 3.0.1 to easy-install.pth file Installing miniterm.py script to C:\Users\User\AppData\Local\Programs\Python\Python35\Scripts

Installed c:\users\user\appdata\local\programs\python\python35\lib\site-packages\pyserial-3.0.1-py3.5.egg Processing dependencies for pyserial==3.0.1 Finished processing dependencies for pyserial==3.0.

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