Monday, September 1, 2014

PIC 16F1788 Analog Inputs

Another stumbling point in my adventure into the Enhanced 14 bit core was the Analog to Digital converter module.  The PIC16F1788 has optional differential analog ports, and I am using AN0 as a single ended analog signal input.  There are 4 bits in the ADCON2 register that select the negative side of the differential analog input which I had set for AN0, so AN0 was selected for both the positive, and negative input, thus there was no difference, and all I got were zeros from the ADC Module.  Once I realized this, and changed the negative side of the differential input to ground then the ADC Module started producing numbers, and I got my Analog input working.  Then I had to play with the format of the ADC numbers to get the Pulse Width Modulation Module working correctly.  The ADC is generating 12 bit numbers, and the PWM Generator Duty Cycle Register is a 10 bit number.  So what we'll do is shift the ADC over two bits, throw away the two least significant bits, effectively dividing the 12 bit number by 4, and making it a 10 bit number.
Now the analog input, and PWM Module are working right, I had a need to adjust the PWM Period to get the PWM Frequency right.  It was running at 250 Hz, and the target is 1 KHz.  This is an adjustment to the Timer 2 prescaler, which was set for 64, and I changed it to 16 to kick the frequency up times 4.  The above video shows the results of these endeavors.  The goal was to have a 1 KHz PWM signal to be a speed control of a fan motor, with a analog input signal to control the duty cycle.