Serial Communication Raspberry Pi to PC - python

I am trying to connect a raspberry pi to a pc over the serial connection. The goal is to send data from sensors over the serial connection so that I can check its working.
Link to the serial connector.
Link to the USB adapter
Currently I can SSH and Use the Serial Connection with putty. I have been using the following guide to help me get some basic test code written to make sure everything works.
Link to guide
I am trying to run the Serial_Write script. I have made sure I have the Py Serial library installed - and serial is enabled since I can connect over putty.
#!/usr/bin/env python
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0
while 1:
ser.write('Write counter: %d \n'%(counter))
time.sleep(1)
counter += 1
Once I try to run the code I get the following error.
Traceback (most recent call last):
File "Serial_Write.py", line 14, in <module>
ser.write('Write counter: %d \n'%(counter))
File "/home/pi/.local/lib/python3.7/site-packages/serial/serialposix.py", line 532, in write
d = to_bytes(data)
File "/home/pi/.local/lib/python3.7/site-packages/serial/serialutil.py", line 63, in to_bytes
raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: 'Write counter: 0 \n'

Wasn't encoding correctly. I was thinking of Java Bytes, but in python Bytes are just B
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0
while True:
ser.write(b'Write counter: %d \n'%(counter)) #encode to bytes
print("Testing")
time.sleep(1)
counter += 1

Related

Interfacing Nextion with Raspberry Pi 3b+

I am having trouble interfacing my Nextion display via Raspberry Pi. I have a Nextion project that contains one text field called t0. And I want to change the text displayed from Raspberry.
Here is what I tried:
import serial
import time
import struct
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate =9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
k=struct.pack('B', 0xff)
time.sleep(1)
command = 't0.txt=\"hello\"'
ser.write(command.encode())
ser.write(k)
ser.write(k)
ser.write(k)
I am certain that connections are OK hence it is not hardware related.
Thank you for support.
Instead of this:
command = 't0.txt=\"hello\"'
I changed the command line to this:
command = 't0.txt="hello"'
Works for me good luck.

Serial missing data in RPI3 using Python

I'm using raspberry pi 3 and this code to send a request to a device and receive the response from.
#!/usr/bin/python3.7
import socket # Import socket module
import thread
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
while True:
output += ser.read(1)
#time.sleep(0.1)
print "Reading... "+output.encode('hex')
It handles the response but there are missing bytes, it should receive a 56 bytes length string instead of 53.
This is the output:
a5030119010000010001000a20120118180130090100020505030117501701051421000301040120010516039833630004060104c200007d
There are 3 missing bytes
The serial configuration is what the manufacturer says in the documentation.
This device works well with my other application made in Delphi.
EXTRA
This is a comparison from my delphi app and this py script:
Delphi app
A5030119010000010001000A20120118180130090100020505030117501701051421000301040120010516039833630004060104C200007D
Python script
a503011901000001000100 1201181801300901000205050301175017010514210003010401 010516039833630004060104c200007d
The solution was to set the max byte to the serial.read() method
This should be related to the device work behavior
#!/usr/bin/python3.7
#sudo python /home/testing.py
import serial
import time
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=5
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
time.sleep(1)
while ser.inWaiting() > 0:
output += ser.read(10) #setting it to 10 will fix this problem
print "Reading... "+output.encode('hex')

Issue with python serial: ValueError: Attempting to use a port that is not open

I am trying to get the data from a blood pressure monitor using the python in raspberry pi3. I googled and found a few examples to get the data using python.
My code:
#!/usr/bin/python
import serial
neo = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=0
)
print("connected to: " + neo.portstr)
#neo.open() #opens port
print "Is port open ? ",neo.isOpen() #returns true?
#ser.write("help\n");
while True:
dataline = neo.readline();
if dataline:
print(dataline), neo.close()
When I ran above code using "sudo python pyusb.py" command, it is returning the following error:
connected to: /dev/ttyUSB0
Is port open ? True
None
Traceback (most recent call last):
File "pyusb.py", line 18, in <module>
dataline = neo.readline();
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 443, in read
if not self._isOpen: raise portNotOpenError
ValueError: Attempting to use a port that is not open
If un-commented the line "neo.open()" it is throwing another error:
connected to: /dev/ttyUSB0
Traceback (most recent call last):
File "pyusb.py", line 13, in <module>
neo.open() #opens port
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 271, in open
raise SerialException("Port is already open.")
serial.serialutil.SerialException: Port is already open.
I have looked at the similar issue here. But there is a issue with overriding of "serial.Serial()" method. I am unable to identify exactly what is the wrong with code above. Can anyone help me with, what I am doing wrong there?
If you have a look at the docs for pyserial, http://pyserial.readthedocs.io/en/latest/shortintro.html#readline it says you must specify a timeout when using readline(). This is because readline() waits for a EOL character at the end of each transmission. Try increasing the timeout to 1 using something like this:
import serial
neo = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print("connected to: " + neo.portstr)
while True:
dataline = neo.readline();
print dataline

How to read and write from a COM Port using PySerial?

I have Python 3.6.1 and PySerial Installed. I am trying the
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
Code:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
I see from the PySerial Documentation that the way to open a COM Port is as below:
import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windows and I get an error for the following line:
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
This could be what you want. I'll have a look at the docs on writing.
In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
On Windows, you need to install pyserial by running
pip install pyserial
then your code would be
import serial
import time
serialPort = serial.Serial(
port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass
to write data to the port use the following method
serialPort.write(b"Hi How are you \r\n")
note:b"" indicate that you are sending bytes

Serial Reading with Python

I have a rectifier outputting voltage and amperage information every 3 seconds. I installed python 2.7 and pySerial without a hitch. I am trying to get the following code to read data being sent at baud 2400, 7 data bits, even parity, and one stop bit. Other RS232 programs get it without a hitch. When I start the program from cmd I get a blinking underscore. What am I doing wrong?
import time
import serial
ser = serial.Serial(
port='COM3',
baudrate=2400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
while True:
message = ser.readline()
print(message)
time.sleep(3)

Categories

Resources