基于51单片机的dds信号发生器
时间: 2023-10-03 10:09:37 浏览: 107
要实现基于51单片机的DDS信号发生器,需要一些硬件和软件资源。
硬件资源:
1. 51单片机
2. AD9850芯片
3. LCD1602液晶显示屏
4. 其他相关电子器件
软件资源:
1. Keil C51编译器
2. 相关的C语言库函数
下面是一个基于51单片机的DDS信号发生器的示例代码:
```c
#include <reg51.h>
#define FREQ0 1000.0 //默认输出频率为1kHz
#define FREQ1 125000.0 //AD9850的参考频率为125MHz
unsigned long int frequency; //用于存储输出频率
unsigned char phase; //用于存储输出相位
void delay(unsigned int t) //简单的延时函数
{
unsigned int i, j;
for (i = 0; i < t; i++)
for (j = 0; j < 125; j++);
}
void write_ad9850(unsigned char data) //向AD9850写入8位数据
{
unsigned char i;
for (i = 0; i < 8; i++)
{
if (data & 0x80)
P2 |= 0x02;
else
P2 &= ~0x02;
P2 |= 0x04;
P2 &= ~0x04;
data <<= 1;
}
}
void set_frequency(unsigned long int freq) //设置输出频率
{
unsigned long int delta;
unsigned char i;
delta = freq / FREQ1 * 4294967296.0;
write_ad9850(0x20);
write_ad9850(delta >> 24);
write_ad9850(delta >> 16);
write_ad9850(delta >> 8);
write_ad9850(delta);
write_ad9850(0x0);
write_ad9850(0x0);
write_ad9850(0x0);
write_ad9850(0x0);
P2 &= ~0x08;
P2 |= 0x08;
}
void set_phase(unsigned char ph) //设置输出相位
{
unsigned char i;
ph = ph % 360;
ph = ph / 1.41;
write_ad9850(0xC0);
write_ad9850(ph);
write_ad9850(0x0);
write_ad9850(0x0);
write_ad9850(0x0);
}
void lcd_init() //初始化LCD1602液晶显示屏
{
delay(15);
P0 = 0x30;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x30;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x30;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x38;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x08;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x01;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x06;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
P0 = 0x0C;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
}
void lcd_display(unsigned char row, unsigned char column, unsigned char *str) //在LCD1602液晶显示屏上显示字符串
{
unsigned char i;
if (row)
column |= 0x40;
column |= 0x80;
P0 = column;
P2 &= ~0x01;
delay(5);
P2 |= 0x01;
delay(5);
for (i = 0; str[i]; i++)
{
P0 = str[i];
P2 |= 0x04;
P2 &= ~0x04;
delay(5);
}
}
void main()
{
unsigned char buf[16];
frequency = FREQ0;
phase = 0;
lcd_init();
set_frequency(frequency);
set_phase(phase);
while (1)
{
sprintf(buf, "Freq:%dHz", frequency);
lcd_display(0, 0, buf);
sprintf(buf, "Phase:%d", phase);
lcd_display(1, 0, buf);
delay(200);
}
}
```
这个示例代码使用了AD9850芯片来生成DDS信号,并通过LCD1602液晶显示屏显示当前的输出频率和输出相位。在代码中还实现了设置输出频率和相位的函数,并通过按键等外部输入来修改这些参数。你可以根据自己的需求进行修改和扩展。
阅读全文