写一段51单片机代码,实现电压采集并显示在数码管和输出pwm功能
时间: 2024-05-28 22:09:06 浏览: 23
好的,以下是代码:
#include <reg51.h>
#define DISPLAY_PORT P0
sbit PWM_OUT = P2^0;
unsigned int adc_value = 0;
void delay(unsigned int x){
while(x--);
}
void init_adc(){
ADC_CONTR = 0x80; // 开启ADC电源
delay(100); // 延时等待ADC电源稳定
ADC_CONTR = 0x90; // 配置ADC工作方式
// P1.0作为ADC输入口,选择ADC通道0
// ADC采样时间为12个时钟周期
// ADC转换结果右对齐
ADC_RES = 0;
ADC_RESL = 0;
}
unsigned char get_adc_result(){
ADC_CONTR |= 0x08; // 开始ADC转换
while(!(ADC_CONTR & 0x10)); // 等待转换完成
ADC_CONTR &= ~0x10; // 清除转换完成标志
return ADC_RES;
}
void display(unsigned char num){
static unsigned char code table[] = {
0xC0, 0xF9, 0xA4, 0xB0,
0x99, 0x92, 0x82, 0xF8,
0x80, 0x90
};
DISPLAY_PORT = table[num];
}
void main(){
init_adc();
while(1){
adc_value = get_adc_result();
display(adc_value % 10);
delay(1000);
display(adc_value / 10);
delay(1000);
PWM_OUT = (adc_value >= 512) ? 1 : 0;
}
}
注意:本代码仅供参考,具体实现需要根据硬件情况进行修改。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)