Hi,
I'm making a music keyboard and decided to learn about using interrupts. I'm using an Arduino Mega and this is my code right now:
/*
*/
#include <avr/interrupt.h>
byte portB;
volatile byte columns[] = {
22, 23,
24, 25,
26, 27,
28, 29,
37, 36,
};
volatile byte previous[] = {
255, 255,
255, 255,
255, 255,
255, 255,
255, 255,
};
volatile byte Cpin;
void setup() {
Serial.begin(9600);
{
DDRB = B00000000;
PORTB = B11111111;
}
}
void loop() {
for(volatile byte pin = 0; pin < sizeof(columns); pin++)
{
pinMode(columns[pin], OUTPUT);
{
cli();
PCICR |= 0b00000001;
PCMSK0 |= 0b11111111;
Cpin = pin;
sei();
}
pinMode(columns[pin], INPUT);
}
}
ISR(PCINT0_vect) {
portB = PINB;
if (PINB != previous[Cpin])
{
Serial.print ("portB = ");
Serial.print (portB, BIN);
Serial.print (" ");
Serial.print (previous[Cpin], BIN);
Serial.print (" ");
Serial.println (Cpin);
previous[Cpin] = PINB;
}
}
When using the monitor, I get a readout that corresponds to the right byte and column, but it's constantly reading and in turn switching between values. I also get 2 reads on each column. The goal is that the code will only read once when the pin change interrupt fires, and then stick to that reading until another comes along or the button is released.
The keyboard I'm using is velocity sensitive so there are 2 switches for every key, but I haven't gotten to the velocity part of the code yet.
portB = 11111110 11111111 1
portB = 11111111 11111110 1
portB = 11111110 11111111 0
portB = 11111111 11111110 0
portB = 11111110 11111111 1
portB = 11111111 11111110 1
portB = 11111110 11111111 0
portB = 11111111 11111110 0
This is a snippet of the monitor when pressing and holding one key.
Why does my code read each column twice and why is it reading continuously and not only once?
I guess I need some debounce which might solve my problem, so I would love some input on good debounce solutions inside ISRs.
Another thought I had was that disabling the interrupt flag could be a solution, so a second ISR isn't called instantly after the first ISR is done. Would this be an option?
Thankful for any help