基于51单片机的定时器LCD显示正弦波的频率相关程序
时间: 2023-07-02 14:17:08 浏览: 106
以下是一个基于51单片机的定时器LCD显示正弦波频率的示例程序:
```c
#include <reg51.h>
#include <math.h>
#define PI 3.1415926
#define FREQ_CONST 1000
sbit RS = P1^0;
sbit RW = P1^1;
sbit E = P1^2;
void delay_us(unsigned int n)
{
while(n--)
{
_nop_();
}
}
void delay_ms(unsigned int n)
{
while(n--)
{
delay_us(1000);
}
}
void write_command(unsigned char command)
{
RS = 0;
RW = 0;
E = 1;
P2 = command;
delay_us(1);
E = 0;
}
void write_data(unsigned char data)
{
RS = 1;
RW = 0;
E = 1;
P2 = data;
delay_us(1);
E = 0;
}
void init_lcd()
{
write_command(0x38);
write_command(0x0c);
write_command(0x06);
write_command(0x01);
}
void display_freq(unsigned int freq)
{
char freq_str[16];
sprintf(freq_str, "Freq: %d Hz", freq);
init_lcd();
for(int i=0; i<strlen(freq_str); i++)
{
write_data(freq_str[i]);
}
}
void main()
{
unsigned int freq;
unsigned long int time_count;
unsigned int sin_wave;
unsigned char timer_low, timer_high;
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
TR0 = 1;
init_lcd();
while(1)
{
time_count = TH0 * 256 + TL0;
freq = FREQ_CONST / time_count;
display_freq(freq);
sin_wave = sin((time_count / 1000.0) * 2 * PI) * 127 + 128;
timer_low = sin_wave;
timer_high = sin_wave >> 8;
P3 = timer_low;
P2 = timer_high;
delay_ms(10);
}
}
```
在此示例程序中,我们使用了定时器0来计算正弦波的频率,同时使用P2和P3口输出正弦波。
在主循环中,我们计算当前时间计数值,并根据计数值计算正弦波的幅值,在P2和P3口输出幅值,同时在LCD上显示正弦波的频率。
需要注意的是,在此示例程序中,我们使用了数学库的sin函数来计算正弦波的幅值,因此需要在编译器中开启数学库的支持。
阅读全文