Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

// PIC10F202 Software UART - Work 100% with 1200 baudrate.

// email: winnipux2014@gmail.com

/*
Baud � 1bit width in us
1200 � 1/1200=833.33us
2400 � 1/2400=416.66us
4800 � 1/4800=208.33us
9600 � 1/19600=104.16us
19200 � 1/19200=52.08us
38400 � 1/38400=26.04us
57600 � 1/57600=17.36us
115200 � 1/115200=8,68us
230400 � 1/230400=4.34us
250000 � 1/250000=4us
*/

#include <xc.h>
#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4000000
#endif

#define Baudrate 1200 //bps


#define OneBitDelay (1000000/Baudrate)
#define DataBitCount 8 // no parity, no flow control
#define UART_RX GPIObits.GP1 // UART RX pin
#define UART_TX GPIObits.GP0 // UART TX pin
#define UART_RX_DIR GP1 // UART RX pin direction register
#define UART_TX_DIR GP0 // UART TX pin direction register

//Function Declarations
void InitSoftUART(void);
unsigned char UART_Receive(void);
void UART_Transmit(const char);

#pragma config WDTE = OFF // Watchdog Timer


#pragma config CP = OFF // Code Protect
#pragma config MCLRE = OFF // Master Clear Enable

void main()
{
unsigned char ch = 0;

CLRWDT();

TRISGPIO = 0b11111010;

GPIO = 0;

InitSoftUART(); // Intialize Soft UART

while(1)
{
// ch = UART_Receive(); // Receive a character from UART
ch=0xAA;
UART_Transmit(ch); // Echo back that character
ch=0xBB;
UART_Transmit(ch);
ch=0x0D;
UART_Transmit(ch);
}
}

void InitSoftUART(void) // Initialize UART pins to proper values


{
UART_TX = 1; // TX pin is high in idle state

UART_RX_DIR = 1; // Input
UART_TX_DIR = 0; // Output
}

unsigned char UART_Receive(void)


{
// Pin Configurations
// GP1 is UART RX Pin

unsigned char DataValue = 0;

//wait for start bit


while(UART_RX==1);

__delay_us(OneBitDelay);
__delay_us(OneBitDelay/2); // Take sample value in the mid of bit duration

for ( unsigned char i = 0; i < DataBitCount; i++ )


{
if ( UART_RX == 1 ) //if received bit is high
{
DataValue += (1<<i);
}

__delay_us(OneBitDelay);
}

// Check for stop bit


if ( UART_RX == 1 ) //Stop bit should be high
{
__delay_us(OneBitDelay/2);
return DataValue;
}
else //some error occurred !
{
__delay_us(OneBitDelay/2);
return 0x000;
}
}

void UART_Transmit(const char DataValue)


{
/* Basic Logic
TX pin is usually high. A high to low bit is the starting bit and
a low to high bit is the ending bit. No parity bit. No flow control.
BitCount is the number of bits to transmit. Data is transmitted LSB first.

*/

// Send Start Bit


UART_TX = 0;
//__delay_us(OneBitDelay);
__delay_us(104.16); // 9600

for ( unsigned char i = 0; i < DataBitCount; i++ )


{
//Set Data pin according to the DataValue
if( ((DataValue>>i)&0x1) == 0x1 ) //if Bit is high
{
UART_TX = 1;
}
else //if Bit is low
{
UART_TX = 0;
}

// __delay_us(OneBitDelay);
__delay_us(104.16);//9600
}

//Send Stop Bit


UART_TX = 1;
__delay_us(OneBitDelay);
}

You might also like