Analog-to-PWM Conversion with the PIC18f4620

The main function below is reproduced with the kind permission of Robert Byrne who is using it in an Instrumentation project. His program is an adaptation of my PIC18F4620 template code that I posted recently, so to form a complete program it should be copied and pasted into that template code in place of the original main function.

The primary purpose of Robert’s program is to convert an analog sensor voltage into a PWM signal for transmission onwards to a PLC or other device with an appropriate input. The resolution of both the ADC and the PIC’s PWM generator is 10-bit. Robert also modified the setup function very slightly to select external voltage references for the ADC, but that change is not shown here. Finally, the program transmits the numerical value of each reading serially as text over the USART.

// Written by Robert Byrne 11-4-2011

void main(void)
    unsigned int v;


        // Read analog value once a second
        v = read_analog_channel(0);

        // Update PWM duty cycle
        CCPR1L = v / 4; // 8 MSbs of duty cycle
        CCP1CONbits.DC1B1 = (v & 0b00000010) > 0;
        CCP1CONbits.DC1B0 = (v & 0b00000001) > 0;

        // Print result over serial connection
        printf("v = %d\r\n", v);

        // 120ms delay
This entry was posted in PIC and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s