18F ADC Example
This
Analogue to Digital (ADC)
PIC micro example is not only
great for learning how to use ADC with Swordfish, but also to learn how a
Function works. The
Function (colour Gold for
this example) will perform the required task/commands and then return with a
Word variable called Result. you don't need to declare the variable "Result", as its the
sole purpose of using a Function.
In this case, the
Function is called "ADInAsVolt". It gets the
ADC value on channel 0, and converts it to volts, and stores it in the Functions
Result register. Just because the Function is at the start of the program does
not mean
that it is executed at the start - the first line to be executed is "ADCON1
= $07", and the program follows on from there. The command
ADVal = ADInAsVolt instructs the program to call the
function, and store the result in ADVal. Handy!
Device = 18F452
Clock = 20
// some LCD options...
#option LCD_DATA = PORTD.4
#option LCD_RS = PORTD.2
#option LCD_EN = PORTD.3
// uses LCD and AD libraries...
Include "LCD.bas"
Include "ADC.bas"
Include "convert.bas"
Dim ADVal As Word
// Read the AD port and scale for 0.00 - 5.00 volts...
Function ADInAsVolt() As Word
result = (ADC.Read(0) + 1) * 500 / 1024
End Function
// Start Of Program...
ADCON1 = %10000000
ADCON0.7 = 1
ADCON0.6 = 1
DelayMS (150)
LCD.Cls
// main program loop...
While true
ADVal = ADInAsVolt
LCD.MoveCursor (1,1)
LCD.Write("DC Volts = ", DecToStr(ADVal / 100), ".", DecToStr(ADVal, 2), " ")
DelayMS(250)
Wend
Note the PIC's power supply/oscillator are not shown
Voltages over 5V
For voltages that
exceed 5V that you wish to sample, simply use a voltage divider network like the
following;

For best ADC performance of
the
PIC micro, the input impedance should not exceed 2.5K as the PIC's internal
capacitors will take too long too charge/discharge. This isn't really an issue
for most projects though, as you can just change the sample time with a couple
of settings - see the help file of your compiler for more information. I
generally use 10K resistors without any issues.
Video Tutorials:
Also see
this guide for another example of ADC with a 18F4550.
Where you can get the components;
Where you can get
the components;

 | Site Tutorial Index |
|  | 16F PIC Examples |
|  | 18F PIC Examples |
| |  | 7 Segment Displays |
| |  | 7 Segment Displays |
| |  | RS232 and UART |
| |  | Code Snippets |
|  | Handy Tips |