#include "stm32l0xx.c"
#include <stdint.h>
#define GPIOAEN (1U<<0)
#define UART2AEN (1U<<17)
#define SYS_CLCK (16000000UL)
#define APB1_CLK SYS_CLCK
#define BAUDRATE (115200UL)
#define CR1_TE (1U<<3)
#define CR1_UE (1U<<0)
#define ISR_TXE (1<<7)
static void uart_set_baudrate(USART_TypeDef *USARTx,uint32_t PeriphClk,uint32_t baudrate);
static uint16_t compute_uart_bd(uint32_t PeriphClk,uint32_t baudrate);
void uart2_tx_init(void);
int main (void)
{
Serial.begin(115200);
uart2_tx_init();
while(1)
{
uart2_write('H');
uart2_write('\n');
myDelay();
}
return 0;
}
void uart2_write(int ch)
{
/*Check Data Register is empty*/
while(!(USART2->ISR & ISR_TXE));
/*Write data to data register*/
USART2->TDR =(ch & 0xff);
}
void uart2_tx_init(void)
{
/******** configure uart pin********/
/*Enable clock to access GPIOA*/
RCC->IOPENR =GPIOAEN;
/*Set PA2 to alternate function mode*/
GPIOA->MODER &=~(1<<4);
GPIOA->MODER |=(1<<5);
/*Set PA2 alternate function type to uart2_tx AF[04]*/
GPIOA->AFR[0] &=~(1<<16);
GPIOA->AFR[0] &=~(1<<17);
GPIOA->AFR[0] |=(1<<18);
GPIOA->AFR[0] &=~(1<<19);
/******** configure uart module********/
/*Enable clock to access uart2*/
RCC->APB1ENR |= UART2AEN;
/*Configure baudrate */
uart_set_baudrate(USART2,APB1_CLK,BAUDRATE);
/*Configure the transfer direction*/
USART2->CR1 =CR1_TE;
/*Enale the uart mode */
USART2->CR1 |=CR1_UE;
}
static void uart_set_baudrate(USART_TypeDef *USARTx,uint32_t PeriphClk,uint32_t baudrate)
{
USARTx->BRR=compute_uart_bd(PeriphClk,baudrate);
}
static uint16_t compute_uart_bd(uint32_t PeriphClk,uint32_t baudrate)
{
return ((PeriphClk+ (baudrate/2U))/baudrate);
}
void myDelay()
{
for(volatile long i=0; i<100000;i++);
}