How to use pinMode in Arduino
- The Arduino Board comes with GPIO (general purpose input output) pins that can be used in two ways i.e. input, output.
- pinMode Arduino Command is used to define the operation of these Input/output pins, there are three types of modes that can be assigned using this command and are named as:
- OUTPUT.
- INPUT.
- INPUT_PULLUP.
- There are 14 digital and 6 analog pins in the module that mainly depend on the pinMode for setting up their mode of operation as an input or output.
- In this post we mainly discuss the Arduino UNO, that is based on ATmega328 microcontroller, however, you can use other modules like Pro Mini, Mega or Leonardo as per your needs and requirements. The pinMode works same in the module no matter what type of Arduino version you are using.
Syntax for pinMode Arduino
Here's the syntax for our pinMode Arduino command:pinMode(pin#, mode);
where:- Pin defines the Arduino pin number used.
- There are three types of modes that can be assigned to pins of Arduino, which are:
- OUTPUT
- INPUT
- INPUT_PULLUP
pinMode(8, OUTPUT);
pinMode(8, INPUT);
pinMode(8, INPUT_PULLUP);
Note:- It is important to note that, unlike most of the functions used in the C code for Arduino module, this pinMode doesn't store or return any value.
- You have to use any one of these three modes at a time.
Modes of pinMode Arduino
- In the previous section, we have discussed the basic syntax of pinMode, and I hope you have pretty much got the basic idea behind it.
- The only thing worth mentioning here is the difference between INPUT and INPUT_PULLUP.
- So, here's a simple code where I have made Pin # 8 as an INPUT and read its status on Serial Monitor.
int Pin = 8; int Status = 0; void setup() { Serial.begin(9600); pinMode(Pin, INPUT); } void loop() { Status = digitalRead(Pin); if(Status == HIGH) { Serial.println("HIGH"); } if(Status == LOW) { Serial.println("LOW"); } }
- Let's have a look at the Serial Monitor:
- While taking the above image, Pin # 8 was in open state and we are getting just random values.
- We are getting these random values i.e. HIGH, LOW because our Pin#8 is neither connected to +5V nor GND.
- Arduino seems confused here, and we can remove this confusion by simply changing INPUT to INPUT_PULLUP.
- As we run the Serial Monitor, we will get something shown below:
- You can see how we are getting HIGH value only, while the pin is still in open state.
- We can conclude, when we have nothing on our INPUT pin then INPUT_PULLUP will make the pin HIGH.
Difference between Read and Write
There are two ways to send or receive data. You can either define the pin as an input that helps in reading the data from an external device like sensors. Or you can define pin as an output that helps in writing and sending a command to LEDs, motors or actuators for executing the desired functions.- You must look at the How to use digitalRead in Arduino that will help you understand the read function of the board.