- #include <pic18f452.h>
- #include <stdio.h>
- // 配置位设置
- #pragma config OSC = HS // 使用外部高速晶振
- #pragma config WDT = OFF // 关闭看门狗定时器
- #pragma config LVP = OFF // 关闭低电压编程
- // 定义AD转换结果变量
- unsigned int adc_result = 0;
- // 初始化AD模块
- void ADC_Init() {
- ADCON1 = 0x0E; // 配置AN0为模拟输入,其他引脚为数字I/O
- ADCON2 = 0x92; // 右对齐结果,TAD = 12 TOSC,ACQT = 12 TAD
- ADCON0 = 0x01; // 使能AD模块,选择AN0通道
- }
- // 读取AD转换结果
- unsigned int ADC_Read() {
- ADCON0bits.GO = 1; // 启动AD转换
- while (ADCON0bits.GO); // 等待转换完成
- return ((unsigned int)ADRESH << 8) | ADRESL; // 返回10位AD结果
- }
- // 主程序
- void main() {
- // 初始化
- TRISA = 0xFF; // 设置PORTA为输入
- TRISB = 0x00; // 设置PORTB为输出
- ADC_Init(); // 初始化AD模块
- while (1) {
- adc_result = ADC_Read(); // 读取AD转换结果
- PORTB = adc_result >> 2; // 将AD结果的高8位输出到PORTB(10位结果右移2位)
- __delay_ms(100); // 延时100ms
- }
- }
|