Работа с com портом python linux

Библиотека 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В¶

readline() reads up to one line, including the n at the end. 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. If the n is missing in the return value, it returned on timeout.

readlines() tries to read “all” lines which is not well defined for a serial port that is still open. Therefore readlines() depends on having a timeout on the port and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly. The returned list of lines do not include the n .

Both functions call read() to get their data and the serial port timeout is acting on this function. Therefore the effective timeout, especially for readlines() , can be much larger.

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.

Читайте также:  Linux как создать swap после установки

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-2020, Chris Liechti Revision f7e39f06 .

Источник

Работа с ком портом питоне

Продолжаю осваивать питон

Накропал скрипт для лога данных с сенсора в БД

Железка определяется как

Из неприятных минусов — железка перезагружается. Помогите побороть эту бяку.

Когда работает эта программа то перезагружается, а если просто minicom натравить — то не перезагружается?

Где-то эти прекрасные макароны:

и этот тред я уже видел.

а китайская хитрая железяка. перезагружается

Я думаю, что проблема где-то тут. На неё документация есть? Софт с ней какой идёт? Попробуй реверсни и посмотри как с ней работают.

Железка -суровый китайский самопал. Документации нет, софта нет. Населена роботами. Вот она если что. mysku.ru/blog/taobao/40456.html Ребут идет именно по запуску скрипта. Гугл показывает аналогичную проблему с ардуиной, но там хардварное решение -тупо воткнуть конденсатор между пинами

начни с устранения причин перезагрузки.

скорость работы устройство действительно 9600?

вообще если какой тулой вообще посмотреть чё с порта приходит — на какой скорости?

может твой скрипт ненароком просто вычитывает тоны не формата — чисто для себя попробуй посмотреть чё в s = ser.readline() приходит и печатай для себя.

Чтение никак не должно влиять на работу железки. Может у тебя там коротит чего? Питание проверяй. Попробуй конденсатор микрофарад на 100 воткнуть между плюсом и минусом питания, если в железке нет такого. Можно больше.

long — в моём питоне такого нет.

Я бы так написал:

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

У меня он происходил про открытии порта.

Я не спец по железкам. Но она выдает в csv данные. В виде строки данных через запятую.

По крайней мере я так понял. Если можешь подскажи чем и как посмотреть чем плюется железка.

Я в ардуинке тоже сталкивался. Судя по всему оно на ser.open() ресетится.

Ты уже проверил что с программами типа minicom всё нормально работает и не резетится? И лишь только с твоей программой так.

А если чего-нибудь туда послать, тоже ресетится?

крч у питона же интерактивная среда есть

если вручную подключаешься то всё видимо ок?

попробуй ну просто счётчик числа прочитаных строк воткнуть и посмотреть после скольки рвёться соединение например.

(в порядке мозгового шторма)может вообще там у железки после некоторого обьёма ответа какие буферы сыпятся вот и ресетиться — али ещё какие глюки с «таймингами» и действительно попробуй какой «обычной»(т.е обще используемой в таковых задачах) тулзой посмотреть программно свою железку «по разговарий» с ней может до чего и уговоришь

Проверил. оно ресетится на всем что пробовал: CuteCOM, SerialPlot

Проверил — ресетится оно по открытию порта.

Самый неприятный открытый момент — при чтении порта он сначала отдает кривые данные.

Соответсвенно вижу 2 варианта.

1. бесконечный цикл чтения данных и отбор нужных 2. вызов таки по крону, фильтрация медианой пачки считанных данных.

Читайте также:  Отстает мышь windows 10

Сейчас пытаюсь сделать регистрацию на qq (китайский месенджер) чтоб достать продавца

после скольки рвёться соединение например

tsya.ru (я не придираюсь, просто этот сайт поможет)

А железяка дороговата. 157 баксов за такое — перебор если по мне.

А найди аналоги дешевле.

Самому спаять. Там в принципе ничего сложного.

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

Короче, сделал я чтоб не перезапускался. правда велосипед еще тот.

Скрипт запустил в бесконечный цикл чтения т.е. открытие порта происходит всего 1 раз. а чтобы оно постоянно висело, запустил его через supervisor

Из неприятных минусов — железка перезагружается.

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

правильно-неправильно. но мне такое поведение вредно.

Источник

ToolsВ¶

serial.tools.list_portsВ¶

This module can be executed to get a list of ports ( python -m serial.tools.list_ports ). It also contains the following functions.

serial.tools.list_ports. comports ( include_links=False ) В¶

Parameters: include_links (bool) – include symlinks under /dev when they point to a serial port
Returns: a list containing ListPortInfo objects.

The function returns a list of ListPortInfo objects.

Items are returned in no particular order. It may make sense to sort the items. Also note that the reported strings are different across platforms and operating systems, even for the same device.

Support is limited to a number of operating systems. On some systems description and hardware ID will not be available ( None ).

Under Linux, OSX and Windows, extended information will be available for USB devices (e.g. the ListPortInfo.hwid string contains VID:PID , SER (serial number), LOCATION (hierarchy), which makes them searchable via grep() . The USB info is also available as attributes of ListPortInfo .

If include_links is true, all devices under /dev are inspected and tested if they are a link to a known serial port device. These entries will include LINK in their hwid string. This implies that the same device listed twice, once under its original name and once under linked name.

Platform: Posix (/dev files)
Platform: Linux (/dev files, sysfs)
Platform: OSX (iokit)
Platform: Windows (setupapi, registry)

serial.tools.list_ports. grep ( regexp, include_links=False ) В¶

an iterable that yields ListPortInfo objects, see also comports() .

Search for ports using a regular expression. Port name , description and hwid are searched (case insensitive). The function returns an iterable that contains the same data that comports() generates, but includes only those entries that match the regexp.

class serial.tools.list_ports. ListPortInfo В¶

This object holds information about a serial port. It supports indexed access for backwards compatibility, as in port, desc, hwid = info .

Full device name/path, e.g. /dev/ttyUSB0 . This is also the information returned as first element when accessed by index.

Short device name, e.g. ttyUSB0 .

Human readable description or n/a . This is also the information returned as second element when accessed by index.

Technical description or n/a . This is also the information returned as third element when accessed by index.

USB specific data, these are all None if it is not an USB device (or the platform does not support extended info).

USB Vendor ID (integer, 0…65535).

USB product ID (integer, 0…65535).

USB serial number as a string.

USB device location string (“ —

USB manufacturer string, as reported by device.

USB product string, as reported by device.

Interface specific description, e.g. used in compound USB devices.

Comparison operators are implemented such that the ListPortInfo objects can be sorted by device . Strings are split into groups of numbers and text so that the order is “natural” (i.e. com1 com2 com10 ).

Command line usage

Help for python -m serial.tools.list_ports :

List all ports with details:

List the 2nd port matching a USB VID:PID pattern:

New in version 2.6.

Changed in version 3.0: returning ListPortInfo objects instead of a tuple

serial.tools.minitermВ¶

This is a console application that provides a small terminal application.

Miniterm itself does not implement any terminal features such as VT102 compatibility. However it may inherit these features from the terminal it is run. For example on GNU/Linux running from an xterm it will support the escape sequences of the xterm. On Windows the typical console window is dumb and does not support any escapes. When ANSI.sys is loaded it supports some escapes.

The default is to filter terminal control characters, see —filter for different options.

Command line options can be given so that binary data including escapes for terminals are escaped or output as hex.

Miniterm supports RFC 2217 remote serial ports and raw sockets using URL Handlers such as rfc2217:// :

as port argument when invoking.

Command line options python -m serial.tools.miniterm -h :

Available filters ( —filter option):

  • colorize : Apply different colors for received and echo
  • debug : Print what is sent and received
  • default : remove typical terminal control codes from input
  • direct : do-nothing: forward all data unchanged
  • nocontrol : Remove all control codes, incl. CR+LF
  • printable : Show decimal code for all non-ASCII characters and replace most control codes

Miniterm supports some control functions while being connected. Typing Ctrl+T Ctrl+H when it is running shows the help text:

Ctrl+T z suspends the connection (port is opened) and reconnects when a key is pressed. This can be used to temporarily access the serial port with an other application, without exiting miniterm. If reconnecting fails it is also possible to exit ( Ctrl+] ) or change the port ( p ).

Changed in version 2.5: Added Ctrl+T menu and added support for opening URLs.

Changed in version 2.6: File moved from the examples to serial.tools.miniterm .

Changed in version 3.0: Apply encoding on serial port, convert to Unicode for console. Added new filters, default to stripping terminal control sequences. Added —ask option.

Changed in version 3.5: Enable escape code handling on Windows 10 console.

© Copyright 2001-2020, Chris Liechti Revision f7e39f06 .

Источник

Читайте также:  Windows не может загрузить нужные драйверы код 31
Оцените статью
Parameters:
  • regexp – regular expression (see stdlib re )
  • include_links (bool) – include symlinks under /dev when they point to a serial port
Returns: