//**************************************************************************
//* MCU : PIC16F886
//* DATE : 20111003 EDITED BY GARY KAO
//* 轉動可變電阻, 透過A/D 10bit轉換, 取ADRESH 8bit結果, 顯示於RB LED
//**************************************************************************
/*
說明:
此AD解析度是10BIT, 若可變電阻接5V分壓, 則每跳動1 BIT變化0.0048V
5 / 1024 = 0.0048
若設定AD結果靠左, 且只取ADRESH, 忽略ADRESL時, 則每跳動1 BIT變化0.0048 * 4 = 0.0195V
因為ADRESL有3 BIT, 表示每次需經過3次,第4次會進位到ADRESH, ADRESH才會加1
所以若將5V分為5區間, 則判斷式設定如下
1. 0.25V / 0.0195 = 12.8
2. 1.25V / 0.0195 = 64
3. 2.5V / 0.0195 = 128
4. 3.75V / 0.0195 = 192
5. 5V / 0.0195 = 256
*/
#include <pic.h>
#include "DELAY.H"
// CONFIG
//__CONFIG(FOSC_INTRC_NOCLKOUT & WDTE_OFF & PWRTE_OFF & MCLRE_ON & BOREN_OFF & DEBUG_ON & CPD_OFF &LVP_ON&WRT_OFF&FCMEN_OFF&IESO_OFF&CP_OFF&BOR4V_BOR21V);
__CONFIG (FOSC_INTRC_CLKOUT & WDTE_OFF & PWRTE_OFF & MCLRE_ON & CP_OFF & CPD_OFF & BOREN_ON & IESO_OFF & FCMEN_OFF & LVP_OFF & DEBUG_ON);
__CONFIG (BOR4V_BOR21V & WRT_OFF);
void InitIO();
void InitAD();
void main(void)
{
InitIO();
InitAD();
OSCCON = 0x61; // Fosc : 4MHz
GIE = 1;
while(1)
{
GO = 1; // enable ad interrupt
}
}
//*****************
// IO INITIALIZE
//*****************
void InitIO()
{
TRISB = 0x00;
PORTB = 0x00;
TRISC = 0X00;
TRISCbits.TRISC2 = 1; // SET RC2 INPUT
//TRISC = 0X04;
}
//*****************
// A/D INITIALIZE
//*****************
void InitAD()
{
TRISA = 0X01;
ANSEL = 0X01;
ADCON0 = 0X00; // RESET ADCON0
ADCS0 = 1; // OSC : FRC
ADCS1 = 1;
ADON = 1; // ENABLE ADC
ADCON1 = 0X00; // VREF : VSS-VDD
ADFM = 0; // 0 : 左對位
ADRESL = 0X00;
ADRESH = 0X00;
//GIE = 1; // ENABLE GLOBLE INT
PEIE = 1;
ADIE = 1; // ENABLE ADC
}
interrupt void AD_isr()
{
if(ADIF == 1)
{
if(ADRESH <= 13)
{
PORTB = 0X00;
}
else if ( (ADRESH <= 64) && (ADRESH > 13) )
{
PORTB = 0X01;
}
else if ( (ADRESH < 128) && (ADRESH > 64) )
{
PORTB = 0X03;
}
else if ( (ADRESH < 192) && (ADRESH >= 128) )
{
PORTB = 0X07;
}
else
{
PORTB = 0X0F;
}
ADIF = 0;
}
}
沒有留言:
張貼留言