ARM-day6
#ifndef __UART4_H__
#define __UART4_H__
#include"stm32mp1xx_gpio.h"
#include"stm32mp1xx_rcc.h"
#include"stm32mp1xx_uart.h"
//初始化串口
void uart4_config();
void putchar(char dat); //发送单个字符串
char getchar(); //接收单个字符串
void puts(char *s); //发送字符串
void gets(char *s); //接收字符串
#endif
,main.c
#include "uart4.h"
//手动封装延时函数
void delay_ms(int ms)
{
int i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<2000;j++)
{
}
}
}
int main()
{
//uart4初始化
uart4_config();
char str[128];
while(1)
{
puts(str); //接收一个字符串
gets(str);
}
return 0;
}
src/usr4.c
#include "uart4.h"
void uart4_config()
{
//使能GPIOB\GPIOG\UART4的外设时钟
RCC->MP_AHB4ENSETR |= (0x1<<1);
RCC->MP_AHB4ENSETR |= (0x1<<6);
RCC->MP_APB1ENSETR |= (0x1<<16);
//设置PG11和PB2为管脚复用功能
//PB2
GPIOB->MODER &= (~(0x3<<4));
GPIOB->MODER |= (0x2<<4);
//PG11
GPIOG->MODER &= (~(0x3<<22));
GPIOG->MODER |= (0x2<<22);
//设置PG11为UART4_TX功能
GPIOG->AFRH &= (~(0xf<<12));
GPIOG->AFRH |= (0X6<<12);
//设置PB2为UART4_RX功能
GPIOB->AFRL &= (~(0xf<<8));
GPIOB->AFRL |= (0X8<<8);
//设置串口不使能
USART4->CR1 &= (~0x1);
//设置8位数据位
USART4->CR1 &= (~(0x1<<12));
USART4->CR1 &= (~(0x1<<28));
//设置没有校验位
USART4->CR1 &= (~(0x1<<10));
//设置时钟频率不分频
USART4->PRESC &= (~0xf);
//设置16倍过采样
USART4->CR1 &= (~(0x1<<15));
//设置1位停止位
USART4->CR2 &= (~(0x3<<12));
//设置波特率为115200
USART4->BRR=0X22B;
//使能发送器
USART4->CR1 |= (0X1<<3);
//使能接收器
USART4->CR1 |= (0X1<<2);
//使能串口
USART4->CR1 |= (0X1<<0);
}
//发送单个字符
void putchar(char dat)
{
//当发送数据寄存器中没有数据时可以发送
while (!(USART4->ISR & (0x1<<7)));//当TDR中有数据时阻塞等待没有数据
USART4->TDR = dat;//向发送数据寄存器中写入数据
//等大传输完成函数结束
while (!(USART4->ISR & (0x1<<6)));
}
//接收单个字符
char getchar()
{
//当接收数据寄存器中有有效数据时读取
while (!(USART4->ISR & (0x1<<5)));
//将读取到的数据返回
return USART4->RDR;
}
//发送字符串
void puts(char *s)
{
while(1)
{
if(*s=='\0')
break;
putchar(*s);
s++;
}
//发送一个回车
putchar('\r');
putchar('\n');
}
//接收字符串
void gets(char *s)
{
while(1)
{
//循环接收单个字符,当检测到回车键‘\r’被按下,结束
*s=getchar();
putchar(*s);
if(*s=='\r')
break;
s++;
}
//在接收的字符串最后补上一个'\0'
*s = '\0';
//发送一个'\n'表示在串口工具下一行进行显示
putchar('\n');
}
原文地址:https://blog.csdn.net/wanyu_l/article/details/137807907
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!