use interrupts

This commit is contained in:
sfokin 2025-03-07 21:57:20 +03:00
parent 4004ef8780
commit 902d94291d

70
main.c
View File

@ -18,35 +18,53 @@
#pragma config IESO = OFF // Internal/External Switchover disabled
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor disabled
void main(void) {
// Clock setup (8MHz)
OSCCON = 0x70; // Internal oscillator at 8MHz
void __interrupt() isr(void) {
INTCONbits.GIE = 0;
TRISIO = 0b00000010; // GP1 input, GP2 output
ANSEL = 0b01000010; // AN1 analog, ADC clock Fosc/32 (ADCS2=1)
// ADC Configuration
ADCON0 = 0x85; // ADC ON, Channel AN1, ADCS=01 (Fosc/32)
// PWM Configuration
PR2 = 0xFF; // PWM period ~1.95kHz
CCP1CON = 0x0C; // PWM mode
T2CON = 0x04; // Timer2 on, prescaler 1:1
while(1) {
ADCON0bits.GO = 1; // Set GO/DONE bit (bit 1)
while(ADCON0bits.GO); // Wait for conversion
// Read 10-bit result
CCPR1L = ((ADRESH & 0x03) << 8) | ADRESL;
if (PIR1bits.ADIF) {
// Read ADC result
unsigned int adc_result = 0;
adc_result = ((ADRESH & 0x03) << 8) | ADRESL;
// Update PWM duty cycle
unsigned int adc_value = ((ADRESH & 0x03) << 8) | ADRESL;
// Set PWM duty cycle
CCPR1L = adc_value >> 2; // Upper 8 bits
CCP1CONbits.DC1B = adc_value & 3; // Lower 2 bits
CCPR1L = adc_result >> 2; // Upper 8 bits
CCP1CONbits.DC1B = adc_result & 0x03; // Lower 2 bits
__delay_ms(10);
// Clear interrupt flag and restart conversion
PIR1bits.ADIF = 0;
ADCON0bits.GO = 1;
}
INTCONbits.GIE = 1;
}
void main(void) {
// Clock setup
OSCCON = 0x70; // 8MHz internal oscillator
// GPIO configuration
TRISIO = 0b00000010; // GP1 input, GP2 output
ANSEL = 0b00000010; // AN1 analog, ADCS2=0 (Fosc/32)
// ADC configuration
ADCON0 = 0x85; // ADON=1, CHS=AN1, ADCS=10 (Fosc/32)
// PWM configuration
PR2 = 0xFF; // PWM period ~7.8kHz (1:1 prescaler)
CCP1CON = 0x0C; // PWM mode
T2CON = 0x06; // Timer2 on, prescaler 1:1
// Interrupt configuration
//PIR1bits.ADIF = 0; // Clear ADC ready flag
PIE1bits.ADIE = 1; // Enable ADC interrupts
INTCONbits.PEIE = 1; // Enable peripheral interrupts
INTCONbits.GIE = 1; // Enable global interrupts
// Start first conversion
ADCON0bits.GO = 1;
while(1) {
// Main loop sleeps between conversions
//SLEEP();
}
}