Home > Net >  Data conversion in flutter
Data conversion in flutter

Time:06-10

I'm currently playing around with BLE and Flutter trying to learn how it all works. I have an esp32 mcu that is sending a temperature value via ble. While there doesn't seem to be any conversion of the float temperature value in the esp code, when it is received on the flutter app, it's in uint8 (or possibly uint32). How would i go about converting that back into a double in Flutter? An example is 23.9 is converted to 1103049523. Below are some code snippets i believe are relevant.

ESP32 code

 float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();


  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }



  Serial.print(F("Humidity: "));
  Serial.println(h);
  Serial.print(F("Temperature: "));
  Serial.println(t);



  pCharacteristic->setValue(t);
    
  pCharacteristic->notify();
  }

From the flutter code:

 final stream = bleManager.subscribeToCharacteristic(characteristic!);
    await for (final data in stream) {
      var dataInt = ByteData.view(Uint8List.fromList(data).buffer)
          .getUint32(0, Endian.little);
      print("GOT DATA: $dataInt");
      setState(() {
        lastRead = dataInt;
        temp = lastRead.toDouble();
      });
    }

As you can see i tried converting the "lastRead" to a double but that didn't work as i suspect there's more to it.

CodePudding user response:

You seem to be explicitly interpreting your data as a 32-bit integer by calling getUint32() on it. How about trying getFloat32() instead?

CodePudding user response:

Most of the time you could get away with a uint16 and still get two digits behind the . Ex: Multiply the temp by 100 and round to whole number. (Uint16 temp = float*100. -4000 to 12000 (-40.00 degrees celcius to 120.00 would be sufficient for most situations) Move the value up with 4000 because of the minus / unsigned int.

Then make two bytes out of it. Most significant byte msb = temp&0xFF00 >> 8 and lsb (least) = temp&00FF

Send the two bytes. At the receiver side add them together temp(uint16) = msb << 8 | lsb float = ((float)temp - 4000) / 100.00

(If you really want to stick to the uint32 and double/float, you could also use a union to practically convert the value)

  • Related