新手上路
- 积分
- 25
- 金钱
- 25
- 注册时间
- 2023-12-6
- 在线时间
- 4 小时
|
6金钱
void USART2_Init(uint32_t clk, uint32_t baudrate)
{
//1.开启GPIOA和USART2的时钟
RCC->AHB1ENR |= (0x1 << 0);
RCC->APB1ENR |= (0x1 << 17);
//2.配置GPIOA的工作模式
//2.1配置输入/输出模式(PA2-复用推挽输出、PA3-浮空输入)
GPIOA->MODER &= ~(0x3 << 4);
GPIOA->MODER |= (0x2 << 4);
GPIOA->MODER &= ~(0x3 << 6);
GPIOA->MODER |= (0x2 << 6);
//2.2配置输出类型(PA2-推挽)
GPIOA->OTYPER &= ~(0x1 << 2);
GPIOA->OTYPER &= ~(0x1 << 3);
//2.3配置输出速度(50MHz)
GPIOA->OSPEEDR &= ~(0x3 << 4);
GPIOA->OSPEEDR |= (0x2 << 4);
GPIOA->OSPEEDR &= ~(0x3 << 6);
GPIOA->OSPEEDR |= (0x2 << 6);
//2.4配置复用功能
GPIOA->AFR[0] &= ~(0xFF << 8);
GPIOA->AFR[0] |= (0x77 << 8);
//3.配置USART2
//3.1配置波特率(9600)
uint32_t brr = (clk * 1000000 + baudrate / 2) / baudrate;
USART2->BRR |= brr;
//3.2选择过采样模式(16倍采样)
USART2->CR1 &= ~(0x1 << 15);
//3.3选择字长(1 起始位,8 数据位,n 停止位)
USART2->CR1 &= ~(0x1 << 12);
//3.4选择奇偶校验控制(无校验)
USART2->CR1 &= ~(0x1 << 10);
//3.5接收中断使能(RXNE)
USART2->CR1 |= (0x1 << 5);
//3.6空闲中断使能(IDLE)
USART2->CR1 |= (0x1 << 4);
//3.7发射器使能(TE)
USART2->CR1 |= (0x1 << 3);
//3.8接收器使能(RE)
USART2->CR1 |= (0x1 << 2);
//3.9设置停止位(1位)
USART2->CR2 &= ~(0x3 << 12);
//3.10设置NVIC
NVIC_SetPriority(USART2_IRQn, 6);
//3.11使能NVIC
NVIC_EnableIRQ(USART2_IRQn);
//4.使能USART2
USART2->CR1 |= (0x1 << 13);
}
/* 发送一个字节数据 */
void USART2_SendByte(uint8_t byte)
{
//1.等待发送寄存器为空
while((USART2->SR & 0x80) == 0);
//2.将数据写入DR寄存器
USART2->DR |= byte;
}
/* 发送多个字节数据 */
void USART2_SendNByte(uint8_t *buff, uint16_t size)
{
//1.循环发送
for(uint16_t i = 0; i < size; i++)
{
//2.等待发送寄存器为空
while((USART2->SR & 0x80) == 0);
//3.将数据写入DR寄存器
USART2->DR |= buff;
}
}
/* 中断服务函数 */
void USART2_IRQHandler(void)
{
//1.判断是否为接收中断
if((USART2->SR & 0x20) == 0x20)
{
//2.将数据读入接收缓冲区
buff[size] = USART2->DR;
size++;
}
//3.判断是否为空闲中断
else if((USART2->SR & 0x10) == 0x10)
{
//4.清楚IDLE中断标志位
USART2->DR;
//5.将数据发送到串口显示器
USART2_SendNByte(buff, size);
//6.将size清零
size = 0;
}
}
#include "delay.h"
#include "usart.h"
#include "led.h"
#include "key.h"
#include "buzzer.h"
#include "rs485.h"
/* 全局变量 */
uint8_t buff[100] = {0};
uint16_t size = 0;
/* 主函数入口 */
int main(void)
{
/* 中断优先级分组 */
NVIC_SetPriorityGrouping(4);
/* 外设初始化 */
Stm32_Clock_Init(336, 8, 2, 7);
delay_init(168);
LED_Init();
KEY_Init();
Buzzer_Init();
USART2_Init(42, 9600);
printf("串口2测试\n");
while(1)
{
USART2_SendNByte(buff, size);
delay_ms(500);
}
}
#ifndef __RS485_H
#define __RS485_H
/******************** 头文件引用 ********************/
#include "stm32f4xx.h"
#include "stdio.h"
/******************** 全局变量声明 ******************/
extern uint8_t buff[100];
extern uint16_t size;
/******************** 函数声明 **********************/
/* USART2初始化(RS485) */
void USART2_Init(uint32_t clk, uint32_t baudrate);
/* 发送一个字节数据 */
void USART2_SendByte(uint8_t byte);
/* 发送多个字节数据 */
void USART2_SendNByte(uint8_t *buff, uint16_t size);
/* 重写fputc */
int fputc(int ch, FILE *file);
#endif
|
|