Hello,
I'm compleate novice with Arduino and programing.
I want to make my LED light up with a specific read of the potentiometar but compiling comes up with
programming error.
Here is the code, can you help me>
int led1 = 13;
void setup(){
Serial.begin(9600);
}
void loop(){
int sensorValue = analogRead (A0);
int sensorValue2 = analogRead (A1);
int sensorValue3 = analogRead (A2);
int volt1 = sensorValue * (10.0 / 1023.0);
int volt2 = sensorValue2 * (10.0 / 1023.0);
int volt3 = sensorValue3 * (10.0 / 1023.0);
Welcome to the Forum. Before your next post, please read the two posts by Nick Gammon at the top of the Forum for guidelines on posting here, especially about using code tags ("</>") when posting source code. The smiley face is because you didn't use code tags.
Now, about your code:
First, the statement(s) like:
int volt1 = sensorValue * (10.0 / 1023.0);
could be written as:
int volt1 = (int) sensorValue * .009775;
Because you are assigning into int variables, these intermediate float values will be truncated to int variables.
Second, you don't write if statements with a semicolon at the end, as you have done here:
if
(volt1 == 4); // <--- this semicolon is likely not what you want to do here
Is this what you mean?
if (volt1 == 4 || volt2 == 2 || volt3 == 8) { // Note: no semicolon at end
digitalWrite(led1, HIGH);
} else {
digitalWrite(led1, LOW);
}
You could avoid the floating point math altogether by just using:
int volt1 = sensorValue * 10 / 1023;
However, I'm not sure that is really what you want. This logic will convert sensor values to volts like this:
sensorValue
volt1
0-102
=
0
103-204
=
1
205-306
=
2
307-408
=
3
409-511
=
4
512-613
=
5
614-715
=
6
716-817
=
7
818-919
=
8
910-1022
=
9
exactly 1023
=
10
As you can see, you have 11 possible voltage values, each corresponding to a sensor range of 102.3 values, except the last one that only occurs at exactly 1023. This is probably accurate for the actual voltage calculation (assuming the sensor outputs 1023 for 10v), but it probably isn't what you want for your code.
I'm assuming that you are creating some sort of combination "lock" with three dials. I'm also guessing that you want the dials to have 10 values each (1-10) If that is the case, you probably want each digit on the dial to be same "size" (number of degrees of rotation). In that case, you want to split the values 0 through 1023 into 10 equal chunks. 0-1023 represents 1024 distinct values, so each dial position should represent 102.4 of the values. If that's the case, the formula should be:
int dial1 = sensorValue * 10 / 1024 + 1;
Note: I've also changed the variable name to reflect the fact that this is a dial position and not a voltage.
Of course, my guesses could be completely wrong, since you didn't actually say what you were doing (either in your post or as comments in your code - hint, hint).