Sunday 22 October 2017

USART of STM32F103C8T6

USART  of STM32F103C8T6

Steps to program USART of Stm32f103c8t6 in Asynchronous mode. Create new project in keil for STM32F103C8T6 .
create uart.c in this file create four functions 
Function1 UartInit : It should take argument  baudrate and function should not return anything
/*1) Enable Alternate Function  use register APB2ENR of RCC structure  set bit0 for AF */
   RCC->APB2ENR|=(1<<0);
/*2) Clear UART remap (in stm32f UART pins can be remapped to other GPIO pins)
use register MAPR of AFIO structure bit2 if zero UART1 PA9/Tx PA10/Rx  if one UART1 PB6/Tx PB7/Rx*/
AFIO->MAPR&=~(1<<2);
/*3) Enable Port-A
use register APB2ENR of RCC structure bit2 is Port-A*/
 RCC->APB2ENR|=(1<<2);
/*4) Clear Port-A9 and A10  by placing zeros in bits 4-11
use register CRH of GPIOA structure*/
GPIOA->CRH&=~(0x0FF<<4);
/*5) PA9-Tx Alternate output push-pull
use register CRH of GPIOA structure 0b1011 into bits 4-7*/
GPIOA->CRH|=(0x0B<<4);
/*6) PA10-Rx Alternate Input floating
use register CRH of GPIOA structure 0b0100 into bits 8-11*/
GPIOA->CRH|=(0x04<<8);
/*7) Enable Clock to UART
use register APB2ENR of RCC structure bit14 is UART*/
 RCC->APB2ENR|=(1<<14);
/*8) Enable USART , TX , Rx 
use register CR1 of UART1 structure bit 13 bit2, bit3*/
USART1->CR1|=((1<<13)|(1<<2)|(1<<3));
/*9) Set baudrate as f=((float)(72Mhz/16)/baudrate) extract fraction part from it
and multiply it by 16(to get atleast 4 bit fraction part)*/
f=((float)(72000000/16)/baudrate);
q=(((int)f)&0x0FFF);
k=(float)(f-(float)q);
k=(float)(k*16);
/*10)place integer part of f(12bits) and fraction part(4bits) in BRR register
 use register BRR of UART1 structure*/
USART1->BRR=((q<<0)|(((int)k&0x0F)<<8));


 Function2 UartTx: It should take argument as unsigned char and should not return anything
 /*11)For Transmission of Data See bit7 of Status Register
wait when bit7 is zero transmit data when it is 1
use register SR of USART1 structure for status and DR for data
also wait untill Transmission is complete see bit6 of Status Register*/
while(!(USART1->SR&(1<<7)));
USART1->DR=c;

Function3 UartRx: It should not take any argument and it should return unsigned char
/*
12) For Receiption of Data See bit5 of Status Register
wait when bit5 is zero receive when bit5 is 1
*/
 while(!(USART1->SR&(1<<5)));
 return (USART1->DR);


Function4 UartStr:It should take argument as unsigned char* and should not return anything
while(*p!='\0')
  UartTx(*p++); 








Finally write main function which should invoke UartInit(baudrate), UartStr("string"),
superloop should not end