fork download
  1. #include <xc.h>
  2.  
  3. // Configuration bits
  4. #pragma config FOSC = HS
  5. #pragma config WDTE = OFF
  6. #pragma config PWRTE = ON
  7. #pragma config BOREN = ON
  8. #pragma config LVP = OFF
  9. #pragma config CPD = OFF
  10. #pragma config WRT = OFF
  11. #pragma config CP = OFF
  12.  
  13. #define _XTAL_FREQ 20000000
  14.  
  15. void PWM_Init()
  16. {
  17. TRISC2 = 0; // CCP1 pin as output
  18.  
  19. // PWM Frequency ≈ 5 kHz
  20. PR2 = 249;
  21.  
  22. CCP1CON = 0x0C; // PWM mode
  23.  
  24. T2CON = 0x04; // Timer2 ON, Prescaler 1
  25.  
  26. CCPR1L = 0; // Initial duty cycle
  27. }
  28.  
  29. void PWM_SetDuty(unsigned int duty)
  30. {
  31. if(duty > 1023)
  32. duty = 1023;
  33.  
  34. CCPR1L = duty >> 2;
  35.  
  36. CCP1CONbits.DC1B0 = duty & 0x01;
  37. CCP1CONbits.DC1B1 = (duty & 0x02) >> 1;
  38. }
  39.  
  40. void ADC_Init()
  41. {
  42. ADCON0 = 0x41; // AN0 selected, ADC ON
  43. ADCON1 = 0x80; // Right justified
  44. }
  45.  
  46. unsigned int ADC_Read()
  47. {
  48. GO_nDONE = 1;
  49.  
  50. while(GO_nDONE);
  51.  
  52. return ((ADRESH << 8) + ADRESL);
  53. }
  54.  
  55. void main()
  56. {
  57. unsigned int adcValue;
  58.  
  59. PWM_Init();
  60. ADC_Init();
  61.  
  62. while(1)
  63. {
  64. adcValue = ADC_Read(); // 0–1023 from potentiometer
  65.  
  66. PWM_SetDuty(adcValue); // Control motor speed
  67.  
  68. __delay_ms(10);
  69. }
  70. }
Success #stdin #stdout 0.02s 25648KB
stdin
Standard input is empty
stdout
#include <xc.h>

// Configuration bits
#pragma config FOSC = HS
#pragma config WDTE = OFF
#pragma config PWRTE = ON
#pragma config BOREN = ON
#pragma config LVP = OFF
#pragma config CPD = OFF
#pragma config WRT = OFF
#pragma config CP = OFF

#define _XTAL_FREQ 20000000

void PWM_Init()
{
    TRISC2 = 0;      // CCP1 pin as output

    // PWM Frequency ≈ 5 kHz
    PR2 = 249;

    CCP1CON = 0x0C;  // PWM mode

    T2CON = 0x04;    // Timer2 ON, Prescaler 1

    CCPR1L = 0;      // Initial duty cycle
}

void PWM_SetDuty(unsigned int duty)
{
    if(duty > 1023)
        duty = 1023;

    CCPR1L = duty >> 2;

    CCP1CONbits.DC1B0 = duty & 0x01;
    CCP1CONbits.DC1B1 = (duty & 0x02) >> 1;
}

void ADC_Init()
{
    ADCON0 = 0x41;   // AN0 selected, ADC ON
    ADCON1 = 0x80;   // Right justified
}

unsigned int ADC_Read()
{
    GO_nDONE = 1;

    while(GO_nDONE);

    return ((ADRESH << 8) + ADRESL);
}

void main()
{
    unsigned int adcValue;

    PWM_Init();
    ADC_Init();

    while(1)
    {
        adcValue = ADC_Read();    // 0–1023 from potentiometer

        PWM_SetDuty(adcValue);    // Control motor speed

        __delay_ms(10);
    }
}