您的位置:首页 > 其它

STM32 单片机控制无源蜂鸣器唱歌 欢乐颂

2017-04-23 01:58 976 查看
参考:http://www.tuicool.com/articles/EFfYny2

我基本就是按照以上这个连接里面的来的。其中的define的值就是这些音的频率。

定义各个变量:

#define D0 -1
#define D1 262//频率
#define D2 293
#define D3 329
#define D4 349
#define D5 392
#define D6 440
#define D7 494

#define M1 523
#define M2 586
#define M3 658
#define M4 697
#define M5 783
#define M6 879
#define M7 987

#define H1 1045
#define H2 1171
#define H3 1316
#define H4 1393
#define H5 1563
#define H6 1755
#define H7 1971

uint16_t tune_durt[98][2] = {//曲子{频率,节拍}
{M3,8},{M3,8},{M4,8},{M5,8},
{M5,8},{M4,8},{M3,8},{M2,8},
{M1,8},{M1,8},{M2,8},{M3,8},
{M3,12},{M2,4},{M2,16},

{M3,8},{M3,8},{M4,8},{M5,8},
{M5,8},{M4,8},{M3,8},{M2,8},
{M1,8},{M1,8},{M2,8},{M3,8},
{M2,12},{M1,4},{M1,16},

{M2,8},{M2,8},{M3,8},{M1,8},
{M2,8},{M3,4},{M4,4},{M3,8},{M1,8},
{M2,8},{M3,4},{M4,4},{M3,8},{M2,8},
{M1,8},{M2,8},{D5,8},{M3,8},

{M3,8},{M3,8},{M4,8},{M5,8},
{M5,8},{M4,8},{M3,8},{M4,4},{M2,4},
{M1,8},{M1,8},{M2,8},{M3,8},
{M2,12},{M1,4},{M1,16},

{M2,8},{M2,8},{M3,8},{M1,8},
{M2,8},{M3,4},{M4,4},{M3,8},{M1,8},
{M2,8},{M3,4},{M4,4},{M3,8},{M2,8},
{M1,8},{M2,8},{D5,8},{M3,8},

{M3,8},{M3,8},{M4,8},{M5,8},
{M5,8},{M4,8},{M3,8},{M4,4},{M2,4},
{M1,8},{M1,8},{M2,8},{M3,8},
{M2,12},{M1,4},{M1,16}

};
uint16_t length_of_whole_music=98;
uint16_t music_tune=0,music_last_tune=0,music_durt_length,durt_count=0;
uint16_t where_is_singing=0;
uint16_t length_of_music_meter=2;//the time of one meter in music
uint16_t music_gap_count=0;
uint16_t music_gap_length=3;


进行控制变量的操作

music_last_tune=music_tune;

if(durt_count>=music_durt_length)
{
if(music_durt_length<5)//if this tune is very short, no music_gap.
{
music_gap_count=music_gap_length;
}
music_gap_count++;
if(music_gap_count>=music_gap_length)//music gap£ºthe gap between two meters
{
music_gap_count=0;

where_is_singing++;
if(where_is_singing>=length_of_whole_music)
{
where_is_singing=0;
}

durt_count=0;
music_durt_length=tune_durt[where_is_singing][1]*length_of_music_meter;
music_tune=tune_durt[where_is_singing][0];
}
}

durt_count++;


利用控制变量对单片机底层进行操作:

if(music_gap_count>0)
{
PWM_Rate_Set ( 0, &htim1, TIM_CHANNEL_1);//no sound in gap(设置占空比)
}
else
{
PWM_Rate_Set ( 50, &htim1, TIM_CHANNEL_1);
}

if(music_last_tune!=music_tune)//change tune
{
PWM_Set( music_tune, htim1, TIM_CHANNEL_1);//(初始化频率)
HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_2);
}


最后当然是成功啦~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单片机 stm32