For checking a falling edge on pin 12 and rising edge on pin 11 I wrote this small program. The program " buttonstate.ino" is also included as attachment.
int buttonStateRising=1;
int buttonRisingEdge = 1;
int lastButtonStateRising = 1;
int buttonStateFalling=0;
int buttonFallingEdge = 1;
int lastButtonStateFalling = 0;
void setup(){
Serial.begin(9600);
digitalWrite(11,HIGH);//activation of the pull-up resistor of pin 11
digitalWrite(12,HIGH);//activation of the pull-up resistor of pin 12
}
void loop(){
//Here starts the code for detecting a rising edge on pin 11
buttonStateRising = digitalRead(11);
if (buttonStateRising != lastButtonStateRising) {
if (buttonStateRising == LOW) {
buttonRisingEdge = 0;
Serial.println("There was a rising edge on pin 11");
}
}
else{
buttonRisingEdge = 1;
Serial.println("There was no rising edge on pin 11");
}
lastButtonStateRising = buttonStateRising;
//Here starts the code for detecting a fallng edge on pin 12
buttonStateFalling = digitalRead(12);
if (buttonStateFalling != lastButtonStateFalling) {
if (buttonStateFalling == HIGH) {
buttonFallingEdge = 1;
Serial.println("There was a falling edge on pin 12");
}
}
else{
buttonFallingEdge = 0;
Serial.println("There was no falling edge on pin 12");
}
lastButtonStateFalling = buttonStateFalling;
}
It seems to work but when I integrate it in a bigger program (used as a library) the detection doesn't detect all the edges.
These two macros are very handy for edge detection:
//macro for detection af rasing edge
#define RE(signal, state) (state=(state<<1)|(signal&1)&3)==1
//macro for detection af falling edge
#define FE(signal, state) (state=(state<<1)|(signal&1)&3)==2
You need to use them together with a variable dedicated to that signal:
const int btn = 11; //btn pin
int btnState;
...
if(RE(digitalRead(btn), btnState)){
//code here gets executed on raising edge of btn
}
//Here starts the code for detecting a rising edge on pin 11
buttonStateRising = digitalRead(11);
if ((buttonStateRising == HIGH) && (lastButtonStateRising == LOW)) {
if (millis() - millisPrevious >= debounceInterval) { // if debounce interval expired
Serial.println("There was a rising edge on pin 11");
}
millisPrevious = millis();
}
lastButtonStateRising = buttonStateRising;
}
That will not debounce and will fire twice: millisPrevious is already outdated, on first iteration.
Try this, it will fire and set millisPrevious on the first 'valid' state, then reset on timeout.
This will also code with a perfect state change (where a bounce is never discerned)
//Here starts the code for detecting a rising edge on pin 11
buttonStateRising = digitalRead(11);
if ((buttonStateRising == HIGH) && (lastButtonStateRising == LOW)) {
if (millisPrevious == 0) {
Serial.println("There was a rising edge on pin 11");
millisPrevious = millis();
}
}
if (millis() - debounceInterval >= millisPrevious) { // if debounce interval expired
millisPrevious = 0;
}
lastButtonStateRising = buttonStateRising;
}