I/O Port Programming Examples
Example 1:
Let us say that you have built the circuit shown below and you want to turn the LEDs ON and OFF continuously.
To turn an LED ON, there must be enough positive voltage at its anode with respect to the voltage at its cathode. Based from the circuit shown above, applying a positive voltage at the anodes of the LEDs means that the pins of P1 must output 5V and the only way to do that is to write logic 1 to P1.0 to P1.7 or to write 0xFF to P1. To turn the LEDs OFF means that P1 must be written 0×00.
See the code below.
#include <reg51.h> #define LEDs P1 //define P1 as LEDs void my_delay(void) { unsigned int i,j; for(i=0;i<0xFFFF;i++) for(j=0;j<0xFFFF;j++) ; //waste some time to create delay } void main(void) { while(1) //forever loop { LEDs = 0xFF; //turn LEDs ONmy_delay(); //create delayLEDs = 0x00; //turn LEDs OFFmy_delay(); //create delay } }
Example 2
Write a program for the circuit below that will turn LED0 ON by pressing SW1 and OFF by pressing SW2.
Based from the given circuit, P1.7 serves as an output because it is connected to LED0. P1.0 and P1.1 serve as inputs because they are connected to SW2 and SW1 respectively. If SW1 is pressed, its contacts are shorted and makes P1.1 connected to ground. When P1.1 is connected to ground, it means that its pin reads logic zero or LOW. When SW1 is unpressed, P1.1 reads logic one or HIGH because of the pull up resistor connected to its pin.
This is also the same with SW2 and P1.0. Pressing SW2 makes the pin P1.0 read HIGH. Otherwise, P1.0 reads LOW.
Try the code below.
#include <reg51.h> sbit LED = P1^7; //declaring P1.7 as LEDsbit SW1 = P1^1; //declaring P1.1 as SW1sbit SW2 = P1^0; //declaring P1.0 as SW2void main(void) { LED = 0; //initially, LED must be offwhile(1) //forever loop { if(!SW1) //check if SW1 is pressed LED = 1; if(!SW2) //check if SW2 is pressed LED = 0; } }
Conclusion
Programming the IO port of 8051 is as simply as writing a ’1′ or a ’0′ to a pin. The significance of knowing how to access the IO port of a microcontroller is very important. A microcontroller’s pins may be connected to switches, sensors, keypads, or other input devices. A microcontroller’s pins may alse be connected to relays, bulbs, motors, actuators, buzzers, LCDs, or other output devices. If a person knows how to program and access the microcontroller’s IO ports, he also knows how to make life easier (or, sometimes, harder).
Stay tuned for the next tutorial and have a nice day.















Hi there! Thank you very much for this great tutorial! I read it with interest and am sure, I am going to use an 8051 for one of my projects. The problem is, I just don’t know how to get the programm I wrote into my microcontroller. Wich kind of programmer do I nead? Thank you!