Inputs: There are two types of inputs on the 16f88, digital and analog. We will use digital inputs in this lesson. They can be either on or off. For each pin you intend to use as an input you need to declare it as an input above your forever loop. (pin_a7_direction = input) When you wire a button switch into an input you should use a 1000 Ohm or greater resistor to connect the input pin to ground and the switch will connect to +5V. This way, the input pin will see zero volts while the button is unpressed and 5V when pressed. It doesn't take any current at all to raise the input pin to +5V so a large resistor will decrease current drain when the button is pressed. You can use inputs in IF THEN statements like this (IF pin_a7 == high THEN). Sometimes you want something to happen as long as a button is pressed. This is where a WHILE loop comes in.
While Loops: While loops will run until a condition is met. Commonly this is when a variable has counted to a certain number or when an input goes high or low.
Switch bounce: When pressing a switch the contacts actually bounce a few times very quickly. It often is necessary to add a delay after reading an input pin to allow the switch to settle.
Example : This program should count when you press a button switch connected to A7
enable_digital_io() -- this makes all inputs digital. The analog pins won't work as digital inputs without it.
pin_a7_direction = input -- set pin a7 as an input
var byte x = 0
forever loop -- start your main program
while pin_a7 = = low loop -- do nothing while pin_a7 is low
end loop -- When pin _a7 turns high the loop will end
x = x+1
while pin_a7 = = high loop -- do nothing while the button is still being pressed
end loop -- move on to the next command when the button is released
-- <Insert your 7 segment decoder IF Then Statement here without any delays>
end loop -- end your program
You should notice that the counter counts up random numbers at a time. This is switch bounce. The counter is actually detecting the very fast bouncing on and off of the switch when it is pressed.
Debounce the switch by adding a short delay in your code. Where do you want the delay? How long does it need to be? Does it count up by ones now?
Make a reaction timer. It should wait for a few seconds and then turn on a light. After turning on the light it should count up one for every tenth of a second (100ms) and stop when a button is pressed. Then it should display the time it took to press the button on the seven segment display. Make it display an H if the reaction time was more than 0.9 seconds.
Extra credit: Find the random number generator library and make your reaction timer wait a random number of seconds before giving the start signal. This will make it a truer test of your reflexes.