# 微算機 Lab10 - A/D Convertor > 修改自[去年教材](https://hackmd.io/Xm9zal9MTLWvfgiLtkwORA?view)謝謝學長 > 歡迎各位利用註解形式補充以及討論,但請避免貼上完整的程式碼。[name=IanSung] ## 工作原理 * 詳細可參考 [ADC - 成大資工 wiki](http://wiki.csie.ncku.edu.tw/embedded/ADC#introduction-to-adc) 的前面一兩章 以下簡要說明: ADC 主要的功能是將類比訊號轉成數位訊號(其實裡面就是很多電壓比較器),在本次 lab 中,ADC 會把輸入的電壓(類比)轉換成數字的形式。~~不會一直射敵人~~ 幾個重要的參數:VREF+ / VREF- / resolution * VREF+:作為上界的參考電壓,若輸入電壓為此值則輸出為最大值 * VREF-:作為下界的參考電壓,若輸入電壓為此值則輸出為最小值 * resolution:ADC 的解析度,若為 10bit 代表輸出從 0 ~ 1023 > e.g. VREF- = 0V, VREF+ = 10V > 10 bit resolution -> range = [0, 1023] > 0V -> 0 > 5V -> 511 > 10V -> 1023 ADC 分為幾個階段: **Acquisition -> Convertion -> Discharge(wait before next acquisition) -> Idle until you set GODONE bit -> Acquisition** ## A/D conversion clock(ADC 的工作週期) * $T_{AD}$ (A/D Conversion time per bit) * $T_{AD}$ 愈小愈好,但是要大於最小 $T_{AD}$ ![](https://i.imgur.com/qHFm3Me.png) ![](https://i.imgur.com/3C8AIS3.png) 假設今天的頻率 ($F_{OSC}$) 是 2.86 MHz, 則周期 ($T_{OSC}$)會是 $\frac{1}{2.86 \times 10^6} \approx 0.35\mu s$,為了滿足最低 A/D Clock period ($0.7 \mu s$), 我們要把 conversion clock ($T_{AD}$) 設成兩倍的 $T_{OSC}$ ## Acquisition time ![](https://i.imgur.com/U6MTEJr.png) ![](https://i.imgur.com/NujsaTM.png) ## Left/Right justified ![](https://i.imgur.com/0cPibud.png) [Source](https://techetrx.com/pic-microcontroller/adc-in-pic16f887-microcontroller/) ## ADC Module ### Input * AN0~AN12 > Note: 使用 ADC 的同時若發現其他 PORT 的 input 值怪怪的也許是誤把那些 PORT 設成 analog input (參考 ADCON1) ### ADCON0 ![](https://i.imgur.com/fAlebdY.png) ## ADCON1 ![](https://i.imgur.com/2RUZ5c1.png) ## ADCON2 ![](https://i.imgur.com/Yw7oPDM.png) ## Workflow 重要 1. Configure the A/D module: * Select VREF (ADCON1.VCFG0, ADCON1.VCFG1) * Select A/D port control(ADCON1.PCFG) * Select A/D input channel (ADCON0.CHS) * Select A/D conversion clock (ADCON2.ADCS) * Select A/D acquisition time (ADCON2.ACQT) * Turn on A/D module (ADCON0.ADON) * Select justified method (ADCON2.ADFM) 3. Configure A/D interrupt: * Clear ADIF bit * Set ADIE bit * Set GIE bit * Select IPEN bit * Configure ADIP bit 5. Start conversion, set ADCON0.GODONE bit 6. Wait for A/D acquisition&conversion complete (Wait for the A/D interrupt) 6. Read A/D Result registers (ADRESH:ADRESL). 7. For next conversion, clear ADIF for next interrupt, **set GODONE again for next acquisition&convert**. The A/D conversion time per bit is defined as TAD. **A minimum wait of 2 TAD is required before the next acquisition starts.** ## Variable resistor 左右一邊接 5V,一邊接地,中間接 Analog 輸入 ![](https://i.imgur.com/q3vm4OZ.png) ![](https://i.imgur.com/jodQysY.png)