i’m working with odroidm1 and i’m trying to enable uart port but it doesn’t work.
That is the python script
Code: Select all
#!/usr/bin/env/python3
import serial
sim800l = serial.Serial(
port="/dev/ttyS1",
baudrate = 9600,
timeout=1
)
while True:
cmd = input()
cmd = cmd.encode('utf-8')
sim800l.write(cmd)
print(sim800l.read(100).decode('utf-8').rstrip())
This is the error i get:
Code: Select all
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/serial/serialposix.py", line 398, in _reconfigure_port
orig_attr = termios.tcgetattr(self.fd)
termios.error: (5, 'Input/output error')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/Scrivania/tesi/sms/sms.py", line 4, in <module>
sim800l = serial.Serial(
File "/usr/local/lib/python3.9/dist-packages/serial/serialutil.py", line 244, in __init__
self.open()
File "/usr/local/lib/python3.9/dist-packages/serial/serialposix.py", line 332, in open
self._reconfigure_port(force_update=True)
File "/usr/local/lib/python3.9/dist-packages/serial/serialposix.py", line 401, in _reconfigure_port
raise SerialException("Could not configure port: {}".format(msg))
serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
It gives me the same error with port ttyS0,S1 and S3 while with S2 work but the S2 is the console.
Code: Select all
ls -l /dev/ttyS?
crw-rw---- 1 root dialout 4, 64 7 ago 15.25 /dev/ttyS0
crw-rw---- 1 root dialout 4, 65 7 ago 15.25 /dev/ttyS1
crw--w---- 1 root tty 4, 66 12 nov 16.27 /dev/ttyS2
crw-rw---- 1 root dialout 4, 67 7 ago 15.25 /dev/ttyS3
I’ve tried to follow the tutorial to enable uart port on odroid forum(https://wiki.odroid.com/odroid-m1/appli … /gpio/uart) but it doesn’t resolve anything
Here there is my config.ini file, but i’ve tried every possible options for this file.
Code: Select all
[generic]
overlay_resize=16384
overlay_profile=
overlays="uart0 uart1"
[overlay_custom]
overlays="i2c0 i2c1"
[overlay_hktft32]
overlays="hktft32"
[overlay_hktft35]
overlays="hktft35"
- Forum
- The Ubuntu Forum Community
- Ubuntu Specialised Support
- Development & Programming
- Programming Talk
- Python — how to send bytes to serial port?
-
hello, i trying to send bytes over serial port, but there is some problems,
Code:
ser.write("x06x10x46x46")
works fine, but when i try to do it in function, there is no bytes are sended, only ascii codes
Code:
#!/opt/bin/python import serial, string def write_port(data): #usage write_port("06 10 46 46") dataB = "" data = data.split(' ') for i in range(len(data)): data[i] = r"x" + data[i] # raw add "x" so line is x06x10x46x46 dataB = "".join(data) ser.write( dataB ) print "Python 2.7nn" ser = serial.Serial('/dev/usb/tts/2', 115200, timeout=1) print "write bytes.." write_port("06 10 46 46")
my function convert «06 10 46 46» to «x06x10x46x46», so i expect it should works like
ser.write(«x06x10x46x46»), but it does not — it send like a string without transform «x» symbols
-
Re: Python — how to send bytes to serial port?
The point is that the translation of these «x…» sequences is done when reading the .py script. To do so during runtime, you need to use some function like «bin(int(X,16))» for X=»4e» or something like that.
-
Re: Python — how to send bytes to serial port?
thanks it was chr() function, so we should transform String list to Integer list and convert chr(int,16)
here is works code:
Code:
def write_port(data): # write_port("06 10 46 46") dataB = [] data = data.split(' ') for i in range(len(data)): dataB.insert(i,int(data[i],16)) ser.write( "".join(chr(i) for i in dataB) )
-
Re: Python — how to send bytes to serial port?
If you are using Python 3, this function could be better implemented with a star argument. That would make it easier to, for instance, mathematically compute ascii codes to write and then pass them in.
Code:
def write_port(*data): # write_port(6, 10, 46, 46) dataB = [] for i in range(len(data)): dataB.insert(i,int(data[i],16)) ser.write( "".join(chr(i) for i in dataB) )
This will take all arguments and compile them into a tuple.
Code:
write_port(3) data=(3,) write_port(23, 54) data=(23, 54)
Don’t use W3Schools as a resource! (Inconsequential foul language at the jump)
Open Linux Forums (More foul language, but well worth it for the quality of support and good humor.)
If you want to discuss W3Schools, please PM me instead of posting.
-
Re: Python — how to send bytes to serial port?
Originally Posted by sh228
If you are using Python 3, this function could be better implemented with a star argument. That would make it easier to, for instance, mathematically compute ascii codes to write and then pass them in.
That also works in Python 2.7… and I think I’ve even used that in 2.5, but not sure.
-
Re: Python — how to send bytes to serial port?
Hi,
I need to send some bytes via serial port USB , on ubuntu 11.10 and
from the example made aboveser = serial.Serial(‘/dev/usb/tts/2‘, 115200, timeout=1)
the file : ‘/dev/usb/tts/2 ‘ relative to serial port doesn’t exists .
Please, which file have I to use ?
in my dev directory there is no dir named ‘usb’ and in the same dir I found
«ttys0 , …. to ttys28 » & «usbmon0 , … to usbmon7 »
I tried ‘/dev/usbmon0’ and get the error :Could not configure port: (25, ‘Inappropriate ioctl for device’) (this requires su privileges )
I tried also ‘/dev/ttyS0’ and get the error : Could not configure port: (5, ‘Input/output error’)which one is the correct file relative to usb port ?
thanks in advance
-
Re: Python — how to send bytes to serial port?
Originally Posted by yanes
which one is the correct file relative to usb port ?
Run «dmesg» from the terminal. This will show you the kernel log. Somewhere there is a message by the driver for you USB-to-Serial adapter. The message will contain the information where the device was hooked into the file system.
Bookmarks
Bookmarks
Posting Permissions
** Updated for Raspberry Pi 4 **
This used to be relatively straightforward, but with move from Raspbian Wheezy to Raspbian Jessie, (and then Raspbian Stretch and Buster) things changed. Add to this, the newer Raspberry Pi 3 and 4 family with new hardware and the whole thing became a bit of a Dog’s Breakfast and issues with the Bluetooth to boot.
It suddenly got very confusing.
Following lots of wasted time, I’ve noted down what I think I know so far in this post. With luck you can have your cake and eat it: use the serial port on a Raspberry Pi 3 / 4 and use the Bluetooth AND have the same code work on other Raspberry Pi’s (non RPi3 / 4).
NOTE: You will need the latest firmware May 2016 or later for this to work (works with August 2019 firmware). Should this change again, I’ll update this post.
History
Before I dive into the configuration, it’s worth taking a moment for a little history and orientation about the serial port on the Raspberry Pi.
If you’re a bit old school like me, you’d be expecting to find something called COM1 or similar on a header. In Raspberry Pi / Linux land this COM1 equivalent is found on pins 14 and 15 of the GPIO header and is called /dev/ttyAMA0 (obvious, right?).
Also in Raspberry Pi land, you can use the serial port as a terminal to log in, which is useful if you don’t have a network connection to hand. You can connect to another computer via their serial ports and run a terminal emulator on the other computer and you’ll get a login prompt.
By default the Raspberry Pi uses the serial port for this “console” login and via a software service called “getty”.
Using the serial port with other hardware
So that’s the ‘normal” configuration of the serial port, but serial ports are very useful things. What if we want to use the serial port to get data from a GPS card or program an arduino? In this case we need to disable the console login so that we alone get control of the port. Easy right? Yes and no. There is a big elephant in the room and he’s called Raspberry Pi 3 (also applies to 4).
Before we can describe using the serial port, we have to talk about Raspberry Pi 3 / 4, which throws a great big spanner in the works as far as serial ports are concerned.
Raspberry Pi 3 / 4
Raspberry Pi 3’s and 4’s are great little beasts, and add Bluetooth, yay! However, in order to use the Bluetooth correctly the /dev/ttyAMA0 has been “stolen” from the GPIO header and an inferior second one has been substituted in it’s place. No-one will ever know! Unfortunately /dev/ttyAMA0 was a hardware serial port (uart) and high performance (hence it was nabbed for the Bluetooth) and the second port is partly software and a bit flaky. Many people’s applications got broken.
The second serial port you will see referred to as the “mini uart” and lives at /dev/ttyS0. It also calculates it’s bit timing’s from the CPU cores frequency and if the CPU is under heavy load it can corrupt the serial communications. Not good.
In order to work around this, many people “fix” the CPU core frequency so that the serial port is stable. This comes at a slight loss in performance (though normally not noticeable). I’ll describe how you do this in the next section.
By the way, it’s not all bad for the change of serial port on the Raspberry Pi 3 / 4. The Arduino IDE expects the serial communications to be on /dev/ttyS0 so you have no work to do to map the serial ports across. Yay!
To summarise the ports on a Raspberry Pi 3 / 4 and be crystal clear:
/dev/ttyAMA0 -> Bluetooth
/dev/ttyS0 -> GPIO serial port.
If you stick with these as is, your Bluetooth will work as nature intended AND you can use a serial port over the GPIO (there is a way of swapping the serial ports around if you don’t want to use the Bluetooth and I’ll cover that at the end of this post).
Enabling
There is yet another wrinkle in that in the latest Jessie / Stretch / Buster releases (as of August 2019) the GPIO serial port is disabled by default. In order to enable it, edit config.txt:
$ sudo nano /boot/config.txt
and add the line (at the bottom):
enable_uart=1
As of May 2016 this will also lock the cpu core frequency for you so there’s nothing else you need to do (If you aren’t convinced and you really like to belt and braces it the command is: core_freq=250 which you add to the same file aswell).
Reboot for the changes to take effect.
This should get you good serial communications for most uses.
Serial Aliases
On the Raspberry Pi 3 the second serial port is called /dev/ttyS0 and is by default mapped to the GPIO pins 14 and 15. So immediately, if you have code that references /dev/ttyAMA0 you’re going to have problems and things aren’t going to work.
You could go through your code and replace ttyAMA0 with ttyS0 and that should work. However, if you find yourself use the same SD card on a Raspberry Pi other than a rpi3 your code won’t work again.
In order to try and get around this the Foundation have introduced a serial port alias (as of May 2016 – 2016-05-10). Thus you have serial ports: serial0 and serial1 (rpi3). The Raspberry Pi kernel sorts out where these point to depending on which Raspberry Pi you are on. Thus on a Raspberry Pi 3 / 4 serial0 will point to GPIO pins 14 and 15 and use the “mini-uart” aka /dev/ttyS0. On other Raspberry Pi’s it will point to the hardware UART and /dev/ttyAMA0.
To find out where it is pointing you can use the command:
$ ls -l /dev
So where possible refer to the serial port via it’s alias of “serial0” and your code should work on both Raspberry Pi 3 / 4’s and other Raspberry Pi’s.
Disabling the Console
If you are using the serial port for anything other than the console you need to disable it. This will be slightly different depending on whether you are running a Raspberry Pi 3 / 4 or not.
For non Raspberry Pi 3 / 4 machines, remember it’s /dev/ttyAMA0 that is linked to the getty (console) service. So you need to perform this command from a terminal window:
$ sudo systemctl stop serial-getty@ttyAMA0.service $ sudo systemctl disable serial-getty@ttyAMA0.service
The “disable” will stop it loading in the future.
For Raspberry Pi 3’s the command is similar but referencing /dev/ttyS0:
$ sudo systemctl stop serial-getty@ttyS0.service $ sudo systemctl disable serial-getty@ttyS0.service
You also need to remove the console from the cmdline.txt. If you edit this with:
$ sudo nano /boot/cmdline.txt
you will see something like:
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes root wait
remove the line: console=serial0,115200 and save and reboot for changes to take effect.
Swapping the Serial Ports on Raspberry Pi 3 / 4
What if you don’t want to use the Bluetooth and you want that high performance /dev/ttyAMA0 back on the GPIO? Well you can do this and the way you do this is via a device overlay called “pi3-miniuart-bt” i.e. use the mini-uart (/dev/ttyS0) for Bluetooth (you may get some loss of performance on your Bluetooth though).
You can also just disable the Bluetooth all together by using another overlay “pi3-disable-bt”. In both cases if you can find out more of what they do here: /boot/overlays/README
To use add the following line to the /boot/config.txt
$ sudo nano /boot/config.txt
and add:
dtoverlay=pi3-miniuart-bt
Save and reboot for changes to take effect.
You can check that it has worked by:
$ ls -l /dev
and you’ll see something like this:
Есть код на python который просто считывает данные с ком порта, код работает на виндовс но не работает на ubuntu
Ошибка:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/serial/serialposix.py", line 323, in _reconfigure_port
orig_attr = termios.tcgetattr(self.fd)
termios.error: (5, 'Input/output error')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 5, in <module>
ser = serial.Serial(port='/dev/ttyS5', baudrate=9600)
File "/usr/local/lib/python3.8/dist-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/usr/local/lib/python3.8/dist-packages/serial/serialposix.py", line 272, in open
self._reconfigure_port(force_update=True)
File "/usr/local/lib/python3.8/dist-packages/serial/serialposix.py", line 326, in _reconfigure_port
raise SerialException("Could not configure port: {}".format(msg))
serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
Код:
import time
import serial
import datetime
ser = serial.Serial(port='/dev/ttyS5', baudrate=9600)
received = []
ser.write(b'beginn')
time.sleep(5)
ser.write(b'hello')
line = ser.readline()
print(line.decode())
-
Mr_Robot5000
- Posts: 2
- Joined: Mon Jan 11, 2021 3:43 pm
Serial Communication with GPIO troubles
Hello,
I am trying to control multiple servo motors using a Raspberry Pi 3 B and a pololu maestro servo controller.
This was the original guide I followed for starting my project https://rimstar.org/science_electronics … aestro.htm
I have tried using both the code provide there and another piece of code from here
https://github.com/FRC4564/Maestro
Both result in the following error when I run them:
Code: Select all
serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
I’m not too sure where to go from here and am looking for any help!
Thanks!
-
topguy
- Posts: 7312
- Joined: Tue Oct 09, 2012 11:46 am
- Location: Trondheim, Norway
Re: Serial Communication with GPIO troubles
Tue Jan 12, 2021 11:13 am
Useful information is: what is the name of the device/port you are trying to open ?
You can test serial ports with
( assuming /dev/serial0 is the port you are trying to use )
-
cleverca22
- Posts: 7007
- Joined: Sat Aug 18, 2012 2:33 pm
Re: Serial Communication with GPIO troubles
Tue Jan 12, 2021 11:20 am
topguy wrote: ↑
Tue Jan 12, 2021 11:13 am
( assuming /dev/serial0 is the port you are trying to use )
serial0 should always be the one on the gpio header, the firmware will rename things when switching between uart’s to keep that true
-
Mr_Robot5000
- Posts: 2
- Joined: Mon Jan 11, 2021 3:43 pm
Re: Serial Communication with GPIO troubles
Thu Jan 14, 2021 12:16 am
Ok, so I don’t know why this is but the example code was using /dev/ttyS0 as the serial port which was causing errors. Using /dev/serial0 instead works.
For reference, I was using GPIO Pins 14 and 15 as transmit and receive respectively.
(I also might have had the pins switched around, but all well)
-
cleverca22
- Posts: 7007
- Joined: Sat Aug 18, 2012 2:33 pm
Re: Serial Communication with GPIO troubles
Thu Jan 14, 2021 12:19 am
Mr_Robot5000 wrote: ↑
Thu Jan 14, 2021 12:16 am
Ok, so I don’t know why this is but the example code was using /dev/ttyS0 as the serial port which was causing errors. Using /dev/serial0 instead works.
For reference, I was using GPIO Pins 14 and 15 as transmit and receive respectively.(I also might have had the pins switched around, but all well)
https://www.raspberrypi.org/documentati … on/uart.md
by default, ttyAMA0 is routed to the bluetooth, and if you turn serial on, ttyS0 gets routed to the gpio header
but there are overlays to either disable bluetooth or swap the serial ports, then ttyAMA0 is on the gpio header
to make things simpler, the /dev/serial0 alias always points to the one on the gpio header, so you dont need to know how config.txt was setup, it will just work
Return to “Interfacing (DSI, CSI, I2C, etc.)”
Я пытался получить следующие две строки кода Python для работы в течение последних двух дней без особого успеха:
import serial
ser = serial.Serial(0)
Каждый раз, когда я запускаю его, я получаю следующую ошибку:
Traceback (most recent call last):
File "./test.py", line 4, in <module>
ser = serial.Serial(0)
File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 260, in __init__
self.open()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 280, in open
self._reconfigurePort()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 308, in _reconfigurePort
raise SerialException("Could not configure port: %s" % msg)
serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
Я запускаю Ubuntu 11.10 64-bit, с Pyserial 2.5 (python-serial 2.5-2.1) и Python 2.7 (python 2.7.2-7ubuntu2), и мой пользователь является членом группы dialout.
Я запускаю Ubuntu 11.10 на 64-битной работе, с теми же версиями Python и Pyserial, и проблема там не возникает. Любые предложения приветствуются — я довольно смущен…
Спасибо,
Donagh