Here, we are going to discuss:
- Configuring Arduino pin to be input or output
- Reading input pin to control another ouput pin
- Using if() else() syntax to take decision of the control
Arduino that we are going to use is Arduino Uno R3 which uses
atmega328 mcu for the control.
All Arduinos must have its i/o pins as their interfaces to another
device. For the i/o pins as its names has two main function: as input
or output. As we have known how to control pin output on the previous
article:
This part will discuss about another pin function: reading input pin
on arduino. Reading input pin with Arduino is so simple that you can
find syntax on Arduino examples. Here I take one from it and make
little modification to it.
Before we go through with code, make the following circuit first (I
use proteus simulator)
![]() |
Figure 1 Circuit Diagram |
For the circuit diagram above, I deliberately make it similar to the
previous article to make it clearer for you who want know more about
operations inside the microcontroller.
See also:
After you make the circuit (using proteus) just open your arduino IDE
and paste the code bellow:
const char buttonPin = A0; //constant declared
const char ledPin = 13;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the pin state and compare
if (digitalRead(buttonPin) == LOW)
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}
With Arduino, it is so clear and “human readable” code to use
that even a novice can understand and develop the code faster.
The first line on the code above we declare a variable constant,
buttonPin where we assign it by A0 variable (which is pin name of the
arduino, see figure 1). The ‘const’ keyword here means that we
may not change its state, for example in the setup() or loop()
function this line will cause error:
buttonPin = A2; //compilation error
ledPin = 9; //compilation error
The pinMode() inside the setup() function here takes two argument.
The first one is for pin number, in this case we use pin-A0 as an
input and pin13 as an ouput, and the second one is its “role”, in
this case ledPin is used for an output (by passing macro OUTPUT to
it) and buttonPin is for an output (by passing macro INPUT to it).
The digitalRead() in inside the loop() function just takes one
argument, that is pin-variable intended to be input, in this case it
is buttonPin variable. It will return ‘0’ (zero / LOW logic) if
we press the button on the circuit we have made; it is caused by the
ground connected to push-button. Otherwise it will return ‘1’
(one / High logic) when not pressed; it is caused by pull-up resistor
connected to pin-A0 directly.
Finally, in the if() function, if the expression is true
(digitalRead() return LOW / button is pressed), the statement inside
it will be executed, i.e.,
digitalWrite(ledPin, HIGH);
that will turn the led on.
0 Comments
Post a Comment