Sv443
November 9, 2017, 5:51pm
1
So I tried to get the percent value from a byte (val2) with this code:
int val1; //output value
byte val2; //input value
val1 = (val2 / 255) * 100;
Complete Code:
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int val3;
byte val2;
int val1;
void setup() {
lcd.begin(16, 2);
}
void loop() {
val3 = analogRead(A0);
val2 = val3 / 4;
val1 = (val2 / 255) * 100;
lcd.setCursor(0, 0);
lcd.print("I: ");
lcd.setCursor(3, 0);
lcd.print(val3);
lcd.setCursor(9, 0);
lcd.print("B: ");
lcd.setCursor(12, 0);
lcd.print(val2);
if(val3 <= 999){
lcd.setCursor(6, 0);
lcd.print(" ");
}
lcd.setCursor(0, 1);
lcd.print("%: ");
lcd.setCursor(3, 1);
lcd.print(val1);
}
and all I get as an output is 0
what did I do wrong?
Sv443:
what did I do wrong?
You didn't read the sticky "Read this before posting a programming question"
Sv443
November 9, 2017, 6:01pm
3
I don't know what you're referring to. Do you mean I have to post the full code? I did that now.
Hint: Follow the link I gave
You have a byte variable, which can hold a value between 0 and 255. You divide that by 255. What do you expect the result to be?
Regards,
Ray L.
Try
int val1;
byte val2 = 128;
void setup() {
Serial.begin(250000);
val1 = (val2 / 255.0) * 100;
Serial.print(val1);
}
void loop() {}
50
Sv443
November 9, 2017, 6:13pm
7
RayLivingston:
You have a byte variable, which can hold a value between 0 and 255. You divide that by 255. What do you expect the result to be?
I don't actually know. Now that you say it it doesn't make any sense.
I wanted my input value to be for example 150 of 255 which would yield 0.58 , so 58%
Sv443
November 9, 2017, 6:24pm
8
I am so confused now...
The calculation works just fine on my calculator.
For example if I do (15 / 255) * 100 = 5%
My Arduino just prints a 0
Unless forced to do otherwise the calculation will be done with all the values being regarded as integers. Make at least one of the values in the calculation a float and the calculation will be done using floats
See reply #5
Sv443
November 9, 2017, 6:34pm
10
UKHeliBob:
Unless forced to do otherwise the calculation will be done with all the values being regarded as integers. Make at least one of the values in the calculation a float and the calculation will be done using floats
See reply #5
Thank you very much. I did not know that. Now it works just fine.
If you first multiply by 100 and next divide, you will also circumvent the problem.
HaecuD:
Hey, so does anyone know if this calculator can give me the correct percentage calculation?
This post looks suspiciously like spam and/or a SEO link