microcontroller lab
題目
連結可能失效!!!
/*
* File: lab10.c
* Author: mickeytseng
*
* Created on December 8, 2020, 10:46 PM
*/
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <pic18f4520.h>
#pragma config OSC = INTIO67 // Oscillator Selection bits
#pragma config WDT = OFF // Watchdog Timer Enable bit
#pragma config PWRT = OFF // Power-up Enable bit
#pragma config BOREN = ON // Brown-out Reset Enable bit
#pragma config PBADEN = OFF // Watchdog Timer Enable bit
#pragma config LVP = OFF // Low Voltage (single -supply) In-Circute Serial Pragramming Enable bit
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#define _XTAL_FREQ 4000000
void main(void) {
/*
// 設定TIMER2, prescaler為4
T2CON = 0b01111101;
// 設定OSC頻率,Fosc為125k = Tosc為8µs
OSCCONbits.IRCF = 0b001;
// 設定CCP1
CCP1CONbits.CCP1M = 0b1100;
// 將RC2設定為輸出,並初始化(因為CCP1和RC2是同一個port)
TRISC = 0;
LATC = 0;
// 設定pr2和ccp的數字來調整輸出的PWM週期和Duty Cycle
// period = (PR2+1)*4*Tosc*(TMR2 prescaler) = (0x9b + 1) * 4 * 8µs * 4 = 0.019968s ~= 20ms
PR2 = 0x9b;
// duty cycle = (CCPR1L:CCP1CON<5:4>)*Tosc*(TMR2 prescaler) = (0x0b*4 + 0b01) * 8µs * 4 = 0.00144s ~= 1450µs
CCPR1L = 0x0b;
CCP1CONbits.DC1B = 0b01;
// Demo時需要向TAs解釋如何設定Tosc和PR2以及CCPR1L和CCP1CON,並且計算出如何得到週期20ms以及duty cycle的500µs和2400µs。
return;
*/
//set clock to 4 MHz
OSCCONbits.IRCF = 0b110;
//set RD as output
TRISD = 0;
LATD = 0;
//set RA0 as input
TRISA = 0b00000001;
PORTA = 0;
LATA = 0;
//set AN0 as analog input
;ADCON1bits.PCFG = 0b1110;
ADCON0bits.CHS = 0b0000;
//set Vref- and Vref+ as Vss and Vdd
ADCON1bits.VCFG1 = 0;
ADCON1bits.VCFG0 = 0;
//set A/D on
ADCON0bits.ADON = 1;
//set Tad ADCS as 4Tosc
ADCON2bits.ADCS = 0b100;
//set TACQ to 4Tad
ADCON2bits.ACQT = 0b010;
//set Right justified
ADCON2bits.ADFM = 1;
//Clear ADIF
PIR1bits.ADIF = 0;
//Set ADIE
PIE1bits.ADIE = 1;
//Set GIE
INTCONbits.GIE = 1;
INTCONbits.PEIE = 1;
//configure ADIP
IPR1bits.ADIP = 1;
ADCON0bits.GODONE = 1;
__delay_us(4);
while(1){
}
}
void __interrupt(high_priority) ADC_ISR (){
unsigned int number = 0;
number = number | ADRESH;
number = number << 8;
number = number | ADRESL;
unsigned char i = 0;
while(number > 68){
number -= 68;
i++;
}
LATD = i;
PIR1bits.ADIF = 0;
ADCON0bits.GODONE = 1;
__delay_us(4);
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up