Converting arduino serial readings into float or int on the raspberry pi with python3 - python-3.x

I have a serial connection between my raspberry pi and my arduino. I can send data from arduino to the pi but when I try to convert the receiving data into a int or a float I get an error message.
Let's say I try to send the number 35 to the pi, and try to convert it on the python side I get following message:
invalid literal for int() with base 10:''
and when I try to convert it to float I get the following message:
could not convert string to float.
I'm using Idle 3.5.3 on the raspberry pi. I tried many things I've seen in this forum: like strip() but nothing seems to work. What could be wrong?
Arduino Code:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(35);
delay(5000);
}
Python Code:
#!/usr/bin/env python3
import time
import serial
from array import array
import csv
arduino = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
arduino.flushInput()
print("test")
while 1:
incoming = arduino.readline().decode('ascii').strip()
float(incoming)
print(incoming)
I expected a cast to int or float but I get only error messages

I got it.
incoming = arduino.readline().decode('ascii')
if not incoming is "":
if int(incoming.strip()) == 1:
data.append(float(arduino.readline().decode('ascii').strip())/100)

Related

I'm trying to read sensor data through serial communication but when I try to read it just kept on runnin in python but it doesn't display any value

I have light detector sensors connected to a data acquisition box and it is connected to my laptop via RS232 usb cable. I have stabilized serial communication to that port in python. But when I try to read the data it just keeps on running and it doesn't display any value. I have tried this same think in MATALB and it works properly, so I know that port and sensors are working fine. I am just not able to read the data in python. I have three ways(shown below in python code) but nothing works. Please help me.
Here is my python code:
import serial
from serial import Serial
s = serial.Serial('COM3') # open serial port
print(ser.name)
# Set the serial port to desired COM
s = serial.Serial(port = 'COM3', bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, baudrate = 9600, stopbits = serial.STOPBITS_ONE)
# Read the data(method 1)
while 1:
while (s.inWaiting() > 0):
try:
inc = s.readline().strip()
print(inc)
# Read the data(method 2)
data = str(s.read(size = 1))
print(data)
# Read all the data(method 3)
while i <10:
b = s.readlines(100) # reading all the lines
in matlab it gave values with a space but in same line
That indicates there are no newline characters sent by the device.
I've never used your device or the Python serial module. But from the docs, this is what I would do:
from time import sleep
while s.is_open():
n = s.in_waiting()
if n == 0:
print "no data"
sleep(1)
continue
try:
inc = s.read(n)
print(inc)
catch serial.SerialException as oops:
print(oops)
catch serial.SerialTimeoutException as oops:
print(oops)
print("serial port closed")
This gives you feedback for each condition: port open/closed, data ready/not, and the data, if any. From there you can figure out what to do.
The documentation says inWaiting is deprecated, so I used in_waiting.
I wouldn't be surprised if the problem lies in configuring the serial port in the first place. Serial ports are tricky like that.

How to decode payload from modbus using NodeJS?

I have a schneider power meter with rs485 surport. I using python with pymodbus to read register and decode payload from it (success). But now I want to do this with NodeJS, I can get raw data but I dont know how to decode it, I tried some method but result wrong!
This my python code:
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
def validator(instance):
if not instance.isError():
'''.isError() implemented in pymodbus 1.4.0 and above.'''
decoder = BinaryPayloadDecoder.fromRegisters(
instance.registers,
byteorder=Endian.Big, wordorder=Endian.Little
)
return float(decoder.decode_32bit_float())
else:
# Error handling.
return None
validator([5658, 17242]) # Result is 218.1
When I use NodeJS it return buffer and i tried to decode with:
let buf = Buffer.from([0xd6, 0xd4, 0x42, 0x47]);
payload = buf.readFloatBE(0); // It return other float number not 218.1
Can everyone help me ! Thanks !

Storing Value in Arduino Sent From Python via Serial

I have been trying to send a value from a Python program via serial to an Arduino, but I have been unable to get the Arduino to store and echo back the value to Python. My code seems to match that I've found in examples online, but for whatever reason, it's not working.
I am using Python 3.5 on Windows 10 with an Arduino Uno. Any help would be appreciated.
Arduino code:
void readFromPython() {
if (Serial.available() > 0) {
incomingIntegrationTime = Serial.parseInt();
// Collect the incoming integer from PySerial
integration_time = incomingIntegrationTime;
Serial.print("X");
Serial.print("The integration time is now ");
// read the incoming integer from Python:
// Set the integration time to what you just collected IF it is not a zero
Serial.println(integration_time);
Serial.print("\n");
integration_time=min(incomingIntegrationTime,2147483648);
// Ensure the integration time isn't outside the range of integers
integration_time=max(incomingIntegrationTime, 1);
// Ensure the integration time isn't outside the range of integers
}
}
void loop() {
readFromPython();
// Check for incoming data from PySerial
delay(1);
// Pause the program for 1 millisecond
}
Python code:
(Note this is used with a PyQt button, but any value could be typed in instead of self.IntegrationTimeInputTextbox.text() and the value is still not receieved and echoed back by Arduino).
def SetIntegrationTime(self):
def main():
# global startMarker, endMarker
#This sets the com port in PySerial to the port with the Genuino as the variable arduino_ports
arduino_ports = [
p.device
for p in serial.tools.list_ports.comports()
if 'Genuino' in p.description
]
#Set the proper baud rate for your spectrometer
baud = 115200
#This prints out the port that was found with the Genuino on it
ports = list(serial.tools.list_ports.comports())
for p in ports:
print ('Device is connected to: ', p)
# --------------------------- Error Handling ---------------------------
#Tell the user if no Genuino was found
if not arduino_ports:
raise IOError("No Arduino found")
#Tell the user if multiple Genuinos were found
if len(arduino_ports) > 1:
warnings.warn('Multiple Arduinos found - using the first')
# ---------------------------- Error Handling ---------------------------
#=====================================
spectrometer = serial.Serial(arduino_ports[0], baud)
integrationTimeSend = self.IntegrationTimeInputTextbox.text()
print("test value is", integrationTimeSend.encode())
spectrometer.write(integrationTimeSend.encode())
for i in range(10): #Repeat the following 10 times
startMarker = "X"
xDecoded = "qq"
xEncoded = "qq"
while xDecoded != startMarker: #Wait for the start marker (X))
xEncoded = spectrometer.read() #Read the spectrometer until 'startMarker' is found so the right amound of data is read every time
xDecoded = xEncoded.decode("UTF-8");
print(xDecoded);
line = spectrometer.readline()
lineDecoded = line.decode("UTF-8")
print(lineDecoded)
#=====================================
spectrometer.close()
#===========================================
#WaitForArduinoData()
main()
First, this is a problem:
incomingValue = Serial.read();
Because read() returns the first byte of incoming serial data reference. On the Arduino the int is a signed 16-bit integer, so reading only one byte of it with a Serial.read() is going to give you unintended results.
Also, don't put writes in between checking if data is available and actual reading:
if (Serial.available() > 0) {
Serial.print("X"); // Print your startmarker
Serial.print("The value is now ");
incomingValue = Serial.read(); // Collect the incoming value from
That is bad. Instead do your read immediately as this example shows:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
That's two big issues there. Take care of those and let's take a look at it after those fundamental issues are corrected.
PART 2
Once those are corrected, the next thing to do is determine which side of the serial communication is faulty. Generally what I like to do is determine one side is sending properly by having its output show up in a terminal emulator. I like TeraTerm for this.
Set your python code to send only and see if your sent values show up properly in a terminal emulator. Once that is working and you have confidence in it, you can attend to the Arduino side.

Serial communications between PySerial and VEX EDR Cortex

I have been struggling with this for the last 24 hours, I am trying to get PySerial to talk to a VEX Cortex over bluetooth using UART / HC-05. I guess this would be very similar to communicating with a Arduino.
The devices are connected together and data is flowing but its junk
In RobotC:(as you can see no encoding is apparent, i believe its just going over as bytes)
#include "BNSlib_HC05.h"
task main()
{
setBaudRate(UART1, baudRate19200);
bnsATGetBaudrate(UART1)
char stringBuffer[100];;
while(1==1)
{
bnsSerialRead(UART1, stringBuffer, 100, 100);
writeDebugStreamLine(stringBuffer);
delay(500);
bnsSerialSend(UART1, (char*)&"simon");
}
}
In python PySerial
import serial
import time
import struct
ser = serial.Serial(port='COM8', baudrate=19200)
print("connected to: " + ser.portstr)
message = "Simon"
while True:
ser.write(message.encode()) # I guess this is encoding via utf8?
#for b in bytearray("simon was here","UTF-8"):
#ser.write(b)
print("sent")
time.sleep (100.0 / 1000.0);
result = ser.read(25) # tried readline, just hangs
print(">> " + result.decode('cp1252')) # tried utf8, ascii
ser.close()
print("close")
In robotC I get back f˜fžþžøž
In Python I am getting back ýýýýýýýýýýýýýýýýýýýýýýýýý
It turned out the HC-05 module was not configured correctly :(

How do I get a list of my device's audio sample rates using PyAudio or PortAudio?

I'd like to query my audio device and get all its available sample rates. I'm using PyAudio 0.2, which runs on top of PortAudio v19, on an Ubuntu machine with Python 2.6.
In the pyaudio distribution, test/system_info.py shows how to determine supported sample rates for devices. See the section that starts at line 49.
In short, you use the PyAudio.is_format_supported method, e.g.
devinfo = p.get_device_info_by_index(1) # Or whatever device you care about.
if p.is_format_supported(44100.0, # Sample rate
input_device=devinfo['index'],
input_channels=devinfo['maxInputChannels'],
input_format=pyaudio.paInt16):
print 'Yay!'
With the sounddevice module, you can do it like that:
import sounddevice as sd
samplerates = 32000, 44100, 48000, 96000, 128000
device = 0
supported_samplerates = []
for fs in samplerates:
try:
sd.check_output_settings(device=device, samplerate=fs)
except Exception as e:
print(fs, e)
else:
supported_samplerates.append(fs)
print(supported_samplerates)
When I tried this, I got:
32000 Invalid sample rate
128000 Invalid sample rate
[44100, 48000, 96000]
You can also check if a certain number of channels or a certain data type is supported.
For more details, check the documentation: check_output_settings().
You can of course also check if a device is a supported input device with check_input_settings().
If you don't know the device ID, have a look at query_devices().
I don't think that's still relevant, but this also works with Python 2.6, you just have to remove the parentheses from the print statements and replace except Exception as e: with except Exception, e:.
Directly using Portaudio you can run the command below:
for (int i = 0, end = Pa_GetDeviceCount(); i != end; ++i) {
PaDeviceInfo const* info = Pa_GetDeviceInfo(i);
if (!info) continue;
printf("%d: %s\n", i, info->name);
}
Thanks to another thread

Resources