Yes I’ll try. From all the Arduino programming, hopefully I’ll know a thing or two on how to write in C.
But first, when installing MPLAB, make sure that you have installed the Hi-Tech C Compiler also, you will be prompted when the MPLAB installation is done.
Next, when creating a project file, choose the Hi-Tech Universal Toolsuite. In it you will find the C Compiler.
That’s about it when creating a project. I’ll attempt to re-write my assembly code for the ADC Demo I’ve done in a previous post.
I’m using a 10k potentiometer to vary the voltage going into Analog Channel 0. The ADC will convert that voltage input and store it in ADRESH. From there, the code will decide how many LEDs will turn on. The higher the input voltage, the more LEDs will turn on. Without further ado, let’s get to the code.
Here it is and it took me quite a while to write this simple code. Done some heavy googling to find equivalent functions for set bit and clear bit. I’ll try to explain the code line by line. Also, I have tested this code on the actual hardware and it works just the same like my old code written in assembly language.
First I got the set bit, clear bit, flip bit and test bit function code from an online forum. For the initialization, we need to include pic.h and htc.h. That’s where all the function is from. Now instead of calculating the delay manually, we can use the delay function. But of course the compiler needs to know what is your oscillator frequency. I’ve set it to 4MHz because that’s what I’m using. The delay function is given by _delay(in seconds), __delay_ms(in ms) and __delay_us(in us). That’s far more easier than using assembly code.
The configuration of the ADC is self-explanatory. The following infinite while loop is to test whether the ADC conversion is completed or not. If completed, the code will start testing the values of ADRESH to determine how large it is and correspondingly decide how many LEDs to turn on.
If the value of ADRESH is more than 40, the 1st LED will turn on. If the value of ADRESH is more than 80, the 2nd LED will turn on. That goes on in increments of 40 until it reaches 200. Yes I know 255 is the maximum but I don’t need accuracy in this code, this is just a demo to show the capabilities of the ADC.
I hope this will help some of my readers out there. If you have any questions, feel free to ask me. I’ll be glad to answer them (if I can 🙂 ).