Вы находитесь на странице: 1из 12
su0/2017 powering you with sls PO eee ‘Analog a Digital Converter in PIC Microcontroller ~XCé | Student Companion SA CONTACT US Analog to Digital Converter in PIC Microcontroller - XC8 Posted by on Friday, 24 May 20 sa9s: 15 Comments reece ie Les) Pog on Watch the Video Tutorial Most of PIC microcontrollers today have built-in analog ta digital converters (ADO) with the number of channels depending on the number of pins a particular microcontroller have. Analog signals: Directly measurable quantities in terms of some other quantity Some examples: ‘Thermometer: The mercury liquid inside the thermometer rises as Car Speedometer: Needle ofa car speedometer moves farther right as you accelerate ‘Audio Amplifier: The volume of an audio amplifier increases as you turn the kaos, Digital Signals: Have only two states.0 or 1,0 or off Example: A switch can be either an or off bulit in ADC channels, the (28 pins) has 40 (28 pins) has 7 builtin ADC channels etc. The (40 pins) nas 3 built in ADC channels, the hitp:lwwnstucentcompanion.c,za/analog-o-digita-converter-in-pie-microcontrolt-xc8! Stay Update: Boom’ Search Here Custom Sear| (Sama) febsite into your Selecone oiioma¥ Please support our work with a Donation Writing tutors and ecording orl videos lot fre ra sand time. you Coton Rene ey tree BU) foley eee eau) rd Google Cloud Categories we suiov2017 ‘Analg pins Nota thet Chama 6 Figure 1: ADC Channels These analog to digital converters allow analeg continuous voltages to be converted into discreet digital numbers inside the PIC as the PIC can only pracess digital numbers, This can enable 2 PIC to be connectee to analog sensors such as temperature sensors, pressure sensors, humidity sensor, optical sensors, and power sensors. [Any sensor which can generate a voltage between QV and a maximum SV can be used. If the output voltage is higher than SV, a method to step it down should be used such as @ voltage divider with resistors Conversion To convert an analog signal to digital format, we have two main steps to process: 41, Quantizing whichis basically to break down analog value in a set set of finite states Example: Let say you have 0-5V signals. ‘The number of possible states thatthe converter can out where mis the numberof bits in the AD converter For a3 bit ND converter, N=2°8 ‘Analog quantization size: Q-(¥max-VminJN = (SV ~ OVY/8 = 0.625V. We will have a set of voltages from 0 to SV in a set of discrete states with 0.625V + ovtoos25v = 0625v%0 1.25 = L25ve0 1a75v = 1875Vt0 25V = 25Vt0 3.125 = 3.125Vt0 375 = 3.75vt0 4375 = 4375V00 5¥ The resolution ofthe converter indicates the numberof discrete values it ean produce over the range of analogue values, The resolution is usually expressed in bits and itis equals to the quantization size (Q) (@)= Vrange / 2*n, where Vrange is the range of analog voltages which can be represented The higher the resolution, the accurate the converted value. Most of PIC38F ricrocontrollers have analog channels with a 10-bit resolution. 2. Encoding which is now to assign a digital word or number to each state anc ‘matching it to the input signal IF0V is detected by a 10-bit ADC channel, then once the conversion is complete, 00 0000 (0000 should be stored in memory. On the other extreme, if 5Vis detected by the ADC channel, 11 1411 1111 should be stored in memory. Any value in between will produce a corresponding binary number htpwwstucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! ‘Analog to Digital Converter in PIC Microcontroller — XC8 | Student Companion SA repre 7) owen frei Foweade orc 2 apn Ur artce 7) arnt of Tas) mia fr PE ra xc (3) maser (8) Recent Posts Getting Started wit Easy20A 2 web-basee PCB Design Sotnare ‘raw Cite Fre with EasyEOA {onvating a PIC Meoconalie ram 2 PC Graphical User Interac (CU Introduc'on o Progamming Mcoconrllers vith Floncade Ve Getting Started with Raspberry Pi Popular Posts Astomatc Temperature Be _ 5 AB contro systern using PIC | Mierconater = Mio 54398 eaten iy 28 Ieracing LCD Dsplay Win Pe Mleecontlir = a Free Professional CV Teriates ago reer ns ) Modem with PIC Vag) cosa commana we Addy Google 1 ent Peer a 3Pi Cnr Pea Recent Topics in the Forum ‘eyo input probier. by! "beth 112 ours, 11 minates 290 ana svio2017 ‘Analog to Digital Converter in PIC Microcontrller— XC8 | Student Companion SA = Receba nosso Guia sobre pearininhaiaimaiaaal Integridade de Dados-Fagao download ‘rte testy! Ter 7 cess oy! Tayor Jor boost Parts by tyr ADC Configuration with MPLAB Code 2 iment age Configurator Subscribe to our Newsletter MPLAB is phasing out the PICLBF Peripheral Library which is no longer included in XCB from v1.35. In this version, you have to download and install them separately into you compiler and they are now called Legacy Peripheral Libraries. Enter emai ‘Subserbe | Unsubscribe The MPLAB® Code Configurator (MCQ) isa user friendly Graphical User Interface (GUI) plugrin tool for MPLAB® X IDE which generates easy to understand C code that is inserted Into an MPLAB® X project, based on the settings peripherals configurations and selections ‘made in the Graphical User Interface (GUN. The advantage of MCC, it can generate codes not only for PICIBF but for a wide range of PICs including PICL6F and PIC24 series. Key words “Seana ADC Arn Carer guidance (0M gt Temanear To learn more, ead the article: MPLAB® Code Configurator Entrepreneurship evens: Flowcode Flowcode VS coats sss below isthe ADC configuration wth MCC Inths example we ae wing the «x Interfacing i rob courD PICLEF26K20. These are our configurations was Microcontroller MikroC meas code configurator + Clock Source: F05C/2 :AD Clock source definitions (select clock frequency used MPLAB X vtas,ce Open a new fret sme Ame wae business PIC acu acer PIC lt also affects duration of conversion) The clack i critical to produce the fastest but also accurate Analog to Digital Conversion Communication Projects wm RS252 esp cara 21 SUCESS Sich = Acq TAD, One full 10-bit conversion requires 11 TAD perioes. For corect conversion the appropriate TAD specification must be met. Check your device datasheet to get the {ADC conversion requirements, for PICLBF26K20 the min TAD is 0.7 uS and max 25 jon Time: 2 TAD: The time to complete one bit conversion is defined as Tutorials user nasuce Wealth XCB = Result Alignment: Right. You can Right justity or Left justify the result * Positive Reference: we are using the VDD (+5V) as the postive reference. = Negative Reference: We are using the VSS (OV) as our negative reference = Channel ANo: In the Pin Manager, we enabled pin RAO which is Analog Channel Like Us On Facebook Sroune Meta Register og in enies RSS Figure 2: ADC Configuration with MCC Comments BSS WoroPressong htpwwstucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! ana suiov2017 ‘Then all we need to do is cick on generate to generate our source and header files. Figure 3 below shows the generated files. The Header files adch, mech, pin_managerh and Source files ade, mec and pin_managerc. Figure 3: MCC generated files “The functions we can use with the ADC module are declared in the adch file: = ADC Initialize(): This routine initializes the Initializes the ADC. This routine must be called before any other ADC routine is called. This routine should only be called (once during system initialization, = ADC StartConversion(ade_channel t channel): This routine is used to select desired channel for conversion. The ADC. Initialize function should have been called before calling this function. ‘= ADC IsConversionDone(): This routine is used to determine it conversion is completed. When conversion is complete routine returns tre. It returns false othenwise, = ADC_GetConversionResult(): This routine is used to get the analog to digital converted value, This routine gets converted values from the channel specified Example: TInRIEE converteaVaTuey s0c_tnittetized; /7niviotize 10C ADe_StartConversion(ANi Channel); /7/Start conversion on channel ANA WwhiTe(ADC_TetorverstendaneQ); 7 Check if conversion is done ‘convertedValue — ADC GetConverstontesult(); // Get the results = ADC GetConversion(ade_channel t channel): This routine is used to select desired ‘channel for conversion and to get the analog to digital converted value, htpwwstucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! ‘Analog to Digital Converter in PIC Microcontroller — XC8 | Student Companion SA ana svio2017 Loot Figure 4: Displaying analog voltage from ANO Below is the main. fle: The voltage across the potentiometer connected to AND is read and display on the lcd as shown on figure 4 above, ‘Analog to Digital Converter in PIC Microcontrller— XC8 | Student Companion SA Finclude “nee_generated_Files/nec.F include “ledsh" Hineluge “stdio.h" T 2 3 4 sr é Woin opptication 7 a 8 // This function creates seconds delay. 10 // The arganert specifies the delay tine in seconds 51 void Delay_SecondsCunsigned char 2) wt 35 © unsigned chor x,y5 fer Gy 8) 28) //reenvenn 22 uinei6-t convertedvalue 2 Float. voltage ; 25 char Buffer(20]; 26 void maincvotd) 2 // nisiolize the device 23 SYSTEMLInieielizeO% Se 77 initialize the LCD BS. Uea initialize: 32 33 34 LeDPUECndCLCOLCURSOR_OFFD; //LCD Cursor off 85 ——_LDPUESEPCADE with MCC"D; //Display String "ADC with MCC” 36 LGC, 19; 1160 to second Line 87 LeDputStr"Tuen POT on AN"); //Display String "Turn Potentioneter on 38 Delay Seconds(2); 7/2 seconds delay 83 isplayCirO; 1 Cear the isploy a a 42 while @ “Bf 4 convertedvalue = 4 46 ADC. StarsConverstonGchannel AN); 47 whideC!ADC_TsConverstonDoneG))3 a convertedValue = AUC GetConversionResult(; 43 0 voltage = 5 Ueoputserctvottage = 82 sprintfCbuffer, " X.3g", voltage ); // Convert voltage to string, rour 53 Leputstr(uffer); //0tSplay the Yortage on the screen Intpwwn stucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! sna suo2017 [Analog a Digital Convertarin PIC Microcontroller ~XCé | Student Companion SA st Leoputstret™ "D5 // Clear after com 55 Lcocotoc0,e); Vio to Fi 56 53) 53 yo ® “End of File a, ADC Configuration with PIC18F Peripheral Libraries ochip XCB PICIBF Peripheral brates provide Analog to Digital brary functions as shown in table below. F Peripheral Library Help Document found inside your comp! ip xe v1.34 MPLAB. XCB_Perisheral,Librariespdf (assuming you instal jon directory in: Program Files (x86) Micro rin the Pr be different if you a Files (86) directory. v1.34 sing a differen ‘Search forthe PIC you are going to use, click on: “CLICK HERt the Peripheral Library ot a 18F2620 family, the ADC functions are from page ‘Support Details for this Dev 904 in the pa Watch the Video Tutorial: closeaDe SetchanADC BusyADC: Ifthe value returned ist; it indicates thatthe AL value is'0, them it indicates that the ADC has completed conversio CloseADC: Ths function disables the A/D converter module CConvertADC: This function starts an A/D conversion, The function BusyADC{) should b ied to find out when Open ADC: This fun arguments that this 's busy In conversion, ion is used to configure the A/D converter module, The number o function can take depe on the type of mic The PICL8F2620 takes three argume controller use config, config2 and portConfig. 3 PICLBF: The values defi can be bitwise AND ed. 20 the important definitions suiov2017 ‘Analog to Digital Converter in PIC Microcontroller — XC8 | Student Companion SA Config: ‘ND Clock source definitions (select clock frequency used for internal synchronization of ND converter Italso affects duration of conversion) The clock is critical to produce the fastest but also accurate Analog to Digital Conversion: ADC_FOSC_2=FOSC /2 ADC_FOSC4=FOSC/4 ADC FOSC_8 = FOSC/8 ADC FOSC_16 = FOSC/ 16 ADC FOSC_32 = FOSC/32 ADC_FOSC_64 = FOSC /64 ADC_FOSC_RC= Internal RC oscillator ADC_FOSC_MASK = Mask ADC Conversion Clock Selection bits ND Result justification: ADC RIGHT JUST = Right justify the result ADC_LEFT JUST = Left Justify the resutt ADC_RESULT_MASK = Mask ADC Result adjust 6° ND acquisition time select (In order to enable the ADC to meet its specified accuracy itis necessary to provide a certain time delay between selecting specific analog input and measurement itself. This time is called ‘acquisition time’ and mainly depends on the source impedance). The time to complete one bit conversion is defined as TAD. One full 10-bit conversion requires 11 TAD periods. For coreect conversion, the appropriate TAD specification must be ‘met Check your device datasheet to get the ADC conversion requirements, for PIC18F26K20 the min TAD is 0.7 uS and max 25 us ADC_9_TAD = A/D Acquistion Time is TAD ‘NDC_2_TAD = A/D Acquistion Time is 2 TAD ADC_4 TAD = A/D Acquistion Time is 4 TAD ‘ADC_6 TAD = A/D Acquistion Time is 6 TAD ADC_8 TAD = A/D Acquistion Time is 8 TAD ADC_12_TAD = A/D Acquisition Time is 12 TAD ADC_16_TAD = VD Acquisition Time is 16 TAD ADC_20_TAD = A/D Acquisition Time is 20 TAD ADC_TAD_MASK = Mask ADC Acquistion Time Selection bits Config2: Channel: ADC,CH0 = Select Channel 0 ADC_CHt Select Channel 1 ADC_CH2 Select Channel 2 up tothe last channel, ‘ND Interrupt: ADC_INT_ON = Interrupts enabled ADC_INT.OFF = Interrupts disabled ADC_INT._MASK = Mask ADC Interrupt Enable/Disable ‘ND Veef configuration: ADC, REF_VDD_VR' ADC.REF_VOD_VSS ADC.REF_MASK ND port configuration: ADC_OANA = All channels are digital ADC_1ANA = analog: ANO and remaining channels are digital [ADC_2ANA = analog: ANO-AN1 and remaining channels are digital, AADC_3ANA = analog: ANO-AN? and remaining channels are digital up tothe last channel, ‘An example forthe use of OpenADC function is given below: OpenADC(ADC FOSC._? & ADC RIGHT JUST & ADC_2_TAD, ADC_CHO & ADC_INT_OFE & ADC_REF_VDD_VSS, ADC_LANA}: htpwwstucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! mma suiov2017 {)FOSC/2 as conversion clock, Result is right justified, Aquisition time of 2 AD, Channel & for sampling, ADC interrupt off and ADC reference voltage from VDD & VSS ReadADC: Tis function reads the ADC Buffer register which contains the conversion value. To use more than one ADC channels, you need to select the appropriate number of channels in PortConfig and convert each channel individually. Example to convert 3 ADC channels [7 unsigned int ADCResuIeIS]- 1}; 222 *+&4 2 float voltage; 5 unsigned enor Resuleser[10]; | 4 5 void maincvaia) | et Finis AOCOH 17 Call initiatize Ave | a while) ot | 20) //---sanple ond convert 21 forcunsigned char 1-0;i0-2;1++) //Loop 3 times to sarple and read each channd ze SS AvCONODItS.CHS-i; _//SeLect « channel to sample Cindex i = @ (first channel) | 3h //rans for’ the first tine, i will be 1 then 2 for each successive runs) 55 Conver:ADCO} 77 Convert Analog to Digital | 25 whalecsusyA0CQ); 27 ADGResult{i] = Cinsigned int) RecdADCQ; //Read each channel | 28 voltage = CAucResuLt[i}*5.0)/2023;, Zeorvert 10-dit ADC data into 2) 20} 2 | 22 void init aoccveia (eonfigare NOC with 3 analog channels 3 2 Display the voltage reac from analog channel Oto the LCD display as shown on the circuit, iagram above. The MCLR is not enabled and the circuit uses internal oscillator at 8MHz so an external crystal device and a resisitor to MCLR pin are not needed. The contrast resistance connected to VSS, VDD and VEE of the LCD is not shawn here. * Autor: Student Conporion SA: www. studentconpanion.co.24 | * Analog to Digital converter with PIC microcontroller | v include “ADC.” | Hinelude #incluge ); //check {F the LCD controler 1s not busy, 61 //oefore writing sone coneands? 182 WriteCmdXLCD(Ox@6); // move cursor right, don’t shift display 13 WriteCndXLCDCOxeC); //turn display on without cursor 4 6 > (6 void init ADCLGvoid) //initialize ADC 67 { 8/995 ADC configured For 63 FOSc/2 a6 conversion clock 7 * Result is right justifies 71 * Aquisition tine of 2 AD 72 * Channel 1 for sampling 75 + AOC interrupt off 7% * ADC reference voltage from VOD & YSS 73 +7 75 OpenADCCADC_FOSC_2 & ADCRIGHT_IUST & ADC_2.TAD, 77 ADCLCH@ & ADC_INT_OFF & ADC_REF_VOO_VSS, 78 ADC_taN); 7} 80 void DelayFori87CVC void ) //28 cycles delay ay 2 Detayiererx(2e); 8} aw 85 void DelayPORXLCD (void) // Deloy of 15ns cone 57 DeLaytKrcvx¢30)5 a} 5 90 void DelayxLcD (void) // Delay of Sas of 92 DetayiKTevxc1e); = You can download the full project files (MPLAB XCB source code and Proteus Schematic design) below here. All the files are zipped, you will need to unzip them Download a free version of the Winzip utility to unzip files). sample ond convert Download: ADC with MCC MPLAB Project Download: ADC with MCC Proteus htpwwstucentcompanion.cozalanalog-o-digital-converter-impic-microcontroler-xc8! ona suo/2017 ‘Analog to Digital Converter in PIC Microcontroller — XC8 | Student Companion SA Download ADC Header Download ADC HEX Download ADC Main € Download ADC Proteus DAs by Gooale ~ ITE ON tsa) SO a 4G MAIS RAPIDO Dr —™ =o = Google AdWords - Analog to Digital Reduce Code Review Digital Thermometer Oficial Converter with PIC Timo using PIC Microcontroller and... 2% Microcontrolle Network Inventory Interfacing LED Connecting Light Reading Switches Tool Display With PIC Emitting Diodes (LED) With PIC Microcontroller ~ XC8 toa PIC... Microcontroller - XC8 Related Posts Getting Start Introduction to EasyEDAa wel Programming Design Software Microcontrollers with Flowcode V6. 14 Comments Student Companion @ Erandi Brito htpwwnstucentcompanion.cozalanalog-o-igital-converter-impic-microcontrole-xc8! sone svio2017 © Recommend 4 ‘Analog to Digital Converter in PIC Microcontrller— XC8 | Student Companion SA Sort by Newest nL Join the discussion. tiago perelra 8 year ago - but 18F26K20 works in 3:3V how to take measure of SV in analog pin? 1A |v > Reply » Share> Jq_ Student Companion (EE) viogoporora a yoar apo ‘BY ar correct. we dd ake into consideration the supply volage in this simulation. The point was to explain the ADC. Bult in hardware 3.3V should be considered, Thanks A |v = Reply » Share» Hassan a year ago - Hello, 1am using MPLAB XC16 C Compiler. How may | get Peripheral Libraries? 1A) Reply Share» @ _ student companion CED Hssan yer ago - <=> Hi, you can download them as a separate download fie, then install them into your current compiler installation fle. Under the compiler download page at microchip website, they are now called: PIC24/dsPIC Peripheral Libraries v2.00 then choose your operating systems. 1A \ > Reply » Shares BURAK - 2 yoare apo - fi, 'm follow u, dni have a problem. everything good but finclude undeclered error. do u share me delays.h your library 2 1A) Reply » Shave» Student Companion (TED SURAK: 2 years ago - <> Ityou are using XC8 v1.35, the PIC18 Peripheral Libraries (plib) are no longer included. That is why you cant find the fle. you need to download them separately. They are now called: PIC18F Legacy Peripheral Libraries. You can download them at tis link under the downloads tab: hitp:viww.microchip.comipa, 2 Reply » Shares Bela Ceoke > BURAK 2 yare 890 - The compiler shoulé content delays.h library, AtXC8 isa bit "hidden \include\plibidelays.h. So you have to modify to pliodelays.h OR you can tty if you use MPLAB X IDE, simply stat to ype #include< as if you hit the < sign automatically will cose with > and leave for a bit unt tell you "Please wait” and wil sted all available header fles. Most likely You wil find plib directory atthe end of thelist. Double lick on it then you will see an another Iist, there you can find delays.h as well tale ply » Share > chris kins «2 yoarsag0 - Hi Guys, Would using a § k ohm variable resistor instead of an 1 k ohm ‘variable resistor damage the pic chip? . Just thought that | had better check as Ido not have a 1 k. Thanks for you help and advice in advance. Chris, Av = Reply « Shore Student Companion (TED chs Petkns “2 yeas ego - htptwwstucentcompanion.co.zalanalog-o-igita-converter-impic-microcontrolr-xc8! ane suo/2017 Analog a Digital Conwertrin PIC Microcontroller ~XCé | Student Companion SA Sy Chris Perkins 2 yours ago Many Thanks and | ike the look of your Redesigned Website. Reply «Share» ® civ Perkins > Thank you @ Student Companion (D+ cis Perkins 2 yous ago Thank you, iy - Share Chris Perkine 2 yoars 90 Hi, The links to download the different fles appear to be broken !?! @ Student Companion (T+ civs Perkins 2 yous ego ‘Thanks for letting us know about that, we have redesigned our website we are stl fixing some few broken inks. We have fixed the links to the fles. Thanks Reply » Share Interfacing a Relay with PIC Microcontroller ~ MikroC Avatar —how can be relay I” ‘SMS Home Alarm System with PIR and GSM — MikroC. ‘Avalarcsions — Great project. Thank you Incracing LO Display With PIC Merocontolar = XCB Creating a Serial Port Interface with cH vata We have ted ‘the lnk, you can download the flo Analog to Digital Converter with PIC Microcontroller - MikroC Avatar Tanks Digi Thermometer using PIC hitp:lwwn:stucentcompanion.cozalanalog-o-igital-convertsr-in-pic-microcontrole-xc8! rane

Вам также может понравиться