Hello, there is a potentiometer, and when rotating in 1 direction, it is necessary to send 1, in the other 0, did I correctly set the condition in if ? when changing by one, send, but this does not work, then 0, then 1 is constantly sent, even if the potentiometer does not rotate. How can I specify this task in if ? is this even possible ? it is necessary that even if the value has increased from 127 to 253, 1 still goes
void setup() {
Serial.begin(9600);
pinMode(A1, INPUT);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
void loop() {
int val = analogRead(A1);
if (val++) {
Serial.println("1");
}
if (--val) {
Serial.println("0");
delay(100);
}
}
Please follow the advice given in the link below when posting code. Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination
This statement will evaluate the value of val and will return false if it is zero or true if it is any other value. Once evaluated the value of val will be incremented. This is not what you need to do at all
Instead, each time you read the pot you need to compare the current value with the previous value to determine whether it has increased or decreased and save the current value as the previous value ready for the next time the check is done
And to easily get the process to start up you will need to unconditionally read and store the value as part of your setup() code. Then the loop does not need any special one-time processing.
Paul
if you want to compare the current reading you must remember the old reading in a variable. Otherwise you have nothing to compare with.
/*
if this is for school, you are not allowed to remove this comment
https://forum.arduino.cc/t/how-can-i-specify-this-task-in-if-is-this-even-possible/900081
by noiasca
*/
const byte sensorPin = A1;
int previousReading = 0;
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
}
void loop() {
int currentReading = analogRead(sensorPin);
if (currentReading > previousReading) {
Serial.println("1");
}
if (currentReading < previousReading) {
Serial.println("0");
}
previousReading = currentReading;
delay(500); // dirty delay
}
Thank you, there are a couple of options for how to remove the noise, probably the anti-rattle function will be enough, but I'm not sure. I'm very busy right now, I can't check all the options right now, I think I'll get it a little later without noise.