There are two main portions of code that we are concerned with:
-The Initializations
-Forever While Loop
The compiler used for this project is the C18 Compiler Provided Free From Micropchip. The first part of this software initailizes the A/D converter and the PWM module in the PIC.
PIC Initializations For Motor Control
------------« Begin Code »------------
.. ... /* Timer2 Prescalary Details: 0b00 = Prescalar x 1 0b01 = Prescalar x 4 0b10 = Prescalar x 16 */ T2CONbits.T2CKPS0 = 0; T2CONbits.T2CKPS1 = 0; // PWM Frequency = [(period ) + 1] x 4 x TOSC x TMR2 prescaler // Tosc = 20 MHz // TMR2 Prescalar = 1 // Period = 128 // PWM Frequency = (256) x 4 x (1/20,000,000) x 1 = 19.5 KHz OpenPWM1( period ); //Motor Initially Off SetDCPWM1( speed_0 ); // configure A/D convertor OpenADC( ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_20_TAD, ADC_CH0 & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS & ADC_INT_OFF, 0 ); ... ..
------------« End Code »------------
This next chunk of code is the forever while loop which controls the motor and LED bar. This loop, takes the sensor input data, evaluates it and then outputs to the LED Bar and Motor depending upon the distance detected.
Forever Control/While Loop
------------« Begin Code »------------
while(1){ Delay10TCYx( 5 ); // Delay for 50TCY ConvertADC(); // Start conversion while( BusyADC() ); // Wait for completion result = ReadADC(); // Read result //Update Motor Speed Setting & LED Bar if(result < dist_6cm && result > dist_8cm){ SetDCPWM1( speed_8 ); PORTD = 0xFF; } else if(result < dist_8cm && result > dist_10cm){ SetDCPWM1( speed_7 ); PORTD = 0xFE; } else if(result < dist_10cm && result > dist_12cm){ SetDCPWM1( speed_6 ); PORTD = 0xFC; } else if(result < dist_12cm && result > dist_14cm){ SetDCPWM1( speed_5 ); PORTD = 0xF8; } else if(result < dist_14cm && result > dist_16cm){ SetDCPWM1( speed_4 ); PORTD = 0xF0; } else if(result < dist_16cm && result > dist_18cm){ SetDCPWM1( speed_3 ); PORTD = 0xE0; } else if(result < dist_18cm && result > dist_20cm){ SetDCPWM1( speed_2 ); PORTD = 0xC0; } else if(result < dist_20cm && result > dist_22cm){ SetDCPWM1( speed_1 ); PORTD = 0xFE; } else if(result < dist_22cm){ SetDCPWM1( speed_0 ); PORTD = 0x00; } Delay10KTCYx( 5 ); // Delay for 50TCY }
------------« End Code »------------
These are the two main portions of the program. Download the full .c file at the top of the page to see the small things I left out. Give it a compile with the C18 libraries in MPLAB, load the hex file onto the PIC and the system is ready to go!