embedded - Led on/off using PIC 16f777a -


i doing exercise using push button. when button pressed once led starts blinking , when pressed again stops. when tried led blinking on 1st press not stopping on 2nd. using pic16f877a mcu hitech c compiler. code :

#include<pic.h> #define _xtal_freq 20000000  void main() {  trisb = 0x01;  portb = 0x00;  while(1){ if(rb0 == 1){         while(1){             portb = 0xff;             __delay_ms(250);             portb = 0x00;             __delay_ms(250);             if(rb0 == 1){                 break;                 }             }         }     } } 

i think "too short" loop.

using double while catch input causes both if can valid thousand of times until release pushbutton.

a suggest manage on release of button, means trigger push of button , valid push when button released.

a simple solution can be:

#include <pic.h> #include <stdint.h> #define _xtal_freq 20000000  void main() {    unit8_t pressed = 0;    bool blink = 0;     trisb = 0x01;    portb = 0x00;    while(1)    {        // button pressed first time        if ((rb0 == 1) && (pressed == 0))        {            pressed = 1;        }        // button released = valid         else if ((rb0 == 0) && (pressed == 1))        {            pressed = 2;        }         if (pressed == 2)        {           blink ^= 1;           pressed = 0;        }         if (blink == 1)        {           portb ^= 0xfe;           __delay_ms(250);        }     } } 

with simple solution, elaborated yours, have "strange feeling" push button, because of there 250ms delay each loop (in case 500ms) means can loose single button pressure.

take notes also simple input have manage debounce, also. when contacts of mechanical switch bang rebound bit before settling, causing bounce. debouncing, of course, process of removing bounces, of converting brutish realities of analog world pristine ones , zeros.

anyway best solution add timer manage blink of led , use main loop evaluate button pressure. avoid delay between input checks.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -