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')
Related
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
I was trying to read data from smart power meter using ttl rs485 converter and ft232 serial converter connected to PC. I've tried to read the data from serial port using the Pyserial python module and used the code below but the only output I've got was ("b, "b, ",b), I was wondering if there is any mistake in my code!
Thanks.
The code I used
import serial
ser = serial.Serial(
port= 'COM5',
baudrate= 9600,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout= 2
)
print("connected to: " + ser.portstr, "Please wait" )
print('COM5 is now Open!')
ser.flushInput()
ser.flushOutput()
while True:
data = ser.readline()
print(data)
The output I got
connected to: COM5 Please wait
COM5 is now Open!
b''
b''
b''
b''
b''
So this is the script I am using to send each 2 seconds for four time the Time in microsecond to the microcontroller stm32f4 but unfoturnately it only sends some numbers(from 1-->4) which are not the same as when I do a print,it is like random numbers .
import time
import serial from datetime
import datetime from time
import gmtime, strftime
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.writeTimeout = 0
ser.isOpen()
TM1 = int(round(time.time()*1000000))
ser.write(str(TM1).encode())
#ser.write( str(TM1)+" \r\n")
time.sleep(2)
TM2 = int(round(time.time()*1000000))
ser.write(str(TM2)+" \r\n")
time.sleep(2)
TM3 = int(round(time.time()*1000000))
ser.write(str(TM3)+" \r\n")
time.sleep(2)
TM4 = int(round(time.time()*1000000))
ser.write(str(TM4)+" \r\n")
I cannot see anything obviously wrong at first sight. I have a almost identical snippet of code running here that works. My guess would be that the settings of the serial port do not match. Double check that the baudrate, parity and stopbit settings match.
Second guess would be a mess-up with encodings. Have you set your default encoding in python to utf-8? If so you could try
ser.write(str(TM1).encode('ascii'))
Posting the output you get would help as well.
Edit: to avoid the microcontroller skipping some characters. You could use a small function like this. (I used that to send commands to a sensor that had the same issues. When I sent a command like this `ser.write("start logging") it would receive something like "sart lgging".
def write_safe(cmd):
for x in cmd:
ser.write(x)
sleep(0.05)
ser.write('\r\n')
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)
I have two Xbee Pro 900's, each attached to a Raspberry Pi. Both are updated to version 1061 and are set to API Enable with escapes. They also have the same Modem VID of 7FFF. Both Pi's have PySerial and the python-xbee library installed.
Xbee 1(Receiver) has a serial number of 0013A200409A1BB8
Xbee 2(Sender) has a serial number of 0013A200709A1BE9
I've included my code below, which is just sample code I've found online. My issue is that I'm not receiving anything on the appropriate Xbee. I have absolutely no idea what is wrong, I've triple checked the destination address, and both of the Xbee's configuration settings.
Xbee 2 Code(Sender):
#! /usr/bin/python
import time
from xbee import XBee
import serial
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = XBee(ser,escaped=True)
import pprint
pprint.pprint(xbee.api_commands)
DEST_ADDR_LONG = "\x00\x13\xA2\x00\x40\x9A\x1B\xB8"
# Continuously read and print packets
while True:
try:
print "send data"
xbee.tx_long_addr(frame='0x1', dest_addr=DEST_ADDR_LONG, data='AB')
time.sleep(1)
except KeyboardInterrupt:
break
ser.close()
Xbee 1 Code(Receiver):
#! /usr/bin/python
from xbee import XBee
import serial
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = XBee(ser,escaped=True)
# Continuously read and print packets
while True:
try:
print "waiting"
response = xbee.wait_read_frame()
print response
except KeyboardInterrupt:
break
ser.close()
When both programs are running, the Tx light on the sending Xbee blinks, but I receive nothing on the receiving Xbee. Is there something I'm missing? Thanks for your time!
Are you using XBee or XBeePro? I had the same problem and this post helped me a lot.
Try to modify the Receiver Code the following way:
import config
import serial
import time
from xbee import ZigBee
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
hv = '0x' + hv
lst.append(hv)
def decodeReceivedFrame(data):
source_addr_long = toHex(data['source_addr_long'])
source_addr = toHex(data['source_addr'])
id = data['id']
samples = data['samples']
options = toHex(data['options'])
return [source_addr_long, source_addr, id, samples]
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
zb = ZigBee(ser, escaped = True)
while True:
try:
data = zb.wait_read_frame()
decodedData = decodeReceivedFrame(data)
print decodedData
except KeyboardInterrupt:
break
In my case the code above outputs the following:
[['0x00', '0x13', '0xa2', '0x00', '0x40', '0x9b', '0xaf', '0x4e'], ['0x68', '0x3f'], 'rx_io_data_long_addr', [{'adc-0': 524}]]
Here I shared configuration settings for Controller Node (compatible with X-CTU)
Are you sure the XBee modules are in escaped API mode (ATAP=2)? And 9600 baud?
Can you enable a mode in python-xbee to dump all characters in and out?
Have you confirmed the serial wiring is correct? (I see you're using USB, so that's not an issue.)
If you don't have hardware flow control hooked up, make sure the XBee modules have ATD6=0 and ATD7=0 set (disable RTS and CTS) and that python-xbee isn't expecting handshaking.
If you do have hardware flow control configured on the XBee, make sure you've told python-xbee to use it.
Can you use minicom or another serial terminal on the RaspPi to confirm that serial is working? Use minicom on the receiving end to see if you're getting anything at all?
Can you try sending and receiving with the radios connected to a PC instead of the Pi? Sending from the PC to the Pi, or vice-versa?