1

I'm trying to send a float from arduino, and read it with python using serial.

I'm generating numbers on the arduino with the following code:

This is the arduino code, it works

long randNumber;
float avgMe;
float theTemp;

void setup() {
  Serial.begin(9600); // initialize print
  Serial.println("Start session");
}

void loop() {
  avgMe = 0;
  for (int i = 0; i < 10; i++) {
    randNumber = random(0, 11);
    delay(100);
    avgMe = avgMe + randNumber;
  }
  theTemp = avgMe / 10;
  Serial.print(theTemp);

}

It prints what i want to grab in python:

Start session
4.90
6.80
3.90
5.70
6.10

This is what i trid in python to grab it:

# %% Import
import serial
import time
import struct

# %% connect
try:
    ser = serial.Serial('COM3', 115200, timeout=.1)
    time.sleep(2)
    print("Connection to " + 'port' + " established succesfully!\n")
except Exception as e:
    print(e)

# %% loop for some time
t_end = time.time() + 10
while time.time() < t_end:
    data = ser.read(4)
    if data:
        # test = struct.unpack(">fff",data)
        print(data)

time.sleep(1)
ser.close()

Python prints:

b'\x00\x00\x00\x00'
b'\x00'
b'\x00\x00\x00\x00'
b'\x00\x00\x00\x00'
b'\x00\x00\x00\x00'
b'\x00\x00\x00\x00'
b'\x00'

But firstly i can't convert that, also it doesn't seem like the information is there. I would love your input on this

2
  • Your Refresh rates are different. the Arduino is sending data at 9600 while python is collecting at 115200. They need to be the same for data transfer to work correctly. Commented Mar 27, 2019 at 9:30
  • 1
    You are absolutely right. Thank you! It worked. Please answer so i can upvote you Commented Mar 27, 2019 at 9:35

1 Answer 1

1

Same problem I had when I was first learning how to send data over a serial port from an arduino. The baud rates have to be the same or the outputs will turn out weird and wonderful.

If the arduino is using this baud rate

Serial.begin(9600); // initialize print

then python needs the same baud rate

ser = serial.Serial('COM3', 9600, timeout=.1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.