侯詠章
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 微算機 ## CH7 Assembler programming ### 1. Signed Multiplication algorithm ![image](https://hackmd.io/_uploads/SktPRNdPa.png) 判斷相乘兩數M跟Q的值,再去決定result正負 (1)初始化放值(MULT)跟放check bit(SIGN)的register ![image](https://hackmd.io/_uploads/HJhpyruDT.png) (2)判斷兩數的check bit(SIGN),看是否為負 ![image](https://hackmd.io/_uploads/HJSmeBODT.png) (3)相乘並決定結果正負 ![image](https://hackmd.io/_uploads/HklYeBuv6.png) ### 2.Unsigned division algorithm ![image](https://hackmd.io/_uploads/BJiDmHuDT.png) (1)初始值(DIVIDEND,DIVISOR)和counter(當作商) ![image](https://hackmd.io/_uploads/r1OoXruDT.png) (2)看Dividend是否>=Divisor,決定是否繼續 ![image](https://hackmd.io/_uploads/HJUzNB_vp.png) ### 3.signed division ![image](https://hackmd.io/_uploads/rJQjrrOvT.png) 跟signed multiplication類似,但 !!**注意**!!第4點,餘數(remainder)的值和被除數(divedend)同 號 (1)初始化值(DIVIDEND,DIVISOR),商(COUNTER)與sign register(SIGN) ![image](https://hackmd.io/_uploads/Sk5fRruP6.png) (2)若是被除數與除數是負的,把SIGN設成1 ![image](https://hackmd.io/_uploads/S19QASuD6.png) (3)進行unsigned除法(先看是否等於,再看是否大於) ![image](https://hackmd.io/_uploads/SJL8CHuDp.png) (4)對結果的正負進行調整(注意remainder與divdend的關係) ![image](https://hackmd.io/_uploads/B1AhAB_Pa.png) ### 4.delay routine ![image](https://hackmd.io/_uploads/ByE_lLdDp.png) * 4個clock會是一個cycle * 如果*branch成功跳回去會有2個cycle*,否則只有1 EX (1)想要100micro sec,需要25 isntruction counts ![image](https://hackmd.io/_uploads/HJSTzLuvT.png) (2)會有count-1次有3個instruction(因為bnz是conditional),最後一次2個 ![image](https://hackmd.io/_uploads/SJTxQIOP6.png) 25(需要的instruction count) = 1+1+3(count-1)+1+1 (前面的movlw和movwf各1) (有count-1次的iteration有3個instruction) (後面的branch和return各1) ***BRA(unconditional)只要1個cycle,其餘conditional都要2個*** (1)跟前個例子相似,但注意**DECFSZ如果skip有2個cycle**,return也有一個cycle ![image](https://hackmd.io/_uploads/HyEsNIOPa.png) (2)最後結果如下 ![image](https://hackmd.io/_uploads/r1wWr8_Dp.png) ## CH8 Pic18 programmed i/o using assembly 1.Pic18 有 memory mapping i/o,讓i/o instruction可以順利進行 2.TRISx 預設都是1(當作input) 3.比較 SETF R1 #將R1的所有bit設成1 BSF R1,2 #將R1的第2個bit設成1 ### Analog input 1.PORTA,B,E 的幾個bit拿來當作analog input(共13個bit) ![image](https://hackmd.io/_uploads/SyR5qPOwa.png) 2.但得先設定ADCON1的bit來決定digital或analog i/o(當需要用的PORTA,B,E時才需要設定) ![image](https://hackmd.io/_uploads/Bk0YivuwT.png) 3.在設定i/o bit可利用define精簡 ![image](https://hackmd.io/_uploads/HyympDOwT.png) ### LED 4.因為LED是靠壓差產生電流發亮,所以以下兩種接法都可行(但注意output結果與亮暗的差別 ![image](https://hackmd.io/_uploads/Hy4NRD_Pp.png) 5.7段顯示器的接法跟LED類似,只要兩側有電壓差即可發亮 ![image](https://hackmd.io/_uploads/rJQVf1tDp.png) (其中有common cathode(一般的接法) 和 common anode兩種接法,如下) ![image](https://hackmd.io/_uploads/BJlD41tPp.png) 如下圖,當PORTC0,PORTD0為1,電路為open,input有5V電壓,所以沒有壓差,不亮,反之 ![image](https://hackmd.io/_uploads/SJO5DkYw6.png) ### 配置i/o的config 6.program i/o 常見的config配置 ![image](https://hackmd.io/_uploads/Sy2NBJYvp.png) ### Ex 判斷PORTD 的6,7 bit來操控LED ![image](https://hackmd.io/_uploads/rksZgksDp.png) (a)初始化PORTC(output)跟PORTD(input) ![image](https://hackmd.io/_uploads/rJeKlJiwT.png) (b)判斷PORTD(用11000000)來判斷 ![image](https://hackmd.io/_uploads/By3hlksPT.png) ### Ex 判斷PORTA輸入的BCD,查表讓數字顯示 ![image](https://hackmd.io/_uploads/H12sGksP6.png) (a)在data memory 初始化table的值 ![image](https://hackmd.io/_uploads/HkzVHkjPa.png) ### 會考(建立table) >利用DB和TBLRD在program memory建立table >![image](https://hackmd.io/_uploads/B1I_VZW_6.png) >在500H創建一個table,利用DB將值依序存在500H,502H >![image](https://hackmd.io/_uploads/By8CYyiPa.png) >如上圖,已經有個table在program memory,只需將address放到TBLPTR,再用TBLRD讀取該位置的數值,就會存在TABLAT >![image](https://hackmd.io/_uploads/SkFsrbWdT.png) >也可像此圖,先initial table一開始的值之後,在用TBLRD來移動table pointery在整個table進行讀值 >Ex for DB >![image](https://hackmd.io/_uploads/SJsOVgswT.png) >this is alternative for FSR with DB >![image](https://hackmd.io/_uploads/S1e0Nxswa.png) (b) repeatedly讀table的值 ![image](https://hackmd.io/_uploads/rkbIDE3vp.png) ### 會考 >Ex delay 10 sec with Delay10KTCYx(250) >Delay10KTCYx() (delay for nums of x * 10K instruction) >![image](https://hackmd.io/_uploads/BkCGsI0Da.png) > >for a 4Mhz oscilator , one instruction has period 1 miu second >so we need 10/10^-6 = 10^7 instructions >因為x範圍在0-255,所以我們用重複4次的for來達成10^7個instruction ### Ex 判斷high switch 個數for LED ![image](https://hackmd.io/_uploads/Skt10IRP6.png) 1.mask portc for lowest three bit(因為只需用到最下面3個bit) ![image](https://hackmd.io/_uploads/SyMeCLCDT.png) 2.對portc 最少3bit 判斷,有奇數個1,不亮,反之 ![image](https://hackmd.io/_uploads/rksN0ICPT.png) ## CH9 Interrupt I/O , LCD and keyboard interfacing ### Unconditionall i/o vs conditional i/o 1.unconditioal i/o * 可以在任何時刻收到資料 * Ex:LED、七段顯示器 2.conditional i/o * 需要有 **hand_shaking** 才會進行資料的傳輸 * Ex:AD converter (the signal of conversion done) ### AD convertor (1) 在轉換過程,busy signal會設成0,直到完成後把busy signal設成1,並將結果輸出 ![image](https://hackmd.io/_uploads/Bkr-ntCDa.png) (2) 在等待busy signal若是用pool i/o,會有spin lock(反覆檢查是否available)的情形發生 >so interrupt i/o come to fix this ### interrupt i/o (1)外部裝置準備好時,主動傳送訊號到INT ![image](https://hackmd.io/_uploads/SJxzhY0Pa.png) >ISR和subroutine的差別 > >ISR:由外部裝置給予訊號,來跳到subroutine-type program(也就是interrupt), >subroutine:由軟體本身來呼叫subroutine > >兩者都利用pop from program counter來exit,但ISR還須在enable interrupt(將interrupt flag bit歸0)讓之後的interrupt可以work ### Ex 用comparator和switch控制LED ![image](https://hackmd.io/_uploads/B1cuAFRPp.png) (1)設定input和output的configure ![image](https://hackmd.io/_uploads/HkNO7n0P6.png) (2)判斷RB0和RB1 for comparator 和switch ![image](https://hackmd.io/_uploads/SJRaOMZO6.png) ### External vs Internal interrupt External:caused by external device like ad convertor Internal interrupt:caused by inner signal like timer 4.edge-triggered interrupt: low or high 需要停留2個instruction cycle,才能被判斷是edge 5.default有三個external interupt(INT0,INT1,INT2),初始INT0有最高priority,INT1和INT2一樣,再透過config設定priority 6.INTCON : INT0,RB,TIMER的interrupt 設定,以及設定IPEN(讓high 跟low interrupt可執行) ![image](https://hackmd.io/_uploads/Byftw9y_6.png) 7.INTCON3 : INT1,INT2的Enable,prior,flag,原先預設INT0是high priority for all,而INT1,INT2則需要另外設定 ![image](https://hackmd.io/_uploads/BJGfu91ua.png) 8.由各個interrupt合在一起的gram ![image](https://hackmd.io/_uploads/SywEFc1_p.png) 9.實作interrupt要注意的設定 (1)interrupt enable和清空interrupt flag (2)設定GIE為1 (3)將ADCON1設成digital,因為int0-int2有跟AN的腳位有重複 ![image](https://hackmd.io/_uploads/SJaut9yO6.png) 10.INTCON2 的INTEDG設成1是rising edge,0是falling edge ![image](https://hackmd.io/_uploads/By_7a9y_a.png) 11.當0x0008到0x0018擺滿後,將isr放在其他地方,用goto來執行 ![image](https://hackmd.io/_uploads/BkZJ05JuT.png) ### keyboard interrupt 12.keyboard interrupt,由KB10-KB13(RB4-RB7)判斷電位變化,進而知道哪個鍵被按 ![image](https://hackmd.io/_uploads/rJK2fo1d6.png) 13.在c裡實作asm的指令 利用#pragma把code放在指定位置 _asm,_endasm在c寫assembly ![image](https://hackmd.io/_uploads/HkhGusJuT.png) ### Ex 利用switch和comparator來控制LED燈的亮暗 ![image](https://hackmd.io/_uploads/SyYraikup.png) config ![image](https://hackmd.io/_uploads/Bk3uTj1_p.png) (1)在main_prog設定i/o和interrupt ![image](https://hackmd.io/_uploads/Bk8ATjkOa.png) (2)Wait跟while類似,等待Int_serv,有interrupt產生的話會直接到INT_SERV的位置 ![image](https://hackmd.io/_uploads/HyjT6ikuT.png) ### Ex利用comparator(high prior)和switch(low prior)控制LED ![image](https://hackmd.io/_uploads/rkrr12yOa.png) (1)設定main和high,low interrupt service routine ![image](https://hackmd.io/_uploads/Syw3knyda.png) (2)將INT0(high)和INT1(low)設定 ![image](https://hackmd.io/_uploads/Syg012JO6.png) (3)high跟low的ISR,進來後先看INT0和INT1是否還是1(持續2個cycle),再作LED的操作 ![image](https://hackmd.io/_uploads/r1t4lny_T.png) ### peripheral interupt 1.會有自己的interrupt flag register,像ADC,需要另外設定PEIE ![image](https://hackmd.io/_uploads/Hk6Te3kup.png) 2.gram ![image](https://hackmd.io/_uploads/ry2Sb2kda.png) ### typical LCD ![image](https://hackmd.io/_uploads/rybAdkeOa.png) Pin1(GND) Pin2(VCC) Pin3(Contrast):利用可變電阻來調整 Pin4(RS-Register Select):RS=0 , 輸入command;RS=1 , 輸入data Pin5(RW-Read Write):RW=0 , WRITE , RW=1 , READ Pin6(EN -Enable) : 當EN從1到0持續450ns,就會傳送資料 (1)因為EN的關係需要利用time delay或是busy flag 讓LCD能正常顯示資料 ![image](https://hackmd.io/_uploads/BypYokxup.png) ### Ex 在LCD上顯示switch代表的BCD value ![image](https://hackmd.io/_uploads/B1kdpyguT.png) (1)需要3個subroutine,輸出command、delay和LCD顯示 ![image](https://hackmd.io/_uploads/Hkmnp1xdT.png) ![image](https://hackmd.io/_uploads/B1ID5_b_a.png) (2)設定PORT PORTB紀錄EN、RW等等的值 PORTD紀錄OUTPUT PORTC紀錄Switch的INPUT ![image](https://hackmd.io/_uploads/HySYgee_a.png) (3)三個subroutine ![image](https://hackmd.io/_uploads/SkkillxOa.png) (4)對cursor作指令,來output需要的baseline ![image](https://hackmd.io/_uploads/BJX_WgxdT.png) (5)對BCD轉換到數字 ![image](https://hackmd.io/_uploads/HJCefgeOT.png) ### Keyboard interface Ex : c is pressed ![image](https://hackmd.io/_uploads/Sys9XNluT.png) #### 2 solution for keyboard There might be keyboard conflict , two solutions two-key lockout:當一個按鈕按下,其他就不能用了 N-key roll over:可以判定按鈕被按下的順序,藉此依序送出訊號 ### Display interface (1)多個display需要決定顯示的順序,但實際上肉眼其實看不出來 ![image](https://hackmd.io/_uploads/HkpBUNeOp.png) (2)nonmultiplexed vs multiplexed nonmultiplexed:要先在microcontroller decode,才能順利display multiplexed : 在display裝置上decode,像是可以利用PORT選擇要顯示哪個位置上 ![image](https://hackmd.io/_uploads/SJOSvElO6.png) ![image](https://hackmd.io/_uploads/S1F-_Eeua.png) PORTB:輸出按鈕所傳送的code讓7段顯示 PORTC:偵測是否有按鈕被按下(需要搭配delay讓debounce不會影響結果) PORTD:偵測哪個按鍵被按下 (3)看PORTC檢查是否有按鍵被按下 ![image](https://hackmd.io/_uploads/S1GB1SeOT.png) (4)看PORTD檢查是哪個被按下 ![image](https://hackmd.io/_uploads/rJNYJSguT.png) ## CH10 ### Timer 兩種用途 - on-chip -> time delay - 接 external clock,紀錄來了幾次 - 在背景紀錄時間,前台進行其他操作 實際上是一個 register,可以對它加或減 一開始給一個預設值,一路數到 FF,多一個 cycle 後會 overflow,然後會產生一個 interrupt。每次加都是一個 instruction cycle。 比 subroutine 的優勢在於,能有更長的 delay、不需要 branch 所以容易計算 timer 也能用做 event counter,每次過一個 event 都加一/經過N次後再加一 ### Timer 0,1,2,3 - Timer 0 - Timer 0 can be 8 bit or 16 bit timer. - used as timer -> use internal clock - as counter -> use external clock - Timer 1 - use internal/external clock like timer 0 - can't be 8-bit timer/counter - Timer 2 - Timer 2(TMR2) uses another register(PR2), count to that register's value, have another cycle, than set timer to 0, and interrupt (count to certain number and stop) - can be 8-bit timer using internal clock - can't be used as counter - Timer 3 - can be 16-bit timer/counter - can't be 8-bit timer/counter |function\timer|0|1|2|3| |---|---|---|---|---| |8-bit timer| o | x | o | x | |8-bit counter| o | x | x | x | |16-bit timer| o | o | x | o | |16-bit counter| o | o | x | o | Timer 1,2,3 are for CCP (no timer0) Summary: a binary counter that can count clock pulses, if full(0xFF/0xFFFF), overflow and interrupt(if enabled) ### timer flag when overflow, TMRxIF(x=0,1,2,3) is set, you can poll for the flag. But it's wasting CPU power, so we can use timer interrupt. counter register means which number they will count to, and stop. Timer is peripheral device -> peripheral interrup(PEIE) bit is in INTCON for four timers. ![image](https://hackmd.io/_uploads/rJrD1Ziwp.png) To interrupt, clear TMR0IF (clear interrupt bit), set TMR0IE, PEIE, GIE ![image](https://hackmd.io/_uploads/HJD3TrhDa.png) ### Prescalar && Postscalar Divide clock with a number in the beginning, reduce clock period, and create **higher delay**(make oscillator slower) Divide clock by number after timer is used, after n times of overflow, an interrupt will happen, also creates **higher delay** prescalar -> 頻率變慢 postscalar -> 做 n 次才會 interrupt ### Use Timer 0 - as counter - external clock(T0CK1) is used when used as a counter - set T0CS bit - as timer - must initialize value when using TMR0H and TMR0L (they store value from last time) - to use interrupt, enable TMR0IE - set interrupt priority with TMR0IP (0 is low, 1 is high) > TimeDelay = (Instruction cycle clock period) \* (Prescalar value) \* (Counter value) > Control timeDelay with counter value timer can be stopped by clearing TMR0ON ### Use Timer 1 - use external oscillator to become counter - TMR1IF flag is in PIR1 register - if overflow, it's set to 1 - use T1CON register to control timer1 - Oscillator enable bit(T1OSCEN) - set/clear TMR1ON(bit 0) to enable/disable timer1 - T1OSCEN: 0/1-> disable/enable timer1 oscillator - T1SYNC: 0 -> synchronize extenal clock input, 1: don't - decide clock with TMR1CS(timer 1 clock source) bit - Timer 1 interrupt - When TMR1H:TMR1L overflow, enable interrupt bit(TMR1F in PIR1) - Delay 1ms - Clock is 4MHz, instruction cycle is $4 * \frac{1}{4MHz} =1\mu s$ - instruction count for 1ms delay = $1ms/1\mu s$ = 1000 - with prescalar 1:4, instruction cycle count = 1000/4=250 - total number of counts = 65535-250 +1 = 0xFF06 ( add one because setting TMR1IF takes one cycle) - set TMR1H with 0xFF and TMR1L with 0x06 - **Time delay = Instruction cycle \* prescale value \* (count+1)** ### Use Timer 2 - contain 8-bit timer register(TMR2) and 8-bit period register(PR2) - prescale can be 1:1, 1:4, 1:16; postscale value can be 1:1 through 1:16 - T2CON register control timer 2, prescalar and postscalar value - bit 7: no function - 6~3: (T2OUTPS3:T2OUTPS0) postscalar value, 0~16, ex: 0000 -> 1:1, FFFF -> 16 - 2: (TMR2ON) timer2 is on or off - 1~0: (T2CKPS1:T2CKPS0) prescalar value, 00->1, 01-> 4, 1X-> 16 - Timer 2 Operation - normal: increment TMR2 until equals PR2, if equal, output HIGH in TMR2IF and reset TMR2 in next cycle - interrupt 1. set PEIE and GIE in INTCON 2. set TMR2IE in PIE1 register 3. clear TMR2IF in PIR1 register 4. clear TMR2 register 5. init PR2(count) and T2CON(prescalar, postscalar, enable timer) 6. turn timer2 on with T2CON ``` OSCCON = 0x60; // 4MHz, run this in main() ``` - <ins>**Delay =Instruction cycle \* prescale value \* postscale value \* (counter value +1)**</ins> NOTE: for 4MHz clock, instruction cycle is 4*1/4Mhz (because there are 4 crystals) ### Use Timer 3 - as 16-bit timer or counter - bits - 7: (RD16) enable read/write mode - 6,3: (T3CCP2:T3CCP1) TODO: taught in next chapter - 5,4: (T3CKPS1:T3CKPS0) choose prescale to 1,2,4,8 - 2: (T3SYNC)clear(0) means synchronize external clock input - 1: (TMR3CS) select clock source, 1 is external, 0 is internal - 0: (TMR3ON) 1 enables timer 3 - modes: sync counter, async counter, timer - PIR2 register: only important is bit 1, TMR3IF: interrupt bit for timer3 - PIE2 register: care bit 1, TMR3IE, enable interrupt for timer3 ### PIC18F on-chip ADC (Analog-to-Digital Converter) - ADC output 8-bit or 10-bit - contains resolution, reference voltage, ADC channels, acquisitino time, ADC clock - Resolution: how precise the conversion can be, ex: 0~5V divided into 256 sections(8-bit), section is 19mV, cannot distinguish 1mV and 18mV - Reference Voltage: min and max voltage of analog input voltage. $V_{ref}+$ and $V_{ref}-$ are usually 5V DC and 0V - ADC channel: ADC is connected to mulltiple channels with multiplexer, allowing them to use analog input (AN0~AN12) - Acquisition time: to convert analog input to binary, we **charge capacitor until it's close to input voltage**, the time for fully charging capacitor is acquisition time - ADC clock(T_{AD}), time for converting one bit - ADCON0 register: select analog input channel, start conversion, check completion, enable/disable ADC module - 7-6: no use - 5-2:(CHS3:CHS0): select which channel uses ADC(0 -> AN0, 1 -> AN1...) - 1: ($GO/\overline{DONE}$) ADC conversion status bit - 0:(ADON): ADC On bit - ADCON1 register, control voltage reference - 7-6: none - 5: VCFG1, negative voltage reference - 1: from $V_{REF-}(AN2)$ - 0: $V_{SS}$ - 4: VCFG0, positive voltage reference - 1:from $V_{REF+}(AN3)$ - 0: $V_{DD}$ - 3-0: PCFG3:PCFG0, A/D port configutation control bits - ADCON2 register, control clock source, acquisition time, justification - 7: ADFM, ADC Result format bit, select right/left justified - 1: right, use 10-bit, low 2 of ADRESH and ADRESL - 0: left, 8-bit, use result in ADRESH - 6: none - 5-3: ACQT2:ACQT0, acquisition time seelct bits, 0 -> 0T_AD; 1-> 2T_AD ... (0,2,4,6,8,12,16,20) - 2-0: ADCS2:ADCS0, A/D conversion clock select bits, F_OSC/64 等(大概不用背) - When A/D conversion is completed, ADIF bit in PIR1 is set to 1, we can make it low priority by clearing ADIP(ADC interrupt priority bit) in PIR1 - Convert 8-bit ADRESH into voltage: 0~255 to 0~5V - Y is voltage, X is binary value - Y=5*(X/255) = X/51 = Quotient + remainder - 200 -> 3.94V - internal clock is 1MHz, T_AD is 2* $1\mu s$ -> acqusition time should **be larger than $2.4 \mu s$** -> select 2T_AD=4, smallest value that > 2.4 ### Interfacing external D/A converter ex: MAX5102 with PIC18F4321 1. Configure PORTB and PORTC as output, PORTD as input 2. Output LOW to A0 via bit 1 of PORTB to select OUTA 3. Output LOW to WR pin of D/A via bit 0 of PORTB 4. Input the switches via PORTD, output to PORTC 5. Output HIGH to WRpin of D/A via bit 0 of PORTB, to latch 8-bit input data ## CH11 Pic18f ccp and serial i/o ### CCP Capture, Compare, PWM CCP1 module is standard CCP with enhanced PWM, it's also called ECCP(Enhanced CCP). CCP2 has standard features we can't do capture/compare + PWM at the same time - mode config - capture, CCPx to input - compare, CCPx to output - PWM, CCPx to output - Capture mode - write 16-bit timer content to 16-bit register upon n-th rising/falling edge - we can capture twice, and get the interval - Compare mode - like stop watch, counts from 0 to preset value, can turn on capture mode according to CCPx pin - we can set/clear something after certain time - PWM, generate square wave, with specified duty cycle(HIGH 佔了多少比例) and frequency - can use polling/interrupt, we can use CCPxIF in PIR1 register for compare/capture, and TMR2IF in T2CON for checking PWM mode - CCPRx is 16-bit data register, contain CCPRxH and CCPRxL - work as 16-bit capture register - 16-bit compare register - 8-bit PWM - Capture mode - 7-6 None - 5-4 DCxB1:DCxB0 (duty cycle bit 1, bit0), compare and capture don't care - 3-0 CCPxM3:CCPxM0, select CCP module mode, 0 is compare/capture, 2 is compare, toggle output on match, capture on falling/rising... - **Timer 1 and 3 can use capture/ compare mode, timer2 is for PWM mode**. we can control with T3CON register - Use Capture mode 1. load CCP1CON register with data 2. configure CCP1 to input with TRISC 3. select timer 1 or timer3 for capture mode 4. clear CPP2 flag, CCP1IF/CCP2IF 5. clear CCPR1H and CCPR1L 6. Check CCP1IF and wait in loop, when rising is detected, start timer 1 with I1CON 7. save CCPR1H and CCPR1L in data memory REGX:REGY 8. clear CCP1IF 9. rising edge, stop timer 1 10. disable capture by clearing CCP1CON 11. PPerform CCPR1H:CCPR1L - REGX:REGY and store result 12. get interval (TODO: rewatch toggle in compare mode) - Compare mode 1. Load the CCPxCON for compare mode. Configure the CCPx pin of PORTC as an output. 2. Load the CCPR1H:CCPRIL (or CCPR2H:CCPR2L) register pair with appropriate values. -> counter value 3. Select Timer1 (or Timer3) as the clock source in the Compare mode by loading data into T3CON register. **T1CON is not used** to select the clock source for Compare mode. Instead, **T3CON** is used to select Timer1 or Timer3 as the clock source 4. Initialize Timer1H:Timer1L (or Timer3H:Timer3L) to 0. 5. Clear CCP1IF in PIR1 (or CCP2IF in PIR2) to 0. 6. Start Timer1 using T1CON (or Timer3 using T3CON). 7. Wait in a loop until the CCP1IF (or CCP2IF) is HIGH. 8. As soon as a match occurs (CCP1IF or CCP2IF HIGH), stop timer1 using T1CON (or Timer3 using T3CON), and the programmed bit value (HIGH or LOW or Toggled or Unchanged) will be outputted to the CCPx pin ### Compare mode 1.Use TIMER1 and TIMER3 用control register 來指定使用的timer以及match時的動作(drive high/low , toggle...) 2.把想要的count次數放進CCPR要的register #### EX當想要有1ms的time delay for ccp1 pin 1.計算需要的instrction count ![image](https://hackmd.io/_uploads/SkdP6ZFDp.png) 2.設定ccp operation ![image](https://hackmd.io/_uploads/r1OapZFP6.png) 3. TIMER3:設定prescale並先turn off CCPR1:設定count值,將CCPR的interrupt flag 設成0 ![image](https://hackmd.io/_uploads/BygUAZtP6.png) 4.等到match的時候,reset CCPR1和timer ![image](https://hackmd.io/_uploads/rJlRRZKPT.png) EX 利用兩個不同值讓CCPR1有週期波的特性 1.計算high 跟low 需要的instruction count ![image](https://hackmd.io/_uploads/HkfUJGKP6.png) 2.其餘跟前個例子相同 ### PWM mode - config CCPx pin to output - 10 bit duty cycle, upper 8bits in CCPRxL, and lower 2bits of CCPxCON(5 and 4) for fractional(小數) part - **PWM Period = [(PR2)+1] \* 4 \* $T_{osc}$ \*(TMR2 Prescale value), where $T_{osc}=\frac{1}{F_{osc}}$** - PR2 (period register 2) = [(Fosc) * (4 * Fpwm * TMR2 Prescale value)]-1 - PWM duty cycle = (CCPxL:CCPxCON<5:4>) * Tosc * (TMR2 Prescale value) Timer 2 count from 0 to duty cycle(CCPxL:CCxCON<5:4>), then it goes down, then it count until it's the same as PR2, then reset. And on in the next cycle ![image](https://hackmd.io/_uploads/SJt-bFb_p.png) **Steps** ![image](https://hackmd.io/_uploads/HyLIbY-up.png) ![image](https://hackmd.io/_uploads/BJewZYW_p.png) ![image](https://hackmd.io/_uploads/Hy9DbtbuT.png) ### DC Motor Control PWM 可以降壓、省電,藉由減少高壓的時間控制馬達速度 反轉馬達可以使用 H-bridge component,得到反向電流 算出 PR2 以後,可以把可變電阻的值(0~255) map 到 0 到 PR2 考到 DC motor

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully