(一)背景介绍
之前学单片机的时候干过这样一件事,通过PWM波让STM32唱歌通过调节音频和延时来实现,今天刚学了LINUX系统编程正好来演练一下。因为找不到歌谱,所以只能暂时使用CSDN上找到的一个。
程序如下,其实和之前基本一样,就是改了一下底层代码。
(二)软件实现
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <string.h>
#define BUZZER_C 2
//cmd:0 off 1 on
int fd;
//响一次
void beepsound(void)
{
ioctl(fd,1,0);
}
//停止响一次
void beepsoundNo(void)
{
ioctl(fd,0,0);
}
//以一定的频率响一次
void Sound(int frq)
{
int time;
if(frq != 1000)
{
time = 500000/frq;
beepsound();
usleep(time);
beepsoundNo();
usleep(time);
}else
usleep(1000);
}
void playmusic(void)
{
// 低7 1 2 3 4 5 6 7 高1 高2 高3 高4 高5 不发音
int tone[] = {247,262,294,330,349,392,440,294,523,587,659,698,784,1000};//音频数据表
//红尘情歌
int music[]={5,5,6,8,7,6,5,6,13,13,//音调
5,5,6,8,7,6,5,3,13,13,
2,2,3,5,3,5,6,3,2,1,
6,6,5,6,5,3,6,5,13,13,
5,5,6,8,7,6,5,6,13,13,
5,5,6,8,7,6,5,3,13,13,
2,2,3,5,3,5,6,3,2,1,
6,6,5,6,5,3,6,1,
13,8,9,10,10,9,8,10,9,8,6,
13,6,8,9,9,8,6,9,8,6,5,
13,2,3,5,5,3,5,5,6,8,7,6,
6,10,9,9,8,6,5,6,8};
int time[] = {2,4,2,2,2,2,2,8,4, 4, //时间
2,4,2,2,2,2,2,8,4, 4,
2,4,2,4,2,2,4,2,2,8,
2,4,2,2,2,2,2,8,4 ,4,
2,4,2,2,2,2,2,8,4, 4,
2,4,2,2,2,2,2,8,4, 4,
2,4,2,4,2,2,4,2,2,8,
2,4,2,2,2,2,2,8,
4, 2,2,2, 4, 2,2,2, 2,2,8,
4, 2,2,2,4,2,2,2,2,2,8,
4, 2,2,2,4,2,2,5,2,6,2,4,
2,2 ,2,4,2,4,2,2,12};
int yanshi;
int i,e;
yanshi = 10;
for(i=0;i<sizeof(music)/sizeof(music[0]);i++)
{
for(e=0;e<(time[i])*tone[music[i]]/yanshi;e++)
{
Sound(tone[music[i]]);
}
}
}
最后好像效果不佳,还是用PWM效果好一点。等我学会LINUX驱动后在回来重写一下。
int main(void)
{
int melody[] = {50, 50, 50, 50, 200, 200, 200, 400, 400, 500, 500, 500};
int buzzer_c;
char *buzzer="/dev/buzzer_ctl";
buzzer_c=BUZZER_C;
//use ioctl
if((fd=open(buzzer,O_RDWR|O_NOCTTY|O_NDELAY))<0)
{
printf("open %s failes\n",buzzer);
}
else
{
printf("ioctl %s success\n",buzzer);
playmusic();
}
close(fd);
return 0;
}