uart.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
void uart4_config();
void putchar(char c);
char getchar();
void gets(char *src);
void puts(char *src);
int strcmp(char *src,char *dest);
#endif
uart4.c
#include "uart4.h"
// UART4的初始函数
void uart4_config()
{
// 使能UART.GPIOG\GPIOB的外设时钟
RCC->MP_APB1ENSETR |= (0x1 << 16);
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
// 设置PB2为复用功能
GPIOB->MODER &= (~(0X3 << 4));
GPIOB->MODER |= (0X2 << 4);
// 设置PB2为UART_RX复用功能
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x8 << 8);
// 设置PG11为复用功能
GPIOG->MODER &= (~(0X3 << 22));
GPIOG->MODER |= (0X2 << 22);
// 设置PG11为UART_RX复用功能
GPIOB->AFRL &= (~(0xf << 12));
GPIOB->AFRL |= (0x6 << 12);
// 禁用串口,UE=0
USART4->CR1 &= (~0x1);
// 设置8位数据位
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
// 设置无奇偶校验
USART4->CR1 &= (~(0X1 << 10));
// 设置1位停止位
USART4->CR2 &= (~(0x3 << 12));
// 设置波特率为115200
USART4->BRR = 0x22b;
// 设置频率不分频
USART4->PRESC &= (~(0xF));
// 设置16倍过采样倍数
USART4->CR1 &= (~(0x1 << 15));
// 使能发送
USART4->CR1 |= (0x1 << 3);
// 使能接收
USART4->CR1 |= (0x1 << 2);
// 使能串口
USART4->CR1 |= 0x1;
}
// 封装单个字符发送函数
void putchar(char c)
{
// 判断发送数据寄存器是否为空,不空则阻塞等待
while(!(USART4->ISR & (0X1 << 7)))
;
// 当为空时将数据写入到数据发送寄存器
USART4->TDR = c;
// 阻塞等待数据发送完毕,函数结束
while(!(USART4->ISR & (0X1 << 6)))
;
}
// 封装单个字符接收的函数
char getchar()
{
// 判断接收数据寄存器中有没有有效数据。如果没有就阻塞等待,如果有直接读取
while(!(USART4->ISR & (0X1 << 5)))
;
// 将读取的数据返回
return USART4->RDR;
}
// 发送一个字符串
void puts(char *src)
{
while(*src)
{
putchar(*src);
src++;
}
// 发送完字符串让光标显示在下一行最开头
putchar('\n');
putchar('\r');
}
// 接收字符串
void gets(char *src)
{
while(*src)
{
*src = getchar();
putchar(*src); // 将读取到的字符回显到串口
if (*src == '\r')
{
break;
}
src++;
}
// *src = '\0'; // 手动补上一个'\0'
putchar('\n'); // 让光标显示在下一行
}
//判断输入指令
int strcmp(char *src,char *dest)
{
while((*src++==*dest++)&&(*src!='\0'));
return *src==*dest?0:-1;
}
main.c
#include "led.h"
#include "uart4.h"
#include "gpio.h"
// 手动封装一个延时函数
// void delay_ms(int ms)
// {
// int i, j;
// for (i = 0; i < ms; i++)
// {
// for (j = 0; j < 2000; j++)
// {
// }
// }
// }
int main()
{/*
//使能GPIO的外设时钟
*((unsigned int *)0X50000A28) |= (0X3<<4);
led1_init();
led2_init();
led3_init();
while(1)
{
//LED1亮
led1_ctl(1);
led2_ctl(0);
led3_ctl(0);
delay_ms(500);
//LED2亮
led1_ctl(0);
led2_ctl(1);
led3_ctl(0);
delay_ms(500);
delay_ms(500);
//LED3亮
led1_ctl(0);
led2_ctl(0);
led3_ctl(1);
delay_ms(500);
delay_ms(500);
// }
uart4_config();
char a;
char buf[32];
while (1)
{
// a=getchar();//读取一个字符
// putchar(a+1);//将读取到的字符+1返回
gets(buf); // 读取字符串
puts(buf);
}*/
//使能PE、PF时钟
// *((unsigned int *)0x50000A28) |= (0x3<<4);
led1_init();
// led2_init();
led3_init();
uart4_config();
char buf[32];
while (1)
{
/*
a=getchar();
putchar(a+1);
*/
gets(buf);
if (strcmp(buf, "led1_on") == 0)
{
led1_ctl(1);
}
else if(strcmp(buf, "led1_off") == 0){
led1_ctl(0);
}
}
return 0;
}