PIC单片机PWM驱动轰鸣器发出音乐
时间:10-02
整理:3721RD
点击:
下面是C代码,但是始终调试不出,请高手帮忙检查问题,万分感谢.MCU是PIC16LF934
#include <pic.h>
unsigned int music_data[][2]=
{
{587,800},{698,800},{466,1600},{523,800},{587,800},{349,1600},
{466,800},{523,800},{587,800},{698,800},{523,3200},{587,800},
{698,800},{466,1600},{523,800},{587,800},{392,1600},{523,800},
{349,800},{523,800},{587,800},{466,1600},{784,1600},{698,1600},
{784,1600},{466,1600},{587,800},{392,800},{587,1200},{698,400},
{523,3200},{587,800},{698,800},{466,1600},{523,800},{587,800},
{392,1600},{523,800},{349,800},{523,800},{587,800},{466,3200},
{ 0, 0}
};
/*CCP5的PWM初始化*/
void CCP5INIT()
{
OSCCON = 0x72; //内部4M晶震
CCPR5L=0x7F;
CCP5CON=0X3C;
INTCON=0X00;
PR2=0x9F;
TRISE=0X00;
PORTE = 0x00;
}
/****************************************
* 1MS延时函数
****************************************/
void delay_ms(unsigned int Xms)
{
unsigned int i;
unsigned int j;
for(i=0;i<Xms;i++)
for(j=0;j<140;j++)
{
;
}
}
void sound(unsigned int i)
{
unsigned int x;
x=i;
if(x!=0)
{
x=500000/x;
PR2=x;
}
else
{
PR2 = 0x00;
}
}
main()
{
unsigned char i;
CCP5INIT();
T2CON=0X05; //启动TMR24分频
//启动PWM
while(1)
{
while(music_data[i][1])
{
sound(music_data[i][0]);
delay_ms(music_data[i][1]);
i++;
delay_ms(5);
}
delay_ms(4000);
i=0;
}
}
#include <pic.h>
unsigned int music_data[][2]=
{
{587,800},{698,800},{466,1600},{523,800},{587,800},{349,1600},
{466,800},{523,800},{587,800},{698,800},{523,3200},{587,800},
{698,800},{466,1600},{523,800},{587,800},{392,1600},{523,800},
{349,800},{523,800},{587,800},{466,1600},{784,1600},{698,1600},
{784,1600},{466,1600},{587,800},{392,800},{587,1200},{698,400},
{523,3200},{587,800},{698,800},{466,1600},{523,800},{587,800},
{392,1600},{523,800},{349,800},{523,800},{587,800},{466,3200},
{ 0, 0}
};
/*CCP5的PWM初始化*/
void CCP5INIT()
{
OSCCON = 0x72; //内部4M晶震
CCPR5L=0x7F;
CCP5CON=0X3C;
INTCON=0X00;
PR2=0x9F;
TRISE=0X00;
PORTE = 0x00;
}
/****************************************
* 1MS延时函数
****************************************/
void delay_ms(unsigned int Xms)
{
unsigned int i;
unsigned int j;
for(i=0;i<Xms;i++)
for(j=0;j<140;j++)
{
;
}
}
void sound(unsigned int i)
{
unsigned int x;
x=i;
if(x!=0)
{
x=500000/x;
PR2=x;
}
else
{
PR2 = 0x00;
}
}
main()
{
unsigned char i;
CCP5INIT();
T2CON=0X05; //启动TMR24分频
//启动PWM
while(1)
{
while(music_data[i][1])
{
sound(music_data[i][0]);
delay_ms(music_data[i][1]);
i++;
delay_ms(5);
}
delay_ms(4000);
i=0;
}
}
要输出PWM信号,需注意PWM信号的周期和工作循环周期Duty Cycle。有两个寄存器分别存储PWM的周期值Period和工作循环周期值,PR2和CCPRxL.
测量一下蜂鸣器的管脚是否有电平变化
看pic的手册PR2是一个8位的寄存器变量,是不是赋值过大导致不正常呢?
看pic的手册PR2是一个8位的寄存器变量,是不是赋值过大导致不正常呢?
不错的文件,值得收藏