This article shows how to create serial connection through USB between your Arduino and your computer in order to monitor the status of a switch.
Components Required
- Arduino Board
- Bread Board
- Jumper Wires
- Momentary switch or Push Button
- 10k ohm resistor
- Computer with Arduino IDE
Circuit and Connections
3 wires should be connected to the board. The first two, red and black, allow access to the 5 volt supply and ground by connecting to the two lengthy vertical rows on the side of the breadboard. Digital pin 2 and one of the push button's legs are connected by the third wire. Through a pull-down resistor (10k ohm in this case), the button's identical leg is connected to ground. The button's opposite leg is wired to the 5 volt supply.
When you press a pushbutton or switch, it connects two points in a circuit. The pin is linked to ground (through the pull-down resistor) and reads as LOW, or 0. When the pushbutton is open (not pressed), there is no connection between the two pushbutton legs. The button connects its two legs when it is closed (pressed), connecting the pin to 5 volts, making the pin read as HIGH, or 1.
Why there is need of pulling-down?
The reading of the digital i/o pin could fluctuate irregularly if you detach it from everything. The reason for this is that the input is "floating," meaning it has no reliable connection to voltage or ground and will consequently randomly return either HIGH or LOW. For this reason, the circuit requires a pull-down resistor.
Code
As soon as you run the software below, the setup function will start serial communications between your board and computer at a speed of 9600 bits per second.
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}
Comments
Post a Comment