Code basics – Arduino pins
The most important feature of the Arduino is its control over digital input/output (I/O) pins. On each pin, we can set a voltage value of 5 V, representing logic HIGH, or 0 V, representing logic LOW. Also, we can read whether a value of 5 V or 0 V is applied externally. Here we will learn how.
Getting ready
For this recipe, ensure that you have the Arduino IDE running on a computer.
How to do it…
The following code turns a pin HIGH and LOW repeatedly while reading the external voltage applied to another:
void setup() { // Set pin 2 as a digital Output pinMode(2, OUTPUT); // Set pin 3 as a digital Input pinMode(3, INPUT); } void loop(){ // Set pin 2 HIGH digitalWrite(2, HIGH); // Wait 100 milliseconds delay(100); // Set pin 2 LOW digitalWrite(2, LOW); // Wait 100 milliseconds delay(100); // Read the value of pin 3 and store it in a variable int pinValue = digitalRead(3); }
How it works…
The code sets two pins in output and input mode and then writes and reads from them. Here is the code breakdown:
In setup()
, we use the pinMode()
function to set pin number 2 as an output. When we set a pin as an output, we can set that pin as either HIGH (5 V) or LOW (0 V). Also, we set pin number 3 as an input. A pin configured as input can read external voltages applied to it. It can read HIGH if the voltage is around 5 V and LOW if the voltage is close or equal to 0 V:
void setup() { // Set pin 2 as a digital Output pinMode(2, OUTPUT); // Set pin 3 as a digital Input pinMode(3, INPUT); }
In the loop()
function, we use the digitalWrite()
function to set pin number 2 to HIGH. Then, we wait for 100 milliseconds using the delay()
function. This function stops the execution of the code for the specified time, in milliseconds. Thereafter, we set the pin to LOW and wait another 100 milliseconds. In the end, we read the value of pin 3 in a variable:
void loop(){ // Set pin 2 HIGH digitalWrite(2, HIGH); // Wait 100 milliseconds delay(100); // Set pin 2 LOW digitalWrite(2, LOW); // Wait 100 milliseconds delay(100); // Read the value of pin 3 and store it in a variable int pinValue = digitalRead(3); }
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.