Code messes with voltage reading transmitted over HC-12

This is this code of the Arduino connected to my PC. It acts as the receiver and plots the received data to the Serial plotter.

#include <SoftwareSerial.h>

SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin

void setup() {
  Serial.begin(9600); // Serial port to computer
  HC12.begin(9600);   // Serial port to HC12
}

void loop() {
  delay(1000);
  HC12.write('B');
  while (HC12.available()) {
    byte bytes[sizeof(float)];
    HC12.readBytes(bytes, sizeof(float)); // Read bytes into an array
    float voltage;
    memcpy(&voltage, bytes, sizeof(float)); // Convert bytes back to float
    Serial.println(voltage); // Print the received float
  }
}

This is the code of the Transmitter. It is running off a 4 volt battery through a step up converter, with A1 connected directly to the positive terminal of the battery.

#include <SoftwareSerial.h>

SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin

void setup() {
  HC12.begin(9600); // Serial port to HC12
}

void loop() {
  while (HC12.available()) {
    if (HC12.read() == 'B') {
      int sensor = analogRead(A1);
      float voltage = sensor / 1024.0;
      byte bytes[sizeof(float)];
      memcpy(bytes, &voltage, sizeof(float));
      HC12.write(bytes, sizeof(float)); // Send the float as bytes
    }
  }
}

The receiver, which is connected to my PC only ever reads 0.80 volts, occasionaly 0.79 volts. Something is wrong and it's not reading 4 volts, but I'm not really sure why.

Both Arduinos are connected to a HC-12 module (SI4463).

Can any of you clever people see the problem?

What do you see if you print the value of the variables on the transmitter ? Do they look sensible ?

Please clarify this by posting a diagram

Yes, I read a range between 3.9 - 4.0.

I hate fritzing, but it can be useful.

The variable voltage will have a value >= 0.0 and < 1.0.

A value of 0.8 would correspond to a voltage of 5.0*0.8 = 0.4V 4.0V at the transmitter.

What's the problem?

No need to hate fritzing. It's not 'great' but it's ok, if you use it correctly. It has a schematic mode for drawing schematics, you don't have to use the breadboard view.

1 Like

Ok, that makes sense. So changing it to float voltage = (sensor / 1024.0) * 5.0; should fix the problem

1 Like

image

Alternatively, send the raw analog reading as an int and do the calculation on the receiver. Then you only send 2 bytes instead of 4.

1 Like

Probably the best idea actually

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.