0% found this document useful (0 votes)
26 views2 pages

Code REport

This document contains C code for initializing and using USART1 on an STM32F4 microcontroller. It sets up the GPIO for transmission, configures the USART module with a specified baud rate, and includes a loop that continuously sends the character 'Y'. The code demonstrates basic USART communication through direct register manipulation.

Uploaded by

jimjammyjimmyjam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2 pages

Code REport

This document contains C code for initializing and using USART1 on an STM32F4 microcontroller. It sets up the GPIO for transmission, configures the USART module with a specified baud rate, and includes a loop that continuously sends the character 'Y'. The code demonstrates basic USART communication through direct register manipulation.

Uploaded by

jimjammyjimmyjam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdint.

h>
#include <stdio.h>
#include "stm32f4xx.h"

//Defines
#define GPIOA_EN (1U << 0)
#define USART1_EN (1U << 4)
#define CR1_TE (1U << 3)
#define CR1_UE (1U << 13)
#define SR_TXE (1U << 7)

#define SYS_FREQ 16000000


#define APB2_CLK SYS_FREQ

#define USART_BAUDRATE 115200

//Prototypes
static void usart_set_baudrate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t
BaudRate);
static uint16_t compute_usart_bd(uint32_t PeriphClk, uint32_t BaudRate);
void usart1_write(int ch);
void usart1_tx_init(void);

int main(void)
{
usart1_tx_init();

while (1){
usart1_write('Y');
}

return 0;
}

void usart1_tx_init(void) {
//CONFIGURE USART GPIO PIN
//Enable clock GPIOA
RCC->AHB1ENR |= GPIOA_EN;
//Set PA9 to Alternate Function
GPIOA->MODER &= ~(0x03 << 18);
GPIOA->MODER |= (0x02 << 18);
//Set PA9 (TX) to AF07
GPIOA->AFR[1] &= ~(0x0F << 4);
GPIOA->AFR[1] |= (0x07 << 4);

//CONFIGURE USART MODULE


//Clock access to USART1
RCC->APB2ENR |= USART1_EN;
//Set Baudrate
usart_set_baudrate(USART1, APB2_CLK, USART_BAUDRATE);
//Set transfer direction
USART1->CR1 = CR1_TE; //This will reset the entire register
also. Reset values are desired.
//Enable USART Module
USART1->CR1 |= CR1_UE;

static void usart_set_baudrate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t


BaudRate){
USARTx->BRR = compute_usart_bd(PeriphClk, BaudRate);
}

static uint16_t compute_usart_bd(uint32_t PeriphClk, uint32_t BaudRate){


return ((PeriphClk + (BaudRate / 2U))/BaudRate);
}

void usart1_write(int ch){


//Check transmit is empty
while (!(USART1->SR & SR_TXE)){}
//Write to transmit DR
USART1->DR = (ch & 0xFF);
}

You might also like