70 lines
2.1 KiB
C
70 lines
2.1 KiB
C
/*
|
|
* File: main.c
|
|
* Author: sfokin
|
|
*
|
|
* Created on March 7, 2025, 4:38 PM
|
|
*/
|
|
#include <xc.h>
|
|
#define _XTAL_FREQ 8000000
|
|
|
|
// Configuration bits
|
|
#pragma config FOSC = INTOSCIO // Internal oscillator
|
|
#pragma config WDTE = OFF // Watchdog disabled
|
|
#pragma config PWRTE = OFF // Power-up Timer disabled
|
|
#pragma config MCLRE = OFF // MCLR pin as digital input
|
|
#pragma config CP = OFF // Code protection off
|
|
#pragma config CPD = OFF // Data code protection off
|
|
#pragma config BOREN = OFF // Brown-out Reset disabled
|
|
#pragma config IESO = OFF // Internal/External Switchover disabled
|
|
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor disabled
|
|
|
|
void __interrupt() isr(void) {
|
|
INTCONbits.GIE = 0;
|
|
|
|
if (PIR1bits.ADIF) {
|
|
// Read ADC result
|
|
unsigned int adc_result = 0;
|
|
adc_result = ((ADRESH & 0x03) << 8) | ADRESL;
|
|
|
|
// Update PWM duty cycle
|
|
CCPR1L = adc_result >> 2; // Upper 8 bits
|
|
CCP1CONbits.DC1B = adc_result & 0x03; // Lower 2 bits
|
|
|
|
// 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();
|
|
}
|
|
} |