0

Why doesn't this code work? All that I want is portb to toggle when I press a button.

main
trisb=0
trisa=0xff
while true
if ra0<>0 then
portb = not portb
end if
wend .end
gary
  • 4,227
  • 3
  • 31
  • 58

1 Answers1

0

I'm not sure what that is; is it pseudocode?

Anyway, you need to trigger on the CHANGE from RA0 == 0 to RA0 == 1. As written, as long as RA0 == 1 then your PORTB will toggle every time through the loop.

Here's an example in C:

int main(void)
{
    unsigned char bButtonValue = 0;

    TRISA = 0xFF;
    TRISB = 0x00;

    while (1)
    {
        if (RA0 != bButtonValue) 
        {
            bButtonValue = RA0;
            if (bButtonValue == 1)
            {
                 PORTB= ~PORTB;
            }
         }
     }
}

Keep in mind that for a real app, you would want to debounce the switch input (make sure it's stable for a few samples before triggering the change event.

Adam Casey
  • 949
  • 2
  • 8
  • 24
  • thnx adam yep!! the mistake I failed in was rb0_bit,, also I must enable the interrupts con. .. can I run two while true loops in pic, as threaded classes in java or c++?? – Mhood Nashabat May 11 '12 at 17:09
  • First, please explain how you need interrupts for your original example. Did you want to put the button scan in an interrupt? If so, use a timer interrupt with a 10ms tick. You can handle debouncing from there. – Adam Casey May 12 '12 at 03:54
  • Also, you can run a loop in your interrupt service routine to scan the button and set a variable for your main loop to read. This is the equivalent of multithreading in an embedded system with no RTOS. – Adam Casey May 12 '12 at 03:55
  • that's it thank you mr Adam, i used interrupts to break the while true, another question: is there any module supports IEEE 802.11 can be connected to pic18?? i wanna transmit data from a smartphone to pic18 via mobile wifi standards thanks alot – Mhood Nashabat May 15 '12 at 02:55