Electronics Projects: How to Check the Status of a Switch in PBASIC
Once you’ve connected a switch to a BASIC Stamp I/O pin in your electronics project, you need to know how to determine whether the switch is open or closed from a PBASIC program. The easiest way to do that is to first assign a name to the pin you want to test. For example, if an active-high input button is connected to pin 14, you can assign it a name like this:
Button1 PIN 14
Here, the name Button1 is assigned to pin 14.
Then, to determine whether the pushbutton is pressed, you can use an IF statement like this:
IF Button1 = 1 THEN HIGH Led1 ENDIF
Here, the output pin designated as Led1 is made HIGH when the button is pressed.
If you want Led1 to be HIGH only when Button1 is pressed, use this code:
IF Button1 = 1 THEN HIGH Led1 ELSE LOW Led1 ENDIF
Here, Led1 is made HIGH if the button is pressed and LOW if the button isn't pressed.
You can put the whole thing in a loop to repeatedly test the status of the button and turn the LED on and off accordingly:
DO IF Button1 = 1 THEN HIGH Led1 ELSE LOW Led1 ENDIF LOOP
Here is an interesting program that works with a BASIC Stamp that has a pushbutton switch connected to pin 14 and LEDs connected to pins 0 and 2. The program flashes the LED connected to pin 2 on and off at half-second intervals until the pushbutton switch is depressed. Then, it flashes the LED on pin 0.
' Pushbutton Program
' Doug Lowe
' July 13, 2011
' {$STAMP BS2}
' {$PBASIC 2.5}
Led1 PIN 0
Led2 PIN 2
BUTTON1 PIN 14
DO
IF BUTTON1 = 1 THEN
LOW Led2
HIGH Led1
PAUSE 100
LOW Led1
PAUSE 100
ELSE
LOW Led1
HIGH Led2
PAUSE 100
LOW Led2
PAUSE 100
ENDIF
PAUSE 100
LOOP
This project shows how to build a simple circuit you can use to test this program. Here’s what the completed circuit should look like:









