Hello everyone, I have been stuck on this problem since sometime. So basically, I just need a state change detection of analogRead(). Its working fine with the "ON" part. But it keeps going on when the switch is in "OFF" state. Here is my code:
char switchPin = A1;
const unsigned long switchReadTime = 50;
const unsigned long debounceTime = 50;
unsigned long lastDebounceTime = 0;
unsigned long previousTime = 0;
int switchValue = 0;
int switchState = 0;
int lastSwitchState = 0;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT);
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - previousTime >= switchReadTime) {
for (int i = 0; i < 10; i++) {
switchValue += analogRead(switchPin);
}
switchValue = switchValue / 10;
switchState = switchValue;
previousTime = currentTime;
}
if (currentTime - lastDebounceTime >= debounceTime) {
if (switchState != lastSwitchState) {
if (switchState == 1136) {
Serial.println("ON");
lastSwitchState = switchState;
lastDebounceTime = currentTime;
} else {
Serial.println("OFF");
lastSwitchState = switchState;
lastDebounceTime = currentTime;
}
}
}
}
At starts I have put switchValue = 0;
Shall I reset switchValue at the end of the loop?
So I was getting 1023 before doing an average of the analog value. But after I averaged it, it was showing 1136 for some reason. I am using a normal switch from home.
Strange. Usually a state change detection of an analog value requires that you first define a detection "window" so that ADC noise isn't detected as a change.
I posted before the last reply.
Logic would be:
if ON
{
if reading < 1136
{
OFF
}
}
else
{
if reading >= 1136
{
ON
}
}
The requirement as you expressed it, does not need any timing at all. The logic in reply #6 will work reliably no matter when the samples are taken. If you need hyteresis, just change one limit:
if ON
{
if reading < 1136
{
OFF
}
}
else
{
if reading >= 1136 + hysteresis value
{
ON
}
}
Actually there is alot of noice in the output, I had to filter it out using millis() which is working like a charm. Now I am getting constant output of the switch which is either ON or OFF. But I need just the change of state detection.
Its working fine when the switch is in ON position, like the output stops at on, but it keeps printing on OFF position. I just want the one output of OFF and wait for the switch to turn on.
The noise suppression is not so much of an issue than getting the state change. But to answer your question, I am connecting it directly from the switch to the board. Without using any resistor or capacitor. I want the circuit connected directly for my current project.
I am averaging the values for getting a stable output from the switch. These value are then used to determine the ON and OFF state of the switch. Due to this method, I don't need to attach any additional electronics to filter out the noise.