I want to avoid the __delay_ms functions and start using timers.
For now i have a very simple project. Generate a square wave with 25% precent duty cycle, and only control the frequency of it between a range of 0 and 5khz with a potentiometer on an analog input.
I created the code below but is doesnt work at all.
#define _XTAL_FREQ 4000000 // Oscillator frequency (4MHz)
void main() {
while(1) {
// Read the value of the potentiometer on pin RA0 (AN0)
ADCON0 = 0b00000001; // Select RA0 as analog input
ADCON0bits.GO_nDONE = 1; // Start the ADC conversion
while (ADCON0bits.GO_nDONE); // Wait for the conversion to complete
// Calculate the frequency based on the potentiometer value
uint16_t potValue = ADRESH << 8 | ADRESL;
uint16_t frequency = 100 + (potValue / 1024.0) * 400; // 100Hz to 500Hz, depending on the potentiometer value
// Generate a square wave on RC2 (pin 17)
T2CON = 0x00; // Turn off Timer2
TMR2 = 0; // Set Timer2 counter to 0
PR2 = (_XTAL_FREQ / (4 * frequency)) - 1; // Calculate PR2 value for the desired frequency
T2CONbits.T2CKPS = 0b11; // Prescaler 1:16
T2CONbits.TMR2ON = 1; // Turn on Timer2
// Wait for a short time (optional)
__delay_ms(100);
}
}
I hope some can help me a little bit with pointing me in how such a function would work.