2
votes

I need some help in retaining an integer datatype through serial communication. My setup right now is an Arduino microcontroller reading a temperature sensor which is outputting a float number through an XBee module via the serial port that looks like this: 76.82 for example.

The XBee receiver is hooked up to my computer in which a Python program reads using the readline() method from the serial module. However, when I do readline(), I receive b'76.66\r\n'. How do I remove all the characters and just keep the numbers in its original datatype?

Here is my Python code:

import serial

ser = serial.Serial(6)

while True:
    x = ser.readline();
    print(x)

Here is my code for the Arduino:

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 3

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

DeviceAddress Thermometer = { 0x28, 0x36, 0x0F, 0xB0, 0x02, 0x00, 0x00, 0xF0 };

void setup(void)
{
    Serial.begin(9600);

    sensors.begin();
    sensors.setResolution(Thermometer, 12);
}

void printTemperature(DeviceAddress deviceAddress)
{
    float tempC = sensors.getTempC(deviceAddress);
    Serial.println(DallasTemperature::toFahrenheit(tempC));
}

void loop(void)
{
    delay(5000);
    sensors.requestTemperatures();

    printTemperature(Thermometer);
}
2

2 Answers

4
votes

Are you looking for this?

>>> a = b'76.66\r\n'
>>> float(a)
76.66

EDIT: If by "retain the original datatype" you mean "keeping it as a string":

>>> a.strip()
'76.66'
3
votes

To convert to a float:

float(b'76.66\r\n')

To round that down to an int:

math.floor(float(b'76.66\r\n'))