How to Set I/O Pins as Digital in a PIC Microcontroller in C



PIC18F4525 microcontroller


In this article, we show how to set I/O pins of a PORT as digital for a PIC microcontroller in the C programming language.

So PIC microcontrollers have PORTs and each PORT is composed of pins, or bits, which can be used as either inputs or outputs.

We first set the pins as either inputs or outputs.

After that, you must decide whether the pins should be analog or digital.

Analog can take on a range of "infinite" values between 0 and the maximum voltage that the pin accepts (such as 3.3V or 5V).

Digital only can take on 2 values, either 0V or 3.3V or 5V, or Off or On.

Analog is used for analog devices such as microphones, speakers, temperature sensors, pressure sensors, etc.

Digital is used for digital devices such as a simple switch, a digital light source, or a digital chip.

As stated before, we can to explicitly define a pin as analog or digital.

By default, all pins are analog.

Thus, to make the pins digital, we have to explicitly define them as digital.

So we show how to do this below.



First, we set PORTA as inputs and PORTB as outputs. Usually you can do this first before

So in order to set pins as digital, the first thing that is necessary is to turn off the ADC.

The ADCON0 register controls whether the ADC is on or off. The line, ADCON0= 0x00;, turns the ADC off.

If the ADCON0 register is truned on, it also specifies which bit or channel the ADC is connected to. But since we want it off, in this case, that wouldn't be applicable.

After we set the ADCON0 register, we then have to set which pins we want to be digital. We do this by setting the ADCON1 register. The ADCON1 register controls what voltage range is used and which bit(s) are analog or digital.

We set the first 16 bits of the ADCON1 register to a logic '1', which makes all pins from PORTA and PORTB digital. Remember that a '1' makes a pin digital and a '0' makes a pin analog. The line, ADCON1= 0x0F;, is equivalent to the binary value of, 0b00001111. This sets pins 0-15 as '1', which makes them digital.

PORTA and PORTB are the ports with the least most significant bits (0-15), while PORTC and PORTD are the ports with the most sigificant bits (16-31). So if you were making every bit in PORTA, PORTB, PORTC, and PORTD digital, then you would use the line, ADCON1= 0x1F

Back to our code, you can use the pins on PORTA as digital input and the pins on PORTB as digital output.

And this is how to make I/O pins digital in a PIC microcontroller in C.


Related Resources

How to Set the Ports of a PIC Microcontroller in C


HTML Comment Box is loading comments...