单片机正弦波代码
时间: 2023-07-09 10:18:14 浏览: 123
正弦波代码
以下是一段基于AT89C51单片机的正弦波代码:
```c
#include <reg51.h>
#define PI 3.141592654
#define FREQ 50 // 正弦波频率,单位Hz
#define AMP 127 // 正弦波振幅
unsigned char code SinTable[256] = { // 正弦波数据表
128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173,
176, 179, 182, 185, 188, 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221,
224, 226, 229, 232, 235, 238, 240, 243, 246, 248, 251, 253, 255, 258, 260, 263,
265, 267, 269, 272, 274, 276, 278, 280, 282, 284, 286, 288, 289, 291, 293, 294,
296, 297, 299, 300, 301, 302, 303, 304, 305, 306, 306, 307, 307, 308, 308, 308,
308, 308, 308, 308, 308, 307, 307, 306, 306, 305, 304, 303, 302, 301, 300, 299,
297, 296, 294, 293, 291, 289, 288, 286, 284, 282, 280, 278, 276, 274, 272, 269,
267, 265, 263, 260, 258, 255, 253, 251, 248, 246, 243, 240, 238, 235, 232, 229,
226, 224, 221, 218, 215, 212, 209, 206, 203, 200, 197, 194, 191, 188, 185, 182,
179, 176, 173, 170, 167, 164, 161, 158, 155, 152, 149, 146, 143, 140, 137, 134,
131, 128, 125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83,
80, 77, 74, 71, 68, 65, 62, 59, 56, 53, 50, 47, 44, 41, 38, 35,
32, 30, 27, 24, 21, 18, 16, 13, 10, 8, 5, 3, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 3, 5, 8, 10, 13, 16, 18, 21, 24, 27,
30, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77,
80, 83, 86, 89, 92, 95, 98, 101, 104, 107, 110, 113, 116, 119, 122, 125
};
void main() {
unsigned char i = 0;
unsigned long period = 1000000 / FREQ; // 正弦波周期,单位微秒
while(1) {
P0 = AMP + (SinTable[i] - 128); // 输出正弦波
i++;
if(i == 256) i = 0;
delay_us(period / 256); // 延迟
}
}
// 微秒级延迟函数
void delay_us(unsigned int us) {
while(us--) {
_nop_();
_nop_();
_nop_();
_nop_();
}
}
```
需要注意的是,由于单片机输出的是PWM信号而非真正的模拟信号,因此需要一个RC滤波电路将PWM信号转化为模拟信号。
阅读全文