在主函数里调试打printf("n: %c ",USART2_RX_BUF[10]);,无论是USART2_RX_BUF[]中的哪一位都是/0。串口1用的例程并未修改,单独使用串口2收发调试没有问题。使用
不是波特率的问题,中断服务程序也没问题。是数据没有传到USART2_RX_BUF吗?
main.c
/****/
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "usart2.h"
extern char j_buf[256];
extern int n_cnt;
extern short angles[3];
int main(void)
{
short axis_x,axis_y,axis_z;
delay_init(); //延时函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
uart_init(115200); //串口初始化为115200
usart2_init(9600); //串口初始化为9600
printf("It's ok");
while(1)
{
j_buf[0] = 0xAA;//数据帧头
j_buf[1] = 0x01;//数据长度
j_buf[2] = 0x01;//读取传感器数据命令
j_buf[3] = 0xAC; //校验和
send_workdata(j_buf,4);//发送至传感器
printf("n: %c ",USART2_RX_BUF[10]);
delay_ms(1000);
}
}
/******/
usart2.c
/*****/
#include "sys.h"
#include "delay.h"
#include "usart2.h"
#include "stdarg.h"
#include "stdio.h"
#include "string.h"
#include "usart.h"
unsigned char j_buf[256]; //缓冲
int n_cnt = 0; //计数标准位
short angles[3]={0}; //存储三个轴的角度
//串口接收缓存区
char USART2_RX_BUF[USART2_MAX_RECV_LEN];
void usart2_init(u32 bound)
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); //串口2时钟使能
USART_DeInit(USART2); //复位串口2
//USART2_TX
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA2
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PA2
//USART2_RX
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PA3
USART_InitStructure.USART_BaudRate = bound;//波特率一般设置为9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式
USART_Init(USART2, &USART_InitStructure); //初始化串口 2
USART2->CR1=USART2->CR1&~(1<<4); //先清除,否则会一直进入idel中断
USART2->SR;
USART2->DR;
USART_Cmd(USART2, ENABLE); //使能串口
//使能接收中断
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//开启中断
//设置中断优先级
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority= 2;//抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
}
void USART2_IRQHandler(void) //串口2中断服务程序
{
u8 res;
res = USART_ReceiveData(USART2);//读取接收到的数据
j_buf[n_cnt] = res;//将读取的数据放到j_buf里去
n_cnt++;
}
void send_workdata(u8 *data,u8 times)
{
int i;
for(i=0;i<times;i++)
{
while((USART2->SR&0X80)==0);
USART2->DR=*(data++);
}
}
|