#include "p18F45K20"
//Condiguration BITS declared "#pragma config"
// Using Internal Clock of 8 MHz
#define FOSC 8000000L
// Delay Function
#define _delay_us(x) { unsigned char us;
us = (x)/(12000000/FOSC)|1;
while(--us != 0) continue; }
void _delay_ms(unsigned int ms)
{
unsigned char i;
if (ms == 0) return;
do {
i = 4;
do {
_delay_us(164);
} while(--i);
} while(--ms);
}
void main(void)
{
unsigned int ipwm;
unsigned char direction;
OSCCON=0x70; // Select 8 Mhz internal clock
TRISC = 0x00; // Set All on PORTC as Output
TRISA = 0x03; // Input for RA0 and RA1
ANSEL = 0x01; // Set PORT AN0 to analog input AN1 to AN7 digital I/O
ANSELH = 0x00; // Set PORT AN8 to AN11 as Digital I/O
PORTC = 0x00; // Turn Off all PORTC
/* Init PWM for Full Bridge Output */
CCP1CON=0b01001100; // Full Bridge Forward; P1A, P1C active-high; P1B, P1D active-high
CCPR1L=0; // Start with zero Duty Cycle
T2CON=0b00000101; // Postscale: 1:1, Timer2=On, Prescale = 1:4
PR2=0x65; // Frequency: 4.90 KHz
TMR2=0; // Start with zero Counter
/* Init ADC */
ADCON0=0b00000000; // Select Left justify result. ADC port channel 0
ADCON1=0b00110000; // Select the FRC for 8 MHz
ADON=1; // turn on the ADC conversion module
direction=0; // Start with Forward Direction
ipwm=0;
for(;;) {
if (RA1 == 0) { // Change the Motor Direction when pressed
_delay_ms(1);
if (RA1 == 0) { // Read again for simple debounce
if (direction == 0) {
direction=1; // Reverse direction
P1M1=1;
P1M0=1;
} else {
direction=0; // Forward direction
P1M1=0;
P1M0=1;
}
}
}
ADCbits.GO_DONE=1; // initiate conversion on the channel 0
while(ADCbits.GO_DONE) continue; // Wait conversion done
ipwm = ADRESH; // Get the highest 8 bit MSB result, ignore the 2 bit LSB
CCPR1L=ipwm; // Set the Duty Cycle base on the ADC result
/* Blink the LED attached on RC0 */
RC0=1; // Turn On
_delay_ms(ipwm);
RC0=0; // Turn Off
_delay_ms(ipwm);
}
}
/