Reading a Pushbutton
For these first two programs the microcontroller is told to read, from a specific I/O pin, the electrical signal coming from the circuit. Since the pushbutton breaks the circuit, if the pushbutton is not pressed, and the current does not run to ground, there is no electrical current for the I/O pin to read. Therefore, it will read "0". However, if the pushbutton is pressed, thus competing the circuit, there is a flow of electrical current into the I/O pin, and it will read "1".
Arduino:
//prints button state on connected computer's screen
int inPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(inPin, INPUT); // declare pushbutton as input
Serial.begin(9600); // start a serial connection with the computer so that you can debug
}
void loop(){
val = digitalRead(inPin); // read input value
Serial.println(val); // debug the pushbutton state in the serial monitor
}
BASIC Stamp
' {$STAMP BS2}
' {$PBASIC 2.5}
' prints button state on connected computer's screen
DO
DEBUG ? IN3 ' Print out the pushbutton state on I/O pin 3 in the Debug Terminal
PAUSE 250 ' Pause for 1/4 of a second
LOOP
(both programs submitted by Ian Bartholomew)
Arduino:
Reads state of pushbutton and turns LEDs on or off according to that state.
// declare variables:
int switchPin = 2; // digital input pin for a switch
int yellowLedPin = 3; // digital output pin for an LED
int redLedPin = 4; // digital output pin for an LED
int switchState = 0; // the state of the switch
void setup() {
pinMode(switchPin, INPUT); // set the switch pin to be an input
pinMode(yellowLedPin, OUTPUT); // set the yellow LED pin to be an output
pinMode(redLedPin, OUTPUT); // set the red LED pin to be an output
}
void loop() {
// read the switch input:
switchState = digitalRead(switchPin);
if (switchState == 1) {
// if the switch is closed:
digitalWrite(yellowLedPin, HIGH); // turn on the yellow LED
digitalWrite(redLedPin, LOW); // turn off the red LED
}
else {
// if the switch is open:
digitalWrite(yellowLedPin, LOW); // turn off the yellow LED
digitalWrite(redLedPin, HIGH); // turn on the red LED
}
}
Program above borrowed from http://itp.nyu.edu/physcomp/Labs/DigitalInOut
Comments (0)
You don't have permission to comment on this page.