Need help with button interrupt?

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I need help with the button interrupt. The thing I want to let it do, is when I click PC1 led0 needs to blink t'ill i stop it by clicking again on PC1.

 

#include <avr/io.h>
#include <util/delay.h>
#include <usart.h>
#include <led.h>
#include <button.h>
#include <avr/interrupt.h>
#define LED_PORT PORTB
#define BUTTON_PORT PORTC
#define BUTTON_PIN PINC
#define LED_DDR DDRB
#define BUTTON_DDR DDRC
#define BUTTON1 PC1
#define LED1 PB2
#define LED2 PB3
int LED0_knippert = 0;
int LED1_knippert = 0;
int LED2_knippert = 0;

ISR(PCINT1_vect) { 
  if (bit_is_clear(BUTTON_PIN, BUTTON1)) {    
    _delay_us(1000);    
    if (bit_is_clear(BUTTON_PIN, BUTTON1)&& !LED0_knippert) {
      LED0_knippert =1;      
      printf("%d",LED0_knippert);
  }
    else{
     LED0_knippert = 0;
     printf("%d",LED0_knippert);
    }
  
  }
}

int main(){
  initUSART();  
  enableLeds(0); 
  enableButton(1);       
  PCICR |= _BV(PCIE1);  
  PCMSK1 |= _BV(BUTTON1); 
  sei();
  while(LED0_knippert){
    ledBlink(0,100);
    printf("ok");
  }
  
  return 0;
}

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

printf() from ISR()? You sure about that?

 

Also back in main() your:

  while(LED0_knippert){
    ledBlink(0,100);
    printf("ok");
  }

only lasts for as long as LED0_knipper is set. As soon as this happens:

    else{
     LED0_knippert = 0;
     printf("%d",LED0_knippert);
    }

that while() loop will end. Then it goes to:

  return 0;
}

so what happens then? (I know. I suspect you don't. It's not good!)

 

Oh and variables shared between main() and ISR() *MUST* be "volatile" (oh and don't make them "int" - just throwing "int" at a variable shows no thought about what type it really should be)

Last Edited: Mon. May 18, 2020 - 09:41 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

and don't forget that buttons bounce ...

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...