Hi all,
Writing a really simple piece of code and I cant figure out why abs(x) is reporting a negative number.
As you can see from my serial prints, the value doesnt change after that line of code.
I cant see if I have written it wrong, or done something else which makes it revert back to a negative number?
int potPin = 2; // select the input pin for the potentiometer
int LED_Clockwise = 12; // select the pin for the LED
int LED_Anti = 11; // select the pin for the LED
int val; // variable to store the value coming from the sensor
int x; //variable which shows how far the potentiometer is from its centre
void setup() {
Serial.begin(9600);
pinMode(LED_Anti, OUTPUT); // declare the ledPin as an OUTPUT
pinMode(LED_Clockwise, OUTPUT); // declare the ledPin as an OUTPUT
}
void loop() {
val = analogRead(potPin); // read the value from the sensor
//potentiometer oscilates between 0 and 621 (which corresponds between 0 and 3.3V)
//1.15V is therefore 311 (rounded)
//LED brightness will be dependent on how close the potentiometer is to its central reading (311)
x = 311 - val; //distance from central point, but could be negative
Serial.print("X value before abs = ");
Serial.println(x);
delay(500);
// return modulus of x so the system doesnt attempt to set brightness to a negative number
abs(x);
Serial.print("X value after abs = ");
Serial.println(x);
x = x / 1.22; //brightness cant be higher than 255, 311/1.22 = 255
Serial.print("potentiometer value = ");
Serial.println(val);
Serial.println(x);
//different LEDs come on depending on the position of the potentiometer
//their brightness should dim the closer the potentiometer is to its centre
if (val > 311)
{
analogWrite (LED_Clockwise,x);
digitalWrite (LED_Anti, LOW);
}
else
{
digitalWrite (LED_Clockwise,LOW);
analogWrite (LED_Anti,x);
}
