Saturday, May 28, 2022

tinkercat pin change interrupt


3 buttons to blink, turn on and off 2nd led, while 1st led flashes
int buttonState = 1;
volatile byte lightState = LOW;

void setup()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(7, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  
  PCICR |= B00000100; //enable PCMSK2 (group 2: PCINT16 to PCINT23)
  PCMSK2 |= B11100000; //D5, D6 and D7 could trigger interrupt
}

ISR (PCINT2_vect){
  if(digitalRead(5) ){
    buttonState = 1;
  }
  
  if(digitalRead(6) ){
    buttonState = 2;
  }
     
  if(digitalRead(7) ){
  buttonState = 3;
  }
}

void loop()
{
  digitalWrite(10, HIGH);
  delay(500);
  
  interruptLed();
  
  digitalWrite(10, LOW);
  delay(500);

  interruptLed();
}

void interruptLed(){
  switch(buttonState){
    case 1:
    lightState = !lightState;
    digitalWrite(9, lightState);
    break;
    case 2:
    digitalWrite(9, HIGH);
    break;
    case 3:
    digitalWrite(9, LOW);
    break;
    default:
    buttonState = 1;
    break;
  }
}

reference:

PCICR

PCMSK

No comments:

Post a Comment