Warning
This page is located in archive. Go to the latest version of this course pages.

T04 - UART communication

Write a program for Nucleo STM32F401RE to send and receive characters over USART.

Instructions:

  1. Send single character from Nucleo to PC, see template.
  2. Modify template to send string (word or sentence).
  3. Modify template to receive character (or more) and display it on Experimental shield.

Lecture

Template

#include "stm32f4xx.h"
 
#define  setBit(reg, bit)  ((reg) |= (1<<bit))
#define  clrBit(reg, bit)  ((reg) &= ~(1<<bit))
#define  tglBit(reg, bit)  ((reg) ^= (1<<bit))
#define  readBit(reg, bit) ((reg) & (1<<bit))
 
void sendChar (char ch)  {
  while (!readBit(USART2->SR,7));
  USART2->DR = ch;
}
 
/*
 * USART2 init
 * USART2 is connected to APB1 bus
 * USART2 uses PA2 as TX and PA3 as RX
 */
void serial2Init(void){        
  setBit(RCC->APB1ENR, 17);    // Enable APB1 clock
  setBit(USART2->CR1, 13);     // Enable USART2
  setBit(USART2->CR1, 2);      // USART2 - enable receive
  setBit(USART2->CR1, 3);      // USART2 - enable transmit
  USART2->BRR = 1094;           // USART2 baudrate, fclk/(8*baudrate) should work
/*
  * proper clock settings (with 16MHz HSI and PLL)
  * STM32F401 maximum clock is 84MHz
  * Check system_stm32f4xx.c (PLL parameters) and figure out, how to set clock properly
  */
 
  setBit(RCC->AHB1ENR, 0);     // Enable AHB1 clock
  setBit(GPIOA->MODER, 5);     // PA2 alternate function, p. 157 of reference manual
  setBit(GPIOA->MODER, 7);     // PA3 alternate function
 
  GPIOA->AFR[0] |= 0x0700;     // alternate function, PA2 will be USART2_TX
                               // see p. 162 of reference manual
                               // see p. 45 of STM32F401xE datasheet
}                           
 
int main(void)
{
  int i;
 
  serial2Init();
 
  while (1)
  {
    for(i=0;i<500000;i++);
    sendChar('x');
  }
}

courses/be2m37mam/tasks/task04.txt · Last modified: 2019/11/21 12:24 by viteks