MICROPROCESSOR SYSTEM DESIGN
MICROPROCESSOR SYSTEM DESIGN ECE 473
Popular in Course
Popular in Engineering Electrical & Compu
This 87 page Class Notes was uploaded by Sam Robel on Monday October 19, 2015. The Class Notes belongs to ECE 473 at Oregon State University taught by R. Traylor in Fall. Since its upload, it has received 55 views. For similar materials see /class/224415/ece-473-oregon-state-university in Engineering Electrical & Compu at Oregon State University.
Reviews for MICROPROCESSOR SYSTEM DESIGN
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/19/15
Submitted by Steve Redfield Here39s my encoder deciphering code This does both encoders independently both can change value in same while execution Encoder deciphering excecution is as follows 1 Update Current Encoder Value 2 If Current is different from Last which hit is different This gives you 4 cases 2 forward 2 backward each with its own distinct quotCurrentquot value 3 Correlate each quotCurrentquot value to either Increment or Decrement Volume 4 Update Last Encoder Value EncoderL PINE amp 0x30 EncoderR PINE amp OXOC ifEncoderL EncoderLtmp ifEncoderL A EncoderLtmp 0x20 ifEncoderL 0x30 EncoderL 0x00 Volume else Volume else ifEncoderL 0x10 Encoder 0x20 Volume else Volume ifEncoderR EncoderRtmp ifEncoderR A EncoderRtmp 0x08 ifEncoderR 0x0C EncoderR 0x00 Volume else Volume else ifEncoderR 0x04 EncoderR 0x08 Volume else Volume EncoderLtmp EncoderL EncoderRtmp EncoderR Submitted by Hai Yue Han Here39s the code for the music that Jason and I are wanting to demo I39m submitting a portion of the code that39s from my music file Fight song array volatile int music3333 12121112 17 17125412 112121112 17 1712541210ooo44477742o12121112 11111111122I11111111111112121111111111 1111111222111111111221111111111112 22122122121221221213212212122122122122713212214121212 2124124121221221221221221271312121214121212121214 unsigned int songCounter 0 Tone array unsigned int tones313 61156577235448351426485394581543242408153852536362 343213239530576 30576288612724125711242682290621621204071926218180171601619715 288 152881442913619128551213311452108091020396309089857980987643 I submitted By zane Kenne Attached as a gif format is the schematic I used for the mac Here is my code for displaying the frequency to the lcd I only kept the directly relevant sections Submitted By Seth Insley in main loop if updatelcd spiinit updatelcd 0 write frequency itoafrequency st3 1 10 homeline2 if fmfreq disp1ay frequency 64 frequency is always in the form 1xxx st30 st31 st31 3939 strinngcdst3 strinngcdquot MHzquot else display actual frequency of lo len strlenst3 st3len st3len 1 st3len 1 3939 st3len 1 39039 strinngcdst3 1 strinngcdquot MHzquot v SIGNALSIGOVERFLOW0 count freq TCNT3 TCNT30 every second if count 128 0 updatelcd 1 if fmfreq frequency int 1000 freq 1000000 else frequency int 10 freq 64 1000000 freq 0 Submitted By Dan Braunworth I don39t know if you wanted to include my fancy quotoffquot button for the alarm clock Like you said it39s a feature Here39s the code IN ALARM FUNCTION if the current time is within the range of the time passed into alarm and the alarm duration AND alarm is armed by ARMALARM flag AND the OFF f1ag cleared THEN enable output compare 1A interrupt ifHOUR hour ampamp MINUTE gt minute ampamp MINUTE lt minuteduration ampamp AM am ampamp ARMALARM 1 ampamp OFF 0 TIMSK 1ltltOCIE1A otherwise make sure to clear the OFF flag for the next alarm event else ifMINUTE lt minute MINUTE gt minuteduration OFF 0 c1ear OFF flag if alarm is not going off OFF BUTTON case 5 OFF 5 state5 state5 ltlt 1 PIND OxEF OxEOOO if state5 0xF000 OFF A 1 return 5 break From Experimental Methods in RF Design Uslng A Table Lookup To Deiermlne Knob Mo lon The table that is stored at the program memory table quotencode is reconsllucted here with the table address chest in binary and the table entries as declmal numbers 4Eil Address Onset Entry 0000 0 o o S I 41 0 0 3 l I A o a o I oe o xaaodoo odd The address otteet is shown as e blnaiy number oorresponding to decimal equivalent numbers oi o to 15 The binary values are the encoderoutput logic levels tor the last measurement iollowed by those tor the current measurement All 16 possible combinations are in the table Relating these to the knob encoder the binary numoers ale B A BA where ihe primed values reler to the last measurements and B and A are the two logic outputs irom the encoder some oi the address onsets such as 0101 or 1111 have the same old an new values and correspond to no motion oi the knob All tour of this type can be iound in the ta le to have an entry value ot a Indicating no ohan e1quot 5X1 are address o ssts such as 0001 Here I output has remained logiclevel 0 bu the A Output has ViomOt LR 39n ba 39 2h oi Fig 111 it can be seen that only it the kno as counterclockwrse motion is this possible This results in an entry at 71 in a similar ieshion en oilset oi 0010 can only occur ior clockwise rotation and on entry value oi 1 results lithe knob is controlling a value such as irequency the new value can result irom adding the 39 Iabls entry to the old Vrequenc Y Note that there are iour address a seis such as 0011 or 1001 that should never occur These correspond to both A and B outputs o1 the encoder changing at me same time Fig 111 would suggest that this cannot occur However it the knob is rotated so last that a slate is skipped over the 0011 combination may be encoun tered This combination tells us that the encoder has changed by two positions but there is no clue as to the direction For this reason the table entry must be zero meaning that no change will be made From R Traylor encoderchk Takes an argument either 0 or 1 the encoder to check If the encoder is moved the function returns 1 if CW rotation detected 0 if CCW rotation detected 1 if no movement detected Note the return value is a singed 8 bit int Expected pinout encoder 0 A output PORTE3 B output PORTE2 encoder 1 A output PORTE5 B output PORTE4 Port E is expected to be pulled up with the encoder causing a switch closure to ground Encoder pulls to ground with a 1K resistor Debounce time is 12 times each ISR run or loop time Code was adapted from Ganssel39s quotGuide to Debouncingquot int8t encoderchkuint8t encoder static uint16t state2 00 holds shifted in bits from encoder uint8t apin bpin if no encoder 1 is not specified assume encoder 0 if encoder 1 apin 5 bpin 4 else apin 3 bpin 2 stateencoder stateencoder ltlt 1 bitisclearPINE apin OxEOOO if stateencoder 0xF000 falling edge detected on A output if bitissetPINE bpin get state of quotBquot to determine direction return 1 detected CW rotation else return 0 detected CCW rotation else return 1 no movement detected encoderchk v From R Traylor chkbutton Checks the state of the button number passed to it It shifts in ones till the button is pushed Function returns a 1 only once per debounced button push so a debounce and toggle function can be implemented at the same time Adapted to check all buttons from Ganssel39s quotGuide to Debouncingquot Expects active low pushbuttons on PIND port Debounce time is determined by external loop delay times 12 The argument quotbuttonquot is the pushbutton on the mega128 board 52 button 0 through sg button 7 uint8t chkbuttonuint8t button static uint16t state8 00000000 holds shifted in button bits statebutton statebutton ltlt 1 bitisclearPIND button OxEOOO if statebutton OXFOOO return 1 if held true for 12 passes through else return 0 chkbutton From R Traylor 3 2 1 0 holds segment data uint8t segmentdata4 0x7F OxBF OxDF OxEF holds digit masks active low uint8t digitmask4 decimal to 7 segment LED display encodings output quot0quot to turn on segment uint8t decto7seg11 0xC0 0xF9 0xA4 0x30 0x99 0x92 0x82 0xF8 0x80 0x90 OxFF quot0quot quot1quot quot2quot quot3quot quot4quot quot5quot quot6quot quot7quot quot8quot quot9quot quotoffquot timercounter 2 ISR When the TCNTZ overflow interrupt occurs display is serviced This presently takes 35uS to execute SIGNALSIGOVERFLOW2 static uint8t i0 update the LED digit to display i update digit to display i i 4 i varies from 0 to 3 xFO cut all digits off PORTB ifsetalarmbool TRUE segsumalarmminutecnt alarmhourcnt else segsumminutecnt hourcnt ifsegmentdata3 0 segmentdata3 10 kill leading zero hours PORTA decto7segsegmentdata3 i send segment data to LED if blinkcolon 0x01 PORTA amp 0x7F blink colon PORTB amp digitmask3 i turn on the digit Submitted by Cassady Roop I39ve attached my frequency counter code counter and display code and button debouncer globals NBUTTONS is defined 8 or less unsigned char buttonVals Oxff holds button stable values unsigned char buttonHits 0 indicates button status changes unsigned char buttonQNBUTTONS debounce queue int main while1 infinite loop scanButtons update buttonHits buttonVals ifbuttonHits respond to button activity put button response code here buttonHits 0 clear flags debounce and monitor button inputs button inputs are passed into a 8 place history queue an unsigned char one per button An input is considered debounced and valid only when the entire queue sees the same bit When the queue first stabilizes to a single value the button hit flag is raised for that button and its value is recorded It is the responsibility of the button action recipient to clear the button hit flag External alteration of buttonVals will confuse this routine This routine must run an absolute minimum of sixteen times before a change in button status will be noted bouncing will increase this requirement uses all of port D void scanButtonsvoid int i unsigned char scandata PIND gather input from all buttons unsigned char oldvalue buttonVals fori 0 i lt NBUTTONS i buttonQi ltlt 1 advance the queue buttonQi scandata amp 1 enqueue latest bit ifbuttonQi 0x00 ampamp oldvalue amp 1 buttonVals amp 1 ltlt i clear val bit buttonHits 1 ltlt i set hit bit ifbuttonQi Oxff ampamp oldvalue amp 1 buttonVals 1 ltlt i set val bit buttonHits 1 ltlt i set hit bit scandata gtgt1 advance to next bit oldvalue gtgt1 Submitted by Cassady Roop globals volatile unsigned char flags 0 statuscontrol flags volatile unsigned long int runcnt 0 running counter tally volatile unsigned long int freqcnt 0 updated each second volatile unsigned char timecnt 0 counts to one second 128 Hz char freqascii7 quotresetquot int main init one time initialization tasks while1 infinite loop ifflags amp UPDATELCD cntToASCII updateLCD output to LCD flags amp UPDATELCD clear flag void initvoid deleted to save room void cntToASCIIvoid int offset 21000 measured error offset WRONG int i unsigned long int na n freqcnt n offset add offset prescaled n 64 L0 is prescaled by 64 a 100000000 fori0 i lt 6 i convert int to ascii freqasciii n a0x30 get digit value add ASCII 0 n a remove that digit from int a 10 next power of ten freqascii6 freqascii5 insert decimal point freqascii5 freqascii4 via embarrassingly lazy method freqascii4 freqascii3 freqascii3 3939 Debounce Ideas Submitted by Ben Hershberg DEBOUNCING PIND IMPULSE STYLE uint8t debouncepind Service routine called by a timer interrupt static uint16t State8 00000000 Current debounce status uint8t pind 0 int i 0 for i 0 i lt 8 i Statei Stateiltlt1 PIND amp 1 ltlt 1 gtgt i OerOO ifStatei0xf000 pind I 1 ltlt i return pind Then in the while loop or if you want to be super precise during an ISR insert this line debouncedpind debouncepind7 debounce DEBOUNCING WHATEVER YOU WANT GHETTO STYLE INTERRUPT FOR DEBOUNCING THE SHAFT ENCODERS INTERRUPTSIGOUTPUTCOMPARE2 LED REFRESH HERE OR WHATEVER YOU WANT debouncedPINE PINE debouncedPIND PIND Debounce Ideas Submitted by Ben Hershberg ONEOTHERNETHOD INTERRUPT SIGOVERFLOW2 StateIndex PIND ifIndexgtMAXCHECKS Index0 Inside main while loop jOXFF fori0 iltMAXCHECKS lijj amp Statei DebouncedState j buttons DebouncedState srbrokenc RLT 10606 This code serially shifts out a pattern to a 748C595 that causes the LEDs attached to its outputs to light one at a time in an ascending pattern from bit 0 to bit 7 It illuminates each LED for about 22 sec include ltavriohgt uint8t outvar g obal for holding output data simply creates a good sized delay void pause uint32t i fori0 ilt100000 i twidd1e the shift register clock pin to shift in data void c1kshiftreg toggle bit 1 shift register clock PORTS 0x02 PORTB OXFD twiddle the output register clock pin to output data void c1koutputreg togg2e bit 2 output register clock FORTE 0X04 FORTE OXFB sends out the eight bits of data stored in outvar uses a moving mask to detect the value each bit void senddata send eight bits of data uint8t mask uint8t i mask 0x01 0i0 ilt8 i clkshiftreg clock data bit i outyar amp mask test each bit of outvar PORTB PORTS 1 0x81 set data bit to 1 setup bit mask do for 8 bits else PORTB PORTB amp OXFE set data bit to 0 mask mask ltlt 1 shift mask left once for lsenddata main int main uint8t i DDR8 0x07 lower three bits of port B form interface 9data 1shiftreg clock 2output reg clk PORTS 0x00 initalize to zero whilel outvar 0x01 fori0 ilt7 i senddata send 8 bits c1koutputreg send data to output register outvar outvar ltlt 1 shift the bit left for next time forj0 jlt20 j pause do forever start with bit in zero position rotate through all bit positions wait 05 sec to make it Visible lmain Friday October 06 2006 Printed by Trayior Roger r 33cm Nb f 984 3 h g sieL Panto 5 W 901732 gmw 1a Pomai we SWFH uzstst t VLSOIS srbr0keno 111 Serial Peripheral Interface SP1 SPl Simple 3 Wire full duplex synchronous serial data transfer Interfaces to many devices even many nonSP1 peripherals Can be a master or slave interface 4 interface pins MOSl master out slave in MIOS master in slave out SCK serial clock SSin slave select PIN conoL LDGlC 3 registers SPCR control register SPSR status register SPDR data register sm CONTROL 5m lNIERRUFT lNIERNAL amust mm BUS Serial peripheral Interface 391 Full mm mm serial data trsmfu mam SP1 dsm39ee mmm Dam it shi admgnfmzms M3128 Moslp39m and minMIEOpin Data me as initimd by ixany writing dank the SPI data regime All dam Wt i3 mdinamd by 30K Wmlwmmmmmmmmmmmmm Togamdaumlyynummmk umsmawumuacm Serial Peripheral Interface SP1 Slave Select use it carefully In master mode SPI interface has no control of SSn User software has full control of SSn Port B bit 0 If configured as output it s a general purpose output If configured as input it must be held high else you will enter slave mode We will use SP1 in master mode full duplex Serial Peripheral Interface SP1 SP1 Control Register SPCR ReadWm nun m interrupt enable if set interrupt occurs when SPI interrupt ag and global interrupt enable are set enable if set SPI interface is enabled data under if set LSB is transmitted rst matter I SPI in master mode 39 ave select if set Elntk Elntk WW 39039 sc1lt low in idle 39139 sc1lt high in idle phase 039 leading edge sarnple trailing edge setup 39139 leading edge setup trailing edge sample in SPSR SPIZX SPRI SPRO 0 0 0 0 0 1 1 1 1 HHootu o duck raft Hot tob Ob O Serial P ripheml Interface SPI as mm W 5933 Wan5mm mmmsmma SPDRkIWWWfGMme Writing WDKWW mum MWgwaumammuwmimmso Serial Peripheral Interface SP1 Megal 28 LCD interface SCKPB1 LCD strobe MOST 9bit shi register enable pulse genemtor Serial Peripheral Interface SP1 SP1 Application Code 9 spiinit Initializes the SP1 port on the megal28 Does not do any further external device specific initializations 9 void spiinitvoid DDRB DDRB 0x07 Turn on SS MOSI SCLK SS is output SPCR lltltSPEN lltltMSTR spi enabled master low polarity msb 1st SPSR lltltSPI2X run at io clock div 2 spiinit 9 spisend Sends command and data to the SP1 port SPI device chip select is active low and is connected to port F bit 2 16 bits total sent void spisenduint8t data PORTF amp OXFB port F bit 2 assert active low SPDR 0x13 send command byte fixed value while bitisclearSPSRSPIF wait till data is sent out SPDR data send data byte while bitisclearSPSRSPIF wait till data is sent out PORTF 0x04 port F bit 2 deassert to logic high HF spisend Serial Peripheral Interface SP1 Typical SP1 1c MCP42010 su Putenuameter P1 5 Duly ava ahle on me dua MCPAZXXX Vemun Data 5 away mm m onthe edge m W39squot 51v e5 7 Ne may 5 x xEI EA Em 07305Xn5y34 D3L39D2I1V m so x 1 X TThere must away hemu um m tr ammwrpm Smsumymaxameum a P1 m nun nar mncrme MCFMXXX a mamms cs 5 mm W cammandswm ban n MCPAZXXXdeme Serial Peripheral Interface SP1 SP1 Gotchas Now my board won t program SP1 shares SCK with programming interface If it won t program anymore you likely messed up SCK SP1 acts totally wierd Often a symptom of SSn being configured as an input and being let to oat or allowed to go high SP1 goes in and out between slave and master modes 1 never get data to the SP1 device 1s clock correctly oriented Did you assert the device chip select hint put SP1 write inside a tight loop and check with scope Watch SCK data and chip select Debouncing Switches Mechanical switches are one of the most common interfaces to a uC Switch inputs are asynchronous to the uC and are not electrically clean Asynchronous inputs can be handled with a synchronizer 2 FF 39s Inputs from a switch are electrically cleansed with a switch debouncer What is switch bounce The nonideal behavior of the contacts that creates multiple electrical transitions for a single user input Nm Debcuncing Switches Switch bounce from the mega128 board pushbuttcn switches Debouncing Switches The problem is that the uC is usually fast enough to see all the transitions uC acts on multiple transitions instead of a single one The oscilloscope traces showed bounce durations of lO300uS our megal28 uC runs at 625nS per instruction a lOuS bounce short is leO395625X10399 160 instructions long a lOOuS bounce could be sampled as a valid true of false 100 s of times results are incorrect behavior as seen by user Characteristics of switch bounce nearly all switches do it the duration of bouncing and the period of each bounce varies identical switches bounce differently bounce differs depending on user force and speed typical bounce frequency is l5mS Effective switch debouncing can also reject EM and static charge effects ElH can be periodic don39t sample synchronously false triggering on static electricity is like a single random input Debmmcing Switches Sahm39m Analug mm mm 4311 RC daisy m lm cut the rapid charms in mm 3th uskiamahmRmCsudzmimmmidismmmud whkbomcingiamlloccmm in ll Debouncing Switches Solarium Cm wupled gamMC14044 40356 gates lack in one Intuition with a m39ngle pola doubim tmw switch bath swimMSEx Q and chipf038 are cxpensive mammary click witches ah AVR heard an 612 Debouncing Switches Solutions Software need to minimize CPU usage independent of clock speed do not connect to interrupt pins only programmed IO multiple interrupts will tie up processor don39t scan synchronously to any noise making device identify initial switch closure quickly lOOmS max Two approaches of many Count based identify initial closure count safe time check for same value watch for CPU speed dependencies use constant defines Digital filter based mimics an analog filter with firstorder recursive low pass filter includes a software schmitt trigger good EMI filtering quick response Debouncing Switches Solutions Count based Frorn Gansel s Guide to Debouncing routine called from timer interrupt or delay loop checks for Port D bit 2 pushbutton depression bit will be grounded returns 139 only once per button push pulsed output acts like an edge detector int8t debounceswitch static uintl6t state 0 holds present state state state ltlt 1 1 bitisclearPIND 2 OxEOOO if state OxFOOO return 1 return 0 value of state fhstpassa erreset 1110 0000 0000 0001 renn110 a erlZfaherxmses 1111 1111 1111 1111 renn110 a er7truerstes 1111 1111 1000 0000 renn110 a erthruernwses 1111 0000 0000 0000 rennn l a errnanytruernwses 1110 0000 0000 0000 renn110 a er5i sernwses 1110 0000 0001 1111 renn110 Debouncing Switches Solutions Digital filter based acts like analog RC filter followed by schmitt trigger nearly continuous output like an analog circuit l2ampOX3F075OXCOl0OXFF uint8t output0 external variable indicating switch state uint8t debounceswitch2 static uint8t yold0 flag0 uint8t temp digital filter part yold Xnew025 yold075 temp yold gtgt 2 this gives yold4 yold yold temp do yold075 by subtraction if button is pushed add 025 3F of new value 10 ifbitisclearPIND 2yold yold OX3F software schmitt trigger ifyold gt OxFOampampflagOflagl outputl ifyold lt OxOFampampflaglflag0 output0 Debouncing Switches Behavior of the digital lter debounce with schmitt trigger amingL mm mm mm mm yv 1v r TTTI T rrr vi TNTMMHM 114L A t 1 i K zF Armser nsm 13 AE 41be BC 4 a 55 s n mgmi mi away 9 m as m in mi rn m m 7HV 42 7O2157323 23 2 1w ar umymginm22 m m i 39 i 4 f i i k y W 24 mh Irll yiquot 50 Lw shilt h 7 Debouncing Switches Types of debouncer output Sometimes we want a continuOus output eg organ keyboard Other times we want a pulsed output eg increment hour alarm The first counting algorithm gives a pulsed output The digital filter algorithm gives a continuous output button push l pulsed output l l continuous output l r Debouneing Switches Converting between types of debouncer output To get a pulsed output from a continuous debouncer tput 1 always output O pushed0 output Debouneing Switches Converting between types of debouncer output To get a continuous output from a pulsed output pushedrising edge tput 1 pushedfalling edge output 0 Note that this requires sensing rising and falling edges USART and Asynchronous Communication The USART is used for synchronous and asynchronous serial communication USART Universal SynchronousAsynchronous Receiver Transmitter Our focus will be on asynchronous serial communication Asynchronous communication does not use a clock to validate data Serial data is transferred one bit at a time Asynchronous serial interfaces are cheap easy to use and until recently very common USB is well on its way to replace the serial comm ports on PCs The USART communicates in a fullduplex mode simultaneous xmit rcv USART and Wch3 Communicatim smut mm imam Bvuy mcv lhullm mini mum 5657801 canth hitth USART and Asynchronous Communication How can two asynchronous devices communicate with each other AVRl gt AVRZ 16Mhz lt 161Vth There is no known phase relationship between the two AVR boards How can a receiving board know where the center of a bit frame is How can it know where the start bit is 0123 start bit What do we need to know USART and Asynchronous Communication Need to know how fast the bits are coming baud rate Need to know where the start bit begins its falling edge Then we know when to sample 0123 tttt start bit sample sample sample sample USART and Asynchmnnus Ccmmunication mummsmmclzummwmmm a P A H 1 Y 7 w n H m p 1 r M mm t A A ulwmm chlw um thvm Hmml m mmdmm mmmwmmmm USART and Asynchronous Communication The USART internal clock is set by the UBRR register an I 7 a 2 a Reaman n R R R WW RW ww RW w WW ww R W Rrw RW WW Rw m a Value 0 0 a 0 0 u 0 u o o o o a n a n The intemal clock is derived from the internal CPU clock Both transmitter and receiver use the same clock to operate from The transmitter is synchronous to the clock In coming data to the receiver is not The baud rates are not exact power of 2 multiples of the CPU clock thus baud rate inaccuracies occur at some settings rm 16 MHz Ea an 77 bps uann Error ERR Error 2400 m 1 522 0 4500 207 a 2 416 0 r 9500 ms 0 2 207 02 144k as 00 135 01 re 2k 5r 0 2 ma 02 253 34 0 3 as 05 35 4k 25 u 2 31 02 57 6k 16 24 34 0 5 763k r2 0 2 25 02 u52k s 25 16 21 2304k a a 5 a a 5 250k a u 0 7 00 mm 1 u 0 a n 0 1M 0 u 0 1 00 Max W 1 M ps 2 laps 1 r Lu 2 n 2 n a USAR I and Asynchronous Communication Em dmw m mwmxokwmww Mamba Mamet P xmdnl X10sz mu madman wa 1XUPdIk1XOR PI limbawe adlmmmltlml Mmmoddpan ty np tyhitismwa m wm amiowuu nthmmoddmm aofm w101101 u uwityml USART and Asynchmous Communication Em taaim v mm hummwhmhmhme umm anddoeam ndit dwhmmammia mfa m mmmmum WW 13 mm 15quot Wmmmmit inkLt 1 USART and Asynchrmous Communication Um r eeui dpah Wcm umnzmm rmmmma PC 3343 audio animmted 3 Val imam a avoluixemma Iquotm mar gt3mumma We may 2 3V USART and Asynchronous Communication 5v TNPUT USART R8232 transceiver Charge Pump inverter used to generate negative voltages 10V m m mv vome nousm rTOV uov Va 4w vaLucE warm TTLCMOS NPUTS R3232 OUTFUTS TTLCMUS OUTPUTS R5232 INPUTS USART and Asynchronous Communication USART Electrical path The mega128 board uses the MAX232 chip It has an internal charge pump to generate the negative and positive voltages for the RS232 interface The DB9 connector is standard for mating with a PC serial connector The port D interface is shared with the IR LED lO devices They are inverted also so that an space signal does not keep the 1R LED on lOOmA USART and Asynchronous Communication USART Electrical path UART can be used with IR LED also IR Trarwsmtter zmuuz H jruiwm vv W a 39f ii Eg i WEE 7 n mu mum mu mm m mm a x USART and Asynchronous Communication Some useful USART Software Routines it uartinit RXDO is PORT E bit 0 TXDO is PORT E bit 1 Jumpers J14 and J16 mega128l OR Jumpers J7 and J9 mega1282 must be in place for the MAX232 chip to get data void uartinit rx and tx enable 8 bit characters UCSROB lltltRXENO 1ltltTXEN0 async operation no parity one stop bit 8bit characters UCSROC 1ltltUCSZ01 lltltUCSZ00 set to 9600 baud UBRROH0X00i UBRROLOx67 USART and Asynchronous Communication Some useful USART Software Routines it uartputc Takes a character and sends it to USARTO void uartputcchar data while 1UCSROAamp1ltltUDRE Wait for previous transmission UDRO data Send data byte while 1UCSROAamp1ltltUDRE Wait for previous transmission it it uartputs Takes a string and sends each charater to be sent to USARTO void uartputsunsigned char str void uartputschar str int i 0 Loop through string send each char whilestri l 39039uartputcstri i USART and Asynchronous Communication Some useful USART Software Routines it uartgetc Modified to not block indefinately in the case of a lost byte char uartgetcvoid uint16t timer 0 while 1UCSROA amp 1ltltRXCO timer iftimer gt 16000 return 0 Wait for byte to arrive return UDRO Program Development Tools Programming Editors Many good editors for programming exist Two are available most anywhere vi emacs vi pronounced vee eye Being able to use vi ensures that you will always have an editor available vz is available on all uniX systems other editors are not no need to remove your fingers from the typing area of the keyboard vi stays out of your way no menus and short commands you really only need to know about a dozen commands Once those are mastered 30min add to your repertoire global replacement is 7 split files vertically and horizontally A quotm THATquot copy and paste between multiple open files make program and never leave the editor vi help sites http staff washington edu rellsRl 1 0 helpvi html httpwwwvmuniXcomgaborvihtml httpdocsfreebsdorg44docusd12vipaperhtml Joy an Horton httpthomercomvivihtml fun way to waste time Program Development Tools Vi commands To begin editing a file Vi vi filename To close vi q q 1 X ltShiftgt 22 Writing a le W w newname wq Read in a le r filename opens vi opens vi on f i lename quit it will query you if changes were made quit without save save and exit save and exit write out current file write out current file as newname write file and quit like or ltshiftgtzz Read in f i lename into current one after the cursor Program Development Tools Vi commands Modes input command Input Mode Insert text i insert text just prior to cursor Append text a append text just after cursor Open line 0 open a new line below the current one 0 open a new line above the current one Replace r replace the character under cursor R replace continuously Exit input mode ltescgt Program Development Tools Vi commands Modes input command Command mode In command mode we do everything e1se moving around in the le search and replace yank copy and put paste de1ete split screens Command mode entered from input mode by ltescgt You enter Vi in the command mode Program Development Tools Vi commands Modes input command Moving around in the le UWI D ltCtrlgtu ltCtrlgtd move one character left move one character right move one line up move one line down move up one page move down one page move forward 1 word move back 1 word move to end of line move to line 1 column 1 move to last line column 1 go to line n Program Development Tools Vi commands Modes input command Yankpaste delete YY p 8 YY cw dw dd yank current line paste a line yank next 8 lines a subsequent paste will paste all 8 lines delete character change word delete word delete current line line goes in paste buffer join next to line to current undo multilevel repeat repeat last command Program Development Tools Vi commands Modes input command Search and Replace pattern search for pattern forwards pa 1 t e rn search for pa 1 t e rn backwards I1 repeat last search soldnewg replace every occurrence of old with new in entire le Program Development Tools Vi commands Modes input command Multiple screens sp newf i le open split screen with newf i le displayed Vsp newf i le open vertically split screen with newf i le displayed lt c t r l gtww move between screens lt c t r l gtwn split existing Window lt c t r l gtwv split existing Window vertically Program Development Tools avrgcc One of the GCC cross compilers Free Open source world class optimizing compiler Runs on Linux Solaris Mac PC Available for almost any target uCuP See AVR Freaks site for avrgcc help wwwavrfreaksnet uisp Universal In System Programmer Allows programming of AVRs through the parallel port avrdude Another in System Programmer Allows programming of AVRs through the parallel port or USB avrobjcopy copies and translates object files avrobjdump diplays information from object les Program Development Tools avrgeCavrobj copyuisp avr gcc g c Wall 02 mmcuatmega128 o mycodeo mycodec avr objcopy j text j data 0 ihex mycodeelf mycodehex uisp dprogstk200 dpartatmega128 dlptdevparport0 erase upload ifmycode hex V Program Development Tools make To automate and simplify the process of making an executable image for the microcontroller we use the make utility make is the puppetmaster of your build environment It checks file dependencies and compiles only the files that require it executes other commands to generate other les EEPROM images is very general purpose it works with any language and other tools lets us make one Makefile that can be used with many other programs In more complex programming environments make is an excellent way to manage the creation of an executable from 10 s or 10039s of files Program Development Tools Make les make reads a le called Makefile or makefile that describes the dependencies and actions to take to generate the executable image The syntax of a makefile rule is as follows target list dependency list lthard tabgt command list src src avr gcc g c Wall 02 mmcuatmega128 o sro src This rule tells make that sr o is dependent on sr c if sr c changes sr 0 must be recreated by running the avrgcc command Program Development Tools make a simple make file for src PRG sr all PRGelf SI 0 src avr gcc g c Wall 02 mmcuatmega128 o sro src SI f sro avr gcc g Wall 02 mmcuatmega128 Wl MapPRGmap o srelf sro 39 i srhex srelf avr objcopy j text j data 0 ihex srelf srhex program PRGhex uisp dprogstk200 dpartatmega128 dlptdeVparport0 erase upload ifsrhex de endanc with no command lst PRG 1st p y srlst srelf avr objdump h S srelf gt srlst clean k a phony target rm rf o elf hex lst map Program Development Tools make PRG sr OBJ PRG O MCUTARGET atmega128 OPTIMIZE 2 OO options are l 2 3 s OBJCOPY avr objcopy OBJDUMP avr objdump CC avr gcc override CFLAGS g Wall OPTIMIZE mmcuMCUTARGET override LDFLAGS Wl MapPRGmap The automatic variables make recognizes file name of target ie left hand side of lt name of first prerequisite name of all the prerequisites that are newer than the target A Names of all the prerequisites all PRGelf lst text eeprom The dependency for 39allquot is the programelf and three other rules The target quotallquot is known as a quotphony targetquot as it is not a file but a name used to have quotmakequot do something for you Program Development Tools make PRGelf OBJ cc CFLAGS LDFLAGS o Make understands that to make an obj you compile a c Thus we only need to say we want a elf from an obj is make shorthand for left hand side of quot2quot A is make shorthand for right hand side of quot2quot A clean rm rf o PRGelf lst map The target quotcleanquot is another phony target that cleans up all the extra files we make at each compile program PRGhex uisp dprogstk200 dpartatmega128 dlptdeVparport0 erase upload ifPRGhex Target quotprogramquot depends on the hex file which it downloads to the target board using the parallel port Program Development Tools make lst PRGlst lst elf OBJDUMP h S lt gt The target quotlstquot is another phony target Its depends on the lst list file The list file shows the assembly language output of the compiler intermixed with the C code so it is easier to debug and follow avr objdump OBJDUMP is the avr binutil tool we us to get information from the elf file lt is shorthand for source file for the single dependency Program Development Tools make Following are rules for building the text rom images This is the stuff that will be put in flash text hex bin srec hex PRGhex bin PRG bin srec PRGsrec hex elf OBJCOPY j text j data 0 ihex lt Take any elf file and build the hex file from it using avr objcopy avr objcopy is used to extract the downloadable portion of the elf file to build the flash image srec elf OBJCOPY j text j data 0 srec lt Make the Motorola S record file hex elf OBJCOPY j text j data 0 binary lt Make a binary imagae also Program Development Tools make Following are rules for building the eeprom images This is the stuff that will be put in EEPROM eeprom ehex ebin esrec ehex PRGeepromhex ebin PRGeeprombin esrec PRGeepromsrec eepromhex elf OBJCOPY j eeprom change section lma eepromO O ihex lt This builds the EEPROM image from the elf file for downloading eepromsrec elf OBJCOPY j eeprom change section lma eepromO O srec lt This builds the S record image from the elf file if necessary eeprombin elf OBJCOPY j eeprom change section lma eepromO 0 binary lt This builds a binary image from the elf file if necessary Power Management and Sleep Modes A key feature of many microcontrollers is low power consumption The principle way to reduce power consumption is to stop the clock Quiescent CMOS consumes essentially no power at feature sizes gt 35u CMOS power dissipation is mostly due to dynamic power dissipation ie power dissipation caused by signals transitioning For example in the DEC Alpha microprocessor 1995 approximately 50 of the 30W dissipated was spent in simply driving the clock tree Rough figure for power dissipation in CMOS neglicting leakage Pd CVZf where C capacitance V voltage f frequency of operation Power Management and Sleep Modes To save power in the AVR cut off the clock to unused modules The MCU Control Register holds the power management settings MCU Control Register an 7 a RW w lnml Wu H n n n n n sleep enable if s t the MCU will enter sleep mode when the SLEEP i nstmctjon is executed 5M2 5M1 5M0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 s 5 1 a t t Emma m mm w NW NW NW Rw n n Idle ADC noise reduction Power Down Standby Extended Standby Power Management and Sleep Modes Sleep Modes Idle Mode Stopped CPU Flash memory Running SP1 USART Comparator ADC TWI TCNTO3 Watchdog Wakeup external and internal interrupts ADC Noise Reduction Mode Stopped All above plus the IO clocks Running ADC TWI TCNTO Watchdog Wakeup external and internal interrupts Powerdown Mode Stopped All the above plus the external oscillator Running External interrupts TWI address match Watchdog Wakeup Watchdog or brown out reset external interrupt Power Management and Sleep Modes Sleep Modes Power Save Mode identical to Powerdown except Running TCNTO also if clocked externally asynchronous mode Wakeup can also wakeup from TCNTO interrupts Standby Mode identical to Powerdown except Running External crystal clock oscillator still running Wakeup just like Powerdown except wakes up in 6 clock cycles Extended Standby Mode identical to Powersave except Running External crystal clock oscillator still running Wakeup just like Powersave except wakes up in 6 clock cycles ATMegal28 lO Ports The AVR IO ports are the path to the outside world Understand how to use them and life is good Failure to understand how the ports are used will cause grief and possibly cost 39s An abused IO port is fairly easy to burn outwith excessive current or static damage most all the IO ports are oating inputs that can build up large static charge Never carry your AVR board in a non staticdissipative bag dry fall days are perfect for creating conditions for BSD damage practice safe electronics use the pink bag Using proper port software conventions Will keep code transportable readable and more bug free ie TIMSK 1ltltTOIEO Versus TIMSK bOlOOOOOO ATMegalZS IO Ports 0 Port input structure Logic See Figure General Digiial lO lor Details protection diodes programmab1e pullup resistor What happens if voltages exceeding Vcc are applied to an UO pin can you power a chip from an UO pin ATMegal28 lO Ports All ports have bitselectable pullup resistors have bitselectable tristate outputs What are these have schmitt trigger input buffers What is that can you draw one are synchronized to the system clock to prevent metastability What is that have symmetrical DC drive capability What does that mean All ports have readmodifywrite capability ie ie you can change pin direction pin value or pin pullup resistor without effecting any other pins in the port Control of all ports and pins is done with three registers DDRX ie DDRB is data direction register port B PORTX ie PORTB is the output register for port B Ple ie PINB in the input register for port B All of these ports may be read Writing the Ple register does nothing ATMegalZS IO Ports A VR port architecture EW ullup resistor 1 analog switch Pun PULLuP msng SLEEP SLEEP CONTROL PX mm OCLOCK HRx READ PORTX REG STEH x READ PORTX P ATMega128 IO Ports A VR 10 port usage bit 0 output mode logic 39139 asserted if PINBO is read it returns a 39139 bit 1 output mode logic 39039 asserted if PINBI is read it returns a 39039 bit 2 input rnode no pullup resistor if P1NB2 read returns state of pin bit 3 input rnode pullup resistor on thus if PINB3 is read it returns a 39039 if pin is driven 39039 returns a 39139 if the pin is not driven 7 6 5 4 3 210 DDRB 00000011 7 6 5 4 3 210 P0RTB00001001 7 6 5 4 3 210 PINB 01 ATMegal28 IO Ports A VR 10 port usage DDRX selects pin direction in or out PORTX determines the driven pin value if the pin is an output determines if a pullup is present if the pin is an input PlNX holds the value of the pin Port usage ne points Regardless of the setting of the DDRX register the port pin can be read from PINX Thus an driven output value in PORTX can always be read in PINX When the pullup disable bit in the Special Function IO Register SFIOR is set all pullups are disabled regardless of the setting of DDRX and PORTX Pullups are also disabled during reset Input pins have a 15 clock cycle delay before a new value can be read l NOP instruction necessary to read updated pin Use pullups on unused IO pins to lower power consumption Using alternative functions of some port pins does not effect other pins ATMega128 IO Ports A VR 10 port programming In the le iom128h define statements are used to make shorthand notation for po sandb s Foreanpb Data Register Port B define PORTB SFRI08OX18 and also Port B Data Register PORTB define PB7 7 define PB6 6 define PBS 5 define PB4 4 define PB3 3 define PB2 2 define PB4 1 define PB3 O ATMegal 28 10 Ports A VR 10 port programming The def ines allow us to program like this PORTB 0x05 DDRB OXOA OR SPCR 1ltltSPE 1ltltMSTR DDRB 1ltltDDB2 1ltltDDBO AND tempo PINB Which way of setting SPCR and DDRB is better What is the difference ATMe gal 28 IO Ports A VR 10 port programming By using AND OR and XOR we can manipulate individual bits toggle bit 5 PORTB PORTB A 0x20 invert PORTB A 0x20 invert again another way set bits 7 and 2 don39t bother others PORTB PORTB 0x84 PORTB 1ltltPB71ltltPB2 shorter more portable Clear bit 0 and 1 but nothing else PORTB PORTB amp OXfC PORTB amp 1ltltPBO1ltltPB1 more portable ATMegal 28 10 Ports A VR 10 port programming Assume correctly that after reset the following is true DDRD 0X00 DDRB 0X00 Assume a megal28 board has a normally open switch attached to port D bit zero When the switch is closed the port D bit is connected to ground Write code that reads port D bit zero inverts its value and outputs that value to port B bit 0 Do not disturb the values of any other pins 5 minutes ATMegal 28 10 Ports A VR 10 port programming Assume a rnegal28 board has a normally open switch attached to port D bit zero When the switch is closed the port D bit is connected to ground Write code that reads port D bit zero inverts its value and outputs that value to port B bit 0 Do not disturb the values of any other pins include ltavriohgt read port d bit 0 invert and output to port b bit 0 int main DDRD amp OxFE make port d bit zero input mode PORTD 0x01 turn on bit 0 pull up DDRB 0x01 set port b bit 0 to output mode ifPIND amp OX01PORTB amp OxFE else PORTB 0x01 ATMega128 IO Ports A VR 10 port DC characteristics The Absolute Maximum Ratings are not Where you want to operate an IC Ahaelute l39u39leximum Hetinga Dperat39ng Temperature 55Ctr 125 Etcrage Temperature4591319 1 513 C Voltage an any Pin emeptFiEE ET 191111 reapeat 11 Ground to ch0539quot 1uquotltage n RESET with reepen to Gram IZI5quot 1I 130 Maximu39n Opera ng thage 61Tquot DC Current lit P39n me JG Current V a GNU 2000 me Where do these ratings come from NDTIBE Stresses beycnd mcee listed under hmlute Maximum Ratingsquot may eause permanent dam age 1 1he dewiee This is a etrese rating enli and fumtienal epera on 01 The device at these cur Eitth ejnditiam39ra bevpnd 1110a indicated in 1113 qzeratiznnal aeetiene 1 this epecificatim is not implied Ernstaura 1e absome maxihum rathg mndilicuna for extended rnay affectdevice reliability ATMega128 IO Ports A VR 10 port DC output characteristics Output Buffer characteristics mega128 datasheet page 321 31H Input rug aung ncclzl pll v0 39rco 39 7 1 LL 339 V output Low Voltage 0 so me v53 5a 07 V 1 Ports AElGD E F G rm to me vet as 05 tr 1 output High Voltagequot lgH so mA v35 EU 42 V 393 Ports Aeco E F at tIH 4o ma 939 av 24 tr Always read the footnotes 3 41 mans u Honest mu m s Although each MO port can sink more than the test conditions 20 mA at VD 5V to me at V0 3V under steady state conditions mntransientjl the following must he deserved TO FF and MLF Package 1The sum of all IDL for all ports should not exceed 400 me 2 The sum of all IDL for ports AC AT G2 I33 C should not exceed 300 me 3 The sum of all IDL for ports Co 132610 Gt Do DT HALE should not exceed 150 me 4The sum of all IDL for ports Bo BT GS G4 E0 E should not exceed 150 mA 5 The sum of all ICIL for ports Fe FT should not exceed 2e me If ICIL exceeds the test condition Iart39le may exceed the related speci cation Pins are not guaranteed to sink current greater than the listed test condition Humnnucwu N La 1qu m III II Although each lquotO port can source more than the test cend itions I120 mA at do 5V to me at Vcc 3le under steady state conditions tmn Wansientil the following must he observed TQ PP and MLF Package 1The sum of all IOH for all ports should not eetoeed 400 mA 2The sum of all ICIH for ports A0 A 32 G3 C should not exceed so me 3The sum of all IOH for parts Go 321134 I31 Do 37 XTALE should not exceed 15o me 4 The sum of all ICIH for ports Bo E2183 I34 EU E should not exceed 150 mA 5The sum of all IOH for parts Fe FTE should not exceed 2o me If lCtH exceeds the test condition 39uiOH may exceed the related speci cation Pins are not guaranteed to source current greaterthan the listed test condition ATMega128 IO Ports A VR 10 port DC input characteristics Input Buffer characteristics mega128 datasheet page 321 TAL 4CI C to BEE VD 2V to 55V unless otherwise noted Symbol Parameter Cenditlon I in Typ Max Units Exce XTAL1 and VIL Input Low Voltage RESET pins 435 02 lm If V Input Lew Veltage szgi gmal 435 01 V5351 It VH2 Input Lew h eltage REELr pin 43 02 VIEW it Except XTAL1 and 239 VIH Input High Whage RESET ping I3 is 39u gnl 39 V0 v5 V elm Input High v eltage i s c mm a axle vac 05 V VH4 Input High Voltage RESET pin 085 Vm j i39 RICE L15 39u39 nanl Irul39 39l I na A II rm 5 H I Input Leakage VCC 55V pin law 1 D A quot Current I D Pin abetlute value u I Input Leakage Vsc 55V pin high 1 U A quot4 Current I O Pin atajlutemluel 39 u 39 FIRST Fleset Pullup Resisth 30 all he FIFEquot PEN Pullup Flee39stor 30 ea hi Flpu LICI Pin Pullup Resistor 2D 50 IL I quotquotJ quotquot I In IIIElllI IlDI39I Ll l y39 I 133 DUquot I I IUIIJ Mates 1 39MaJf means the highest value IIirhere the pin is guaranteed te Ize read as lea E 39I39elin means the lamest value where the pin is guaranteed to be read as high ATMegal 28 10 Ports A VR 10 port interfacing Pullups are handy for terminating switch terminals but watch the leakage current Quadrature encoder 90 deg phased outputs How would you hook it up What about protection of output drivers What about protection for input buffers Led Drive Circuits Highside or lowside drive How do you determine the correct values of current limit resistors When do you need external drive help with a transistor Motor or relay drive circuits catch diodes for inductive kickback Interface directly to a speaker Can it be done 5V to 33V or 33V to 5V interfacing resistor and protection diodeor two resistors or resistor and zener diode 74LVC244 TXBOlO8
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'