Skip to content

Instantly share code, notes, and snippets.

@marioIncandeza
Created October 23, 2015 01:05
Show Gist options
  • Save marioIncandeza/e8b5b13f353f644e72bc to your computer and use it in GitHub Desktop.
Save marioIncandeza/e8b5b13f353f644e72bc to your computer and use it in GitHub Desktop.
PWM Motor Control with TMR2 on RC2
// PIC16F887 Configuration Bit Settings
#include <xc.h>
// CONFIG1
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator: High-speed crystal/resonator on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled and can be enabled by SWDTEN bit of the WDTCON register)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON // RE3/MCLR pin function select bit (RE3/MCLR pin function is MCLR)
#pragma config CP = OFF // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF // Brown Out Reset Selection bits (BOR disabled)
#pragma config IESO = OFF // Internal External Switchover bit (Internal/External Switchover mode is disabled)
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is disabled)
#pragma config LVP = OFF // Low Voltage Programming Enable bit (RB3 pin has digital I/O, HV on MCLR must be used for programming)
// CONFIG2
#pragma config BOR4V = BOR40V // Brown-out Reset Selection bit (Brown-out Reset set to 4.0V)
#pragma config WRT = OFF // Flash Program Memory Self Write Enable bits (Write protection off)
void init()
{
ANSEL = 0X02;
ANSELH = 0x00;
TRISA = 0xFF; //set PORTA input
TRISC = 0x00; //set PORTC output
PORTC = 0;
ADCON1 = 0x00; //Left justify A/D result, use VDD and VSS as voltage references
ADCON0 = 0x05; //system clock Fosc/2,select RA0(AN0) as analog channel,turn on A/D module, but don't set GO yet
PR2 = 0xFF;
CCP1CON = 0x0C; //single output pwm mode on RC2/CCP1
CCPR1L = 0xFF; //start duty cycle high
TMR2IF = 0;
T2CON = 0x07; // tmr2 enable
TRISC = 0xFB; //set RC2 output
}
void main()
{
init(); //call initialize function to setup ports and configure A/D settings
while(1) //infinite loop
{
GO = 1; //start conversion
while(GO);
CCPR1L = ADRESH;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment