Hello everyone, I'm new to using Arduino and got stuck in a little school project I have. The idea is to interface a potentiometer with the Arduino (I'm using Arduino UNO) which will then display a message on the computer screen saying if the value of the pot increased, decreased or stayed the same. Basically the message screen should look like something like:
- Same value
- Same value
- Same value
- Same value
- Increased Value
- Same value
- Same value
- Decreased value
- Same value
- Same value
Attached is the code that I've been working on. I would like to ask you to help me please as I'm stuck in some small part of the code. Thanks and regards in advance 
int potPin = A0;
void setup()
{
Serial.begin(9600);
pinMode(potPin, INPUT);
}
void loop()
{
int val = analogRead(potPin);
int prev_val = 0;
int delta = prev_val - val;
if (delta > 0)
{
Serial.println("Increase Value");
}
else if (delta < 0)
{
Serial.println("Decrease Value");
}
else /*if (delta = 0) */{Serial.println("Same Value");}
delay(500);
prev_val = val;
}
[pre][code]int potPin = A0;
void setup()
{
Serial.begin(9600);
pinMode(potPin, INPUT); << not needed analog reads
}
void loop()
{
int val = analogRead(potPin);
int prev_val = 0; << move this to setup() for the very first read comparison - otherwise you lose prev_val every time thru after saving it at the end of the prior pass thru loop.
int delta = prev_val - val;
if (delta > 0)
{
Serial.println("Increase Value");
}
else if (delta < 0)
{
Serial.println("Decrease Value");
}
else /*if (delta = 0) */{Serial.println("Same Value");}
delay(500);
prev_val = val;
}
[/code]
You could try telling us what you're stuck on, and what exactly the problem is.
I spot a problem, but without reading your mind I can't be certain it's the problem. And Crossroads gave about 1/2 of one solution to the problem that I see.
The bug is obvious. The declarations
void loop()
{
int val = analogRead(potPin);
int prev_val = 0;
make the variables local to loop, so that the value of prev_val is set to zero all the time.
Moving the prev_val declaration out of and before loop() makes the variable global, so that it can remember the last value even after exit from loop().
Another solution:
static int prev_val = 0;
makes the variable persistent, so that it also can remember its last value. In addition this static variable is visible only inside loop(), thus can not be modified or confused with another variable of the same name outside loop().