Converting float to bytes



  • Hello - I'm trying to convert an ambient sensor readout into bytes so I can squeeze it down the LoRa tube! I can't seem to get the float.hex() attribute to work, I get this back: AttributeError: type object 'float' has no attribute 'hex'.

    The Python3 docs say that float.hex() is a built in type, am I missing something here?

    I tried the following:

    temp = float.hex(sensordata)
    temp = sensordata.hex()
    

    Both return the same attribute error. Where am I going wrong? Is there a module I need to include? Here is the main module from my project:

    import bme680
    from bme680.i2c import I2CAdapter
    from machine import Pin
    import time
    import struct
    
    # Config pin:
    configPin = Pin('P21', Pin.IN, Pin.PULL_UP)
    
    # Setup I2C and BME680: P9/G16=SDA, P10/G17=SCL
    i2c_dev = I2CAdapter(1, pins=('P9','P10'), baudrate=100000)
    sensor = bme680.BME680(i2c_device=i2c_dev)
    
    # These oversampling settings can be tweaked to
    # change the balance between accuracy and noise in
    # the data.
    sensor.set_humidity_oversample(bme680.OS_2X)
    sensor.set_pressure_oversample(bme680.OS_4X)
    sensor.set_temperature_oversample(bme680.OS_8X)
    sensor.set_filter(bme680.FILTER_SIZE_3)
    
    config = configPin()
    
    if config:
        while True:
            if sensor.get_sensor_data():
    
                output = "{} C, {} hPa, {} RH, {} RES,".format(
                    sensor.data.temperature,
                    sensor.data.pressure,
                    sensor.data.humidity,
                    sensor.data.gas_resistance)
    
                print(output)
    
                temp = float.hex(sensor.data.temperature)
    
                print(temp)
    
                time.sleep(5)
    


  • @aidanrtaylor Yes, you need pack() to make a bytes string out of a float, and unpack() will convert that back.
    unpack() returns a tuple, wheras pack() in addition to a tuple accepts a single value.



  • isn't unpack the opposite of what I want? I thought I would need pack

    Oh, I see you are showing me how to do both ;)



  • @robert-hh beat me to it ;-)

    struct.unpack('f',binascii.unhexlify(binascii.hexlify(struct.pack('f',1.234))))

    and using 'e' instead of 'f' for the format will mean the float uses 4 bytes in hex form. at the loss of precision but doubt you need that much for temp ;-)



  • thanks, trying it out now (I already had stuct imported as you can see above :P)



  • @aidanrtaylor use struct.pack() instead.


 

Pycom on Twitter