1V 0.1 1LED/Switch IO16F873RB4RB6To configure (LED initially off):/* RB6 Inputs, others off */TRISB = 0x40;PORTB = 0x00;V 0.1 2Count #number of switch press/releases.A common error:int i;TRISB = 0x40;PORTB = 0x00;i = 0;while (1) {if (!bittst(PORTB, 6)) {/* switch pressed, increment */i++;}} Will be incremented MANY times. A human CANNOT press/release a switch faster than a few milliseconds, so code in loop executed an unknown number of times.V 0.1 3Count #number of switch press/releases.int i;TRISB = 0x40;PORTB = 0x00;i = 0;while (1) {/* wait until button is pressed */while (bittst(PORTB, 6));/* wait for button to be released */while (!bittst(PORTB, 6)); i++; } Correct solution:V 0.1 4Toggle LED for each switch press/releaseTRISB = 0x40; PORTB = 0x00;/* LED initially off */while (1) {if (!bittst(PORTB, 6)){/* switch pressed, turn on LED */bitset(PORTB,4);}if (bittst(PORTB, 6)) {/* switch released, turn off LED */bitclr(PORTB, 4);} } Code does not work; LED will be turned on as long as switch is held down; once it is released, will be turned off. So LED doesNOT toggle for each press/release.V 0.1 5Toggle LED for each switch press/releaseTRISB = 0x40; PORTB = 0x00;/* LED initially off */while (1) {while (bittst(PORTB, 6)); /* wait for press*/while (!bittst(PORTB, 6)); /* wait for release*/ bitset(PORTB,4); /* turn on */while (bittst(PORTB, 6)); /* wait for press*/while (!bittst(PORTB, 6)); /* wait for release*/bitclr(PORTB,4); /* turn on */} This code works.V 0.1 6Toggle LED for each switch press/releaseTRISB = 0x40; PORTB = 0x00;/* LED initially off */while (1) {while (bittst(PORTB, 6)); /* wait for press*/while (!bittst(PORTB, 6)); /* wait for release*/ if (bittst(PORTB, 4)) bitclr(PORTB,4);else bitset(PORTB,4);} This works because reading an output returns the value of the output. This will set the RB4 output to a ‘0’ if it is currently a ‘1’, to a ‘1’ if it is currently a ‘0’.2V 0.1 7Toggle LED for each switch press/releaseTRISB = 0x40; PORTB = 0x00;/* LED initially off */while (1) {while (bittst(PORTB, 6)); /* wait for press*/while (!bittst(PORTB, 6)); /* wait for release*/ PORTB = PORTB ^ 0x10;} This works because the ^ is the exclusive OR operation, and an exclusive OR with a ‘1’ value will toggle that
View Full Document