【LINUX系统编程】系统延时函数让蜂鸣器放⾳乐
(⼀)背景介绍
之前学单⽚机的时候⼲过这样⼀件事,通过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,
linux系统安装步骤csdn
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);
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。