How Do You Know What Kind of Oscillator to Use for a Pic Microcontroller

This is our 10th tutorial ofLearning PIC microcontrollers using MPLAB and XC8. Till now, we have covered many bones tutorials like  LED blinking with PIC, Timers in Movie, interfacing LCD, interfacing 7-segment, ADC using Moving-picture show etc. If you are an accented beginner, then please visit the complete listing of Picture show tutorials here and start learning.

In this tutorial, we will learnHow to generate PWM signals using Picture PIC16F877A. Our Flick MCU has a special module called Compare Capture module (CCP) which can be used to generate PWM signals. Hither, nosotros volition generate a PWM of 5 kHz with a variable duty cycle from 0% to 100%. To vary the duty cycle we are using a potentiometer, hence it is recommended to learn ADC tutorial before starting with PWM. PWM module also uses timers to gear up its frequency hence acquire how to use timers beforehand hither.  Further, in this tutorial we will employ a RC excursion and a LED to convert the PWM values to Analog voltage and utilise it for dimming the LED light.

What is a PWM Betoken?

Pulse Width Modulation (PWM) is a digital point which is most commonly used in command circuitry. This signal is set high (5v) and low (0v) in a predefined time and speed. The time during which the bespeak stays high is called the "on time" and the time during which the signal stays depression is called the "off time".  There are two important parameters for a PWM equally discussed below:

Duty cycle of the PWM:

The percentage of fourth dimension in which the PWM bespeak remains Loftier (on fourth dimension) is called as duty cycle. If the signal is ever ON it is in 100% duty bicycle and if information technology is ever off it is 0% duty cycle.

Duty Cycle =Turn ON time/ (Turn ON time + Plow OFF time)

pulse-width-modulation-duty-cycle

Frequency of a PWM:

The frequency of a PWM signal determines how fast a PWM completes ane catamenia. One Period is consummate ON and OFF of a PWM signal as shown in the to a higher place effigy. In our tutorial nosotros volition set a frequency of 5KHz.

PWM using PIC16F877A:

PWM signals can exist generated in our Movie Microcontroller by using the CCP (Compare Capture PWM) module. The resolution of our PWM indicate is 10-bit, that is for a value of 0  there volition be a duty cycle of 0% and for a value of 1024 (2^10) there be a duty cycle of 100%. There are two CCP modules in our PIC MCU (CCP1 And CCP2), this means we tin generate two PWM signals on two different pins (pivot 17 and 16) simultaneously, in our tutorial we are using CCP1 to generate PWM signals on pin 17.

The following registers are used to generate PWM signals using our PIC MCU:

  1. CCP1CON  (CCP1 control Register)
  2. T2CON (Timer 2 Command Register)
  3. PR2  (Timer 2 modules Flow Register)
  4. CCPR1L (CCP Register 1 Depression)

Programming Motion picture to generate PWM signals:

In our programme we will read an Analog voltage of 0-5v from a potentiometer and map information technology to 0-1024 using our ADC module. Then we generate a PWM betoken with frequency 5000Hz and vary its duty cycle based on the input Analog voltage. That is 0-1024 volition be converted to 0%-100% Duty cycle. This tutorial assumes that you have already learnt to use ADC in Picture show if not, read it from hither, because nosotros volition skip details almost it in this tutorial.

Then, once the configuration bits are set and plan is written to read an Analog value, we can proceed with PWM.

The following steps should be taken when configuring the CCP module for PWM operation:

  1. Set the PWM period by writing to the PR2 register.
  2. Set the PWM duty wheel by writing to the CCPR1L annals and CCP1CON<5:4> bits.
  3. Make the CCP1 pivot an output by immigration the TRISC<2> bit.
  4. Gear up the TMR2 prescale value and enable Timer2 by writing to T2CON.
  5. Configure the CCP1 module for PWM operation.

There are two important functions in this program to generate PWM signals. Ane is the PWM_Initialize() part which will initialize the registers required to gear up PWM module and then gear up the frequency at which the PWM should operate, the other function is the PWM_Duty() function which volition set up the duty wheel of the PWM signal in the required registers.

PWM_Initialize() {   PR2 = (_XTAL_FREQ/(PWM_freq*iv*TMR2PRESCALE)) - one; //Setting the PR2 formulae using Datasheet // Makes the PWM work in 5KHZ     CCP1M3 = i; CCP1M2 = 1;  //Configure the CCP1 module      T2CKPS0 = 1;T2CKPS1 = 0; TMR2ON = 1; //Configure the Timer module     TRISC2 = 0; // make port pin on C equally output }

The higher up function is the PWM initialize function, in this office The CCP1 module is prepare to utilise PWM by making the scrap CCP1M3 and CCP1M2 as loftier.

CCP-register-in-PIC-Microcontroller

The timer module's prescaler is ready by making the chip T2CKPS0 as high and T2CKPS1 every bit depression the bit TMR2ON is set to beginning the timer.

timer-register-in-PIC-Microcontroller

At present, we have to set the Frequency of the PWM signal. The value of the frequency has to be written to the PR2 register.  The desired frequency can be set up by using the beneath formulae

PWM Period = [(PR2) + i] * four * TOSC * (TMR2 Prescale Value)

Rearranging these formulae to become PR2 will give

PR2 = (Period / (4 * Tosc * TMR2 Prescale )) - ane

We know that Flow = (ane/PWM_freq) and Tosc = (one/_XTAL_FREQ). Therefore.....

PR2 = (_XTAL_FREQ/ (PWM_freq*4*TMR2PRESCALE)) – 1;

Once the frequency is prepare this function need not be called once again unless and until nosotros need to change the frequency again. In our tutorial I have assigned PWM_freq = 5000; then that we can go a 5 KHz operating frequency for our PWM point.

Now allow united states of america fix the duty cycle of the PWM past using the below function

PWM_Duty(unsigned int duty) {       if(duty<1023)   {      duty = ((float)duty/1023)*(_XTAL_FREQ/(PWM_freq*TMR2PRESCALE)); // On reducing //duty = (((bladder)duty/1023)*(1/PWM_freq)) / ((1/_XTAL_FREQ) * TMR2PRESCALE);     CCP1X = duty & 1; //Store the 1st fleck     CCP1Y = duty & 2; //Shop the 0th bit     CCPR1L = duty>>2;// Shop the remining eight bit   } }

Our PWM point has 10-bit resolution hence this value cannot exist stored in a single register since our Picture show has only 8-bit data lines. Then we have apply to other 2 bits of CCP1CON<v:iv> (CCP1X and CCP1Y) to store the last ii LSB and then shop the remaining 8 $.25 in the CCPR1L Register.

The PWM duty cycle time tin be calculated by using the below formulae:

PWM Duty Bike = (CCPRIL:CCP1CON<5:4>) * Tosc * (TMR2 Prescale Value)

Rearranging these formulae to get value of CCPR1L and CCP1CON will give:

CCPRIL:CCP1Con<5:four> = PWM Duty Cycle / (Tosc * TMR2 Prescale Value)

The value of our ADC will be 0-1024 we need that to be in 0%-100% hence, PWM Duty Wheel = duty/1023. Further to convert this duty wheel into a period of fourth dimension we take to multiply it with the period (1/ PWM_freq)

We too know that Tosc = (i/PWM_freq), hence..

Duty = ( ( (float)duty/1023) * (1/PWM_freq) ) / ( (1/_XTAL_FREQ) * TMR2PRESCALE) ;

Resolving the higher up equation will give united states:

Duty = ( (float)duty/1023) * (_XTAL_FREQ / (PWM_freq*TMR2PRESCALE));

Y'all can check the complete program in the Code section below along with the detailed Video.

Schematics and Testing:

As usual let us verify the output using Proteus simulation. The Circuit Diagram is shown below.

PWM-with-PIC-Microcontroller-MPLAB-XC8-circuit-diagram

Connect a potentiometer to 7th pivot to feed in a voltage of 0-5. CCP1 module is with pin 17 (RC2), here the PWM will be generated which tin can be verified using the Digital oscilloscope. Further to convert this into a variable voltage we have used a RC-filter and an LED to verify the output without a scope.

What is a RC-Filter?

An RC filter or a Low laissez passer filter is a unproblematic excursion with ii passive elements namely the resistor and the capacitor. These ii components are used to filter the frequency of our PWM signal and make it a variable DC voltage.

If we examine the circuit, when a variable voltage is applied to the input of R, the capacitor C will begin to accuse. Now based on the value of the capacitor, the capacitor volition take some time to go  fully charged, once charged information technology will block the DC current (Remember capacitors block DC only allows Air conditioning) hence the input DC voltage will appear across the output. The loftier frequency PWM (Air-conditioning betoken) will be grounded through the capacitor. Thus a pure DC is obtained across the capacitor. A value of 1000Ohm and 1uf was found to be advisable for this project.  Calculating the values of R and C involves circuit assay using transfer role, which is out of scope of this tutorial.

RC-low-pass-filter

The output of the program can be verified using the Digital Oscilloscope as shown below, vary the Potentiometer and the Duty wheel of the PWM should change. Nosotros can likewise notice the output voltage of the RC excursion using the Voltmeter. If everything is working as expected we can proceed with our hardware. Further check the Video at the terminate for total process.

PWM-with-PIC-Microcontroller-simulation

Working on Hardware:

The hardware setup of the project is very simple, we are merely going to reuse our Motion-picture show Perf board shown below.

PERF-baord-for-PIC-Microcontroller-tutorials

We will too demand a potentiometer to feed in the analog voltage, I have attached some female terminate wires to my pot (shown below) and so that we can directly connect them to the Picture show Perf board.

Potentiometer-for-PWM-with-PIC-MicrocontrollerPWM-with-PIC-Microcontroller-PerfBoard

Finally to verify the output we need a RC excursion and a LED to see how the PWM signal works, I have simply used a small perf board and soldered the RC circuit and the LED (to control brightness) on to it every bit shown below

PWM-with-PIC-Microcontroller-LED-baord

Nosotros tin can use unproblematic female to female connecting wires and connect them according to the schematics shown to a higher place. One time the connection is done, upload the program to the Picture show using our pickit3 and you should exist able to go a variable voltage based on the input of your potentiometer. The variable output is used to command the brightness of the LED here.

I used my multimeter to mensurate the variable outputs, nosotros can also notice the effulgence of the LED getting changed for different voltage levels.

PWM-with-PIC-Microcontroller-demo-with-multimeter

That's it we have programmed to read the Analog voltage from the POT and convert into PWM signals which in plow have been converted into Variable voltage using RC filter and the result is verified using our hardware. If you have some doubtfulness or get stuck somewhere kindly use the annotate section below, nosotros will exist happy to help you out. The complete working is working in the video.

Also check our other PWM Tutorials on other microcontrollers:

  • Raspberry Pi PWM Tutorial
  • PWM with Arduino Due
  • Arduino Based LED Dimmer using PWM
  • Ability LED Dimmer using ATmega32 Microcontroller

Code

// CONFIG
#pragma config FOSC = HS        // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF       // Watchdog Timer Enable chip (WDT disabled)
#pragma config PWRTE = ON       // Ability-up Timer Enable bit (PWRT enabled)
#pragma config BOREN = OFF      // Brown-out Reset Enable fleck (BOR disabled)
#pragma config LVP = ON         // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3/PGM pin has PGM function; depression-voltage programming enabled)
#pragma config CPD = OFF        // Data EEPROM Retention Code Protection bit (Data EEPROM lawmaking protection off)
#pragma config WRT = OFF        // Wink Program Memory Write Enable bits (Write protection off; all program memory may exist written to by EECON command)
#pragma config CP = OFF         // Wink Program Retentiveness Code Protection bit (Code protection off)

#ascertain _XTAL_FREQ 20000000
#define TMR2PRESCALE 4

#include <xc.h>

long PWM_freq = 5000;

PWM_Initialize()
{
PR2 = (_XTAL_FREQ/(PWM_freq*4*TMR2PRESCALE)) - 1; //Setting the PR2 formulae using Datasheet // Makes the PWM work in 5KHZ
CCP1M3 = 1; CCP1M2 = 1;  //Configure the CCP1 module
T2CKPS0 = 1;T2CKPS1 = 0; TMR2ON = 1; //Configure the Timer module
TRISC2 = 0; // brand port pin on C as output
}

PWM_Duty(unsigned int duty)
{
if(duty<1023)
{

    duty = ((float)duty/1023)*(_XTAL_FREQ/(PWM_freq*TMR2PRESCALE)); // On reducing //duty = (((float)duty/1023)*(i/PWM_freq)) / ((1/_XTAL_FREQ) * TMR2PRESCALE);
CCP1X = duty & one; //Store the 1st scrap
CCP1Y = duty & 2; //Shop the 0th bit
CCPR1L = duty>>ii;// Store the remining 8 fleck
}
}

void ADC_Initialize()
{
ADCON0 = 0b01000001; //ADC ON and Fosc/xvi is selected
ADCON1 = 0b11000000; // Internal reference voltage is selected
}
unsigned int ADC_Read(unsigned char channel)
{
ADCON0 &= 0x11000101; //Immigration the Channel Selection $.25
ADCON0 |= channel<<3; //Setting the required $.25
__delay_ms(2); //Acquisition time to charge hold capacitor
GO_nDONE = 1; //Initializes A/D Conversion
while(GO_nDONE); //Wait for A/D Conversion to complete
render ((ADRESH<<8)+ADRESL); //Returns Result
}

void primary()
{
int adc_value;
TRISC = 0x00; //PORTC equally output
TRISA = 0xFF; //PORTA every bit input
TRISD = 0x00;
ADC_Initialize(); //Initializes ADC Module
PWM_Initialize();  //This sets the PWM frequency of PWM1

  do
{
adc_value = ADC_Read(four); //Reading Analog Aqueduct 0
PWM_Duty(adc_value);

      __delay_ms(50);

  }while(1); //Infinite Loop

}

winklersuffected.blogspot.com

Source: https://circuitdigest.com/microcontroller-projects/pic-microcontroller-pic16f877a-pwm-tutorial

0 Response to "How Do You Know What Kind of Oscillator to Use for a Pic Microcontroller"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel