STM32单片机外接扩展板D2、D3接开关S2和S3,D9、D10、D11接RGB三色LED灯,要求每次按下S2开关一次,三色灯按红、绿、蓝颜色变化,每次按下S3开关一次,三色灯按蓝、绿、红颜色变化,每次颜色变化时,通过串行口向计算机发送“按下按钮:SX,当前颜色是:X色!”
时间: 2023-07-04 18:16:12 浏览: 85
你想要实现的这个功能比较简单,可以通过 C 语言编写程序来实现。首先,需要初始化相关引脚的状态和串口通信,可以参考以下代码:
```c
#include "stm32f10x.h"
void GPIO_Configuration(void);
void USART_Configuration(void);
int main(void)
{
GPIO_Configuration();
USART_Configuration();
uint8_t color = 0;
uint8_t button = 0;
while(1)
{
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0) // S2按下
{
color = 1 - color; // 0表示红色,1表示绿色
button = 2;
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0); // 等待按键释放
}
else if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == 0) // S3按下
{
color = 2 - color; // 0表示蓝色,1表示红色
button = 3;
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == 0); // 等待按键释放
}
// 根据颜色值控制RGB三色灯
switch(color)
{
case 0:
GPIO_SetBits(GPIOB, GPIO_Pin_9);
GPIO_ResetBits(GPIOB, GPIO_Pin_10);
GPIO_ResetBits(GPIOB, GPIO_Pin_11);
break;
case 1:
GPIO_ResetBits(GPIOB, GPIO_Pin_9);
GPIO_SetBits(GPIOB, GPIO_Pin_10);
GPIO_ResetBits(GPIOB, GPIO_Pin_11);
break;
case 2:
GPIO_ResetBits(GPIOB, GPIO_Pin_9);
GPIO_ResetBits(GPIOB, GPIO_Pin_10);
GPIO_SetBits(GPIOB, GPIO_Pin_11);
break;
}
// 通过串口发送按键和颜色信息
switch(button)
{
case 2:
printf("按下按钮:S2,当前颜色是:%s色!\n", color == 0 ? "红" : "绿");
break;
case 3:
printf("按下按钮:S3,当前颜色是:%s色!\n", color == 1 ? "红" : "蓝");
break;
}
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
// S2和S3按键
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// RGB三色灯
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void USART_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// USART1 Tx
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// USART1 Rx
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
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(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
```
需要注意的是,上述代码中的串口通信使用的是 USART1,Baud Rate 为 115200。如果你使用的是其他的串口通信方式,需要进行相应的修改。