//*******************************************************************
//www.go8051.com
//Chapter 9
//Making PC Controlled Serial Robot using 8051 Microcontroller on Breadboard
//Created By go8051.com
// Open source
//email : 8051blog@gmail.com
//*******************************************************************

#include<reg51.h>		// Header file for 8051 microcontroller

sbit IN1=P3^7;	 		// Defining Port 3.7 as Input1 for motor
sbit IN2=P3^6;	 		// Defining Port 3.6 as Input2 for motor
sbit IN3=P3^5;		    // Defining Port 3.5 as Input3 for motor
sbit IN4=P3^4;	 		// Defining Port 3.4 as Input4 for motor
unsigned char rx();
void main()				// Start of main function
{   
	IN1=0;				// Declare IN1 pin as Output pin
	IN2=0;				// Declare IN2 pin as Output pin
	IN3=0;				// Declare IN3 pin as Output pin
	IN4=0;				// Declare IN4 pin as Output pin

	TMOD=0x20;			// selecting Timer 1, with mode 8bit auto reload.
	TH1=0xFD;			// setting baud rate = 9600
	SCON=0x50;			// setting the 8bit Control reg which control the SBUF with RC5
	TR1=1;				// starting the timer

	while(1)			// Infinite while loop
	{
		if(rx()=='f')	// if the character received is 'f' then move robot forward			 
		{   
			IN1=1;			// Set IN1 as 1
			IN2=0;			// Set IN2 as 0
			IN3=1;		    // Set IN3 as 1
			IN4=0;	 		// Set IN4 as 0
		}
	    else if(rx()=='l')	// if the character received is 'l' then move robot left			 
		{	
			IN1=0;			// Set IN1 as 0
			IN2=1;			// Set IN2 as 1
			IN3=1;			// Set IN3 as 1
			IN4=0;	  		// Set IN4 as 0
		}
	    else if(rx()=='r')	// if the character received is 'r' then move robot right			 
		{	
			IN1=1;			// Set IN1 as 1
			IN2=0;			// Set IN2 as 0
			IN3=0;			// Set IN3 as 0
			IN4=1;			// Set IN4 as 1
		}
		else if(rx()=='b')	// if the character received is 'b' then move robot backward			 
		{	
			IN1=0;			// Set IN1 as 0
			IN2=1;			// Set IN2 as 1
			IN3=0;			// Set IN3 as 0
			IN4=1;			// Set IN4 as 1
		}
	    else				// if any other character received then stop the robot			 
		{  
			IN1=0;		    // Set IN1 as 0
			IN2=0;			// Set IN2 as 0
		    IN3=0;			// Set IN3 as 0
			IN4=0;	   		// Set IN4 as 0
		}
	}
}

// function to receive the serial data coming from rx pin
unsigned char rx()			
{
	unsigned char val; 	// defining a variable to store the incoming character
	while(RI==0);		// while receive interrupt is 0 loop in this line
	val=SBUF;			// when receive interrupt gets 1 store the incoming value from sbuf register to val variable
	RI=0;				// set the receive interrupt again to zero to reset and again detect new incoming character
	return(val); 		// return the data stored in val vairable in the main program
}