I'm trying to print percentage values from my Arduino Uno
It's connected to a linear pot on pin A0 and its not printing the percentage right, it just shows 0.00 or 100.00 and nothing else. I also made it to print the raw sensor value
I'm using a A10KX2 potentiometer i bought from amazon, the wiring is same as the calibration example in the IDE excluding the LED
Here's my code
const int sensorPin = A0; // pin that the sensor is attached to
// variables:
int sensor = 0; // the sensor value
int sensMin = 1023; // minimum sensor value
int sensMax = 0; // maximum sensor value
void setup() {
Serial.begin(9600);
}
void loop() {
sensor = analogRead(sensorPin);
sensor = constrain(sensor, sensMin, sensMax);
sensor = map(sensor, sensMin, sensMax, 0, 255);
Serial.println(sensor);
float percent = round(sensor/255) * 100.0;
Serial.println(percent);
}
is an integer one. Dividing "sensor", an integer, by 255, another integer, is an integer division so unless the value is exactly 255, it will ever give 0, then multiplied by 100 and lastly converted into float that will always be 0 (or 100).
You need to force a "float" division using at least one of the two operands as a "float":