开发环境
- Win10 64位
- Keil MDK5
- 【火牛开发板 STM32F103VCT6】
- USB 转串口线(CH340),这里使用RS232的串口,注意区分 TTL电平的
- 5V 直流电源,用于给开发板【牛角座】供电,当然可以使用USB线供电
- J-Link V9,用于调试与下载程序
蜂鸣器
- 开发板上有一个蜂鸣器,这个是【直流】型的,也就是通电就发出声音
- 使用引脚控制,控制GPIO引脚的高低输出即可
- 查看原理图:使用的是PB5
- 注意有个排针跳线,需要使用【跳线帽】短接 JP5的 1、2,这样GPIO 的引脚PB5,才能控制BEEP的导通与关闭
测试程序
- 这里使用RT-Thread,环境搭建可以参考
- 【火牛STM32F103VC】RT-Thread 开发测试环境搭建
- beep.c
#include "beep.h"
#include "board.h"
#include <stdlib.h>
void beep_gpio_init(void)
{
/* set BEEP pin mode to output */
rt_pin_mode(BEEP_PIN, PIN_MODE_OUTPUT);
rt_pin_write(BEEP_PIN, PIN_LOW);
rt_kprintf("%s : beep init\r\n", __func__);
}
void beep_power_on(rt_uint8_t bon)
{
if (bon == 0x00)
{
rt_kprintf("%s : beep off\r\n", __func__);
rt_pin_write(BEEP_PIN, PIN_LOW);
}
else
{
rt_kprintf("%s : beep on\r\n", __func__);
rt_pin_write(BEEP_PIN, PIN_HIGH);
}
}
void beep_test(int argc, char **argv)
{
if (argc < 2)
{
beep_power_on(0x01);
rt_thread_mdelay(200);
beep_power_on(0x00);
}
else
{
int beep_cnt = atoi(argv[1]);
while (beep_cnt > 0)
{
beep_power_on(0x01);
rt_thread_mdelay(50);
beep_power_on(0x00);
rt_thread_mdelay(80);
beep_cnt--;
}
}
}
/* 导出 串口 shell 命令 */
MSH_CMD_EXPORT(beep_test, beep_test);
- beep.h
#ifndef __BEEP_H__
#define __BEEP_H__
#include <rtthread.h>
/* defined the BEEP pin: PB5 */
#define BEEP_PIN GET_PIN(B, 5)
void beep_gpio_init(void);
void beep_power_on(rt_uint8_t bon);
#endif
- 在 main 函数(main 线程)中调用
beep_gpio_init()
初始化 BEEP的控制引脚
测试
- 这里导出了 MSH 串口的命令,这样再串口输入
beep_test 3
这样的命令就可以让蜂鸣器吱吱叫了 - 如:
beep_test 3
,蜂鸣器叫 3声
msh >beep_test 3
beep_power_on : beep on
beep_power_on : beep off
beep_power_on : beep on
beep_power_on : beep off
beep_power_on : beep on
beep_power_on : beep off
小结
- 普通的蜂鸣器控制起来很方便,类似引脚控制
- 注意 shell 命令执行的环境是线程环境,也就是
rt_thread_mdelay(100)
这的延时函数,需要在线程环境中执行,不能在中断环境,如按键中断里执行延时函数 - 如果想使用【按键控制BEEP】,需要线程环境,或使用【工作队列】,这个实现方法,后面再整理出来