Why decode("utf-8") not working in serial? - python

using serial, am trying to send a number then reading it on the other side....error:
Traceback (most recent call last):
File "C:\Users\desk\Downloads\serialTestPy_processing3.py", line 8, in <module>
serPrint = serPrint.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x98 in position 0: invalid start byte
sending code:
import serial
from time import sleep
ser7 = serial.Serial('COM7',19600)
while True:
ser7.write(str.encode('80'))
sleep(1)
Receiving code:
import serial
from time import sleep
ser8 = serial.Serial('COM8',19600)
while True:
serPrint = ser8.read()
serPrint = serPrint.decode("utf-8")
print(serPrint)

friend!
I have tested this and worked for me,
Sending Part:
import serial
import time
ser7 = serial.Serial('COM7',19600) while True:
ser7.write('80')
time.sleep(1)
Receiving Part:
import serial
from time import sleep
ser8 = serial.Serial('COM8',19600)
while True:
serPrint = ser8.read()
serPrint = serPrint.decode('utf-8')
print(serPrint)

Related

Modbus RTU master - python script with minimalmodbus

I would like to control an actuator with a python script in MODBUS RTU
master. I tried to use the library minimalmodbus to communicate (write
bit, write & read registers) with my slave.
When I start my code, I have some errors. So, someone can I help me to find a solution?
My code:
import minimalmodbus
import os
import struct
import sys
import serial
import time
instrument = minimalmodbus.Instrument('/dev/ttyRS485', 1)
instrument.serial.port
instrument.serial.baudrate = 9600
instrument.serial.parity = serial.PARITY_NONE
instrument.serial.bytesize = 8
instrument.serial.stopbits = 1
instrument.mode = minimalmodbus.MODE_RTU
instrument.serial.timeout = 0.05
modbus = instrument.write_bit(0x0427, 1)
print (modbus)
alarme = instrument.write_bit(0x0404, 1)
print (alarme)
alarme = instrument.write_bit(0x0404, 0)
print (alarme)
on = instrument.write_bit(0x0403, 1)
print (on)
home = instrument.write_bit(0x040B, 1)
print (home)
position = instrument.write_register(0x9900, 0, number_of_decimals=2,functioncode=16, signed=False)
print (position)
posi = instrument.write_register(0x9901, 6000, number_of_decimals=2,functioncode=16, signed=False)
print (posi)
Errors:
========================= RESTART: /home/pi/test.py =========================
None
None
None
None
None
None
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py", line 2448, in _pack
result = struct.pack(formatstring, value)
struct.error: 'H' format requires 0 <= number <= 65535
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/test.py", line 36, in <module>
posi = instrument.write_register(0x9901, 6000, number_of_decimals=2, functioncode=16, signed=False)
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py",line 518, in write_register
payloadformat=_PAYLOADFORMAT_REGISTER,
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py",line 1166, in _generic_command
payloadformat,
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py",line 1514, in _create_payload
value, number_of_decimals, signed=signed
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py", line 1991, in
_num_to_twobyte_string outstring = _pack(formatcode, integer)
File "/home/pi/.local/lib/python3.5/site-packages/minimalmodbus.py", line 2454, in _pack
raise ValueError(errortext.format(value, formatstring))
ValueError: The value to send is probably out of range, as the num-to-bytestring conversion failed.
Value: 600000 Struct format code is: >H
In response to your request in the comments for an alternative library, here is what I use to read modbus with the pymodbus library:
import pymodbus
from pymodbus.pdu import ModbusRequest
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer
client = ModbusClient(
method = 'rtu'
,port='/dev/tty.usbserial-AQ00BYCR'
,baudrate=38400
,parity = 'O'
,timeout=1
)
connection = client.connect()
registers = client.read_holding_registers(0,100,unit=1)# start_address, count, slave_id
print (registers.registers)
Note that in the above, the reading begins from address 0 and continues to address 100, for slave_id 1.
To write registers, do the following:
write = client.write_register(1,425,unit=1)# address = 1, value to set = 425, slave ID = 1

Error when try send a file using paho.mqtt.python

I'm using paho.mqtt.python in python 2.7 and when I try to send a file (image), I see the next error:
Traceback (most recent call last):
File "/home/pi/Desktop/Device1/Scripts/mqtt_publish.py", line 39, in
mqttc.publish(MQTT_TOPIC,byteArr,0,True)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 980, in publish
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False, info)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1988, in _send_publish
upayload = payload.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
The publish script is the next:
# Import package
import paho.mqtt.client as mqtt
# Define Variables
MQTT_HOST = "192.168.1.39" #iot.eclipse.org
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "Device1"
#MQTT_MSG = 25
def on_connect(mqttc, userdata, flags, rc):
#Subscribe to a Topic
mqttc.subscribe(MQTT_TOPIC, 0)
print("Connection returned result: "+connack_string(rc))
# Define on_publish event function
def on_publish(mqttc, userdata, mid):
print "Message Published..."
print("mid: " +str(mid))
mqttc.disconect()
# Initiate MQTT Client
mqttc = mqtt.Client(client_id="LCESS", clean_session=False)
# Register publish callback function
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
# Connect with MQTT Broker
# probar mqttc.username_pw_set(username, password)
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
# Publish message to MQTT Broker
f= open("/home/pi/Desktop/images/image.jpg")
filecontent = f.read()
byteArr = bytes(filecontent)
mqttc.publish(MQTT_TOPIC,byteArr,0,True)
The solution is the following:
replace:
byteArr = bytes(filecontent)
to
byteArr = bytearray(filecontent)
and replace:
connack_string(rc)
to
mqtt.connack_string(rc)
Because I've imported the module: import paho.mqtt.client as mqtt
Error using: bytes(filecontent).decode()
Traceback (most recent call last):
File "/home/pi/Desktop/Device1/Scripts/mqtt_publish.py", line 37, in <module>
byteArr = bytes(filecontent).decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

Read the serial port

I dont seem to get the proper reading Id like from my serial.write/read. What do I do wrong?
After one turn in the loop, I would like to have another A00 output, but instead I get D13HIGH, as you can see below.
import serial
from time import sleep
import math
port = '/dev/ttyAMA0'
baud = 9600
ser = serial.Serial(port=port, baudrate=baud)
sleep(0.2)
count = 0
while count < 20:
ser.write('a--A00READ--')
sleep(0.2)
reply = ser.read(12)
print(reply)
adc = reply[7:]
adc = adc.strip('-')
adc = int(adc)
volts = (adc / 1023.0 * 5.0)
ser.write('a--D13HIGH--')
count += 1
ser.close()
Output:
>>>
a--A00+487--
a--D13HIGH--
Traceback (most recent call last):
File "/home/pi/serialcom.py", line 21, in <module>
adc = int(adc)
ValueError: invalid literal for int() with base 10: 'IGH'
>>>

'utf-8' codec can't decode byte 0xc4 in position 6: unexpected end of data

I'm coding with Python on Raspberry pi 2.
I'm trying to send several orders to two devices by bluetooth at the same time but it doesn't work.
According to the error message, when I send an order to the second device, I can't decode the response. I already tried to encode with 'UTF-8' but it didn't work either...
Here is the error message:
Traceback (most recent call last):
File "/home/pi/Desktop/Bluetooth-master/Bluetooth-master/rfcommcli.py", line 60, in <module>
StartBTClient()
File "/home/pi/Desktop/Bluetooth-master/Bluetooth-master/rfcommcli.py", line 54, in StartBTClient
print('reception 2 : ', rec2.decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 6: unexpected end of data
So can you help me, please.
Here is the code :
import bluetooth
class BT(object):
address_2 = ('00:04:3E:93:39:A9')
address_1 = ('00:04:3E:6A:10:A9')
def __init__(self):
self.btSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
def __exit__(self):
self.Disconnect()
def Connect(self, mac, port=1):
self.btSocket.connect((mac, port))
print('Connecter')
def Disconnect(self):
try:
self.btSocket.close()
except Exception:
pass
def Send(self, data):
self.btSocket.send(data.encode())
def Receive(self, size=1024):
return self.btSocket.recv(size)
def StartBTClient():
cli = BT()
print('BT1 Connexion en cours ...')
#cli.Discover()
cli.Connect(cli.address_1, 0o01)
cli2 = BT()
print('BT2 Connexion en cours ...')
#cli.Discover()
cli2.Connect(cli2.address_2, 0o02)
print('Donner un ordre ... (ordre shutter)')
while True:
data = input()
if (data == 'exit'):
break
cli.Send("read\r")
cli2.Send("read\r")
rec = cli.Receive()
rec2 = cli2.Receive()
print('reception 1 : ', rec.decode())
print('reception 2 : ', rec2.decode())
cli.Disconnect()
cli2.Disconnect()
if __name__ == '__main__':
StartBTClient()
Apparently device #2 is responding with some, but not all, of the bytes of a UTF-8 encoded value.
You need to ensure that you have received and assembled all of the bytes of the message before you attempt to decode them. This may involve calling .recv() multiple times.

How to read a string of integers received on python from serial arduino

I'm sending a list of values (e.g. 80,539,345,677) from Arduino to a Python app running on my RPi. I have not been successful in extracting the values and assigning them to respective variables or objects in the app.
Here's my code:
def read_values():
#if DEBUG:
print "reading arduino data"
ser = serial.Serial('/dev/ttyUSB0', 9600)
print "receiving arduino data"
ser_line = ser.readline()
print ser_line
ser.close()
ser_list = [int(x) for x in ser_line.split(',')]
ambientLight = ser_list[1]
print ambientLight
return ambientLight
What I'm getting from Python is:
reading arduino data
receiving arduino data
80,477,82,2
Traceback (most recent call last):
File "serialXivelyTest4c.py", line 77, in <module>
run()
File "serialXivelyTest4c.py", line 63, in run
ambientLight = read_values()
File "serialXivelyTest4c.py", line 27, in read_values
ser_list = [int(x) for x in ser_line.split(',')]
ValueError: invalid literal for int() with base 10: '8254\r80'
You can see that I'm getting values, but that they're being truncated. Can anyone please tell me where I'm going wrong here. Thanks so much.
I've never used an Arduino but here's how I read from serial with a different board. I used serial.
import streamUtils as su # see below
ser = su.connectPort("/dev/tty.SLAB_USBtoUART") # make sure you have the right port name
data = ""
while True:
try:
data = data + ser.read(1) # read one, blocking
time.sleep(1) # give it time to put more in waiting
n = ser.inWaiting() # look if there is more
if n:
data = data + ser.read(n) # get as much as possible
# I needed to save the data until I had complete
# output.
if data:
# make sure you have the whole line and format
else:
break
except serial.SerialException:
sys.stderr.write("Waiting for %s to be available" % (ser.name))
sys.exit(1)
sys.stderr.write("Closing port\n")
ser.close()
Here's the streamUtils.connectPort():
import serial
def connectPort(portname):
# connect to serial port
ser = serial.Serial()
ser.port = portname
ser.baudrate = 9600
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.bytesize = serial.EIGHTBITS
ser.timeout = 15 # need some value for timeout so the read will end
try:
ser.open()
except serial.SerialException:
sys.stderr.write("Could not open serial port %s\n" % (ser.name))
sys.exit(1)
return (ser)

Categories

Resources