What am I doing wrong here? My head hurts from banging it on the wall...
I keep getting an error "else without previous if" and cant figure it out.
Please help
#define PotentiometerPin A0 #define led 3
void setup() {
// put your setup code here, to run once:
pinMode (PotentiometerPin, INPUT);
pinMode (led, OUTPUT) ;
Serial.begin (115200);
}
void loop() {
// put your main code here, to run repeatedly:
int transistorPWMValue = analogRead (PotentiometerPin);
transistorPWMValue= map (transistorPWMValue, 0, 1023, 0, 255);
I never understand why people insist on being so cryptic when people ask about very common syntax problems...
I think this is far and away the most common syntax mistake that people make - and because it compiles (when there's no else), people new to programming routinely miss it.
Here's the rule:
if(condition) will - if the condition is true, run the next statement or block, if it's not true, it will skip the next statement or block. However, two things that people don't often think about conspire to make this into an easy pitfall:
it is legal to put a block anywhere (this allows you to define variables local to a block, which i guess might be useful in some contexts, maybe? if you do byte x=0 inside a block, x will still not be defined outside that block), not just after a control structure (like if, while, for).
a statement is any valid line of c followed by a semicolon. A semicolon alone is an empty statement.
so when you do:
if(condition);
{
block of code you think will execute conditionally
}
it will check if the condition in the if statement is true. if it is, it will run the empty statement, which does nothing, otherwise it will skip the empty statement, which also does nothing. Now the if is over, and it will run the code in the block - the code you expected to only execute under that specific condition - no matter the results of the test.
And indeed, people often discover this when they find that the code seems to always execute the code that they intend to run conditionally, or they're doing and if...else structure, and the compiler complains that there's no if to go with the else - because the conditionally executed code must be immediately followed by else, with no intervening statements.