Turn ON and OFF led using serial communication.

 

 Code : 

#include<reg51.h>                            // Include 8051 library .
void ser_init();                                   // Initialize serial communications.
void tx(unsigned char w);                  // Serial transmission function definition.
unsigned char d;                                // Store the character received from user 
unsigned char rx();                            // Serial receive function definition.
sbit led = P1^0;                                 // Set led bit.

void main()                                      // Main function starts
{
ser_init();                               // Serial function calling. 
d=rx();                                   // Receive data and store it in d.
tx(d);                                      // Transmit data stored in d.

if(d=='O')                                   //  if character is 'O'
{
led = 0;                               // led will turn On.
}

       if(d=='F')                                    // if character is 'F,
{
led = 1;                              // led will turn Off.
}
}
void tx(unsigned char w)                      // Transmit function.
{
SBUF = w;                            // SBUF temporary buffer location where character is stored.
while(TI==0);                       // Wait until transmission completed flag gets high.
TI=0;                                     // Once high , make it zero for the next character. 
}

void ser_init()                                // Serial transmission function
{
SCON = 0X50;                        // Mode 1 (8-bit UART ) 
TMOD = 0X20;                      // Timer 1 in Mode 2.
TH1 = 0XFD;                         // Baud rate of 9600.
TR1 = 1;                                 // Timer run flag enabled.
}

unsigned char rx()                        // Receive function.
{
while(RI==0);             // Wait while receive flag is not high.           
RI=0;                           // Reset the receive flag.
return SBUF;               // Return data received in SBUF.
}

 :  Circuit Diagram

 Led is connected in sinking mode. Sinking mode is when cathode of  LED is connected to Port of 8051 and anode is connected to Vcc.

            A ballast resistor is added in series with led to limit the flow of current through the led and prevent excess current that can blow the led. 

A terminal window is connected to microcontroller 
for serial comm. 

 RxD of  8051 is connected to TxD of terminal.
TxD of  8051 is connected to RxD of terminal.



Character  controlled LED result : 

If  ' O '  is typed led will turn ON.
If  ' F '  is typed led will turn OFF.

Comments