代码是阿波罗767的串口通信的代码,也就是能在串口调试助手里看到自己发送的数值。后面我就想能不能通过电脑在串口上发送特定的数值使单片机读取串口数值后进行判断,从而驱动LED灯的开和关。于是就在主函数里加了一个标志位flag来接收串口缓存区的数值,并且用if语句来判断这个flag是否为0,如果不为0,就灭,如果为0,就亮。编译后没有报错。程序下载完成后,没接串口前,也就是单片机还没从串口读取数据时,灯时亮的,表示串口缓存区里的值为0,可以理解。当接上串口后,发送了1,灯也灭了,说明串口缓存区的值1赋给flag,使flag不为0,执行关灯操作,也可以理解。但是,当发送0过去后,led灯确没有再亮起来,就有点不太明白为什么了。按理来说这个时候flag应该被赋0然后执行点亮操作才对。难道串口输入0,赋给flag的值不是0吗?那怎样才能给flag赋0呢?萌新请求大神指教。以下是代码,具体操作在主函数的while语句里。
#include "sys.h"
#include "delay.h"
#include "usart.h"
#include "led.h"
u8 rdatabuff[1];
UART_HandleTypeDef uart1_hand1;
void chuankou_init()
{
uart1_hand1.Instance=USART1;
uart1_hand1.Init.BaudRate=115200;
uart1_hand1.Init.WordLength=UART_WORDLENGTH_8B;
uart1_hand1.Init.StopBits=UART_STOPBITS_1;
uart1_hand1.Init.HwFlowCtl=UART_HWCONTROL_NONE;
uart1_hand1.Init.Mode=UART_MODE_TX_RX;
uart1_hand1.Init.Parity=UART_PARITY_NONE;
HAL_UART_Init(&uart1_hand1);
}
void HAL_UART_MspInit(UART_HandleTypeDef *huart)//串口回调函数
{
GPIO_InitTypeDef GPIO_Initure;
if(huart->Instance==USART1)
{
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_USART1_CLK_ENABLE();
GPIO_Initure.Pin=GPIO_PIN_9 | GPIO_PIN_10;
GPIO_Initure.Mode=GPIO_MODE_AF_PP;
GPIO_Initure.Pull=GPIO_PULLUP;
GPIO_Initure.Speed=GPIO_SPEED_HIGH;
GPIO_Initure.Alternate=GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOA,&GPIO_Initure);
HAL_NVIC_SetPriority(USART1_IRQn,3,3);//设置中断优先级
HAL_NVIC_EnableIRQ(USART1_IRQn);//使能中断通道
}
}
void USART1_IRQHandler(void)
{
HAL_UART_IRQHandler(&uart1_hand1);
HAL_UART_Receive_IT(&uart1_hand1,rdatabuff,sizeof(rdatabuff));//使能开启串口接收中断
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
u8 rdata;
if(huart->Instance==USART1)
{
rdata=*((huart->pRxBuffPtr)-1);
//rdata=rdatabuff[0];
HAL_UART_Transmit(&uart1_hand1,&rdata,1,1000);
}
}
int main(void)
{
u8 flag;
//u8 buff[]="test";
Cache_Enable(); //打开L1-Cache
HAL_Init(); //初始化HAL库
Stm32_Clock_Init(432,25,2,9); //设置时钟,216Mhz
delay_init(216);
chuankou_init();
LED_Init();
HAL_UART_Receive_IT(&uart1_hand1,rdatabuff,sizeof(rdatabuff));//使能接收中断
while(1)
{
flag=((u8)rdatabuff[0]);
if(flag)
{
LED0(1);//led0口上拉,使led熄灭
delay_ms(100);
}
else LED0(0);//led0口接地,使led亮起
delay_ms(100);
}
}
|