18F Switch Example

Checking the status of Pins is very simple, and this basic
switch
program demonstrates it. The 10K (Could be any large value)
resistor is a
"Pull-Down"
resistor, and keeps the Pin
tied to earth (0v) should
the
switch
be open (contacts not touching).
If it was not in place, the input Pin (After having a logic
High value) would have residual voltage remaining, as its
impedance is very
high, and would falsely interpret the Pin as still having a
logic High
state. With the
resistor in place, its brought back to 0v
immediately
after any switching, also known as "tied to earth."
One other thing to keep in
mind is that switches "chatter" or "bounce" as the contacts meet.
The PIC operates so fast that it can read this chattering as multiple presses,
so a debounce routine is required.

Note the PIC's
power supply/oscillator are not shown
Click here to
see this circuit in action!
Code example:
Device = 18F4520
Clock = 8
Config OSC = INTIO67 // Use the Internal Oscillator
Include "utils.bas"
Dim
Switch As PORTA.0, // Assign an alias for "Switch"
Signal As PORTB.7 // Assign an alias for "Signal"
Sub Debounce()
DelayMS(10) // Small delay to stop "bouncing"
While Switch = 1 // Wait for the switch to be de-pressed
Wend //
End Sub
// Start Of Program...
OSCCON = %01111111 // Sets up the internal oscillator
SetAllDigital // Make all Pins digital I/O's
Input(Switch) // Make the switch pin an input
Low(Signal) // Make the LED an output and set it Low
While True
Repeat // Wait for the switch to be pressed
Until Switch = 1 //
Signal = 1 // Make "Signal" High (5V) and wait for the
// button to be depressed
Debounce //
Signal = 0 // Return "Signal" to Low (0V)
Wend
Where you can get the components;

 | Site Tutorial Index |
|  | 16F PIC Examples |
|  | 18F PIC Examples |
|  | Handy Tips |