Home

Developing Embedded Control System Platform using

image

Contents

1. 28 5 5 3 ATmegal28 SPI 29 5 505 30 Prototype I O card 31 601 oer Be Se ee S pesce thE eS ah ed 31 6 2 Beat res si eos oo Bee aa eG a BAe x Ve ES 31 6 3 Components i24 te s Due yout pr hy ure Ue de 32 Schematic uc EU EB 32 6 4 1 Power 33 6 4 2 Reset Crystal and Analog Supply Circuit 34 6 4 3 JTAG header and Analog Input Connectors 34 6 4 4 RS 232 circuit and Digital Output Connectors 35 6 4 5 5 1000 headers and Digital Input Connectors 35 6 4 6 Decoupling Capacitors and VCC GND Connectors 35 6 4 7 Analog Output 37 6 5 7 Ps EV 38 6 6 Assembly nd 40 6 6 1 Power Regulator 40 6 6 2 ATmegal28 and JTAG Interface 40 6 0 3 Crystal ee ee ba eae eee he use 40 6 6 4 RS 232 and Reset Al 6 6 5 Headers for STK1000 and debugging Al 6 6 6 ADC Supply Al 6 6 7 Analog Output 42 6 7 Errors in Schemiati 2 Ea p ip dog ee os ee 42
2. H ONnorwh NNN 144 APPENDIX CODE int StartStopWatch struct sStopWatch sWatch This function stops the stopwatch and returns the result int StopStopWatch struct sStopWatch xsWatch include stopwatch c 3 6 stopwatch c int StartStopWatch struct sStopWatch xsWatch t Returns an error if the watch have already been started if sWatch gt state SWATCHSTARTED return 1 Starts the watch notice that gettimeofday is the last thing to happen This is because that will be most accurate sWatch gt state SWATCHSTARTED sWatch usec 1 gettimeofday amp sWatch gt start NULL return 0 int StopStopWatch struct sStopWatch sWatch Returns an error if the watch havent been started if sWatch gt state SWATCHSTARTED return 1 Stops the watch and calculate the result and return this Notice that gettimeofday is the first thing to happen This is because that will be most accurate gettimeofday amp sWatch gt stop NULL sWatch gt state SWATCH STOPED sWatch gt usec sWatch gt stop tv_sec 1000000 sWatch gt stop tv_usec sWatch gt start tv_sec 1000000 sWatch gt start tv_usec return sWatch usec C 4 Matlab S functions C 4 1 Analog input TLC Yimplements avr32io adc C function InitializeConditions block system Output lt
3. 95 12 User manual for AVR32 I O 97 1244 Installing zo Repo xd a v E d s X3 97 12 1 1 Install AVR32 tool chain 97 12 1 2 Compile Linux kernel with AVR32 I O card support 98 12 1 3 Install AVR32 support in 98 12 2 AVEOZ DO 99 12 2 1 Hardware description 99 12 2 2 Connecting 1 101 12 2 3 Analog Input ee e 101 122A Analog Output 3 94 Fie bed ee PE a ee i 101 12 3 Rapid prototyping with Matlab Real Time Workshop 102 12 3 1 AVR32 System 102 12 3 2 S functions for I O card 14 5 rp hd oe ig a 102 13 Discussion 105 Linux Pre n eee eene pe vt Dan ws ig 105 13 2 95 oo ds Rock ect de oR Op tte inh qe v S auc se 105 13 3 I O card Communication and Drivers 106 13 4 Matlab Real Time Workshop 107 14 Conclusion 109 15 Further Work 111 Digital appendix 113 B Schematics 114 B 1 Schematic for protoype card 114 B 2 Schematic for final card a 114 C Code 117 CT 128 gt 222 nthe Bk ok oe ee ee Sa AW 117 Maketile reae hos Es Wee ase ee Rer a 117 C12
4. 3 1 Send dummy Received ack code Yes 3 2 Send dummy 3 3 Save data 3 4 Send data ack 3 5 Save data Expect more data No 3 6 Send data ack Received dummy L 4 1 Send OK Received slave OK L No Yes 1 E E NH NH NH NH NH HEH Error Success Figure 7 5 Activity diagram for device driver when master sends data 53 54 CHAPTER 7 DESIGN OF I O CARD SOFTWARE Synchronization 3 E EH OH BH HB NH B EH HB H NH NH 1 1 Send code Received slave ready Master data B m m NM Yes m m BH E H H NH NH NH 2 1 Send data No Received code ack Yes 2 2 Send data Received data ack Yes send more Received last data ack BH oH OH HB HB B NH Yes Confirmation E NM NH NM NM NH NH NH NH NH NH NH 4 1 Send Received i slave OK Yes m BH NH NH NH NH NH NH Error Success Figure 7 6 Activity diagram for device driver when master requests data o Confirmation phase e Activity 4 1 sends the master OK signal e Decision point 4A checks if the received data was a slave OK signal If it was a slave OK signal the message was sent successfully 7 3 3 Request Data from Slave activity diagram in figure 7 6 describes how the device driver sends a message that retrives data from the slave The Synchronizat
5. Sends SPI message for Digital out Number Received from master Returned to master 1 code READY D mask code 4 1 3 value mask 4 1 4 DUMMY vaule 1 5 MASTER_OK SLAVE 2 int Cmd SetDOut u8 fromUser ifdef BUFFERING MODE Sends SPI message for enable analog in 66 67 68 69 70 71 72 73 74 75 76 77 78 70 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE Number Received from master Returned to master il code READY 2 enable code 1 DUMMY enable 1 5 MASTER_OK SLAVE OK int Cmd_EnableAIn u8 en int ch fendif Sends SPI message for analog out resolution Number Received from master Returned to master 1 code READY 2 resolution code 1 DUMMY resolution 1 5 MASTER_OK SLAVE_OK A int Cmd_SetAOutResolution u8 resol int ch ifdef INTERRUPT MODE DECLARE WAIT QUEUE HEAD wq Makes a wait queue Function that runs om interrupt irqreturn t irqFunk int irq void dev id struct pt regs regs Zinclude avr32io Zendif KM_AVR32IO_CMD_H When using interrupts for the analog input command an interrupt function has to be used This functions runs when the kernel receives an interrupt and it can wake up a sleeping analog input command These functions are all very similar and below the Cmd_SetAOut function are showed as an example of the functions in the code file Line 72 of this function checks that the channel is a
6. gt Block XName Enables all analog input channels when system starts up foreach opIdx NumDataOutputPorts LibBlockOutputSignalConnected opIdx avr32io_EnableAnalogIn lt opIdx gt 1 Aen dif endforeach endfunction function Outputs block system Output lt gt Block XName Do command for getting analog input value foreach opIdx NumDataOutputPorts LibBlockOutputSignalConnected opIdx 23 24 25 26 27 25 26 27 28 30 31 32 33 34 ANookwnre C 4 MATLAB S FUNCTIONS 145 lt LibBlockOutputSignal opIdx 0 gt avr32io_GetAnalogIn lt opIdx gt 0 0048828 endif endforeach endfunction C 4 2 Analog output TLC implements avr32io dac C function InitializeConditions block system Output UKType gt Block lt gt Set resolution for both of the analog out channels avr32io SetAnalogOutResolution 0 int 9cLibBlockParameter P1 0 gt avr32io SetAnalogOutResolution 1 int 9cLibBlockParameter P2 0 gt endfunction function Outputs block system Output UKType gt Block XName through all ports and set analog out functions for the ports that are connected static int count 6 int ret foreach opIdx NumDatalInputPorts if LibBlockInputSignalConnected opIdx if opIdx 3 ret avr32io SetAnalogOutDouble 0 96copIdx
7. Write data to device node and close it ret write fd data 3 close fd if ret lt O DEBUG avr32io_user error on write i n ret return ret pthread mutex unlock amp spiMutex 64 65 66 f F ONMDOBRWNFOOANDWAKWNEHE 41 42 43 45 46 74 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE return 0 8 5 Threaded User Mode Driver The threaded driver was implemented as a layer above the user mode driver which means that it will use the functions of this driver It should contain function calls for starting the analog I O threads and functions that sends and gets data to these threads The header file for the threaded driver are below while the code file is in the appendix C 3 2 include periodicTask h include avr32io_driver h define MASTER PERIOD 0 001 Structure containing information about each of the analog input channels struct sAinChan int chanNumber double value pthread_mutex_t mutex struct sPeriodicTask samplingTask struct sAinChan ainChanList 8 Structure for list of command the worker thread has to execute struct sAoutCmd int chanNumber int subchanNumber double value struct sAoutCmd next h struct sAoutCmd xaoutCmdListFirst aoutCmdListLast pthread t aoutWorker Worker thread for analog out pthread mutex t cmdListMutex PTHREAD MUTEX INITIALIZER for command list pthread
8. 1 1 0 0 02 0 04 0 06 0 08 0 1 0 12 0 14 Figure 11 4 Results of sending sinus signal through digital I O 11 3 shows what may happen if the sampling thread has a long period Several of the Simulink time steps will read the same analog input value This will be a problem if the input signal changes fast but for a more stable signal it would be a good opportunity to reduce the SPI usage 11 4 2 Results of Digital Test This test was executed almost in the same way as the analog test This means that a sinus signal was sent to one of the channels of the digital outputs that was connected to the digital input Since the digital output only can send OV or 5V signals the digital input should receive a square signal Figure 11 4 shows how two different square signals are made in this way with a sinus signal The two signals have different duty cycles since they have been made with different limit values in the digital output S function 96 CHAPTER 11 MATLAB REAL TIME WORKSHOP Chapter 12 User manual for AVR32 I O In June 2007 yvind Netland finished a master thesis 24 about how to use the new Atmel AVR32 processor architecture as a control system In this work a STK1000 development board was used together with an I O card that was developed during the thesis This I O card communicates with the STK1000 through SPI and it has 6 channel analog output 8 channel analog input 8 channel digital output and 8 channel digital
9. Chapter 7 Design of I O card software This chapter describes the design of the I O card drivers and firmware Chapter 8 Implementation of I O card software This chapter describes the implementation of the I O card drivers and firmware Chapter 9 Testing with prototype card This chapter testing the prototype card with the I O card drivers and firmware Chapter 10 Final version of I O card This chapter describes the design and production of the final version of the I O card Chapter 11 Matlab Real Time Workshop This chapter adapts Matlab Real Time Workshop to be used as a rapid prototyping tool for the control system platform Chapter 12 User manual This chapter describes how to install the necessary tools and use the control system platform Chapter 2 Background 2 1 Embedded Control System An embedded control system 14 or control system for short is a computer system whose main task is to control a physical device or a system These can vary in sizes from large and complex systems like a ship or a factory to smaller devices like a toy robot control system will have a predefined task that won t change over time This allows a control system to be more specialized than a workstation computer 2 11 Real time Constraints Control systems often have real time 18 constraints which means that an operation has to be done both correctly and within a time limit Hard real time constraints means that the system will fail wit
10. ek A ee BEE Ge ee bunt 117 cam 1281026 o Ben te s a ee its 118 1 4 aml28spiSlave c 2 122 2 15 ain 128 ade Ce Sle sO ad Doha at eek bed ed hate OS lok 122 G6 vam 28 eie Rec ey eed XR UE ae 124 CU oe oa NC ha SIS 126 2 2 Kernelimodule ura dudo 128 C 2 1 Makene bie ob aie ee ree 128 C2222 ANTS 210C Sect Eth Pe Eee ity E ue Rie ee arte he do 128 2 8 avr3210 Cmd 6 apres he eu ee el 131 C221 avr3210 SBEC i RARE ERA 135 gt User dist Mte deri Ee d dr EE des 136 vavr32io drivere 26 nero sodes m Xe 136 C3 2 avr32io threads 6 2 WIRT p aor eh dum ug 139 lt 98 3 periodict sk hi peus doge unde eR el 141 C 3 4 perio dietask o 222 22 noto e ke 142 7 3 5 stopwatebhi s oos edes omen ue me E T em EL 143 C 3 6 stopwatclue 144 CA Matlab S tuncetions ao ceu ROUES esc he RS OS Se 144 C 4 1 Analog input TLO Rb RUE E d x 144 C 4 2 Analog output 145 C43 Dieitakanput a h huis 145 CAA Digitaloutput TLG io Re qoe MUS 146 vi Chapter 1 Introduction Today computer electronics are foun
11. temp gt chanNumber chanNumber temp gt subchanNumber subchanNumber temp gt value value temp gt next NULL Lock mutez add item to the list and unlock mutes pthread_mutex_lock amp cmdListMutex if aoutCmdListFirst NULL List empty aoutCmdListFirst temp else List not empty aoutCmdListLast gt next temp aoutCmdListLast temp workCount 4 pthread_mutex_unlock amp cmdListMutex 119 21 22 123 124 USER MODE 141 Signaling the worker thread pthread_cond_signal amp workCond return 0 void Worker_Aout struct sAoutCmd xtemp Forever loop while 1 Wait for work pthread_mutex_lock amp workMutex pthread_cond_wait amp workCond amp workMutex pthread_mutex_unlock amp workMutex Executes commands until list is empty while workCount gt 0 Locks mutex grab first list item and unlock mutex pthread_mutex_lock amp cmdListMutex temp aoutCmdListFirst aoutCmdListFirst temp gt next workCount pthread mutex unlock amp cmdListMutex Send value to I O card and free the list items memory avr32io_SetAnalogOut temp gt chanNumber temp subchanNumber int aoutMultiplier temp chanNumber temp gt value free temp C 3 3 periodictask h ifndef DEF PTASK define DEF PTASK includes include lt signal h gt include lt pthre
12. CH TO CODE AIN EN ch ret if ret lt 0 return ret Prepare to send several bytes tx 0 enable tx 1 DUMMY expectedRx 0 CH TO_CODE_AIN_EN ch 1 expectedRx 1 enable 1 Send data and check returns ret SPI_SendTableOfBytes tx expectedRx 2 if ret lt 0 return ret Confirm command ret SPI MasterTransferByte MASTER DEBUG masterOK _ i_slaveOK _ i n MASTER OK ret if ret SLAVEOK return EIO return 0 endif int Cmd_SetAOutResolution u8 resol int ch int ret unsigned char tx 2 expectedRx 2 Synchronize with 128 ret Cmd_WaitForAM128 CODE AOUT_RES ch DEBUG code _ i _ count _ i n TOCODE RES ch ret if ret lt 0 return ret Prepare to send several bytes tx 0 resol tx 1 DUMMY expectedRx 0 CH TO CODE AOUT RES ch 1 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 00 109 Cu NNNRPE RPE RRB RPP 23 2 KERNEL MODULE expectedRx 1 resol 1 Send data and check returns ret SPI_SendTableOfBytes tx expectedRx 2 if ret lt 0 return ret Confirm command ret SPI_MasterTransferByte DEBUG masterOK _ i_slaveOK _ i n MASTER OK ret if ret SLAVEOK return EIO r
13. Use 8 bit data no parity and 2 stop bits UCSRIC 1 lt lt UCSZ11 1 UCSZ10 1 lt lt USBS1 Start sending by writing to the send data register UDRI A 6 6 5 Headers for 5 1000 and debugging These headers were tested by connecting the header to the general expansion header J29 on the STK1000 board and try the same test as in 5 5 Since the SPI communication also worked through the header it meant that the header are connected properly To check if the STK1000 can be used as power supply for the I O card the jumper was from external power supply to STK1000 This worked which meant that the STK1000 can supply the ATmegal28 with power 6 6 6 ADC Supply Filter The filter for the ADC supply is a LC filer and it s used to filter out digital noise so the analog reference is kept as stable as possible This is to ensure that the analog in is 42 CHAPTER 6 PROTOTYPE I O CARD as accurate as possible On this prototype card the inductor of the LC filter was short circuited since no inductor of correct value was available The inductor works as a short circuit for DC current but it stops AC current So replacing the inductor with a short circuit will just make the filter stop high frequency noise less effective 6 6 7 Analog Output Circuit The analog output circuit was assembled with different filters that were used to find a filter for the final I O card 9 2 2 describes the different filters that were tes
14. if ret lt 0 4 DEBUG avr32io_user error on write i n ret return ret pthread_mutex_unlock amp spiMutex return 0 short avr32io SetAnalogOutDouble char channel char subchannel double value Converting the double value to integer and call the analog out function return avr32io SetAnalogOut channel subchannel int aoutMultiplier channel value short avr32io GetDigitalIn int fd ret unsigned char data pthread_mutex_lock amp spiMutex Open the correct device node fd open dev avr32Din ORDWR if fd lt 0 DEBUG avr32io user fd return Read data from device node close it ret read fd amp data 1 close fd if ret lt 0 4 DEBUG avr32io_user error on _ read i n ret return ret pthread_mutex_unlock amp spiMutex Return result return short short avr32io_GetDigitalInBit char bit short data unsigned char ucData Get digital in data data avr32io GetDigitalIn if data lt 0 return data Check the bit and return the result ucData unsigned char data if ucData amp 1 lt lt bit gt 0 return 1 else 137 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
15. int minor iminor filp f dentry d inode DEBUG avr32io_Ioctl ioctl minor 96i cmd 96i jisAout 96i isAin 6i Nn minor cmd IS AOUT minor IS_AIN minor switch cmd case AVR32IO IOCTL_RES_AOUT Change resolution on a analog channel if IS_AOUT minor return Cmd_SetAOutResolution u8 MinorToChAout minor ifdef BUFFERING MODE case AVR32IO IOCTL EN AIN Enables or disables analog in if IS_AIN minor return Cmd_EnableAIn u8 arg MinorToChAin minor endif If is mot valid command return ENOIOCTLCMD 2 3 avr32io Cmd c int WaitForAM128 u8 code int count 0 F H 0 1 67 68 69 70 71 72 132 APPENDIX CODE 18 ready Loops until it receives the correct code from ATMegal28 while ready SLAVE READY SPI MasterTransfer amp ready amp code 1 if count gt 100 return EIO return count int Cmd_GetAIn u8 toUser int ch int ret check for valid channel if ch lt 0 return EIO Synchronize with 128 ret Cmd_WaitForAM128 TO CODE AIN ch DEBUG code i count _ i n CH TO CODE AIN ch ret if ret lt 0 return ret Send DUMMY receive code ack ret SPI_MasterTransferByte DUMMY DEBUG dummy _ i code 1 _ i n DUMMY ret if ret CH TO CODE AIN
16. ret IO TestAck value rx if ret lt 0 return ret 4th byte check received MASTER return SLAVE OK ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 Debug printing if enabled Print c code UART Print v value return 0 signed char IO DigitalOut unsigned char code unsigned char mask value rx char ret i 1st byte store received mask return code 1 ret SPI SlaveTransferByte code 1 amp mask TIMEOUT if ret lt 0 return ret 2nd byte store received value return mask 1 ret SPI SlaveTransferByte mask 1 amp value TIMEOUT if ret lt 0 return ret 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 1 ATMEGA128 121 3rd byte check received DUMMY return value 1 ret SPI_SlaveTransferByte value 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 4th byte check received MASTER OK return SLAVE OK ret SPI SlaveTransferByte SLAVE OK TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 When the message is confirme
17. Design of I O card Software 43 7 1 Communication 43 La sCommands 43 7 1 2 Message Structure 44 i 7 1 3 Acknowledgments 46 Ix Ge Rosi nian urat rdg eis 46 7 2 ATmegal28 Firmware 48 TAU SPIconum nds d Be A 48 7 22 Analog Input 522 e wn 50 2 9 Timeout esa ases m m ae OE moa 51 7 3 Device Driver 51 23 1 Device Nodes GEORG Ee Eee UR 52 7 3 2 Master send uf ade da 52 7 3 3 Request Data from Slave 54 4 User Mode Driver end pm um RISE Da deme es 55 7 5 Threaded User Mode 55 7 5 1 Threaded Analog Input 55 7 5 2 Threaded Analog Output 56 8 Implementation of I O card Software 57 81 ATmegal28 Firmware 2 57 ami28m2aS1m Lieu e ERA de oh EAE CR Be 57 8 1 2 aml28103 4 asus Ree se ret re qe ll es 59 8 1 3 aml28slaveSpi e Gg Ro ee 61 8 1 4 128 62 91592 ahs eite ROSE
18. MASTEROK ret if ret SLAVEOK return EIO return 0 int SetDOut u8 fromUser int ret unsigned char tx 3 expectedRx 3 Synchronize with 128 ret Cmd_WaitForAM128 CODE DOUT DEBUG code _ i_count _ i n CODEDOUT ret if ret lt 0 return ret 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 134 APPENDIX CODE Prepare to send several bytes tx 0 fromUser 0 tx 1 fromUser 1 tx 2 DUMMY expectedRx 0 CODEDOUT 1 expectedRx 1 fromUser 0 1 expectedRx 2 fromUser 1 1 Send data and check returns ret SPLSendTableOfBytes tx expectedRx 3 if ret lt 0 return ret Confirm command ret SPI MasterTransferByte MASTER OK DEBUG masterOK _ i_slaveOK _ i n MASTER ret if ret SLAVEOK return EIO return 0 ifdef BUFFERING MODE int Cmd_EnableAIn u8 enable int ch int ret unsigned char tx 2 expectedRx 2 check for valid channel if ch lt 0 return EIO Synchronize with 128 ret Cmd_WaitForAM128 CH_TO_CODE_AIN_EN ch DEBUG code _ i_count _ i n
19. NTNU Innovation and Creativity Developing Embedded Control System Platform using Atmel AVR32 Processor Using Rapid Prototyping with Matlab Real Time Workshop yvind Netland Master of Science in Engineering Cybernetics Submission date June 2007 Supervisor Amund Skavhaug ITK Norwegian University of Science and Technology Department of Engineering Cybernetics Problem Description The goal of this master thesis is to use the new AVR32 processor architecture together with a developed 1 0 in a control system The control system should be able use Matlab Real Time Workshop generated code for rapid prototyping The assignment consists of Learn how the AVR32 architecture and the STK1000 card works Install developing and debugging tools for the AVR32 architecture on a Linux workstation Make a basic Linux system for the STK1000 card Implement timers for controlling the periodic Matlab execution and test how accurate these are Design and implement a 1 0 using an 8 bit AVR microcontroller Design the interface between the 1 0 and AVR32 and implement a driver the AVR32 can use to control the 1 0 Find out how to compile and run Matlab Real Time Workshop generated code under Linux on the AVR32 architecture Make Matlab Simulink blocks for the 1 0 Make it easy to use Matlab Real Time Workshop code on AVR32 for rapid prototyping Test and identify the efficienc
20. Norway MODULE DESCRIPTION Device driver for AVR32 I O card developed Oyvind Netland during a master thesis NINU Trondheim Norway Zendif KM AVR32 IO H 8 2 DEVICE DRIVER 69 8 2 7 avr32io_Cmd avr32io Cmd h and avr32io_Cmd h contain functions that sends messages containing the commands that the user space program has asked for The header file is shown below and it includes descriptions of the structures of the different SPI messages 0 1 9 c0r 23 ifndef AVR32IO CMD H define AVR32IO CMD H Sends code until ready code is received int Cmd_WaitForAM128 u8 code Sends SPI message for Analog in Number Send to slave Returned by slave 1 code READY 2 DUMMY code 1 Wait for interrupt in interrupt mode 3 DUMMY vauleH 4 valueH 1 vauleL 5 valueL 1 DUMMY 6 MASTER_OK SLAVE_OK int Cmd GetAIn u8 toUser int ch Sends SPI message for Analog out Number Received from master Returned to master 1 code READY 2 valueH code 1 3 valueL vauleH 1 4 DUMMY vauleL 1 5 MASTER SLAVE OK int Cmd SetAOut u8 fromUser int ch int sch Sends SPI message for Digital in Number Send to slave Returned by slave 1 code READY 2 DUMMY code 1 3 DUMMY vaule 4 value 1 DUMMY 5 MASTER_OK SLAVE OK 22 int GetDIn u8 toUser
21. communicate with the AVR32 Linux from a workstation it s possible to use both a serial connection and telnet via Ethernet Both of these solutions are available on the preinstalled Linux system on the SD flash card They both give a text based terminal just like a normal text based Linux system would give The AVR32 Linux system also has a small web server that in an embedded control system can be used to display a simple web page with status information and measurement logging 2 3 5 AVR32 Linux development tools Atmel Norway has also ported development tools for use with the AVR32 Linux platform These tools are available precompiled for different Linux distributions and for Windows or they could be compiled from source The development tools for AVR32 Linux includes the tools below o Binutils GNU Binary utilities for handling object code o GCC GNU compiler uClibc lightweight version of the standard C library u boot A boot loader for many different processor architectures o GDB GNU debugger that together with a GDB server on AVR32 can debug code running AVR32 o GDB server server version of that can run on the AVR32 2 4 Rapid Prototyping In computer engineering rapid prototyping is a development technique that rapidly make a simplified version of a system This prototype usually implements a part of the complete Busybox is a lightweight program that includes the functionality of
22. o Digital output writes values to digital outputs of the I O card Limit values can be selected for each channel and are used to decide if the digital output should be high or low 11 3 1 Simulink S function File Simulink S function file is the file that defines how the S function works in Simulink sfuntmpl basic c isa template file for simple S functions and it will be used here Since the workstation computer that runs Simulink can t use the I O card the S functions will have Simulink S function files that doesn t do anything during simulation This means that the only function from sfuntmpl_basic c that will be modified is the mdlInitial izeSizes that defines different sizes of the S function The sizes that are changed from the template is the number of input outputs and param eters used by the S function These numbers are different for the different S functions as described in table 11 1 Notice that the input S functions has outputs and visa verca since a input S function reads from the I O card and send the signals out of the block able 11 1 Sizes of the different S functions S function Inputs Outputs Parameters Analog input 0 8 0 Threaded analog input 0 8 8 sampling time Analog output 6 0 2 resolution Threaded analog output 6 0 2 resolution Digital input 0 8 0 Digital output 1 0 8 limit value Below is the mdlInitializeSizes function of the analog input S function
23. Data command codes define CODE AIN 0x78 01111000 ch define CODE 0x68 01101000 ch define CODE AIN RET 0x70 01110000 ch define CODE AOUT 0x58 01011000 lt lt 2 sch define CODE DIN 0x38 00111000 define CODE 0x18 00011000 Control command codes define CODE AIN EN Oxf8 11111000 ch CODE RES Oxd8 11011000 gt gt 2 Macros for finding channels from codes define CODE_TO_CH_AIN code code amp 0 7 define CODE TO CH AOUT code code amp 0 4 gt gt 2 define CODE TO SCH AOUT code code amp 0x3 Macros for finding codes from channels define CH TO CODE AIN ch CODE AIN 4 ch define CH TO CODE EN ch CODE AIN EN ch define CH TO CODE AIN REQ ch CODE AIN REQ ch define CH TO CODE AIN RET ch CODE AIN RET ch define CH TO CODE AOUT ch sch CODEAOUT ch lt lt 2 sch define CH TO CODE RES ch CODE RES ch lt lt 2 endif SPLBYTES CODES All the codes are unique and they are also different from the other special bytes that are used during SPI messages This includes the SLAVE READY MASTER OK SLAVE and DUMMY This means that the error checking used in the message will be more effective since each code only has one meaning 48 CHAPTER 7 DESIGN OF I O CARD SOFTWARE Synchronization EH NH NH NH EH NH E
24. Figure 6 4 RS 232 circuit and digital output connectors 6 4 4 RS 232 circuit and Digital Output Connectors Figure 6 4 shows a circuit for RS 232 interface for AT mega128 so it can connect to a serial cable on a PC The microcontroller has two UART signals and one of these was converted into RS 232 signal with the MAX233 5 from Maxim This signal was made available on a 9 dsub connector that connects to a normal serial cable The figure also shows screw clamps for digital out signals of the I O card Like the analog in these will be placed on the edge of the card 6 4 5 STKI1000 headers and Digital Input Connectors Figure 6 5 on the following page shows the circuit for STK1000 headers and digital in signals same as for digital output A 36 pin header are used to connect to one of the expansion headers the STK1000 board This header includes signals for SPI interrupts and ground The I O card can also draw power from the 5V source from STK1000 Two of the interrupts are connected directly to the ATmegal128 and two are available on screw clamps To make debugging simpler a header was placed on the card that had pins for the different SPI signals These pins makes it easy to probe these signals and look at them on an oscilloscope 6 4 6 Decoupling Capacitors and VCC GND Connectors Figure 6 6 on the next page shows a small but important part of the I O card This is the two capacitors that are used for decoupling the ATme
25. First of all this means that the AVR32 uses much more time preparing and configuring the SPI transfer than it uses on the SPI transfer itself It also means that 77 78 CHAPTER 9 TESTING WITH PROTOTYPE CARD to minimize the time used it s important to send several bytes at the same time whenever possible This have been used in the device driver When sending data to the I O card all the data are sent at once and the acknowledgments returned by the I O card was checked afterwards When receiving data from the I O card this was not possible to do since each acknowledgment consist of the previously received byte This means that only one byte can be sent at the time This makes the digital input command slower than the digital output command as seen in 9 1 3 even if they transfer the same amount of data 9 1 3 Time used on Commands How many commands that could be sent during a period of time depends on how long it takes to send a command To find out this a test was designed to find the average time used by each command when doing 10000 equal commands When testing the analog out command the code below was used StartStopWatch amp sw for i 0 i lt COUNT i ret avrIO SetAnalogOut 0 0 2 5 if ret lt 0 break usec StopStopWatch amp sw printf Analog out result i usec i n ret usec COUNT Table 9 1 shows the average number of microseconds the different commands used It shows that the commands
26. This is an example of what these functions look like The whole files are on the CD ROM static void mdlInitializeSizes SimStruct S int i 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 11 4 RESULTS 93 See sfuntmpl_doc c for more details on the macros below ssSetNumSFcnParams S 0 Number of expected parameters if ssGetNumSFcnParams S ssGetSFcnParamsCount S Return if number of expected number of actual parameters return ssSetNumContStates S 0 ssSetNumDiscStates S 0 if ssSetNumInputPorts S 0 return if ssSetNumOutputPorts S 8 return 1 0 1 lt 8 1 ssSetOutputPortWidth S i 1 ssSetNumSampleTimes S 1 ssSetNumRWork S 0 ssSetNumIWork S 0 ssSetNumPWork S 0 ssSetNumModes S 0 ssSetNumNonsampledZCs S 0 ssSetOptions S 0 11 3 2 Target Block Files Target block files are written in the TLC language and defines how code should be gener ated for the S function Two TLC functions are used the InitializeConditions function generates code that initialize the I O card and the Outputs function generates code that reads or writes to the I O card each time step Since the TLC language is able to find out which inputs and outputs of the blocks that are connected code will only be generated for the connected ports target block files for the S functions are in th
27. UCSZ10 1 lt lt USBS1 endif void UART_TxByte char data ifdef RS232 DEBUG Wait until last message is sent then send this one loop_bit_is_set UCSR1A UDRE1 UDRi data endif 1 128 void _ ifdef RS232 DEBUG UART TxByte 32 void UART_TxNewLine ifdef RS232 DEBUG UART_TxByte n UART_TxByte r Penge void UART_TxDecimal unsigned char value ifdef RS232 DEBUG char tx 3 i 0 075 for i 0 i lt 3 i if value gt 99 tx 0 tx 0 1 value value 100 fts 1 elit 20 for 1 0 1 lt 10 1 if value gt 9 4 tee Jat SE ale value value 10 2 70 for 1 0 1 lt 10 1 if value gt i tee 19 ce ile Print for i 0 i lt 3 i UART TxByte tx i H endif void UART_Print char symbol unsigned char value ifdef RS232 DEBUG UART_TxByte symbol UART_TxByte UART_TxSpace UART_TxDecimal UART_TxNewLine endif alue DE 127 H O00 1O9 0 H 37 38 39 128 APPENDIX CODE C 2 Kernel module C 2 1 Makefile Include the AVR32 header files CFLAGS I usr local avr32 linux include CFLAGS D__AVR32_AP7000__ MAKE make ARCH avr32
28. double 96 LibBlockInputSignal opIdx 0 gt 1 ret avr32io_SetAnalogOutDouble 1 lt opIdx gt 3 double 96 LibBlockInputSignal opIdx 0 gt endif if ret lt 0 count lt opIdx gt printf lt opIdx gt _count data 96fNn count lt opIdx gt lt LibBlockInputSignal opIdx 0 gt endif endforeach endfunction C 4 3 Digital input TLC implements avr32io din C function Outputs block system Output UKType gt Block XName Reads digital inout values from I O card unsigned char din avr32io GetDigitalIn foreach opIdx NumDataOutputPorts if LibBlockOutputSignalConnected opIdx if din amp 1 lt lt lt gt LibBlockOutputSignal opIdx 0 gt 5 else lt LibBlockOutputSignal opIdx 0 gt 0 17 18 19 20 21 146 endif endforeach endfunction APPENDIX C CODE C 4 4 Digital output TLC implements avr32io dout C function Outputs block system Output 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 Checking all lt gt Block XName to the unsigned char dout 0 unsigned char mask 0 if LibBlockInputSignalConnected 0 mask mask 1 lt lt 0 if double lt LibBlockInputSignal 0 LibBl
29. void PWM_SetOutValue char ch char sch char valueH char valueL Changes the resolution of one of the channels affecting all subchannel When resolution are changed the output value of all subchannels affected are set to zero void PWM SetResolution char ch char resolution include aml28pwm c Zendif 128 PWM 8 1 0 ami28uart ami28uart h and ami28uart c contain functions for using UART With the MA X233 IC on the I O card it s possible to use to UART to communicate with a workstation through a serial cable This is very useful for debugging since it s possible to print small messages to the screen of a computer The code below is the header file am128uart h and the code file am128uart c is in the appendix C 1 7 ifndef AMI28 UART define AMI28 UART doubly circularly linked list is a list where each item points both to its next and previous item and the last item in the list points to the first NOOBWNFOTOANDUBW 64 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE Initialize the UART with baud rate 19 2k void UART Init Transmit one byte of data via UART void UART_TxByte char data Send byte containing a lt space gt void UART_TxSpace Send two bytes that togeter makes a new line void UART_TxNewLine Convert a decimal number to a string of three characters and send them void UART_TxDecimal unsigned char value Send a character a
30. 1 B 2 C 3 case 0 OCR3AH valueH OCR3AL valueL break case 1 OCR3BH valueH OCR3BL valueL break case 2 OCR3CH valueH OCR3CL valueL break break 99 100 101 102 103 104 105 106 107 15 16 7 18 19 20 21 22 23 24 25 26 27 126 void PWM SetResolution char ch char resolution char resL i resH 0x00 resL 0x00 APPENDIX C CODE Finds values for the ICRn registers that gives the requested resolution if resolution lt 8 For resolution equal or less than 8 bits for i 0 i lt resolution i set_bit resL i else For resolution over 8 amp bits resL Oxff for i 0 i lt resolution 8 i set_bit resH i Writes the values to the right ICRn register switch ch case 0 resH ICRIL resL break case 1 ICR3H resH ICR3L resL break Sets output on all subchannels to zero PWM SetOutValue ch 1 0x00 0x00 PWM SetOutValue ch 2 0x00 0x00 PWM SetOutValue ch 3 0x00 0x00 C 1 7 am128uart c void UART Init ifdef 65232 DEBUG Set direction registers set_bit DDRD 3 clear_bit DDRD 2 BAUD rate 19 2k UBRRIH 0 UBRRIL 51 Enable both transmit and receive UCSRIB 1 lt lt RXEN1 1 lt lt Use 8 bit data no parity and 2 stop bits UCSRIC 1 UCSZ11 1
31. CROSS_COMPILE avr32 linux KERNELDIR home oyvindne diplom source linux PWD shell pwd obj m avr32io o default MAKE KERNELDIR M PWD modules clean rm f mod cmd core rm rf tmp versions install cp avr32io ko home oyvindne diplom fs avr32io ko C 2 2 avr32ioc include avr32io h static int init avr32io Init void int ret if l device kzalloc sizeof struct avr32io_device GFP KERNEL printk KERN ALERT avr32io Init kzalloc failed n return ENOMEM Major minor number allocation ret alloc_chrdev_region amp device gt number 0 COUNT TOTAL avr32io if ret lt 0 printk KERN ALERT avr32io_Init _alloc_chrdev_region failed_ i n ret goto errRegion Adding cdev device gt charDevice cdev_alloc device gt charDevice gt ops amp fops device charDevice gt owner THIS MODULE ret cdev_add device gt charDevice device number COUNT TOTAL if ret lt 0 printk KERN ALERT avr32io_Init _charDevice failed_ i n ret goto errCharDevice Registration of the driver with the linux device model ret spi register driver amp avr32io driver if ret lt 004 printk KERN ALERT avr32io Init spi register driver failed 96iNXn ret goto errRegDriver ifdef INTERRUPT MODE Registration of IRQ ret request irq EIM IRQ BASE irqFunk IRQF TRIGGER RISI
32. DEBUG code i count i n CH TOCODEAOUT ch sch ret if ret lt 0 return ret Prepare to send several bytes tx 0 fromUser 0 tx 1 fromUser 1 tx 2 DUMMY expectedRx 0 CH TOCODEAOUT ch sch 1 expectedRx 1 fromUser 0 1 expectedRx 2 fromUser 1 1 Send data and check returns ret SPI_SendTableOfBytes tx expectedRx 3 if ret lt 0 return ret Confirm command ret SPI_MasterTransferByte MASTER OK DEBUG masterOK 96i slaveOK 96i Vn MASTER OK ret if ret SLAVEOK return EIO return 0 int GetDIn u8 toUser int ret Synchronize with 128 ret Cmd_WaitForAM128 CODE DIN DEBUG 1 code _ i count _ i n CODEDIN ret if ret lt 0 return ret Send DUMMY receive code ack ret SPI_MasterTransferByte DUMMY DEBUG 2 dummy _ i _ code 1 _ i n DUMMY ret if ret CODEDIN 1 return EIO Send DUMMY receive data0 ret SPI MasterTransferByte DUMMY DEBUG 3 dummy 96i data0 96i Nn DUMMY ret if ret lt 0 return ret toUser 0 u8 ret Send data0 ack receive DUMMY ret SPI_MasterTransferByte toUser 0 1 DEBUG 4 _data0 1 _ i_dummy _ i n u8 toUser 0 1 ret if ret DUMMY return EIO Confirm command ret SPI MasterTransferByte MASTER DEBUG masterOK 96i slaveOK i n
33. Ee ASE ATE bU 63 Wart Be Sek to kane a alae oe VEM AR 63 8 2 Device driver 2 5 qun ets gus eru te se he a eee de Be EA 64 8 2 1 Init and Exit Functions 64 8 2 2 Major and Minor Numbers 64 8 2 3 Char Device registration 65 8 2 4 SPI device and driver 66 8 2 5 Changes in Linux Kernel Source Code 66 8 2 6 ae ee US cee Bae ee Fc 67 B2 E eden 69 82 8 0 uote tere HUS send drerit dms T1 8 3 Lima Kerel LISSE IRURE ERES 72 8 4 User Mode 72 8 5 Threaded User Mode 74 8 5 1 Threaded Analog Input 75 8 5 2 Threaded Analog 75 9 Testing with prototype card 77 9 1 Test of communication 77 9 1 1 Frequency of SPI connection 77 9 1 2 Time used on SPI transfers 77 9 1 3 Time used Commands 78 9 1 4 Reliability 2 244048402 78 9 1 5 Reliability when using 79 9 2 Test of Analog 79 9 20 11 Simulation eee mt
34. OBJCOPY j text O am128main out am128main hex 8 9 ami28main out 128 10 CC CFLAGS am128main out Wl Map ami28main map am128main o 11 12 ami28main o am1l28 amp 8main c 13 CC CFLAGS Os c am128main c 14 15 clean 16 rm f out hex 17 18 install 19 avrdude P usb pm128 cjtag2 Uflash w am128main hex 1 2 am128main c 1 include am128main h 2 3 int main 4 5 Initialize UART 6 UART Init 7 8 Initialize am128 9 IO Init 10 11 Main program loop 12 while 1 13 Prepare to send ready signal and wait for code from master 14 SPDR SLAVE READY 15 16 Wait for SPI transfer 17 while test bit SPSR SPIF 18 ifdef BUFFERING MODE 117 19 20 21 22 23 25 26 47 48 49 50 51 52 53 54 55 56 118 APPENDIX CODE Checks if conversion is finished if using bufering mode ADC_CheckBuffer endif Start receiving new command IO NewCommand SPDR 1 3 am128io c void IO Init Init I O SPI_SlavelInit PWM_Init ADC_Init Direction of the digial io DDRA 0x00 DDRC Oxff signed char IO TestAck unsigned char tx unsigned char rx 25 If the ack has overflowed if rx 0 return 1 else Normal ack if rx tx 1 return 1 Ack was correct return 0 sig
35. a analog signal These jumpers are on the card to make it possible control as many instruments as possible 12 3 Rapid prototyping with Matlab Real Time Workshop 12 3 1 AVR32 System Target The AVR32 system target are used to easily configure Real Time Workshop to generate and compile code correctly for rapid prototyping on AVR32 In addition to selecting this system target file some Simulink preferences has to be changed solver has to be fixed step solver since the generated code has to use a constant time step It s also a good idea to specify the time step since Matlab might try and use a lower period than the AVR32 is able to run The minimum time step is lms but complex system has to use a higher time step The code automatically logs the average period time and the average time used for work each period and this information will be displayed after completing the simulation This makes it easy to find out if the periods are stable and if the AVR32 are able to complete each time step inside the period 12 3 2 S functions for I O card Four S functions have been made for each of the four I O on the card analog input analog output digital input and digital output analog input has 8 channels that gives a value between 0 and 5 which is an analog voltage between OV and 5V Each channel that are connected is an active channel This means that the generated code will read from the I O card and this takes approx
36. appendix C 3 1 ifndef _AVRDRIVER_H define _AVRDRIVER_H include sys ioctl h include lt unistd h gt include lt stdio h gt include lt stdlib h gt include fcntl h Zinclude lt math h gt include lt pthread h gt include linux ioctl h Defines IOCTL numbers define AVR321O IOCTL MAGIC k define AVR32IO IOCTL RES AOUT IOW AVR32IO IOCTL MAGIC 0 int define AVR321O IOCTL EN AIN IOW AVR32IO IOCTL MAGIC 1 int Defines if driver should print out debugging information fdefine VERBOSE DEBUG ifdef VERBOSE DEBUG define DEBUG fmt args printf fmt args telse define DEBUG fmt args fendif Get integer result from analog in channel long avr32io GetAnalogIn char channel Set integer value to analog out channel and subchannel short avr32io SetAnalogOut char channel char subchannel unsigned short value Set double value to analog out channel and subchannel short avr32io SetAnalogOutDouble char channel char subchannel double value 8 4 USER MODE DRIVER 73 Get digital in byte short avr32io GetDigitalIn Get single bit of digital in short avr32io GetDigitalInBit char bit Set digital out with a mask and value short avr32io SetDigitalOut unsigned char mask unsigned char value Set just a single digital out bit short avr32io_SetDigitalOutBit char bit char value Set a new analog out resolution for a channel short avr32io
37. bad feature If the block is supposed to do the same in both cases it will be error prone and time consuming to upgrade two files at the same time In some applications like controlling I O it might be preferable that the Simulink simulation does something different than the RTW generated code o Wrapper S functions are a special type of inlined S functions where a third code file is used This file has functions that both the t1c file and S function code files uses This allows the Simulink and RTW to execute the same code as in a noninlined S function but without the loss of performance 11 2 Making a AVR32 Real Time Target When using Matlab RTW a system target has to be chosen This system target defines how code will be generated and compiled As mentioned in 11 1 1 the GRT system target generates code that will run on most platforms and in 4 3 GRT generated code with a few modifications compiled and ran on AVR32 One of the goals with this thesis is to make a system that is easy to install and use Because of this a new system target was created based on the This system target was named AVR32 Real Time Target and will be installed by moving a directory into MATLAB ROOT rtw c 1 2 168 46 193 11 2 MAKING AVR32 REAL TIME TARGET 89 11 2 1 avr32 tlc This is the system target file for the new AVR32 Real Time Target and it s the file that controls how code are generated Since the code generated by GR
38. be etched or milled off and leave electrical circuits Most electronics are implemented on PCBs and they may have different numbers of layers and each layer can contain circuits There are a number of different software solutions for designing PCBs In this thesis the freeware version of Eagle 4 was used This program has a limitation on the size of the finished card and it can t design cards with more than two layers This wasn t a problem since the maximum size 8rl0cm and two layers were enough for the purpose 6 2 Features This card was designed to have these features o ATmegal28 with 16 MHz crystal as controller o JTAG interface for 128 o Reset button for 128 o RS 232 connection for debugging to a serial port on a workstation o Header ready to connect to general expansion header on STK1000 with power supply SPI and interrupt signals o Jumper for choosing between external power supply and power supply from STK1000 o 2 AVR32 interrupts that can be triggered from ATmegal28 31 32 6 3 CHAPTER 6 PROTOTYPE I O CARD 2 AVR32 interrupts that can be triggered externally 2 ATmegal28 interrupts that can be triggered externally 6 channel 8 to 12 bits analog output 8 channel 10 bits analog input Common ground for both STK1000 and STK500 8 channel digital output 8 channel digital input SPI signals available on debug header Components components used for this car
39. chCount i 4 if temp gt channel channel enabled 1 break temp temp gt next If channel aren t enabled the function ends if enabled 0 return Update pointers inside the list temp gt prev gt next temp gt next temp gt next gt prev temp gt prev 123 138 124 chCount if chCount 0 ADC StopConversion void ADC_CheckBuffer if test bit ADCSRA ADIF Storing new data dataL channels gt channel dataH channels gt channel ADCH Start new conversion ADC_NewConversion void ADC_NewConversion channels channels gt next ADMUX ADMUX amp 0xe0 ADMUX ADMUX channels channel Start conversion set_bit ADCSRA ADSC void ADC_StopConversion endif clear_bit ADCSRA ADSC ifdef INTERRUPT MODE void ADC StartConversion char channel ADMUX ADMUX amp 0 0 ADMUX ADMUX channel Start conversion set_bit ADCSRA ADSC signed char ADC_CheckConversion unsigned char 1 if test bit ADCSRA ADIF Clear status bit set bit ADCSRA ADIF Storing new data data 1 ADCL ADCH data 0 Finished return 1 Not finished return 0 1 6 128 void PWM Init Set the PWM ports as output APPENDIX C CODE AND Cu
40. devices receive or send big chunks of data at the time Most devices except hard drives and RAM are char devices 2 3 4 AVR32 Linux AVR32 Linux 3 is a porting of the Linux kernel done by Atmel Norway This means that it s a version of the Linux kernel that are able to run on this processor architecture 3Porting software is to do modifications so the software can run on other processors or operating systems further description in 16 2 4 RAPID PROTOTYPING 7 AVR32 support was included in the mainstream Linux kernel 2 6 19 release but it doesn t contain all the drivers for AVR32 and STK1000 board get these it s necessary to use the AVR32 Linux kernel patches from the AVR32 Linux web page http avr32linux org Basic system utilities and development tools for the AVR32 architecture can also be found on this web page The STK1000 board comes with a SD flash card with a runnable Linux system This system includes a patched 2 6 16 version of the Linux kernel and Busybox STK1000 uses U Boot which will boot from the SD card by default By changing the boot arguments in U Boot it is also possible to boot from network The advantage of network booting is that the kernel image file system and programs that all have been developed on a workstation can be used by AVR32 Linux through the network This makes development much faster since new files and programs don t have to be transferred to a physical medium like a SD card
41. error occur The error detection means that all data passing between the two processors are returned to the sender for confirmation This uses the full duplex capability of SPI but it still takes longer to send a command than it would without error detection Sending a command to the I O card takes between 180 13 and 40043 This is a considerable amount of time specially if the control system uses small time steps The main reason that sending command takes this long is that the SPI driver for AVR32 Transferring one byte takes only 25 but when sending several bytes after each other the AVR32 uses at least 94s between each transfer If two bytes are sent individually after each other as much as 2345 was used between the transfers The SPI driver is obviously not very effective since so much time is used before and between transfers For the implementation of the I O card driver it meant that it was important to try and avoid transferring individual bytes since this takes longer than sending several bytes at the time When testing the SPI communication almost no commands ended with errors This means that the error detection may not be necessary since it s almost never used By not using error detections the commands would probably be executed faster since the number of transfers would be reduced For special situations where the time used for sending SPI messages has to be as low as possible this may be a possibility but normally the e
42. error on open i n fd return fd Perform IOCTL command on the device node and close it ANowkwner USER MODE ret ioctl fd AVR32IO IOCTL RES AOUT resolution close fd if ret lt 0 DEBUG avr32io user error on write i n ret return ret pthread mutex unlock amp spiMutex return 0 short avr32io EnableAnalogIn char channel char enable int fd ret char devFile 14 pthread_mutex_lock amp spiMutex Open the correct device node sprintf devFile dev avr32Ain i channel fd open devFile ORDWR if fd lt 0 DEBUG avr32io_user error on open i n fd return fd Perform IOCTL command on the device node and close ret ioctl fd AVR32IO_IOCTL_EN_AIN enable close fd if ret lt 0 4 DEBUG avr32io_user error on write i n ret return ret pthread mutex unlock amp spiMutex return 0 C 3 2 avr32io threads c Zinclude lt stdio h gt include lt pthread h gt Zinclude lt math h gt void Init_I1O if 1O_Started Initialize periodic tasks Init PeriodicTasks Starts analog output worker thread aoutCmdListFirst 0 aoutCmdListLast 0 workCount 0 pthread_create amp aoutWorker NULL Worker_Aout NULL Marks that this function have been run IO Started 1 int avr32io InitAnalogIn int chanNumber double period Enables sele
43. have one node each This will make it easier to control them individually The I O card is a typical the char device since only small amounts of data are transferred serially with SPI 7 3 22 Master send Data The activity diagram in figure 7 5 on the facing page describes how the device driver sends a message containing data to the slave It does not describe how the type of command are decided or how to read and write user mode data This are described in more detail in 8 2 7 Synchronization phase e Activity 1 1 sends the appropriate code to the slave e Decision point 1A checks if the received data was a slave ready signal If it wasn t the ready signal the code has to be sent again o Master data phase e Activity 2 1 sends the first data e Decision point 2A checks if the received data was an acknowledgment of the code No acknowledgment means that sending the message failed e Decision point 2C checks if there is more data to send e Activity 2 2 sends the next data e Decision point 2B checks if the received data was an acknowledgment of the previously sent data No acknowledgment means that sending the message failed e Activity 2 3 sends a dummy byte to retrieve the acknowledgment of the last data e Decision point 2D checks if the received data was an acknowledgment of the last sent data No acknowledgment means that sending the message failed 7 3 DEVICE DRIVER Start Synchronization BH E NH NH
44. in the appendix C 3 3 and C 3 4 The stopwatch library mentioned in 4 1 was also used 4 2 1 Code Zinclude lt stdio h gt Zinclude lt math h gt Zinclude periodictask h Zinclude stopwatch h define COUNT 10000 define PERIODE 1 int main int i usec COUNT totUsec float totVar avrUsec avrVar avrStd struct sPeriodicTask task struct sStopWatch watch Init PeriodicTasks StartPeriodicTask amp task PERIODE StartStopWatch amp watch for 1 0 i lt COUNT 1 WaitPeriodicTask amp task usec i StopStopWatch amp watch if i COUNT 1 StartStopWatch amp watch totUsec 0 for 1 5 i lt COUNT 5 1 totUsec totUsec 1 totVar totVar pow float usec i 10000 PERIODE 2 avrUsec float totUsec COUNT 10 avrVar tot Var COUNT 10 avrstd sqrt avrVar printf Average periode time f n avrUsec printf Variance _ f n avrVar printf Standard _derivate _ f n avrStd 4 2 2 Result In table 4 2 on the next page the results of the test when performed on different platforms are shown STK1000 has the best timer precision of the two machines The average period is less than the correct value but the difference is not significant The standard deviation describes 16 CHAPTER 4 PRELIMINARY TESTS OF AVR32 Table 4 2 Results of timer tests Platform CPU A
45. instructions for installing on other platforms check the AVR freaks Wiki http www avrfreaks net wiki 12 1 2 Compile Linux kernel with AVR32 I O card support This system uses a patched version of the Linux kernel version 2 6 20 The patches needed are the 2 6 20 avr2 patchset from http www avr32linux org and the avr32io patch from the CD ROM To patch configure and compile the kernel with AVR32 I O card support Use the commands below from a directory with the Linux source tarball and the two patches 7 tar xjf linux 2 6 20 tar bz2 7 cd linux 2 6 20 7 patch 1 lt linux 2 6 20 avr2 patch 7 patch pl lt linux 2 6 20 avr32io patch 7 make ARCH avr32 CROSS COMPILE avr32 linux menuconfig 7 make ARCH avr32 CROSS COMPILE avr32 linux The second last command will open a menu based configure tool for the Linux kernel enable AVR32 I O the Atmel SPI Controller and AVR32 I 0 card has to be enabled These are both found in device drivers SPI support Another solution is to use the linux 2 6 20 avr32io config file from the CD ROM and rename it to config and move it to the linux source folder The last command will compile the kernel and make an ulImage which is the kernel binary file To be able to use the AVR32 I O card support the file system of AVR32 Linux needs some device nodes for this card T hese are made by running a script as root on the workstation called mknod sh that are on
46. subchannels The header file spiByteCodes h below has constants and macros for 7 1 COMMUNICATION PROTOCOL 47 easy usage of these codes It also contains comments that explain what the different bits in the code means ifndef SPI BYTES CODES define SPI BYTES CODES E SF Sk Sk ke sk ok ok ok ACI CIC A I The code bytes are generated the following rules No code can have the value 0 because thats used as dummy byte Bit 7 MSB Equals 0 for commands that sends or receives data Equals 1 for comtrol commands Bit 6 Equals 0 for commands for digital IO Equals 1 for commands for analog IO Bit 5 Equals 0 for commands for output Equals 1 for commands for input Bit 4 and 8 Equals normally 11 Can have other values if bytes 5 7 is the same for multiple commands Bit 2 to 0 LSB For analog out bit 2 equals channel and bit 0 1 equals subchannel For analog bit 0 2 equals channel For digital IO bit 0 2 equals 000 ICCC I a codes define SLAVE READY 10101010 define SLAVE OK 0 11 00010001 define MASTER OK 0x22 00100010 define DUMMY 0x00 00000000
47. subchannels has its own second order passive low pass filter that smooth the PWM signal to constant analog voltage between and 5V These filters consists of two resistors and two capacitors each The 6 subchannels can have different filters and since this is a prototype card it s imperative that several different filters are tested The reason for choosing a second order filters are that it will give a good compromise between ripple response and physical size first order filter would give too much ripple while a higher order filer would take too much physical space Figure 6 8 on the next page shows that by using different cut off frequencies it s possible to get similar behavior from a second and a third order filter This means that higher order filter not necessarily gives a better result After each filter an op amp circuit is placed These are voltage followers which means that their output voltage is the same as their input voltage T hey are not used for amplifying the voltage but they are used to amplify the current since an op amp can supply a lot more current than ATmegal28 can op amps high input impedance means that the current flowing from the 128 through the filter and to the op amp are minimal This is important since the properties of passive filters depends on the current flowing through High current will mean a high voltage loss in the resistors of the filter 38 CHAPTER 6 PROTOTYPE
48. the ripple of the analog signal Figure 5 4 shows how two second order filters with different time constants RC filters the same PWM signal filter is passive if it only consists of passive components like resistors capacitors and inductors Passive filters can t amplify signals only filter out the unwanted frequencies 24 CHAPTER 5 PRELIMINARY TESTS OF I O CARD ET resolution 4 5 12 bit resolution 4 3 5r 3L BOB n Figure 5 5 8 bit and 12 bit DAC with equal filters 5 3 4 Frequency and Resolution The frequency of the PWM signal depends on the clock frequency of the device the mi croprocessor that makes the PWM and the resolution of the DAC Equation 5 1 describes how the frequency of the PWM signal can be calculated pm 5 1 A high PWM frequency will give lower ripple than a low PWM frequency This means that increasing the resolution will increase the ripple Figure 5 5 shows a 8 bit and a 12 bit resolution DAC filtered with the same filter It shows that the response time is about the same for both but the 12 bit resolution result has significant ripple 5 3 5 Order of low pass Filter By adding several first order filters after each other a higher order filter is created second filter will then filter the result of the first filter and so on Figure 5 6 on the next page shows a DAC with equal same RC filters of differe
49. the CD ROM The script has to be modified to use the correct major number and file system path The major number are printed out during booting or can be found when running more proc devices on AVR32 Linux The file system path is the path to the file system of AVR32 Linux either a SD card or a shared folder on the workstation 12 1 3 Install AVR32 support in Matlab Matlab Real Time Workshop can generate code that with few modifications can be com piled for AVR32 but to make it easier to use a new system target files have been created These are located on the CD ROM in the folder matlab avr32 The content of this folder should be copied into matlab root rtw c avr32 on the workstation computer where matlab root is the folder where Matlab is installed When copying the avr32 directory the subdirectory blocks is also copied This directory contain the S functions that are used to control the I O card These has to be compiled for Matlab Start up Matlab and move to the blocks directory If using Linux Matlab has to be started as root Run the commands below to compile the S functions 7 mex avr32io ain c 7 mex avr32io aout c 7 mex avr32io din c 7 mex avr32io dout c 7 mex avr32io_ain_thread c 7 mex avr32io aout thread c 12 2 AVR32 I O CARD 99 If this gives an error the mex compiler has to be configured The following command starts a simple interactive configuration 7 mex s To use the S functions in the libra
50. tools for the platform on a Linux or Windows computer and how to use the it Contents 1 Introduction 2 Background 21 Embedded Control 2 1 1 Real time Constraints 231 2 Lg ek 2 2 Atmel AVR32 Architecture 221 1000 2 224 be RE ode 2 22 0 teh ERE RU RUE BEG AAG ie 2 51 Linux Control Systems e eo so ta ar a Gepa a a Oa e ia 2 3 2 Kernel Mode and User Mode 2 3 3 Linux Device Driver 2 2 2 9 4 AVR32 Linus 2x e X weeds Wu Yee 2 3 5 AVR32 Linux development tools 2 4 Brototyplhg 22 52 foe Gos ee bol ROC em o PORC Rod mg 2 41 Rapid Prototyping Control Systems 3 AVR32 Linux on STK1000 4 4 Preliminary Test Conclusion 5 Preliminary tests of I O card 3 1 Development Tools 3 11 Compiling Development Tools from Source 3 2 AVR32 Linux Kernel Versions 22 22 3 3 Configure booting over 3 3 1 Workstation Configuration 3 3 2 Configure 4 Preliminary tests of AVR32 41 Floating point and Fixed point operation AVA COG oo oe le ae enol Soe a
51. tx i rx i if rx i expectedRx i return EIO return 0 C 3 User Mode C 3 1 avr321o driver c long avr32io GetAnalogIn char channel int ret char devFile 13 unsigned char data 2 unsigned short result pthread_mutex_lock amp spiMutex Open the correct device node sprintf devFile dev avr32Ain i channel fd open devFile ORDWR if fd lt 0 DEBUG avr32io_user error on open i n fd return fd Read data from device node and close it ret read fd data 2 close fd if ret lt 0 DEBUG avr32io_user error on read i n ret return ret pthread_mutex_unlock amp spiMutex Convert result and return result data 0 lt lt 8 data 1 return long result APPENDIX C CODE i expectedRx i i short avr32io_SetAnalogOut char channel char subchannel unsigned short value int ret fd char devFile 14 unsigned char data 3 Prepare data to send data 0 subchannel data 1 value gt gt 8 data 2 value pthread_mutex_lock amp spiMutex Open the correct device node sprintf devFile dev avr32Aout i channel fd open devFile ORDWR if fd lt 0 DEBUG avr32io_user error on open i n fd 110 113 14 15 116 17 18 USER MODE return fd Write data to device node and close it ret write fd data 3 close fd
52. use between 180 and 400us This means that only a two to five commands can be sent each millisecond Table 9 1 Time used for executing the different commands Command Average time Enable analog in channel 229s Change analog out resolution 233 Us Get analog in voltage continuous mode 2865 Get analog in voltage interrupt mode 4068 Set analog out voltage 25048 Get digital in 2178 Set digital out 182 9 1 4 Reliability When testing the average time used by each command the reliability of the communication was tested as well If any of the 10000 commands returned an error the test would abort The test was performed several times with almost no errors so it s safe to say that the communication is almost free for errors Since the transfer nearly error free the error detection might not be necessary 9 2 TEST ANALOG OUTPUT 79 9 1 5 Reliability when using Timeout The ATmegal28 can use timeouts when it waits for SPI transfers to avoid the possibility of ending in an unknown state The problems with this is that a timeout may be triggered before the AVR32 is able to send the next SPI transfer A test was performed to find out how often errors occurs for different timeout values The results are in table 9 2 The results show that a high timeout has to be selected to avoid errors but when using a timeout about 100 45 the chance of error is low enough to be ignored Table 9 2 Chance of error with dif
53. will use which means that one major number has to be allocated and one minor number for each of the nodes To allocate major and minor numbers for a char device the function 11 chrdev region should be used This allocated unused major number and a chosen number of minor numbers oo 1o9 0 8 2 DEVICE DRIVER 65 allocated minor numbers will be used to number the device nodes The first eight numbers 0 7 were given to the analog input channels the next two 8 9 were given to the two analog output channels and the two last were given to digital input and digital output header file called minorNumbers h was made to make it easier to use these minor numbers This file is shown below Defines number of analog channels define COUNT AIN 8 define COUNT AOUT 2 define COUNT TOTAL COUNT AIN COUNT 2 Minor numbers of first channel of each type define MINOR AIN 0 define MINOR COUNT define MINOR DIN MINOR COUNT define MINOR MINOR AOUT 4 COUNT AOUT 4 1 Macros for finding minor number for channel define CH TO MINOR AIN ch MINOR AIN ch define CH TO MINOR AOUT ch MINOR ch Macros for testing if a minor number is a spesific type define IS_AIN minor minor gt MINOR AIN amp minor lt MINOR AOUT define IS minor iminor22MINOR amp minor MINOR DIN
54. 01054 4 zozoroa ZAINTZEA v 22 29 anoa M d NIL 03410414 1340030 ZIAN sos 3914929220 SIASII 1340420 m cod ssl 184508 2815070 racon 58559120 393120 1332120200 994009 29209 2924809 op 594509 994909 194409 XNI OO1vN amp ZNI o0 221 03 0999233 4209 34 6209234 209 34 212090934 520595 33 0012099233 991309 133 91799 99590259 OSQLE Sd 945 9499 2049 3359 1191 19535 L ZONO 24 aNO CONO ZV ONO SOT rN TOOT HN TOOT HN 0 1 Schematics for the prototype card E gt S 4713 5 223 13538 o 7817 J y vo3 55 f 323 Figure B 1 SCHEMATICS APPENDIX B 116 T T 5 ZE vy E p4e2 zg4 E sino WO 5 1107 2 0 4 9120 jiuaun2og 1281114 Q z uno a osovrad 225 Jeod Schematics for the final card Figure B 2 Appendix Code 1 ATmegal28 C 1 1 Makefile 1 CC avr gcc 2 OBJCOPY avr objcopy 3 4 CFLAGS g mmcu atmegal28 I usr avr include 5 aml28main hex am128main out 7
55. 1 128 125 set_bit DDRE set_bit DDRE set_bit DDRE set_bit DDRB set bit DDRB 2 set_bit DDRB NOD amp W SI MU 9 Set the control registers for to fast with no prescaler and clear output on compare match non inverting mode TCCRIA 1 lt lt 1 1 lt lt COMIB1 1 lt lt COMIC1 1 lt lt WGM11 TCCRIB 1 WGMI3 1 lt lt WGMI12 1 lt lt CS10 1 lt lt 1 1 lt lt 1 1 lt lt COM3C1 1 lt lt WGM3B1 TCCR3B 1 lt lt WGM33 1 lt lt WGM32 1 lt lt CS30 Set both PWM to have 8 bit resolution PWM_SetResolution 0 8 PWM SetResolution 1 8 Set all PWM outputs to zero PWM SetOutValue 0 1 0x00 0x00 PWM SetOutValue 0 2 0x00 0x00 PWM SetOutValue 0 3 0x00 0x00 PWM SetOutValue 1 1 0x00 0x00 PWM SetOutValue 1 2 0x00 0x00 PWM SetOutValue 1 3 0x00 0x00 void PWM_SetOutValue char ch char sch char valueH char valueL Checks which PWM timer that should be set switch ch case 0 Either 0 or 1 Checks what channel of the PWM timer A 1 2 and C 3 switch sch case 0 OCRIAH valueH OCRIAL valueL break case 1 OCRIBH valueH OCRIBL valueL break case 2 OCRICH valueH OCRICL valueL break break case 1 Checks what switch channel of the PWM timer A
56. 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 138 APPENDIX CODE return 0 short avr32io_SetDigitalOut unsigned char mask unsigned char value int fd ret unsigned char data 2 Prepare data to send data 0 mask data 1 value pthread mutex lock amp spiMutex Open the correct device node fd open dev avr32Dout ORDWR if fd lt 0 DEBUG avr32io_user error fd return fd Write data to the device node and close it ret write fd data 2 close fd if ret lt 0 DEBUG avr32io_user error on write i n ret return ret pthread_mutex_unlock amp spiMutex return 0 short avr32io SetDigitalOutBit char bit char value unsigned char mask newValue Prepare data for function call mask 1 bit newValue 0 if value gt 0 4 newValue 1 bit Write data and return return avr32io_SetDigitalOut mask newValue short avr32io_SetAnalogOutResolution char channel char resolution int fd ret char devFile 14 aoutMultiplier channel double pow 2 resolution 1 5 pthread_mutex_lock amp spiMutex Open the correct device node sprintf devFile dev avr32Aout i channel fd open devFile ORDWR if fd lt 0 DEBUG avr32io_user
57. 4 265 266 267 268 269 270 271 272 273 274 275 276 277 H 1 ls wn H mre 59 59 2 NOrFCOEONDWUBWNH 122 APPENDIX CODE 2nd byte check received DUMMY return resolution 1 ret SPI SlaveTransferByte resolution 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 8rd byte check received MASTER return SLAVE OK ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 When the message is confirmed the analog out resolution of the selected channel will be updated PWM SetResolution CODE TO CH AOUT code resolution Debug printing if enabled UART Print c code UART Print r resolution 1 4 ami128spiSlave c void SPI SlaveInit void Enables SPI and sets the MISO signal as an output SPCR 1 lt lt SPE DDRB 1 lt lt 3 Timer prescaler 256 16us ifdef TIMEOUT ENABLE TCCRO 1 lt lt CS02 1 lt lt 0801 endif signed char SPI_SlaveTransferByte unsigned char tx unsigned char unsigned char usec ifdef TIMEOUT ENABLE Starts timer TCNTO 0 endif Prepare data to send and wait for SPI transfer from master SPDR tx while SPSR amp 1 SPIF ifdef TIMEOUT ENABLE Checks for timeout if TCNTO gt usec return 1
58. 4 the highest possible SPI frequency was about 1 9 Hz which was about one quar ter of the clock frequency of STK500 When using a clock twice as high the ATmegal28 should be able to receive SPI transfers with twice as high frequency In avr32io c the following line sets the SPI frequency to the highest that works with ATmegal128 as slave gt speed hz 2100000 When using an oscilloscope to probe the SPI clock the time used by one high and one low period was measured to 0 2545 This is the time used to transfer one bit of data This gives a frequency of 4M Hz This is one quarter of the frequency of the ATmegal28 which is the theoretical maximum 9 1 2 Time used on SPI transfers In 9 1 1 the time used to transfer one bit of data was measured to 0 25 The SPI transfer consists of 8 bits of data serially which means that the total 8 bits 1 byte takes 21s test how much time the kernel uses before and between SPI transfers small test system was created that sent out pairs of data transfers By using an oscilloscope the time between the two pairs of data was measured test system could send pairs of data in two different ways Either sending two individual bytes of data or sending two bytes of data at the time When sending two individual bytes the test system used 23 55 from the end of the first to the start of the last byte When sending the two bytes at the same time this time was reduced to 9 28
59. 4 times longer time on a floating point than on a fixed point which was regarded as a positive result It was a bit concerning that the AVR32 uses about 3 times as many clock cycles per fixed point operation than the Pentium 4 specially since Atmel Norway promise more throughput with lower clock This may be due to the employed test program inability to compare one fast and one slow processor with each other 4 2 Timer precision Test Most control systems have tasks that have to be carried out with regular intervals every millisecond or shorter This can be implemented using timers easy solution was to use the internal Linux timers that has a maximum resolution of 1000Hz setitimer will start a timer that sends a SIGALRM signal periodically signal function can register gt 4 2 TIMER PRECISION TEST 15 this signal and select a function that runs each time the SIGALRM is received This is all done inside a user mode program The test consists of 10000 periods of 10ms each The reason for not choosing 1775 which is the lowest available timer is that the standard Ubuntu kernel doesn t have the highest precision timer This can be changed by recompiling the kernel but the test is just as good with 10ms The periodic tasks was created using the periodicTask library that was developed to make it easy to make and start periodic tasks This library consists of periodicTask h and periodicTask c that are
60. 56 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 120 APPENDIX CODE 3rd byte check received DUMMY return valueL 1 ret SPI_SlaveTransferByte valueL 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 4th byte check received MASTER return SLAVE OK ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 When the message is confirmed the mask and data are applied to digital out PWM_SetOut Value CODE TO CH AOUT code CODE TOSCH AOUT code valueH valueL Debug printing if enabled UART Print c code UART _Print h valueH UART_Print 1 valueL signed char IO DigitalIn unsigned char code unsigned char rx value char ret Only read from the port once during communication value PINA 1st byte check received DUMMY return code 1 ret SPI_SlaveTransferByte code 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 2nd byte check received DUMMY return value ret SPI SlaveTransferByte value TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 8rd byte check received value 1 return DUMMY ret SPI SlaveTransferByte DUMMY TIMEOUT if ret lt 0 return ret
61. AT megal28 to generate an analog signal PWM is a digital signal with a constant frequency and a controllable duty cycle The duty cycle is a value that describes how much of the period the digital signal is high A 5096 duty cycle means that the signal is high half of the periode then low the rest of the periode and will look like square wawe signal 5 3 1 Generating Analog Signal from PWM low pass filter is also called an averaging filter and it will convert the PWM signal into an analog voltage equal to the average voltage of the PWM signal This analog voltage can be set by varying the duty cycle of the PWM making this a digital to analog conversion DAC An example of a PWM signal before and after a first order low pass filter are shown in figure 5 1 on the next page As all the figures describing PWM signals shows what happens when a PWM duty cycle increases from 0 to 50 which is the same as the DAC increases it s value from to 2 5V 5 3 2 Quality of Analog Signal The quality of an analog signal made with a PWM can be described with two values ripple is how much the output varies and the response time is how fast the output change when the duty cycle change second order filter in figure 5 2 on the following page has ripple marked with green The ripple are measures as the amplitude of the signal between the green dotted lines in the figure about 0 15V The response time are defined throughout this rep
62. H H EH E NH 3 5 SPDR dummy a Slave data Figure 7 3 Activity diagram for SPI on ATmegal28 7 2 ATmegal28 Firmware 7 2 1 SPI commands The main task for the AT megal28 is to listen for commands from the AVR32 and do what these commands tells it to do 7 1 2 defines the message structure used by AVR32 to give commands Figure 7 3 is an activity diagram that describe what the AT mega128 has to do when receiving a message This activity diagram is divided in four phases each corresponds to one of the different phases of the structure o Synchronization phase 7 2 ATMEGA128 FIRMWARE 49 Activity 1 1 sets the SPI data register SPDR to the Slave ready code The data in this register will be sends to the master during the next SPI transfer Activity 1 2 waits until the next SPI transfer Decision point 1A validates the received data and check if it s one of the codes defined in 7 1 4 This code tells the slave what kind of command the message contains Depending on the type of message the next activity will either be 1 3 slave sends or 2 1 master sends Activity 1 3 sets the SPI data register to an acknowledgment of the code Activity 1 4 waits until the next SPI transfer Decision point 1B checks if the received byte is a dummy byte No dummy byte means that the message failed o Master data phase Activity 2 1 sets the SPI data register to an acknowle
63. H NH NH NH NH NH NH NH NH gt 1 1 SPDR Slave ready lt Invalid i code 2 1 2 Wait for SPI transfer I Master send Validate SPDR code Slave send Yes Confirmation 3 6 Wait for SPI transfer SPDR ack last data Do command No command command Mpster data MCN CN H EH NH EH EH NH NH NH HB NH 1 3 SPDR ack code 2 1 SPDR ack code LI A 2 2 Wait for SPI transfer eee sr GES SPDR Dummy m a gt n 2 3 Save data in SPDR Yes 2 4 SPDR ack data mH H HH H NH eee H NH NH H H NH NH n Expect more data 3 1 SPDR data z 3 2 Wait for SPI transfe i i 2 5 Wait for SPI transfer SPDR Dummy SPDR Dummy No z lt gt Yes 3 3 SPDR data n E RON RR m m 3 4 Wait for SPI transfer M NM NM BH HH OH H EH NH m SPDR ack previous data 2 Ha 4 1 SPDR slave OK More data 4 2 Wait for SPI transfer to send SPDR Master AA m No Yes 4 E
64. I O CARD third order filter second order filter Volt Time x 107 Figure 6 8 Second order and third order low pass filters with equal ripple and response time 6 5 Layout The layout of a circuit is a representation of how the different parts are placed on a PCB and how the copper layers should be etched To ensure that the parts are connected the same way as in the schematics Eagle uses the schematics as a template When making the layout it s important to make the connections between the different parts as straight and short as possible This will make assembly easier and it will minimize noise problems Figure 6 9 on the facing page shows the top side of the first prototype and figure 6 10 on the next page shows the bottom side Below are some important design choices are commented ATmegal28 was placed on the bottom layer This was because it s a surface mounted device and many of its pins were connected to parts that isn t surface mounted By placing it on the bottom the number of vias was reduced since most signals started and ended up on the same layer o All the digital I O analog I O and external interrupts was connected to screw clamps to give easy access to them and the ability to connect wires easily This did unfortunately take a lot of space on the card o Only the ATmegal28 was a SMD This was done to make it easier to debug and to make small changes
65. I O card did which strenghten the theory that the card was assembled poorly A Simulink diagram was made that contained a sinus source a data logger and the blocks for analog input and output This can be seen in figure 11 1 The time step used in this diagram was 5ms Figure 11 2 shows the original sinus signals together with sinus signals sent through the analog I O both by using normal and threaded I O blocks Figure 11 2 shows that sinus signals that was sent through either the normal or threaded analog I O blocks was delayed compared to the original signal The normal blocks were delayed one time step of 5ms which makes sense since it means that the value sent to the analog output one time step will be read by the analog input the next The threaded blocks have higher delays about 3 time steps This is because of the double buffering and that the complexity of the threaded drivers adds some overhead This is a considerable delay and means that threaded I O gives a worse result than normal I O To get a performance gain from using threads the implementation has to be optimized 1A breadboard is a electronics prototype board where components can easily be connected without soldering 11 4 RESULTS 95 1 1 1 1 1 1 1 0 0 02 0 04 0 06 0 08 0 1 0 12 0 14 Figure 11 3 Results of sending sinus signal through analog I O with low sampling fre quency
66. MU and DMA controller o Peripherals like audio DAC LCD controller USB 2 0 and two Ethernet MACs o Serial interfaces like RS 232 USART TWI I2C SPI PS 2 2 3 Linux Linux kernel 15 is an open source and free Unix like operating system kernel The kernel is a single binary program that controls the hardware resources of the computer and makes them available for other running programs Most people think about Linux they think about a Linux distribution However a distribution is actually a collection of lThroughput is a measurement of how much work the processor is able to do Free software is a matter of liberty not price To understand the concept you should think of free as in free speech not as in free beer is a good explanations on free software given in The Free Software Definition 23 2 5 LINUX 5 Figure 2 1 STK1000 development board programs including the Linux kernel that can easily be installed on a computer They may consist of thousands of programs but it s only the kernel that is called Linux 2 3 1 Linux Control Systems Linux based operating systems are used in many different systems from servers and work stations to embedded systems like control systems In recent years they have been used more and more in embedded systems This will most likely increase further in the future as indicated in the article in Datarespons magazine Interrupt 22 Below is a list over reasons to use Linux i
67. NG avr32io interrupt NULL 2 KERNEL MODULE 129 if ret lt 0 DEBUG avrIO Init request irq failed i n ret goto errRegIRQ device gt irqID ret printk KERNINFO avr32io_Init sucessfull_major _ i n device gt number Return sucessfull return 0 Error roll back resourses ifdef INTERRUPT MODE errRegIRQ spi_unregister_driver amp avr32io_driver Hendif errRegDriver cdev_del device gt charDevice errCharDevice unregister_chrdev_region device gt number 4 errRegion kfree device return ret static void exit avr32io_Exit void ifdef INTERRUPT MODE Free the IRQ free irq EIM IRQ BASE NULL endif Unregister the driver from the linux device model spi_unregister_driver amp avr32io_driver Unregister the character device from the kernel cdev_del device gt charDevice Unregister major minor numbers allocated unregister_chrdev_region device gt number COUNT TOTAL Free memory used by the device struct kfree device printk KERN INFO avr32io Exit module exit Vn static int __devinit avr32io Probe struct spi device spi int ret Initialize the spi struct device gt spi spi spi gt mode SPI MODE 0 spi bits per word 0x08 8 bits per transfer spi gt max_speed_hz 2100000 highest value that works is 2100000 Q0 16MHz spi gt chip
68. RE 63 The code for interrupt mode is very simple it consists of one function that starts conversion on a channel and one that checks if the ongoing conversion is completed The last one will also return the conversion result in an array The code for buffering mode is more complex The idea is that the ATmegal28 should convert one analog input channel save the result in a buffer before starting to convert the next channel Since each conversion takes some time it would be a good idea to only convert the channels that are in use A doubly circularly linked list was designed to contain all the active channels Since the list is circular the program can always move to the next channel in the list whenever a new conversion should be started 8 1 5 aml28pwm ami28pwm h and ami28pwm c contain functions for using the PWM Pulse width modu lation timers as analog output signals With these functions it s possible to change the output value of the subchannels and the resolution of the channels All subchannels of the same channel will always have the same resolution The code below is the header file am128pwm h and the code file am128pwm c is in the appendix C 1 6 ifndef 128 PWM define 128 PWM Initialize 2 PWM channels with 3 subchannels each By default all PWM are 8 bit and has an output value of zero void PWM_Init Changes the output value of one of the subchannel The new value are given with two 8 bit values
69. Ree Rae as BE 79 9 2 2 Testing Filters 79 iii 9 2 3 Operational 80 9 3 Test of 1 Input nau ete keane a oe bee a 81 9 3 1 Precision of Analog Input 81 9 3 2 Buffering and Interrupt 81 10 Final version of I O card 83 10 1 Changes from 83 10 2 ut d p dr ue tee der ed Ge 84 10 3 Layouts 4 oro LR OE AURIS UU EUR URS IR el 84 10 4 Problems with Analog 84 11 Matlab Real Time Workshop 87 11 1 Matlab Real Time Workshop 87 11 1 1 Target Language Compiler TLC 87 112152 S fUCulOn8 ss gh eee we ee ue ex ae RAS E e RU 88 11 2 Making a AVR32 Real Time Target 88 I124L 8Vr32 0 89 AD QED BVT SQ GME uh eke Bee at Gores ae Peo Ae GaP BAR 89 11 2 3 AVIS uou da cheese ae ren Robe o er Sel qa d 90 11 3 functions for I O card 91 11 3 1 Simulink S function 92 11 3 2 Target Block Files 2 2 3 m REY UR 93 TLA Resultsa z uz aAA Bel E bom CR Eu AOA ed rd deren th 93 11 4 4 Results of Analog 93 11 4 2 Results of Digital
70. SetAnalogOutResolution char channel char resolution Enables or disables an analog in channel will only work in BUFFERING MODE short avr32io EnableAnalogIn char channel char enable Containing a double value for as fast as possible convert 0 5 double value to integer with the correct resolution double aoutMultiplier 2 Mutex used so only one thread can access the SPI at the same time pthread mutex t spiMutex PTHREAD MUTEX INITIALIZER Zinclude avr32io driver c endif AVRDRIVER The avr32io_SetAnalogOut function are shown below and are an example on how these functions works T he function are called from a normal user mode program that has included the header file and the new value for the analog out are sent as a parameter function then opens the correct device node and writes the data to it The data that originally was a 16 bit integer are converted into two 8 bit integers so the 8 bit ATmegal28 can use it short avr32io SetAnalogOut char channel char subchannel unsigned short value int ret char devFile 14 unsigned char data 3 Prepare data to send data 0 subchannel data 1 value gt gt 8 data 2 value pthread mutex lock amp spiMutex Open the correct device node sprintf devFile dev avr32Aout i channel fd open devFile ORDWR if fd lt 0 DEBUG avr32io user error i n fd return
71. T will compile and run AVR32 with a few modifications to the Makefile this file will be very similar to grt tlc The few changes necessary are to specify a new Makefile template and change some names Each system target has a short text that describes itself which is showed in the list where users can choose system targets To change this text and specify a new Makefile the following lines has to be added to the top of the avr32 tlc file Any similar lines containing SYSTLC or TMF should be removed SYSTLC AVR32 Real Time Target TMF avr32 tmf MAKE make_rtw EXTMODE ext_comm In the end of the grt tlc file a suffix for the generated code directory is specified This should be changed to another name by using the line below instead of the original line rtwgensettings BuildDirSuffix avr32 rtw 11 2 2 avr32 tmf This is the Makefile template of the system target that was made by doing some modifica tions to the grt unix tmf file The Makefile template for on UNIX Linux platforms The first change was to replace the grt tlc with avr32 tlc as system target file This is done changing the original system target file definition with the line below SYS TARGET FILE avr32 tlc The next step is to change the compiler and compiler flags used by the Makefile This is done by adding the following lines before the flags section of the original template This should be around line 185 of the o
72. The final card on the other hand had a better type of operational amplifiers but the low pass filters didn t work as they should have The most likely reason for this is that the filters were 105 106 CHAPTER 13 DISCUSSION poorly assembled Design of future versions of this card should give the filters more room to make the assembly easier Apart from the problems with the analog output all the parts of the I O card worked as planned Two different solutions were developed for using the ADC of the ATmegal128 The reason for this was that the ADC conversion takes a significant amount of time This was solved by either interrupting the AVR32 when the ADC conversion was finished or continuously convert analog values and store them in a buffer Since the drivers of the I O card doesn t use threading the continuous mode is the best choice specially if only some of the Analog input channels are used The interrupt mode would be a better choice if a thread was running sending the analog input command since then the rest of the program could use the CPU cycles wasted while waiting for the interrupt from the I O card 13 3 I O card Communication and Drivers The communication between the AVR32 and the I O card was successfully implemented with SPI A protocol was developed for this communication that the AVR32 uses to give commands to the I O card This protocol has effective error detection so both the AVR32 and the I O card will detect if an
73. The slave will send the value 111 to the master and it will use the LEDs on the STK500 to display the received data This confirms that the SPI communication works both ways Includes include lt avr io h gt int main Initialize SPI SPCR 1 lt lt SPE DDRB 1 lt lt 3 Initialize LEDs 30 CHAPTER 5 PRELIMINARY TESTS OF I O CARD DDRD Oxff PORID 0 Set data SPDR 111 Wait for transfer while SPSR amp 1 lt lt SPIF Send received data to LEDs and loop forever PORTD SPDR while 1 5 5 4 Result The test of a simple SPI transfer between the two boards was successful This means that it will be possible to use SPI as communication between AVR32 and an I O card The highest SPI frequency that worked was measured to about 1 90M Hz with an oscilloscope According to the ATmega128 data sheet 1 both the low and high period of the SCK signal has to be longer than 2 clock cycles When the clock frequency is 8M Hz this means that the highest theoretical frequency is 2M Hz that are close to the measured value Chapter 6 Prototype I O card This chapter desribes the design and production of the first of two I O card versions produced during this thesis The first card is called the prototype card and was designed to be ideal for testing and debugging 6 1 PCB Software A PCB Printed Circuit Board is an epoxy bonded fiberglass sheet with copper layers that can
74. USSION Chapter 14 Conclusion This thesis has developed the hardware and software necessary for using the AVR32 pro cessor architecture as a control system This resulted in a control system platform that can easily be installed and used The platform it specially suited for applications where low weight and power consumption is important because both the AVR32 itself and the microcontroller used in the I O card are low power devices An 1 and drivers were developed and this enabled the AVR32 to measure and control its environment with digital and analog OV 5V signals AVR32 communicates uses SPI to give commands to the I O card This gave a reasonable fast and very reliable communication Since SPI has no error checking the communication protocol was designed with an effective error detection even if the communication itself was reliable This means that in the case of an unlikely error the system will detect it The platform has be configured to use Matlab Real Time Workshop as a rapid prototyping tool This tool generates code from Matlab Simulink models that makes it suited for designing and testing different controllers With the developed S functions the I O card could be controlled with Real Time Workshop In this thesis standard Linux timers have been used to make the time steps periodical This gives a minimum period of lms but this haven t been a problem since the control system aren t fast enough to use lowe
75. _select 0x02 Uses slave number 2 Setup the SPI driver and channel ret spi_setup spi if ret lt O printk KERN ALERT avr32io Probe spi setup failed d n ret return ret dev set drvdata amp spi dev device return 0 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 130 static int avr32io Open struct inode node struct file xfilp int minor ret minor iminor filp f dentry d inode DEBUG avr32io Open minor 6i Vn minor Take mutex ret down interruptible amp spiMutex if ret 0 return ERESTARTSYS Check if SPI is used if device gt busy 0 SPI busy return error ret EBUSY else SPI not busy mark as busy and return success device gt busy 1 ret 0 APPENDIX C CODE Returns the mutex and return if the SPI was busy or not up amp spiMutex return ret static int avr32io Release struct inode node struct file xfilp DEBUG avr32io_Release n Take mutex ret down interruptible amp spiMutex if ret lt 0 return ERESTARTSYS Mark the SPI as not busy device gt busy 0 Returns the mutex and returns success up amp spiMutex return 0 static ssize t avr32io Read struct file x filp char __user xuserBuf size_t len loff t f pos int ret 18 toUser len int minor iminor filp
76. a message The message structure also makes sure that an error in one of the transfers will be detected 7 1 1 Commands protocol has a number of defined commands Some of them are data commands that are used by the master to either read an input or write to an output of the I O card Another type of commands are control command that change the internal settings of the I O card One of the commands listed here are marked with buffering only which means that it will only be used in one of the two possible solutions defined in 7 2 2 Data commands 43 44 CHAPTER 7 DESIGN OF I O CARD SOFTWARE Get analog input is the command for reading an analog value Set analog output is the command writing an analog value Get digital input is the command for reading all of the 8 digital input channels at once Set digital output is the command for writing more of the 8 digital output channels Control commands Set analog input enable is the command for enabling disabling an analog input chan nel buffering only Set analog output resolution is the command for changing the resolution of an analog output channel 7 1 2 Message Structure The communication protocol also defines two message structures that a message containing a command has to follow There are two structures because commands that send data to the slave set digital output will need a slightly different messag
77. ad h gt include lt sys time h gt Struct that represents one periodic task struct sPeriodicTask struct sPeriodicTask Pointer to the next periodc task int periode The periode of the task pthread_t thread The thread thats running the task pthread_cond_t cond The condition that controls the task pthread_mutex_t mutex The mutex protecting the condition Struct for the timer struct itimerval rttimer Struct for the root task struct sPeriodicTask xrootTask This function initialize the periodic task system int InitPeriodicTasks Function that runs every millisecond signaling all the periodic tasks void fTimer F H 142 APPENDIX C CODE This function starts a new periodic task Started tasks can t be stopped int StartPeriodicTask struct sPeriodicTask pTask int periode This function starts a new periodic thread Started threads can t be stopped int StartPeriodicThread struct sPeriodicTask pTask int periode void function void void data Used inside the periodic task thread to sleep until next periode int WaitPeriodicTask struct sPeriodicTask xpTask Zinclude periodicTask c endif 3 4 periodictask c int InitPeriodicTasks static int initialized if initialized gt 0 return 1 Initialize the timer signal SIGALRM fTimer rttimer it_value tv_sec 0 rttimer it_
78. age like Matlabs own language M C C Ada and FORTRAN This allows users to add their own blocks in Simulink that can have functionality that normal Simulink blocks can t provide When using Matlab RTW rapid prototyping tool for a control system S functions are often used to control I O S functions are written as a code file for the selected computer language but this file has to follow a specific structure use the S function the code has to be compiled using the Matlab command mex As for other compiled program this file has to be compiled again each time changes have been made When using RTW it s possible to use three types of S functions that are described below o Noninlined S functions are S functions that doesn t have a tlc file which means that it s treated equally by Simulink and RTW This is the easiest solution since everything that works in Simulink will work equally in RTW and it s not necessary to write any TLC code Unfortunately this is not very efficient and will need additional CPU and memory usage when running a program from the generated code o Fully inlined S functions have a tlc target block file and the behavior of the S function in RTW is defined by this file and not by the S function code file used by Simulink This means that the S function might not do the same thing when simulating in Simulink as when running the program made by RTW generated code This can both be a good and a
79. also had problems with the analog output The operational amplifiers and the supply voltage for these worked better than on the prototype but the filters for converting the PWM signals to analog voltages didn t work They gave out lower voltages 10 4 PROBLEMS WITH ANALOG OUTPUT 85 Figure 10 1 Top layer of final card Not to scale Figure 10 2 Bottom layer of final card Not to scale 86 CHAPTER 10 FINAL VERSION OF I O CARD Figure 10 3 Final version of I O card than they should have The reason for this is unknown but the filters was difficult to solder since the SMD resistors and capacitors were very small and were placed on a small surface Inaccurate assembly may be the reason for the poor performance of the filters Redesign of this I O card should give the filters more space Chapter 11 Matlab Real Time Workshop 11 1 Matlab Real Time Workshop Matlab Simulink can be used to design and simulate mathematical models With the help of Matlab Real Time Workshop RTW for short C code can be generated from the Simulink model The code will if compiled give a program that does the same simulation as in Simulink This can be used for rapid prototyping control systems as described in 2 4 How to use RTW is described in 13 11 1 1 Target Language Compiler TLC When Matlab Real Time workshop generates C code from a Simulink diagram it actually does it in two steps The first step is to make a rtw file This file co
80. am128io h and am128io c contains functions that receive a code that the main function has received from AVR32 These functions will receive the rest of the message The code below is the header file am128io h and the code file am128io c is in the appendix C 1 3 This header file is quite long but it also defines how all of the different messages are implemented ifndef AM128 IO define 128 IO Initialize the different parts of the I O card void IO_Init Function that checks if an received data rx was a correct ack of the transmitted data tz signed char IO TestAck unsigned char tx unsigned char rx Checks the received code and starts receiving new command if code is valid signed char IO NewCommand unsigned char code Analog in SPI message Number Received from master Returned to master 1 DUMMY code 1 Wait for interrupt if in interrupt mode 2 DUMMY vauleH 3 valueH 1 vauleL 4 valueL 1 DUMMY 5 MASTER_OK SLAVE_OK signed char IO AnalogIn unsigned char code Analog out SPI message Number Received from master Returned to master il valueH code 1 2 valueL vauleH 1 3 DUMMY vauleL 1 4 MASTER_OK SLAVE A signed char IO_AnalogOut unsigned char code Digital in SPI message Number Received from master Returned to master 1 DUMMY code 1 2 DUMMY value 3 value 1 DUMMY 4 MASTER_OK SLAVE OK signed char IO DigitalIn unsigned char code Dig
81. ange the op amp circuit from being a voltage follower to a non inverting amplifier that amplifies the OV 5V signal to a OV 10V signal To use this option the power supply has to be high enough so the op amps can give out 10V o PWM filters were made with resistors with value R 3 9kQ and capacitors with value C 22nF giving them RC 8 58 10 5 This should give a response time around half a millisecond 10 2 Schematic The whole schematic of the final version of the card are in the appendix B 2 This schematic is the same as the prototype except for the changes described in 10 1 10 3 Layout The layout of the final I O card are shown in 10 1 on the facing page and 10 2 on the next page Since it used SMD components whenever possible and other design changes this card was almost half the size of the prototype Since more components are SMD almost all of them were placed on the top layer of the card instead of the bottom layer on the prototype Since the I O signals were ordered after pin numbers it meant that the routing of signals was more complex than for the prototype card This made the gain of placing the ATmegal28 on the bottom layer less than for the prototype card since both solutions would be equally complex Therefor the top layer was chosen because of cosmetic reasons Figure 10 3 on page 86 is an image of an almost assembeled final version of the I O card 10 4 Problems with Analog Output The new I O card
82. ases that are described below The synchronization phase is almost identical to that in the sending structure difference is that after the master sends the code it has to send a dummy byte to retrieve the acknowledgment of the code The slave data phase are similar to the master data phase in the sending structure But since the slave sends data the master has to retrieve the first byte by sending a dummy byte Then it will send an acknowledgment for the first byte and the slave will return the second byte and so on When the master sends an acknowledgment for the last byte the slave will return a dummy byte and the slave data phase is ready The confirmation phase is the same as for the sending interface Both of these structures will have the following advantages bytes sent both master and slave are sent back as acknowledgments and checked Since the communication is full duplex the interfaces defined here won t use more than one or two SPI transfers than similar interfaces without acknowledgments would use Several of the bytes received both by the master and slave are known and can 46 CHAPTER 7 DESIGN OF I O CARD SOFTWARE Master Slave Code 1 SC Unknown Code 2 a ae ee Synchronization Ready Dumm 3 po I gt gt v 3 o gt Slave data Slave data 2 Slave data 2 increase
83. at defines clock source and other important characterisitcs of the AVR These can be written are read with a programming toll like the JTAG ui 6 6 ASSEMBLY AND TEST Al When starting up the ATmegal28 with the crystal circuit and new fuse bits the crystal pins were probed with an oscilloscope The result was a sinus signal with a frequency of 16M Hz which means that the crystal circuit works sudo avrdude P usb pm128 cjtag2 U lfuse w 0xFE m U hfuse w 0x89 m U efuse w 0 xFF m 6 6 4 RS 232 and Reset Circuits These two elements were best to test together The RS 232 circuit consists of the MAX233 IC and a 9 dsub connectors connector used by serial port of a standard computer The reset circuit consists of a button a resistor and a capacitor The RS 232 circuit was tested by sending a byte of data from the card when it was connected to the workstation with a serial cable The code below sends one byte with a baud rate of 19 2kbps When running this code the workstation received the byte when using a program like minicom The reset circuit worked since the same byte was received by the workstation each time the reset button was pressed Includes include lt avr io h gt int main Set direction registers set_bit DDRD 3 clear_bit DDRD 4 BAUD rate 19 2k UBBRIH 0 UBBRIL 51 Enable both transmit and receive UCSRIB 1 lt lt RXEN1 1 lt lt
84. base for making analog out signals The analog supply is necessary to make the ATmegal28 able to read analog input signals The crystal and analog supply circuits are implemented after specification given in the ATmegal28 data sheet 1 6 4 3 JTAG header and Analog Input Connectors Figure 6 3 shows the JTAG header for the ATmegal28 and screw clamps for the analog input signals The JTAG header was added to allow a AVR JTAG ICE either original or mk2 to connect program and debug the ATmegal28 The analog input screw clamps was mounted at the side of the I O card and makes it easy to connect wires with analog signals to the ADC of the ATmegal28 Four of ATmegal28s ports was used both by the JTAG header as analog input This shouldn t be a problem as long as no analog signals are connected to these ports when using the JTAG header 6 4 SCHEMATIC A15 PC7 G_OUT_H 4 A14 PC6 G_OUT_H 3 A13 PC5 G_OUT_H 2 12 4 G_OUT_H 1 A11 PC3 10 2 OUT 1 4 A9 PC1 G OUT 1 3 A8 PCO DIG OUT L 2 G OUT L 1 T2 PD7 T1 PD6 MEGA INT 2 XCK1 PD5 MEGA INT 1 IC1 PD4 TXD1 INT3 PD3 RXD1 INT2 PD2 E 1 SDA INT1 PD1 i EGA_INT_2 SCL INTO PDO ATM GA INI 1 7 T3 INT6 PE6 OC3C INT5 PES 4 4 1 2 TXD PDO PE1 RXD PDI PEO TAIN T2lN R1OUT R20UT T1OUT T20UT R2IN 35 C24 C24
85. card should be disconnected from the STK1000 card and from power supply While soldering it s easy to make short circuits which should be avoided 6 6 1 Power Regulator Circuit The power regulator circuit consists of a power jack a voltage regulator two capacitors and a 3 pin header used for selecting power supply It was tested by connecting a 9V source to the power jack and selecting external power supply The output voltage was measured to 5 0V which means that the voltage regulator are working 6 6 2 ATmegal28 JTAG Interface After soldering the ATmegal28 it s important to check that there are no short circuits between its pins After checking this thoroughly the JTAG header and decoupling capac itor was connected The different functions of the AT megal28 will be tested when they are needed The first test was to connect to the ATmegal128 through the JTAG interface The avrdude command below connects to the ATmegal28 and writes some info about it This command returned correct information about the ATmega128 which means that basic operations of the ATmegal28 works and that the JTAG interface is able to program it sudo avrdude P usb pm128 cjtag2 v 6 6 3 Crystal Circuit The crystal circuit consists of a crystal 16MHz and two capacitors To use this circuit the fuse bits of the ATmegal28 has to be changed The avrdude command below does this Fuse bits are bits in AVR microcontrollers memory th
86. ce Se ae ce 412 Result Ae Sle eee we 4 2 Timer precision Test ADM Code urb y 42 3 Results x EE 4 3 Test of Matlab Real Time Workshop Generated Code 10 10 10 11 13 13 13 14 14 15 15 16 16 19 5 1 AVR Microcontroller 2224s 19 aet 19 541 2 5007501 ius uus ed Be ees Se 20 5 25 Analogdnput a A ee S a SS 20 5 2 1 Test of ATmegal28 20 5 3 Analog Output se ok eR Rd 21 5 3 1 Generating Analog Signal from PWM 21 5 3 2 Quality of Analog 21 Dros gt ume Constant RO dor tor e Sonet a LC E Eae 23 5 3 4 Frequency and Resolution 24 5 8 5 Order of low pass 24 5 3 6 Test of ATmegal28 as 24 Ss ERA S sei ba mates a duelo A ead es 26 BA CORT DUS ss Np dies pee a UA 26 542 SPTSFADSIeE m rte e Re IRR e V SE up der t LOSS Te de iet 27 5 5 Test of SPI communication between AVR32 ATmegal28 27 5 59 17 Hardware set p s Du Gk ER Ea we ee 28 5 5 2 AVR32asSPI master
87. ch 1 return EIO ifdef INTERRUPT MODE Wait for interrupt device irqFlag 0 DEBUG wait n ret wait event interruptible timeout wq device gt irqFlag 0 10000 if ret lt 0 return ERESTARTSYS DEBUG interrupt n Send DUMMY receive data0 ret SPI MasterTransferByte DUMMY DEBUG dummy 961 4 0 DUMMY ret if ret lt 0 return ret toUser 0 08 Send data0 ack receive datal ret SPI MasterTransferByte u8 toUser 0 1 DEBUG data0 1 _ i_datal _ i n u8 toUser 0 1 ret if ret lt 0 return ret toUser 1 u8 ret Send datal ack receive DUMMY ret SPI MasterTransferByte u8 toUser 1 1 DEBUG data0 1 _ i_dummy _ i n u8 toUser 1 1 ret if ret DUMMY return EIO Confirm command ret SPI MasterTransferByte MASTER OK DEBUG masterOK 96i slaveOK MASTEROK ret if ret SLAVEOK return EIO return 0 int SetAOut u8 fromUser int ch int sch int ret unsigned char tx 3 expectedRx 3 check for valid channel if ch lt 0 return EIO 113 114 15 116 117 118 119 120 121 122 23 124 25 26 127 128 29 30 131 132 133 134 135 36 37 138 40 2 KERNEL MODULE 133 Synchronize with 128 ret WaitForAM128 CH TO CODE AOUT ch sch
88. cted channel struct sAinChan it 139 46 140 APPENDIX CODE chan ainChanList chanNumber avr32io_EnableAnalogIn chanNumber 1 Start periodic thread for sampling the analog input channel pthread_mutex_init amp chan gt mutex NULL StartPeriodicThread amp chan gt samplingTask int period MASTER TIMER PERIOD Sampling Ain chan void Sampling Ain void int count 0 struct sAinChan chan chan ptr chan gt value 0 Forever loop for sampling analog input while 1 Wait for periode Wait PeriodicTask amp chan gt samplingTask Lock mutex update value and unlock mutez pthread_mutex_lock amp chan gt mutex chan gt value float avr32io_GetAnalogIn chan gt chanNumber 0 004888 pthread_mutex_unlock amp chan gt mutex int avr32io GetAnalogInThread int chanNumber double data double result struct sAinChan chan ainChanList chanNumber Lock save value and unlock mutex pthread_mutex_lock amp chan gt mutex result chan gt value pthread_mutex_unlock amp chan gt mutex For some reason returning a double didn t work with RIW data result return 0 j int avr32io SetAnalogOutThread int chanNumber int subchanNumber double value f Makes new list item struct sAoutCmd temp temp malloc sizeof struct sAoutCmd
89. d 6 4 A Tmegal28 microcontroller 1 MAX233 UART to RS 232 IC 5 Two 100n F capacitors for decoupling ATmegal28 and MAX233 Linear voltage regulator 7805 with capacitors 7 100n F capacitor and 10 H inductor for LC filter on analog supply 16M Hz crystal and two 18pF capacitors for crystal circuit for ATmegal128 One button 10520 resistor and 100n F capacitor for reset button for ATmegal128 Six second order RC filter for filtering PWM signal to analog value Two resistors and two capacitors for each filter 3 operational amplifiers MC1458 6 Screw clamps for connecting different signals 2x5 male header for J AG connection 2x18 male header for STK1000 connection 1x3 male header with jumper for power supply selection 1x8 header for debug signals Schematic The schematic of a circuit is a logical representation of how the different parts connects to each other When designing a circuit it s normally best to start with this The whole schematic are in the appendix B 1 Different sections of the circuit are presented below Be aware that these are the orignal schematics of the prototype and have errors described in 6 7 6 4 SCHEMATIC 33 P OUT DCJ0202 P IN GND Figure 6 1 Power circuit PG3 TOSC2 PG4 TOSC1 ALE D PG1 R WR Figure 6 2 Reset crystal and analog reference circuits for 128 6 4 1 Power Circuit Figure 6 1 shows
90. d for control systems with higher periods than because of the slow clock and poor floating point performance The last test in this chapter confirmed that the AVR32 can run code generated by Matlab RTW after a few modifications 18 CHAPTER 4 PRELIMINARY TESTS OF AVR32 Chapter 5 Preliminary tests of I O card 2 1 2 describes why control systems need I O specially analog I O Since the STK1000 don t have any analog I O a I O card was developed This chapther performs test to find out if the chosen ATmegal28 microcontroller is able to work as a controller for the I O card and if the SPI bus is useable as communication between STK1000 and the I O card 5 1 AVR Microcontroller 5 1 1 ATmegal128 An 128 1 microcontroller was used to control the I O card This is a 8 bit mi crocontroller from the AVR family from Atmel Norway ATmegal28 is 64 pin micro controller with 128kB flash and 4096B SRAM making it one of AVRs with highest specification Some of the features of the ATmegal28 are shown below 8 amp channel 10 bit ADC analog input o 2 channel 16 bit PWM Pulse Width Modulator timers with 3 subchannels each These can be used as analog output o 2 8 bit timers o 2 USARTS that can be converted RS 232 o Several external interrupts o SPI Serial Peripheral Interface o TWI Two Wire Interface o Several general digital I O pins digital I O With these built in features there was
91. d almost everywhere Many ordinary items contain small embedded computers and new cars have computer controlled breaks fuel injection and stability control A computer system that controls a physical system is called a control system and control systems are continuously getting more complex and smaller in physical size In 2006 Atmel Norway released a new processor architecture called AVR32 This processor architecture is designed for use in embedded systems specially small system with low power consumption Small physical size and low power consumption are very important for many control systems specially if the system is battery powered The main goal of this thesis was to make use of this new architecture to make a platform for control systems This will use an AVR32 version of Linux as an operating system since Linux is an operating system that is free open source and suited for embedded development Atmel Norway has ported the Linux kernel and many tools to the AVR32 architecture so it s a natural choice A control system has to be able to observe and control the environment To give the AVR32 this capability an Input Output card has been developed This card makes the AVR32 able to send and receive analog voltage signal from sensors and actuators and are the AVR32s extension into the physical world To make development of control systems easier on the platform Matlab Real Time Work shop was adapted so it can be used as a rapid pr
92. d by one 6 T LIII Dummy Master OK 7 qood Confirmation Slave OK Figure 7 2 therefor be checked for errors 7 1 3 Acknowledgments When either the master or the slave receives data they will return an acknowledgment during the next transfer as explained in 7 1 2 This is to detect errors that either breaks the synchronization between the master and the slave or errors during transfer of data To be able to tell if the correct data was received the acknowledgment returns the received data back the the sender The natural choice would be that the acknowledgment would have the same value as the original data This proved to be a bad idea because of the way SPI works SPI uses one data register for both sending and receiving If this register isn t deleted after a transfer the previously received byte will be sent during the next transfer This means that an acknowledgment consisting of the original data would fail Therefore the acknowledgment is always the original byte increased by one If the original byte had the value 255 then the acknowledgment would be zero 7 1 4 SPI codes Each message begins with the master sending a code to the slave This code tells the slave what kind of command the message contain and information about channel and subchannel if needed code consists of 1 byte 8 bits where the first 5 bits are reserved for identifying the command and the last three bits are for identifying channels and
93. d the mask and data are applied to digital out for 1 0 1 lt 8 i if test_bit mask i if test_bit value i set bit PORTC i else clear_bit PORTO i Debug printing if enabled UART_Print c code UART_Print m mask UART Print v value ifdef BUFFERING MODE signed char IO AnalogInEnable unsigned char code unsigned char enable rx char ret 1st byte store received enable return code 1 ret SPI_SlaveTransferByte code 1 amp enable TIMEOUT if ret lt 0 return ret 2nd byte store received DUMMY return enable 1 ret SPI_SlaveTransferByte enable 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 3rd byte check received MASTER_OK return SLAVE ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 When the message is confirmed the channel are enabled or disabled if enable 0 4 ADC DisableChan CODE TO CH AIN code else ADC_EnableChan CODE TO CH AIN code Debug printing if enabled UART_Print c code UART Print e enable endif signed char IO AnalogOutRes unsigned char code unsigned char resolution chEnable rx char ret 1st byte store received resolution return code 1 ret SPI_SlaveTransferByte code 1 amp resolution TIMEOUT if ret lt 0 return ret 261 262 263 26
94. define F CPU 16000000 Includes include lt avr io h gt include lt util delay h gt include lt avr interrupt h gt Macros for bit operations define set_bit reg bit reg 1 lt lt bit 57 58 CHAPTER 8 IMPLEMENTATION I O CARD SOFTWARE define clear_bit reg bit reg amp 7 1 lt lt bit define test_bit reg bit reg amp 1 lt lt bit define loop_bit_is_set reg bit while test_bit reg bit define loop_bit_is_clear reg bit while test_bit reg bit Enables debugging over RS 232 This will give problems since the debugging takes a long time define RS232 DEBUG Enables timout of SPI transfers Timeout period TIMEOUT 20 microseconds define TIMEOUT ENABLE define TIMEOUT 25 Defines if buffering mode or interrupt mode will be used for ADC define BUFFERING MODE define INTERRUPT MODE Main function that initialize the I O card and then starts the main program loop which continuously checks for new messages from the AVR82 int main Zinclude am128uart h Zinclude am128io h code below is the main program loop which will wait for new commands On line 14 the SPI data register are set to the SLAVE_READY code This makes sure that the next byte the it sends to the master will be this code Line 17 waits for a new SPI transfer and the code received in this SPI transfer is sent to the function at line 24 This functi
95. define IS DIN minor minor MINOR DIN define IS minor minor MINOR DOUT Functions for converting minor numbers into channels int MinorToChAin int minor if IS_AIN minor return minor MINOR else return 1 int MinorToChAout int minor if IS_AOUT minor return minor MINOR else return 1 8 2 3 Char Device registration Before the char device driver can work one or more char devices have to be registered in the kernel This is done by making a cdev structure and use a function to add it into the kernel The cdev structure contain a pointer to a file_operations structure This structure points to different functions for the different file operations that are associated with the char device When an user mode program should communicate with device driver through a device node the module has to react to different operations done to the node The file_operations structure defines what functions are associated with the different file operations Below is a list of the file operations used in this module and what they do 66 CHAPTER 8 IMPLEMENTATION I O CARD SOFTWARE Open This file operation is performed each time an user mode program opens the device node This has to be done before any other operations can be done on the node Release It s possible to open a file multiple times without closing it Each opening will increment a tim
96. dgment of the code Activity 2 2 waits until the next SPI transfer Activity 2 3 saves the received data in the appropriate variable Activity 2 4 sets the SPI data register to an acknowledgment of the received data Decision point 2A checks if the slave expects more data The slave knows this because the number of data bytes are always the same for the same type of command Further the type of command is known because of the code Activity 2 5 waits until the next SPI transfer Decision point 2B checks if the received data was a dummy byte No dummy byte means that receiving the message failed o Slave data phase Activity 3 1 sets the SPI data register to the first data the slave wants to send Activity 3 2 waits until the next SPI transfer Decision point 3A checks if the received data was a dummy byte No dummy byte means that receiving the message failed Decision point 3C checks if there is more data that should be sent as in the master data phase the number of bytes is defined by the type of command Activity 3 3 sets the SPI data register to the next data the slave wants to send Activity 3 4 waits until the next SPI transfer Decision point 3B checks if the received data was an acknowledgment of the data the slave sent during the transfer before the recent transfer No acknowledgment means that receiving the message failed Activity 3 5 sets the SPI data register to be a dummy byte since no data should be sent from th
97. dif 2nd byte check received DUMMY return high byte value ret SPI SlaveTransferByte data 0 TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 8rd byte check received high byte value 1 return low byte value ret SPI SlaveTransferByte data 1 amp rx TIMEOUT if ret lt 0 return ret ret IO TestAck data 0 rx if ret lt 0 return ret 4th byte check received low byte value 1 return DUMMY ret SPI SlaveTransferByte DUMMY TIMEOUT if ret lt 0 return ret ret IO TestAck data 1 rx if ret lt 0 return ret 5th byte check received MASTER OK return SLAVE OK ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 Debug printing if enabled UART Print c code UART_Print h data 0 UART Print 1 data 1 return 0 signed char IO AnalogOut unsigned char code unsigned char valueH valueL rx char ret 1st byte store received valueH return code 1 ret SPI_SlaveTransferByte code 1 amp valueH TIMEOUT if ret lt 0 return ret 2nd byte store received valueL return valueH 1 ret SPI_SlaveTransferByte valueH 1 amp valueL TIMEOUT if ret lt 0 return ret 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 1
98. e lt double lt 52 53 54 55 56 57 58 59 60 61 62 C 4 MATLAB S FUNCTIONS 9Gen dif LibBlockInputSignalConnected 7 mask mask 1 7 if double lt LibBlockInputSignal 7 LibBlockParameter P8 dout dout 1 7 avr32io_SetDigitalOut mask dout endfunction 0 gt D 0 gt gt double 96 147 Bibliography A C 10 11 12 13 14 15 16 17 18 19 128 datasheet AVR32 82 bit MCU DSP Overview Atmel Corporation http www atmel com products AVR32 AVR32 Linux Wiki AVR32 Linux Wiki contributors http www avr32linux org Eagle Layout Editor CadSoft nttp www cadsoft de MAXIM 298 datasheet 1458 datasheet MC7805 datasheet STK1000 Atmel Corporation http www atmel com dyn products tools card asp tool id 3918 STK500 User guide Ubuntu Canonical Ltd nttp www ubuntu com AVR32 Architecture Manual Atmel Corporation Feb 2006 Real Time Workshop Target Language Compiler The Mathworks Mar 2007 Real Time Workshop Target User s Guide The Mathworks Mar 2007 Wikipedia contributors Control System Wikipedia The Free Encyclopedia May 2007 http en wikipedia org w index php title Control_systemkoldid 131753209 Wikipedia contributors Linux Kernel Wikipedia The Free Encyclopedia Jun 2007 http en wikipedia org w inde
99. e but when the work on this thesis began January 2007 some of the ported software had some problems Especially AVR32 Linux version 2 6 16 was problematic as described in 3 2 By the end of this thesis June 2000 both the Linux kernel version and development tools was more mature and also easy to install on Windows and on popular Linux distributions like Ubuntu and Fedora A small library for making periodic threads and tasks was developed since control system needs to execute work periodically This library used the Linux timer which gave accept able accuracy The shortest period that was possible to make was 1715 that turned out to be more than enough because of the speed of the AVR32 13 2 The I O card has an ATmega128 microcontroller that controls everything on the card It communicates with the AVR32 sets analog and digital output and measure analog and digital input Since this component does all this only a few other components are needed on the card The disadvantage of using a ATmegal28 for analog I O is that making an analog output signal from a PWM signal isn t the best solution and it needs many additional components like passive filters and operational amplifiers circuits The ADC analog input of the ATmegal28 is not the best ADC available The analog output part of the I O card didn t work as planned The prototype card had working low pass filters but a wrong type of operational amplifiers was used
100. e appendix from C 4 1 to C 4 4 Lines start start with are some kinds of TLC statements like looping through all inputs or outputs of a S function There are also some lt gt tags in these files that are TLC variables or functions All these will be replaced with some text in the generated code 11 4 Results Several Simulink diagrams were made to test how signals could be sent through the I O card With Real Time Workshop generated code This was done by connecting inputs and outputs of the I O card together so a signal that was sent to an output in Simulink could be read by an input in Simulink 11 4 1 Results of Analog Test As mentioned in 10 4 the analog output channels of the I O card did not work as planned be able to perform this test a back up filter was made with regular resistors capacitors 94 CHAPTER 11 MATLAB REAL TIME WORKSHOP untitled mat Sine Wave AVR32 AVR32 Analog Analog Output Input Figure 11 1 Simulink model used for testing the S functions and the I O card 7 45r 4 4 3 5 4 3b 4 25r 4 0 5 E 1 1 1 1 1 1 J 0 0 02 0 04 0 06 0 08 0 1 0 12 0 14 Figure 11 2 Results of sending sinus signal through analog I O and breadboard This gave a much better analog value than the SMD components on the
101. e if the system should be able to have a fast changing analog output final card should have RC values around this value 80 CHAPTER 9 TESTING WITH PROTOTYPE CARD 4 5 4L 3 5r 3L 9 25 2L 15r 1 0 5 02 04 06 08 1 x 10 Figure 9 1 RC 1 0 x 1074 gives a response time of 0 3ms Table 9 3 Results of analog output filters R C RC Response time Resolution Ripple 0 36kQ 100nF 0 36 1074 0 2ms 8 bit 20mV 9 bit 75mV 10 bit 222mV 11 bit 640mV 12 bit 1400mV 150 100nF 1 0 10 4 0 5ms 8 bit 5mV 9 bit 15mV 10 bit A5mV 11 bit 140mV 12 bit 400mV 3kQ 100nF 3 0 1074 1 3ms 8 bit lt bmV 9 bit 5mV 10 bit 10mV 11 bit 25mV 12 bit 9 2 3 Operational Amplifiers When connecting the op amps to the prototype card the op amps was only able to give out voltages between 2V and 3V This is because the op amp that was used MC1458 could not give outputs that was less than V 2V or more than Vt 2V Since V GND and V the output range became limited The final version of the card should have another type of op amps and these will need other supply voltages 9 3 TEST ANALOG INPUT 81 9 3 Test of Analog Input 9 3 1 Precision of Analog Input In 5 2 1 the precision of the ADC of ATmegal28 was tested The result was not very precise When testing the ADC of the prototype card the AVR32 used the analog input command to do the c
102. e linux source These lines should be added to the board info structure and the new code should look like below The new file is available on the CD ROM static struct spi board info 0 board info _ initdata QVGA display modalias Itv350qv max speed hz 16000000 chip select modalias Dies x max speed hz 16000000 chip_select 25 47 48 49 50 51 52 53 54 8 2 DEVICE DRIVER 8 2 6 avr32io 67 avr32io h and avr32io h contain the structures and functions described earlier in this chapter These are all defined in the header file below The code file are in the appendix 2 2 ifndef KM_AVR32_IO_H define _KM_AVR32_I1O_H Includes include lt linux module h gt include lt linux init h gt include lt linux errno h gt include lt linux fs h gt include lt linux cdev h gt include linux device h include lt linux spi spi h gt include linux ioctl h include lt linux delay h gt include lt asm uaccess h gt include lt asm avr32 io h gt include lt linux types h gt include lt linux wait h gt include lt linux interrupt h gt Defines IOCTL numbers define AVR32IO IOCTL MAGIC k define AVR321O IOCTL_RES_AOUT IOW AVR32IO_IOCTL_MAGIC 0 int define AVR32IO_IOCTL_EN_AIN IOW AVR32IO IOCTL MAGIC 1 int Defines if driver should print out debugging information def
103. e slave during the next transfer 50 CHAPTER 7 DESIGN I O CARD SOFTWARE e Activity 3 6 waits until the next SPI transfer e Decision point 3D checks if the received data was an acknowledgment of the last data the slave sent No acknowledgment means that receiving the message failed Confirmation phase e Activity 4 1 sets the SPI data register to the Slave OK code This tells the master that the slave didn t discover any errors during the message e Activity 4 2 waits until the next SPI transfer e Decision point 4A checks if the received data is the Master OK code which will confirm that the message was sent without errors 7 2 2 Analog Input The analog to digital conversion inside the ATmegal28 is an operation that takes 13 ADC clock cycles The ADC clock has to be between 50kHz 200kHz to do a 10 bits conversion By using a prescaler of 128 the ADC will get a frequency calculated in equation 7 1 With this frequency an ADC conversion will take 1048 as shown equation 7 2 and 7 3 This means that the ADC conversion will take a considerable amount of time and the ATmegal128 will not be able to do the conversion during a SPI message if the AVR32 doesn t wait for it fuc C 125 7 1 fanc 198 2 7 1 1 8us 7 2 fanc Teonversion 13 TADC 104us 7 3 To solve this problem two solutions were developed The first solution is to use interrupts This is normally the bes
104. e structure than those requesting data from the slave get digital input None of the commands are required to both send and request data from the slave If either the master or the slave fail to send the bytes required during all the transfers of a message the part that detected the error will stop sending and the other part will then be aware the error This ensures that both parts will know if something went wrong while sending the message Figure 7 1 describes the message structure for commands where the master sends data The message structure is further described below The synchronization phase has to make sure that both the master and slave are ready for the command and that they are synchronized If not synchronized it s possible that the slave will interpret the data the master sends wrongly To synchronize the master initially sends the command code from 7 1 4 If the slave returns a code that confirms it s ready for transfer then the synchronization was successful If it returns something different then the master has to keep sending the code until the slave returns the ready code In figure 7 1 this is represented by the first message which is unsuccessful since the slave returns something unknown The second transfer is successful since the slave returns the ready code o In the master data phase the master sends data to the slave Every time the master sends a new byte to the slave the slave will return an acknowled
105. eaknesses the AVR32 architecture may have so the control system platform can be designed to avoid them as much as possible It s also important to test that planned solutions can be used on AVR32 41 Floating point and Fixed point operation Test The AVR32 architecture don t have a hardware floating point unit FPU This means that floating point operations have to be done with software emulation Since Matlab RTW generated code normally has many floating point operations it s important to know the processors ability to calculate these The test referred to in this chapter was set up to reveal this A test for fixed point calculations was performed as well and the two results were compared The tests consists of 100 million either floating point or fixed point multiplications The test program measures the time used by these operations and calculate the number of microseconds and clock cycles one operation takes on average To measure the time the stopwatch library was used This library was developed during the thesis to make time measurements easier and consists of stopwatch h and stopwatch c that can be found in the appendix C 3 5 and C 3 6 4 1 1 Code Zinclude lt stdio h gt Zinclude stopwatch h define COUNT 100000000 define CPU CLOCK 140 Clock frequency of AVR32 on STK1000 int main long a float b long usec i float usecPerCalc ticksPerCalc 14 CHAPTER 4 PRELIMINARY TESTS OF AVR32 struct sS
106. endif Returns data rx SPDR return 0 1 5 am128adc c void ADC Init Direction of adc channels DDRF 0 ifdef INTERRUPT MODE Direction of interrupt set bit DDRD 7 1 128 clear_bit PORTD 7 Initialize ADC ADMUX 1 REFSO ADCSRA 1 lt lt ADEN 1 ADPS2 1 lt lt ADPS1 1 lt lt ADPSO ifdef BUFFERING MODE void ADC_EnableChan char channel char i struct chanList temp temp2 if chCount 0 table element and start converting channels channeltab channel channels gt next channels channels gt prev channels channels gt channel channel ADC_NewConversion else Search through channels and check if the channel is already temp channels for 1 0 i lt chCount i If channel already is enabled the function ends if temp gt channel channel return temp temp gt next Make new channel temp channeltab channel temp gt channel channel Inserts new channel in list temp gt next channels gt next temp gt prev channels channels gt next temp channels gt next gt prev temp Increase number of channels chCount 4 void ADC_DisableChan char channel char i enabled struct chanList temp temp channels enabled 0 Search through channels and check if the channel is enabled for i 0 i lt
107. ent stopwatch structures are used to measure the time used in each period and how much of the period the processor are working the time it doesn t wait for next period The following code are in the start of the main function and it initialize and start the timer rtmGetStepSize S will return the time step in seconds and this is used to set the period time Since that function needs the variable 8 to work these lines have to be added last in the initialization part of the main function This means just above the big comment block which is named Execute the model Initialize AVR32 Timing aC a a a a ak ak Init PeriodicTasks StartPeriodicTask amp matlabSimulationPeriode int rtmGetStepSize S 1000 The last bit of code is used to print out the results of the time measurements This code has to be added in the main function after the simulation is finished It s not dependent on RTW code so it can be added just above the return statement For debugging printf Avrage periode i n usecTimer count printf Avrage work _ i n usecWork count 11 3 S functions for I O card 11 2 described the changes needed to compile the generated code for AVR32 and make the code execute the time steps periodically This means that systems made in Simulink can run on AVR32 but it doesn t
108. er and during a transfer between two devices the content of their SPI data registers is exchanged This is described in figure 5 7 It means that before the transfer both devices need to place what they want to send in their data register and after the transfer the data in the register is the received data Since data is sent both ways at the same time SPI is full duplex If the master just wants to send data not receive the received data can be dropped If the master wants to receive data a dummy byte has to be sent since the slave can t send anything when the master doesn t The slave can t initialize a data transfer and this may give some problems Specially if the slave has to complete something and then report back to the master This can be solved by letting the master poll the slave until it is finished This will slow down both the master and slave more effective solution is to let the slave trigger an external interrupt on the master when it s finished 5 5 Test of SPI communication between AVR32 and AT megal28 By connecting the STK1000 and STK500 boards it was possible to test SPI communica tion between the two processors It was important to find out if SPI would work before designing the I O card 2 dummy byte is a byte that contain data of no value and is just used to request data from the SPI slave The dummy byte can have any value but should be chosen to a value that the slave won t believe is something e
109. er and each closing will decrement it This file operation is performed when the file is closed and this counter equals zero This means that the file is no longer open and used memory can be released hence the name Write This file operation is performed when a user mode program tries to write to the node In this device driver this file operation will be used by user mode programs to write values to outputs on the I O card Read This file operation is performed when a user mode program tries to read from the node In this device driver this file operation will be used by user mode programs to read values from inputs on the I O card Ioctl Is special file operation for device nodes That s used to give commands to the node that aren t normal data In this device driver this file operation will be used by user mode programs to change the properties of the I O card 8 2 4 SPI device and driver use SPI some data structures has to be defined The SPI driver points to probe function for the device that are used by the module to find out if it s possible to use a SPI device In this function the SPI device is configured and properties like the SPI frequency are set 8 2 5 Changes in Linux Kernel Source Code During development the device driver will be compiled as a module but it still needs some minor changes in the kernel to work This is done by adding some lines to the arch avr32 boards atstk1000 atstk1002 c file in th
110. eturn 0 ifdef INTERRUPT MODE irqreturn_t irqFunk int irq void dev_id struct pt_regs regs Wake up queue waiting for interrupt DEBUG received_interrupt n device gt irqFlag 1 wake_up_interruptible amp wg return IRQ HANDLED Hendif 2 4 avr32io SPI c int SPI MasterTransfer u8 rx u8 tx int len Structs for the transfer struct spi message msg struct spi transfer transfer Makes the transferstruct memset amp transfer 0 sizeof transfer transfer len len transfer rx buf rx transfer tx buf tx Makes the messagestruct and includes the transfer in it spi message init amp msg spi_message_add_tail amp transfer amp msg Execute transfer and return result return spi sync device spi amp msg int SPI MasterTransferByte u8 tx 1 int ret 18 rx Execute transfer of one byte ret SPI MasterTransfer amp rx amp tx 1 if ret lt 0 return ret return rx int SPI SendTableOfBytes u8 tx 18 expectedRx int len int i ret 18 rx len Execute transfer of the given number of bytes ret SPI MasterTransfer rx tx len if ret lt 0 return ret 135 41 42 43 44 45 46 4T 48 49 H NOOBWNFOCOANDUBWNEH 136 Checks that all received data was the expected data for i 0 i lt len i DEBUG tx i 96i expected Rx96i i_rx i _ i n i
111. f size t len loff t f pos Runs when an user space program tries to send an IO control command Send the command to I O card static int avr32io_loctl struct inode node struct file x filp unsigned int cmd unsigned long arg Struct containing data structures for the kernel module struct avr32io device 4 dev t number Major and minor mumbers struct cdev Char device struct spi device SPI device int busy Device busy ifdef INTERRUPT MODE int Interrupt used for analog int irqFlag Flag when receiving interrupt endif h Pointer to device used im driver static struct avr32io device device Struct that defines the functions used for different file operations static struct file operations fops owner THIS MODULE read avr32io Read write avr32io Write open avr32io Open release avr32io Release ioctl avr32io lIoctl jt Struct that defines the SPI driver static struct spi driver avr32io driver probe avr32io Probe driver name 3 210 h DECLARE MUTEX spiMutex Includes include minorNumbers h include spiByteCodes h Zinclude avr32io SPI h Zinclude avr32io_Cmd h Defines init and exit functions module init avr32io Init module exit avr32io Exit MODULE LICENSE GPL MODULE AUTHOR Oyvind Netland Trondheim
112. f_dentry gt d_inode DEBUG avr32io_Read minor i_isAin _ i_isDin _ i n minor IS_AIN minor IS_DIN minor if IS_AIN minor Analog In if len 2 return EPERM ret Cmd GetAIn toUser MinorToChAin minor if ret lt 0 return ret copy_to_user userBuf toUser len return len if IS_DIN minor Digital In if len 1 return EPERM ret Cmd GetDIn toUser if ret lt 0 return ret copy_to_user userBuf toUser len 74 175 176 77 178 179 80 81 2 KERNEL MODULE 131 return len If no output matches the minor number the write operation fails return EPERM static ssize t avr32io Write struct file const char __user size_t len loff t f pos 18 fromUser len int minor iminor filp f dentry d_inode copy_from_user amp fromUser userBuf len DEBUG avr32io_Write minor 96i isAout i_isDout _ i n minor IS_AOUT minor IS_DOUT minor if IS_AOUT minor Analog Out if len 3 return EPERM if Cmd_SetAOut fromUser 1 MinorToChAout minor fromUser 0 gt 0 return len if ISDOUT minor Digital if len 2 return EPERM if Cmd_SetDOut fromUser gt 0 return len If no output matches the minor number the write operation fails return EPERM static int avr32io_lIoctl struct inode node struct file x filp unsigned int cmd unsigned long arg
113. fer transfer len len transfer rx buf rx transfer tx buf tx Makes the messagestruct and includes the transfer in it spi_message_init amp msg spi_message_add_tail amp transfer amp msg 17 18 19 20 f UONE Qo Q2 Q9 h2 b2 b2 b2 b2 b2 b2 b2 bh2 gt h2 r2 O Ct 72 CHAPTER 8 IMPLEMENTATION I O CARD SOFTWARE Execute transfer and return result return spi_sync device gt spi amp msg 8 3 Linux Kernel Patch Compiling the device driver as a module was a practical solution during development This made it possible to quickly recompile and install the module when changing the code For users that don t want to change the source code of the device drivers it s easier to have it compiled into the kernel This would mean that the device driver starts up during start up and it will work until the system shuts down make this as easy as possible for users a Linux kernel patch was made that includes the driver into the kernel This patch are included on the CR ROM and the instruction for patching and compiling the kernel are in 12 1 2 8 4 User Mode Driver The user mode driver consists of functions that open read write and close the device nodes and by doing this give commands to the I O card The different functions and what they do are described int he header file avr32io driver below and the code file are in the
114. ferent slave SPI timeouts Timeout us Error 96 1 20 59 196 2 40 5 8596 3 60 5 2396 4 80 0 7096 6 120 0 02096 8 160 0 00596 10 200 0 00496 15 300 0 004 20 400 0 00496 25 500 0 00096 9 2 Test of Analog Output 9 2 1 Simulation One reason for making a prototype card was to try out different filters for the analog out channels To convert PWM signals to analog signals low pass filters were used as explained in 5 3 As explained in 5 3 3 a filter has a RC value that determine the response time With Simulink simulations the value RC 1 0 10 4 was found to give a response time of about 0 3ms This is shown in figure 9 1 9 2 2 Testing Filters In 9 2 1 Simulink simulations was used to find that when testing filters they should have a RC values around 1674 Three different filters were tested one higher one lower and one approximately this value The ripple and response time where measured with an oscillo scope for the different filters with 8 9 10 11 and 12 bits resolutions Since the response time does not change for different resolution only the value for 8 bit was measured Table 9 3 shows the results These results shows the that ripple increases for higher resolution and for lower RC values It also shows that the acutual response time was higher than the simulated response time 1 0 1074 gave a response time of 0 5ms A higher response time than this is not acceptabl
115. gal28 and MAX233 Decoupling is important since it ensures that these ICs gets a stable power supply figure also shows 36 CHAPTER 6 PROTOTYPE I O CARD AD7 PA7 IN AD6 PA6 CDIG_IN_H 3 AD5 PA5 H 2 AD4 PA4 ODIG_IN_H 1 AD3 PA3 AD2 PA2 1 4 AD1 PA1 DIG IN 1 3 ADO PAO DIG 1 2 DIG_IN_L 1 OC2 OC1C PB7 OC1B PB6 OC1A PB5 OCO PB4 MISO PB3 MOSI PB2 SCK PB1 SS PBO Figure 6 5 STK1000 headers and digital input connectors gt GND 1 27 VCC GND 1 1 GND 2 2 MAX GND 2 1 o GND Figure 6 6 Decoupling capacitors and VCC GND connectors 6 4 SCHEMATIC 37 1C R1 1C 2 EJ N 2 d mb OUT1 3 1C C1 1C C2 pL 3 C N Jr 5 i CANALOG_OUT1 2 1B 1B 1 _ 1 1 _ 2 2 N 3 d i OANALOG OUT1 1 E 1A C1 1A c2 pee 3C R1 3C C ANALOG_OUT3 3 3B R1 L LOG_OUT3 2 3B_C1 3B C2 JL LOG OUT3 1 3A C1 Figure 6 7 Analog out circuit two screw clamps that has VCC and GND signals These signals are available for devices connecting to the I O card and are necessary because all I O signal needs a reference 6 4 7 Analog Output Circuit Figure 6 7 shows the filters and operational amplifiers op amp that are used to convert the PWM signal into an analog voltage Each of the 6 analog output
116. ge By using chip select signals the SPI doesn t need to start each data package with an address meaning that a SPI package only contain data while a I2C package contain an address and data This makes SPI more effective when only a few devices uses the bus When more devices uses the bus SPI won t be a good choice This is because each device needs its own chip select signal meaning a dedicated pin on the master for each of the slaves It s also possible to use an additional component that decodes an address to several slave select signals The SPI bus consists of four types of signals describes below All the devices on the bus also needs common ground o MOSI Master Out Slave In sends data from the master to the slave o MISO Master In Slave Out sends data from the slave to the master SCK Serial ClocK is the common clock sent by the master Since it s a common clock on the bus the bus is synchronous o CS Chip Select or SS Slave Select is a signal that master send to start a transfer with a slave 5 5 TEST OF SPI COMMUNICATION BETWEEN AVR32 AND ATMEGA128 27 SPI master data shift register m 77 gt M gt gt am o gt SPI slave data shift register Figure 5 7 How data are transferred between SPI master and slave 5 4 2 SPI transfer When using SPI it s important to know how the data is transferred Each device on the bus has a SPI data regist
117. gment of the previous byte sent by the master How an acknowledgment works is explained in 7 1 3 When the master sends the first data byte then the slave will return an acknowledgment of the code it received during the synchronization period When the master has sent all the data defined by the command it sends a dummy byte to retrieve acknowledgment of the last data byte If any of the acknowledgments were wrong the master will abort the command 7 1 COMMUNICATION PROTOCOL 45 Master Slave Code 1 a na Unknown Synchronization Code 2 Np ee Ready w l v Code increased by one 4 O HERE gt Master data Master data 2 increased by one Master OK gt Confirmation Slave OK a Figure 7 1 If nothing goes wrong during the message both master and slave will get to the confirmation phase at the same time Then the master will send an master OK code and the slave will return an slave OK code After a successful exchange of OK codes both the master and the slave can be sure that the message was successfully transferred For commands where the master sends data it s especially important that the slave get confirmation that the data it received was correct The interface for requesting data from the slave is similar to that just described It is described in figure 7 2 and has three ph
118. h possible disastrous result if a time limit isn t met soft real time constraint is less serious and will only lower the quality of the result if failing to meet a time limit 2 1 22 Input Output control system is useless unless it can measure and manipulate its environment and to do this the system needs to use sensors and actuators These instruments may have analog or digital interfaces If they have analog interfaces which is quite common they are controlled with analog input and output I O If the instruments are digital they probably use a digital communication protocol like RS 232 or USB To be able to use instruments with analog interfaces a computer needs an I O card These cards have a number of analog I O channels that can be used with instruments with an analog interface This normally implies that the card can measure the voltage of a signal analog input or make a signal with a given voltage analog output I O cards often have digital I O as well that can be used instead of analog I O when only digital values low or high are used This is often used together with an analog value one example is control signals for electrical motor analog signal determine the speed or torque of the motor while a digital signal determines its direction 4 CHAPTER 2 BACKGROUND 2 2 Atmel AVR32 Architecture The new AVR32 microprocessor architecture from Atmel Norway claims to be an architec ture for the 21st century 2 M
119. hat should be avoided This is because a busy wait wastes many processor cycles that could be used by other processes For the ATmegal28 this isn t a problem since it can only have one process It would also be possible to use interrupts instead of busy wait but it would make the code more complex and probably not more effective while SPSR amp 1 lt lt SPIF It s also important to notice that the SPI data register SPDR should always be read after a transfer after the while loop is finished The status bit for received SPI transfer will only be cleared if the SPDR is either read or written to Failing to clear the status bit makes it impossible to know if a new transfer has been received or not F NrFCOONDUBWNH H pe c b2 b2 bh2 hO 26 62 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE 8 1 4 am128ADC am128ADC h and am128ADC c contain functions for using the ADC analog to digital con verter I had decided to test two different modes to use analog input and both of them are implemented in the same code file This means that much of the code are inside ifdef statements so only the code for the selected mode will be compiled ifndef 128 ADC define AM128 ADC Initialize the ADC part of the 128 void ADC_Init ifdef BUFFERING MODE Data structures and functions for buffering mode Struct for making a circular array f
120. imately 3005 If connected a channel will be read even if the value isn t used for anything useful analog output has 2 channels with 3 subchannels each Each channel can choose resolution between 8 bit and 12 bit The I O card will give out a voltage between 0V and 5V depending on the value of the S function blocks input Each channel connected to the will be written to each period and it will use about 250 45 digital input has 8 channels and each channel gives out the value 0 if the channel is low and the value 5 if the channel is high If any digital input channels are used it will be 12 3 RAPID PROTOTYPING WITH MATLAB REAL TIME WORKSHOP 103 read each period and it takes 2208 no matter how many of the channels that are in use digital output has 8 channels and each channel can be configured with a threshold value For all values over this threshold the digital output channel will give a voltage of and all values under it will give a voltage of OV 104 CHAPTER 12 USER MANUAL FOR AVR32 I O Chapter 13 Discussion The work in this thesis has consisted of developing the hardware and software necessary for using the a AVR32 processor in a control system The work has consisted of several smaller tasks that had to work together Each of these tasks are discussed separately 13 1 AVR32 Linux Atmel Norway have done a good job when porting the Linux kernel and development tools to the AVR32 architectur
121. ine VERBOSE DEBUG ifdef VERBOSE DEBUG define DEBUG fmt args if printk ratelimit printk KERNALERT fmt args define DEBUG fmt args telse endif Defines if buffering mode or interrupt mode will be used for ADC define BUFFERING MODE define INTERRUPT MODE Runs when kernel is started module is installed Initialize the needed data structures static int init avr32io Init void Runs when module is removed Removes data structures static void exit avr32io_Exit void Runs when spi driver is started Initialize the SPI driver static int _ devinit avr32io Probe struct spi device spi Runs when an user space program opens a device node Tries to mark the SPI as busy error if SPI already is busy static int avr32io Open struct inode x node struct file xfilp Runs when the last user space program closes a device node mark the SPI as mot busy static int avr32io Release struct inode node struct file xfilp Runs when an user space program tries to read from a device mode Send command to I O card and return the result static ssize t avr32io Read struct file char user xuserBuf size_t len loff t f pos 55 56 57 58 59 68 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE Runs when an user space program tries to write to a device node Send command to I O card static ssize t avr32io Write struct file filp const char user userBu
122. input This manual describes a control system platform that consists of AVR32 Linux running on a STK1000 or NGW development board from Atmel and the AVR32 I O card This platform is used together with a Linux or Windows workstation that can use Matlab Real Time Workshop as a rapid prototyping tool Readers of this manual should have some experience with using Linux since not all basic Linux commands are explained Readers should also read the documentation for AVR32 Linux on AVR freaks Wiki http www avrfreaks net wiki and the AVR32 Linux project http avr32linux org 12 1 Installing Before using this system platform some tools has to be installed on the workstation This workstation can be either a Windows or Linux workstation that has Matlab Real Time Workshop installed The install instructions are based on a Ubuntu Workstation but installing on other Linux distributions should be similar 12 1 1 Install AVR32 tool chain For Ubuntu the AVR32 tool chain can be installed with the Apt package management system To add the AVR32 repository to the Apt sources the following line has to be added at the end of etc apt sources list deb http www atmel no beta ware avr32 ubuntu dapper binary install the tools execute the following commands and answer yes to all questions 7 sudo aptitude update 7 sudo aptitude install avr32 linux devel 97 98 CHAPTER 12 USER MANUAL FOR AVR32 I O If this approach doesn t work or
123. ion avr32io_GetAnalogInThread is used by the main thread to get the currently buffered value The SPI connection is also protected by a mutex to avoid that two threads tries to use it at the same time The device driver also has protection against this that will return an error if the SPI connection is busy By using a mutex here these errors are avoided and it s therefore a better solution 8 5 2 Threaded Analog Output The worker thread starts a forever loop and waits for a signal from the main thread This signal is a pthread condition variable and is the same type of signals that are used to control the periodic tasks in periodicTaks When the worker thread receives a signal it means that there is one or more items in the command list This list is a single linked list that contain information about new values to analog out channels After receiving the signal the thread starts executing the commands in the list one at the time until the list it empty This list has to be protected with mutexes as well so new items won t get added to the list while the worker thread reads a command from it 76 CHAPTER 8 IMPLEMENTATION I O CARD SOFTWARE Chapter 9 Testing with prototype card This chapter desribes tests performed on the prototype card and the software developed for it The parts that are tested are the API communication and the analog I O 9 1 Test of SPI communication 9 1 1 Frequency of SPI connection 5 5
124. ion and Confirmation phases are identical as in 7 3 2 o Slave data phase e Activity 3 1 sends a dummy byte 7 4 USER MODE DRIVER 55 Decision point 2A checks if the received data was an acknowledgment of the code No acknowledgment means that sending the message failed Activity 3 2 sends a new dummy byte Activity 3 3 saves the received data Activity 3 4 sends an acknowledgment of the received data Decision point 2B checks if more data is expected Activity 3 6 sends an acknowledgment of the last received data Decision point 2C checks if the received data was a dummy byte No dummy byte means that sending the message failed 7 4 User Mode Driver Each of the commands that can be given to the I O card have one or more functions provided by the user mode driver These functions makes it possible to give the I O cards commands just with a single function call and this function call should return the result of the message This will make it very easy to use the different features of the I O card The reason that some commands should have more than one function is that they can be used in different ways The user mode driver should have the following functionality Read from different analog in channels Write values to different analog out channels Read all digital in channels at once Write to all or a chosen number of the digital out channels o Change different properties of the I O card like analog re
125. ital out SPI message Number Received from master Returned to master 1 mask code 1 2 value mask 1 3 DUMMY vaule 1 4 MASTER_OK SLAVE OK signed char IO_DigitalOut unsigned char code 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 60 CHAPTER 8 IMPLEMENTATION OF I O CARD SOFTWARE ifdef BUFFERING MODE Analog in enable SPI message Only used in buffering mode Number Received from master Returned to master 1 enable code 1 2 DUMMY enable 1 9 MASTER_OK SLAVE_OK E signed char IO AnalogInEnable unsigned char code fendif Analog out resolution SPI message Number Received from master Returned to master 1 resolution code 1 2 DUMMY resolution 1 4 MASTER_OK SLAVE OK af signed char IO_AnalogOutRes unsigned char code Includes include spiByteCodes h include am128spiSlave h include aml28pwm h include am128adc h include aml128io c endif 128 Below is the function I0_AnalogOut from am128io c This function is a good example on how the functions in this file works The other functions are all similar signed char IO AnalogOut unsigned char code unsigned char valueH valueL rx char ret 18 byte store received valueH return code 1 ret SPI_SlaveTransferByte code 1 amp valueH TIMEOUT if ret lt 0 retur
126. larity doesn t matter because of a bridge rectifier 5 Jumper for selecting if external power supply or supply from STK1000 should be used 6 Operational amplifiers used as voltage followers or non inverting amplifiers 100 CHAPTER 12 USER MANUAL FOR AVR32 I O 10 16 15 13 18 4 17 1 Figure 12 1 I O card 12 2 AVR32 I O CARD 101 T Jumpers for bypassing the filter which means that the analog output will become a PWM signal 8 Passive filters that are used to convert a PWM signal into an analog voltage 9 Headers for connecting STK1000 or NGW development boards 10 LC filter for the analog in power supply 11 Reset button 12 UART headers that can be used for debugging 13 AVR32 interrupt signals that can be connected to STK1000 NGW if interrupts are used Not normally used but might be useful for further development 14 ATmegal28 is the microcontroller that controls the I O card 15 JTAG header for programming and debug ATmegal28 16 Screw clamps for analog input signals 17 Header for digital input signals 18 Header for digital output signals 12 2 2 Connecting I O card The I O card connects to either a STK1000 or NGW board through a 14 pin header cable On STK1000 cards this header cable connects from the header marked STK on the I O card to the general expansion header marked J29 on STK1000 On NGW it connects from the header marked NGW to the general expansion header called J5 on NGW O
127. local matlab extern include I usr local matlab rtw c sre I usr local matlab rtw c src ext mode common I home oyvindne diplom matlab simpleTest test grt I home oyvindne diplom matlab simpleTest I usr local matlab rtw c libsrc rt nonfinite c ccl error invalid option 732 make rt nonfinite o Error 1 The compilation ends with an error since the AVR32 compiler doesn t understand the m32 flag When removing this from the Makefile the compilation is successful and the compiled program runs on the STK1000 card with no problems Notice that during the first AVR32 compilation in a folder many object files are compiled since the default ones from Matlab are all 1386 specific These files are only compiled once so future compilations will take much shorter time 4 4 Preliminary Test Conclusion After doing these tests it was concluded that the AVR32 processor can be used in a control system even if the floating point performance wasn t impressive This weakness implies 4 4 PRELIMINARY TEST CONCLUSION 17 that use of floating point has to be minimized whenever possible In situations where it s impossible or hard to avoid using floating point it can be used even if it means that the effectiveness of the program is reduced The timer test gave a good result and these timers will be used through the thesis They give good precision for timers down to lms The AVR32 will probably be best suite
128. lse 3In this context polling is to periodically ask if something is finished until the answer is yes This is not a very sophisticated method but it s usually the easiest to use 28 CHAPTER 5 PRELIMINARY TESTS OF I O CARD Figure 5 8 Image of STK500 and STK1000 with SPI connection STK1000 general expansion header J29 n o eeg ee miso 1 Wis STK500 Port B header Figure 5 9 SPI wires between STK500 and STK1000 5 5 1 Hardware setup SPI signals are available on headers on both STK cards and they were connected with short cables like on the figure 5 8 Figure 5 9 shows which pins on the header that are used The signals are connected as follows MOSI MISO and SCK should be connected to the same signal while the NPCS2 on STK1000 should be connected to the SS signal on STK500 The two processors must also have common ground to communicate with SPI 5 5 2 AVR32 as SPI master As most hardware the SPI driver can t be accessed directly from user mode To make it possible a device driver has to be made 8 2 describes how the device driver for the ui Ot 5 5 TEST OF SPI COMMUNICATION BETWEEN AVR32 AND ATMEGA128 29 I O card was implemented and the device driver used for this test was similar During the test the device driver sends the value 222 to the SPI slave and it prints out the returned value 5 5 3 ATmegal28 as SPI slave SPI with ATmegal28 is used by
129. make it able to use the I O card S functions were made to control the I O card They are as explained in 11 1 2 Simulink blocks that are coded in a programming language There are different types of S functions but here only fully inlined S functions were used First of all it s important that the program are as effective as possible since the AVR32 aren t very fast and STK1000 have a very limited amount of RAM That meant that noninlined functions wouldn t be a good choice Fully inlined was preferred before wrapper since these S functions should behave different when running simulations in Simulink and 45 46 47 92 CHAPTER 11 MATLAB REAL TIME WORKSHOP when running RTW generated program on STK1000 It wouldn t make sense to try and contact the I O card via SPI from a workstation computer The following S functions has been created o Analog input reads one or more analog input channel of the I O card and gives values between 0 and 5 o Threaded analog input does the same as the normal analog input except that it uses the threads for I O operations o Analog output takes value between 0 and 5 and writes it to the used subchannels Can also select resolution between 8 bit and 12 bit o Threaded analog output does the same as the normal analog output except that it uses the threads for I O operations o Digital input reads all digital input channels of the I O card and gives either low 0 or high 5 values
130. most small Linux applications that an embedded system will need in a single binary file U Boot Universal bootloader is a bootloader that can be used on many different platforms among them the AVR32 8 CHAPTER 2 BACKGROUND system that are necessary to test thoroughly These are often important parts of the system and the result of the tests can be used to avoid premature decisions A typical application is to design the user interface with a rapid prototyping tool This allows fast and cheap development of a prototype that the users of the system can test and evaluate User evaluation can often give important information that is difficult to obtain by other means 2 4 1 Rapid Prototyping Control Systems For control systems rapid prototyping tools can be used to generate control algorithms from graphical visualization of mathematical systems It s easier and faster to develop a control system with a tool like this than to write code It s also easier to change and search for errors These generated algorithms can be tested both against simulated and actual systems which is useful during development Parts of the algorithms can also be used in the complete system Two well known tools for simulating and prototyping of control systems are Matlab and Labview Matlab was originally a program for matrix computation the name stands for MATrix LABoratory but it has evolved into a large collection of mathematical software Simulink is o
131. mutex t workMutex PTHREAD MUTEX INITIALIZER for new command signal pthread_cond_t workCond PTHREAD CONDINITIALIZER New command signal int workCount 0 Number of commands in list int IO Started 0 Protects the Init_IO function from beeing run several times Initialize IO void Init IO Initialize an analog input channel and start a periodic thread that samples this channel int avr32io InitAnalogIn int chanNumber double period Function for analog input sampling thread void Sampling Ain void ptr Function for retriving analog input value from buffer For some reason returning double didn t work with the RIW program so the value will be returned a pointer instead int avr32io_GetAnalogInThread int chanNumber double data Give command to the worker thread about a new analog output value int avr32io_SetAnalogOutThread int chanNumber int subchanNumber double value Function for the worker thread used to execute commands with new analog output values 47 48 49 8 5 THREADED USER MODE DRIVER 75 void Worker_Aout iinclude avr32io_threads c 8 5 1 Threaded Analog Input To make periodic tasks that samples from the I O card this driver uses the periodicTask library that allows to easily make periodic threads These tasks samples from the I O card and store the analog values in variables that are protected by a mutex A funct
132. n both boards the header has to be connected to pins 0 13 If interrupts are used interrupt signals from the I O card has to be connected to the STK1000 or NGW boards aswell 12 2 3 Analog Input card has 8 Analog input channels with 10 bit resolution Each of these can measure an voltage between and 5V above GN D The I O card will continuously convert analog values into digital values and buffer them Each analog input channel that are used increased the time a value is stored in the buffer before it s updated by about 1108 This means that if four channels are used the values are stored about 440 before they are updated 12 2 4 Analog Output The card has 2 Analog output channels with 8 bit to 12 bit resolution Each of these channels have 3 subchannels that can have different analog values The analog outputs are generated with PWM timers and passive filters This means that a high resolution will give high ripple on the analog output voltage Table 12 1 contains the maximum ripple amplitude for different resoultions 102 CHAPTER 12 USER MANUAL FOR AVR32 I O Table 12 1 Rippe for different resolutions Resolution Ripple 8 bit 10mV 9 bit 20mV 10 bit 60mV 11 bit 180mV 12 bit 500mV Channel 0 has jumpers that can select the output range of the analog output to be either 0V 5V or 0V 10V And other jumpers that can be used to bypass the filter so the output becomes a PWM signal instead of
133. n a control system some of these are also mentioned in the article Linux and many of the programs running on Linux are free and open source o A Linux system is configurable scalable and able to run on many different hardware platforms o Linux is a stable and well tested operating system kernel o Linux has many skilled users and developers who are often willing to help 6 CHAPTER 2 BACKGROUND 2 3 2 Kernel Mode and User Mode Most processor architectures has the ability to run code in different levels of privilege The x86 architecture has four called ring 0 to ring 3 The AVR32 architecture ll has two normal modes called Supervisor and Application equivalent to ring 0 and ring 3 Other modes are reserved for interrupts and exceptions As described on page 19 of Understanding Linux kernel 20 Linux systems uses two of these levels kernel mode and user mode Kernel mode are often refereed to as ring 0 19 and is the highest privileged mode normal program executes in user mode but is able to switch to kernel mode when requesting a service that the kernel provides Kernel mode is only used when necessary and only when allowed by the kernel User mode programs can switch to kernel mode or communicate with the kernel through different interfaces system call are functions running in kernel mode that can be called from user mode and they are described in chapter 10 of 20 Signals are used to send notifications between u
134. n of The purpose of the prototype card was to make a customizable card with good debugging capabilities while the new and final version of the card was designed to be of less physical size and easier to use The new card also had corrected the flaws of the prototype card and introduced a few extra features 10 1 Changes from Prototype Used SMD components when possible which makes the card smaller Removed the RS 232 connection since this was only used for debugging This makes the card smaller and also reduced total cost of the card since the MAX233 is fairly expensive The UART signals of the ATmegal28 were made available on headers so it s possible to use them if needed Added header interface for the NGW board This is a new AVR32 development board that has a slightly different expansion header than STK1000 The headers are also smaller and only use the necessary signals The interrupt signal was no longer sent through the normal header but has to use another wire between a interrupt header on the I O card and the header on the STK1000 NGW Used headers for digital I O instead of screw clamps The choice of screw clamps for these signals was a mistake since they took to much space Headers are smaller and equally easy to use They are also commonly used for digital signals Added a bridge rectifier before the voltage regulator This means that the polarity of the external power source doesn t matte
135. n ret 2nd byte store received valueL return valueH 1 ret SPI SlaveTransferByte valueH 1 amp valueL TIMEOUT if ret lt 0 return ret 3rd byte check received DUMMY return valueL 1 ret SPI SlaveTransferByte valueL 1 amp rx TIMEOUT if ret 0 return ret if rx DUMMY return 1 4th byte check received MASTER OK return SLAVE ret SPI SlaveTransferByte SLAVE TIMEOUT if ret lt 0 return ret if rx MASTEROK return 1 When the message is confirmed the mask and data are applied to digital out PWM_SetOut Value CODE TO CH AOUT code CODE TOSCH AOUT code valueH valueL Debug printing if enabled UART Print c code UART_Print h valueH UART_Print 1 valueL 10 12 8 1 128 FIRMWARE 61 Each of the transfers is marked with a comment explaining what 128 sends and what it expects to receive After each transfer the return value is checked If this is negative it means that the function timed out before a transfer was received If the return value is negative or the received data wasn t the expected data the function returns an error After the 4th transfer is controlled the received data is written to PWM The channel and subchannel of the PWM is defined by the code Before the function returns it also prints some debugging information via UART if this is e
136. n ret Confirm command ret SPI MasterTransferByte MASTER DEBUG masterOK _ i_ slaveOK _ i n MASTEROK ret if ret SLAVEOK return EIO return 0 8 2 8 avr32io SPI avr32io SPI h and avr32io_SPI h contain functions for doing single or multiple SPI transfers These functions are used by avr32io Cmd c The header file is shown below ifndef AVR32IO SPLH define KM AVR32IO SPLH Function that transfer a given number of bytes over SPI int SPI MasterTransfer u8 rx u8 tx int len Function that transfer one byte over SPI int SPI MasterTransferByte u8 tx Function that sends a table of data and checks the received data against another table int SPI SendTableOfBytes u8 tx 18 expectedRx int len Zinclude avr32io SPI c endif _ KM_AVR32IO_SPLH The function SPI MasterTransfer describes how the kernel module does a SPI transfer As seen below it used two data structures that contains the data and length of the transfer Since these two structures has to be defined and initialized there are some overhead work each time some data are transferred This makes it as mentioned in 8 2 7 faster to send three bytes in one transfer than using one transfer for each int SPI MasterTransfer u8 u8 int len Structs for the transfer struct spi message msg struct spi transfer transfer Makes the transferstruct memset amp transfer 0 sizeof trans
137. n the GRT target files the Makefile has to be changed so it compiles the correct files This are done by adding the following lines The lines that are equal but contain the rtw c grt instead should be removed 96 0 MATLAB ROOT rtw c avr32 c G GCC TEST CMD lt GCC_TEST_OUT CC CFLAGS WALLFLAG MAX lt 11 2 3 avr32main c The Makefile template specifies that the new system target will use C file named avr32 main c This file is also based on the C file called grt main c As men tioned in 11 1 1 GRT version of the file makes a program that execute all time steps as fast as possible The reason for modifying the avr32 main c is to make a control system that executes the time steps of the simulation periodically and it has to include the files necessary to use the I O card For making the program execute the time steps periodically periodicTask library pre sented and used in 4 2 was used The I O card user mode driver has to be included since they are used by the S functions see 11 3 For debugging and testing of the RTW generated code the stopWatch library was used This was used to calculate how much time the AVR32 used on each of the time step The following lines was added after the other include statements of the original file These lines contain the different files required by this new main function file The threaded version of the user mode driver was included since it includes the non
138. nabled 8 1 3 am128slaveSpi ami28slaveSpi h and am128slaveSpi c contain functions for using the ATmegal28 as a SPI slave device During the development several different slave transfer functions were used The end result was just one function that sends and receive one byte and has timeout if this is enabled The functions that receives the SPI messages does this one transfer at the time As opposed to the AVR32 SPI driver the ATmegal128 is able to handle each SPI transfer individually without losing effectivity This gives code that s easier to read and understand The code below is the header file an128spiSlave h and the code file am128spiSlave c is in the appendix C 1 4 ifndef AM128_SPISLAVE define AM128_SPISLAVE Initialize the 128 SPI slave If timeout are enabled then this function will initialize a timer aswell void SPI_Slavelnit void Function for transfer one byte of data It will wait for an SPI transfer from the master If timeouts are enabled the function will return an error after some time Since SPI is fully duplex this function will both send and receive data signed char SPI SlaveTransferByte unsigned char tx unsigned char unsigned char usec include am128spiSlave c endif AM128_SPLSLAVE Below is the while loop that is used to wait for a SPI transfer To wait for something to happen with a loop like this is called a busy wait and normally it s something t
139. nd value void UART Print char symbol unsigned char value Zinclude am128uart c 128 UART 8 2 Device driver The device driver has to be coded in kernel mode and during development it s implemented as kernel module Programming kernel modules are not the same as programming normal C programs even if both use the C programming language To start with the kernel module doesn t have a main function but does have different functions that runs in different situations Another difference is that functions defined by user mode libraries like glibc aren t available Instead of a user mode library it s possible to include header files from the kernel source to get more functionality A third difference is that there are no floating point operations or data types in the kernel 8 2 1 Init and Exit Functions As mentioned different functions in a kernel module runs in different situations The two most basic functions are the init and exit functions These are functions that are run when the module is loaded in and out of the kernel The macros module init and module exit are used to define which functions are the init and exit functions of the module 8 2 22 Major and Minor Numbers 1 3 1 defined the device nodes that should be used in this system these will normally have the same major number but they should have different minor numbers kernel module has to allocate the major and minor number it
140. ne of the programs in this collection and it s a program for simulating dynamical system represented by graphical block diagrams Code can be generated from these block diagrams making it ideal for rapid prototyping Labview uses a data flow language that describes how data flows between different nodes of a system often a control system This language is called G and are the basis of Labview The nodes are representations of physical or logical components and can be placed and connected using a graphical interface The G language is a parallel and platform independent language and is well suited for prototyping Except some special functions Chapter 3 AVR32 Linux on STK1000 This chapter describes how to install development tools for AVR32 Linux and how to configure it for development Some of the problems encountered while working with this version of Linux are described as well 3 1 Development Tools Installing the development tools are very easy when using the Ubuntu 10 Linux distri bution that was used during this thesis This distribution uses the Apt 17 Advanced Packaging Tool package management tool that can install software from servers defined in the etc apt sources list file To add the server containing the AV R32 development tools the following line should be added to this file deb http www atmel no beta ware avr32 ubuntu dapper binary To install the tools execute the following commands and answer ye
141. ned char IO NewCommand unsigned char code Checks the code and start the correct command Only test against 5 MSB since 8LSB only contain information about channel switch code amp 0xf8 case CODE AIN IO AnalogIn code break case CODE AOUT IO AnalogOut code break case CODE DIN IO DigitalIn code break case CODE IO DigitalOut code break ifdef BUFFERING MODE case EN IO AnalogInEnable code break endif case CODE AOUT RES IO AnalogOutRes code break default Prints cmd to UART if it didn t match any codes UART _Print e code amp 0 18 break 105 112 13 115 116 17 118 119 20 21 122 23 24 1 128 119 signed char IO AnalogIn unsigned char code unsigned char rx data 2 char ret 1st byte check received DUMMY return code 1 ret SPI_SlaveTransferByte code 1 amp rx TIMEOUT if ret lt 0 return ret if rx DUMMY return 1 ifdef INTERRUPT MODE Starts conversion and polls until the conversion is complete ADO StartConversion CODE TO CH AIN code while ADC_CheckConversion data Send interrupt to 2 set_bit PORTD 7 _delay_us 2 clear_bit PORTD 7 endif ifdef BUFFERING MODE Store data that should be sent to master data 0 dataH CODE TO AIN code data 1 dataL CODE TO CH AIN code en
142. newTask pTask previousTask gt next newTask Initialize the content of the new task pTask periode periode pthread_cond_init amp pTask gt cond NULL pthread_mutex_init amp pTask gt mutex NULL return 0 int StartPeriodicThread struct sPeriodicTask pTask int periode void Start routine void void data int ret Start a periodic task and a thread ret StartPeriodicTask pTask periode pthread_create amp pTask gt thread NULL __start_routine data return ret int WaitPeriodicTask struct sPeriodicTask Wait for the signal to the given task pthread_mutex_lock amp pTask gt mutex pthread_cond_wait amp pTask gt cond amp pTask gt mutex pthread_mutex_unlock amp pTask gt mutex return 0 3 5 stopwatch h ifndef DEF SWATCH define DEF SWATCH includes include lt sys time h gt Zinclude lt stdio h gt Constants define SWATCHIDLE 0 define SWATCHSTARTED 1 define SWATCHSTOPED 2 Struct that represent a stopwatch struct sStopWatch int state The state of the stopwatch int usec Result of the stopwatch might not be necesary struct timeval start stop Structs for keeping the time E This function starts the stopwatch 21 22 23 24 25 26 27 00 1 10 13 14 17 18 19 20 21 22 23 H
143. no need for extra analog I O components This microcontroller could do both the communication with the STK1000 board and the actual I O This made the design of an I O card easier ft pex 4 022020 000 109 C0tU 20 CHAPTER 5 PRELIMINARY TESTS OF I O CARD 5 1 2 STK500 501 The STK500 9 is an AVR development board that is well suited for early stage devel opment of AVR microcontrollers To use this board with the ATmegal28 model it s necessary to use the expansion module STK501 which supports 64 pins surface mounted AVRs When using STK500 501 all the pins of the used AVR are available as headers and all the basic components that the AVR often uses like clock source and RS 232 circuit are ready to use This development board was used to test how different features of ATmegal28 could be used before making a prototype I O card These test helped minimizing the number of design errors on the prototype 5 2 Analog input Analog input are used to measure the voltage of signals and are done with ADCs Analog Digital Converter These are important for a control system to receive measurement data from sensors The I O card will use the ADC on the ATmegal28 This is a 8 channel 10 bit ADC that can measure the voltage between two pins or between a pin and ground This ADC can convert voltages between GND and AVcc analog supply 5 2 1 Test of ATmegal28 ADC The ADC of ATmegal28 was tested by connecting different v
144. nt orders and it shows that each filter reduces ripple but increases response time 5 3 6 Test of ATmegal28 PWM as DAC 5 3 1 explains how a PWM signal can be used to make an analog voltage This should be possible to do with the ATmegal28 since it has several timers that be used PWM Timer 1 and 3 was used for this since these have changeable resolutions up to 16 bits OANDTBWNEH 5 8 ANALOG OUTPUT 25 third order filter 45r second order filter first order filter Volt Time 107 Figure 5 6 DAC with equal same RC first second and third order filters The STK500 501 board was used to test the PWM This was done by starting PWM on the different outputs while probing them with an oscilloscope The code below starts a 10 bit PWM signal with 50 duty cycle to the first output of timer 1 This should give a square signal with a frequency given by the equation 5 2 on the following page Includes include lt avr io h gt int main Set the timer 1A as output set_bit DDRB 5 Set the control registers for PWM to fast with no prescaler and clear output on compare match non inverting mode TCCRIA 1 lt lt 1 1 COMIB1 1 COMIC1 1 lt lt WGM11 TCCRIB 1 WGMI3 1 lt lt WGMI12 1 lt lt CS10 Set resolution of PWM to 10 0x03 ICRAIL OxFF Set 50 duty cycle OCRIAH 0
145. ntains all the information from the Simulink diagram presented in a hierarchy The TLC language is describes in detail in 12 TLC is the second step of the code generation and it generates multiple source files from the information in the rtw file and several 1 files The rtw file contains information about the Simulink diagram while the different t1c files contain information on how the generated code should look like It s two different types of t1c files The system target file specify the overall structure of the generated code and it s selected before generating code among a list of system target files supplied with RTW It s also possible to change existing or make new system target files For rapid prototyping the general real time target grt is a good starting point This makes C code that can run on most platforms as shown in 4 3 Code generated with grt will as in Simulink execute the simulation as fast as possible control system has to execute the simulation with correct time between each time step or it wouldn t work as intended To make this possible with grt some of the code have to be modified Each Simulink block has its own block target file This file contain the information TLC needs to generate code that does the same as the block would do in Simulink 87 88 CHAPTER 11 MATLAB REAL TIME WORKSHOP 11 1 2 S functions S functions are Simulink blocks written in a computer programming langu
146. ntinue executing the rest of its code ui C0 Chapter 8 Implementation of I O card Software This chapter describes how the design from chapter 7 was implemented in several files of C code Only the header files are shown here The code files can be found in the appendix the functions definitions and variables are commented in the header files which makes it possible to know the purpose of the different functions by looking at the headers Some parts of the code files are shown here and used as examples 8 1 ATmegal28 Firmware The code for 128 are divided into several pairs of headers and code files Each of these pairs provides the code for controlling part of the ATmegal128 8 11 ami128main This file contain the main function of the ATmega128 which is where the code execution starts This main function will initialize the I O card with the help of the other code files and then start the main program loop This loop will run as long as the 128 has power and will listen for SPI messages from AVR32 code below is the header file am128main h and the code file am128main c is in the appendix C 1 2 The header file has some define statements that enables or disables different features in the code These are used to change how the I O card works without having to make changes in the rest of the code Defines the clock frequency of the device Needed for util delay h
147. ockParameter P1 0 gt dout dout 1 lt lt 0 endif LibBlockInputSignalConnected 1 mask mask 1 lt lt 1 if double lt LibBlockInputSignal 1 LibBlockParameter P2 0 gt dout dout 1 lt lt 1 endif 9f LibBlockInputSignalConnected 2 mask mask 1 lt lt 2 if double lt LibBlockInputSignal 2 LibBlockParameter P3 0 gt dout dout 1 2 j endif if LibBlockInputSignalConnected 3 mask mask 1 lt lt 3 if double lt LibBlockInputSignal 3 LibBlockParameter P4 0 gt dout dout 1 3 endif 9f LibBlockInputSignalConnected 4 mask mask 1 lt lt 4 if double lt LibBlockInputSignal 4 LibBlockParameter P5 0 gt dout dout 1 4 endif if LibBlockInputSignalConnected 5 mask mask 1 5 if double lt LibBlockInputSignal 5 LibBlockParameter P6 0 gt dout dout 1 5 endif if LibBlockInputSignalConnected 6 mask mask 1 lt lt 6 if double lt LibBlockInputSignal 6 LibBlockParameter P7 0 gt dout dout 1 6 channels and make mask and data byte that are sendt as a command double 96 double 96 double lt double lt double lt doubl
148. ode will return result immediately while interrupt mode has to wait for the new conversion Interrupt mode will make the implementation of AVR32 kernel module more complex since it will need to react to interrupts Buffering mode won t need this Buffering mode will make the implementation of the 128 more complex since it continuously has to start new analog to digital conversions and save the results This has to be implemented so it doesn t affect the normal operation Interrupt mode won t need this 7 2 3 Timeout 7 2 1 describes one way the ATmegal28 can manage SPI communication with the AVR32 One problem with this solution is that an error can leave the slave waiting for an SPI transfer that never shows up This means that it s impossible or hard to know in what state the slave will end up if it was an error during the message This wouldn t break future messages since the master starts all messages by synchronizing with the slave But it s generally a bad idea that the ATmegal28 can end up in an unknown state The reason that the ATmegal28 risks to end up an unknown state are the Wait for SPI transfers in figure 7 2 3 These could possible wait forever which is the reason for the problem If all of these except for activity 1 1 could have timeouts that would send them back to activity 1 1 then the problem should be solved The trick is to select a correct time out period It should probabl
149. oltages from STK1000 2 5V 3 3V and 5V to one of the analog in channels The code below starts an ADC conversion and shows the result 8 MSB on the LEDs after it was completed Table 5 1 on the next page shows the results Includes include lt avr io h gt Macros for bit operations define set_bit reg bit reg 1 lt lt bit define clear_bit reg bit reg amp 7 1 lt lt bit define test_bit reg bit reg amp 1 lt lt bit int main Direction of ports DDRC Oxff clear_bit DDRF 0 Initialize ADC ADMUX 1 lt lt REFS0 1 lt lt ADLAR ADCSRA 1 lt lt ADEN 1 lt lt ADPS2 1 lt lt ADPS1 Start conversion set_bit ADCSRA ADSC Wait for conversion while test bit ADCSRA ADIF Set result as output to LEDs PORTC ADCH 5 3 ANALOG OUTPUT 21 Table 5 1 Results of ADC test Voltage Multimeter voltage ADC result 8 bit ADC result in voltage 2 5V 2 50V 113 2 21V 3 9V 3 27V 136 2 66V 5V 5 00V 210 4 12V As seen in table 5 1 the results from the ADC were not very accurate All results were 80 90 of the correct value It might be because of an error with the STK500 501 card or maybe the 128 5 3 Analog Output Analog output is used to make an analog voltage This is important for control system so they are able to control actuators The I O card will use PWM Pulse Width Modulation of the
150. on will validate the code and continue the SPI command Main program loop while 1 1 Prepare to send ready signal and wait for code from master SPDR SLAVE READY Wait for SPI transfer while test bit SPSR SPIF ifdef BUFFERING MODE Checks if conversion is finished if using bufering mode ADC_CheckBuffer endif Start receiving new command IO NewCommand SPDR When in buffering mode the ATmegal28 checks for completed ADC conversions while waiting for SPI messages This is only checked inside this loop because checking it during a SPI message can disturb the synchronization between ATmegal28 and AVR32 It would be more logic to use interrupts when a ADC conversion was completed However when doing this about 6 of the SPI messages returned errors This was because these interrupts happend in the middle of a SPI command and it made the ATmegal128 unable to return the correct data at the correct time By polling the ADC whenever the ATmegal128 waits for a new message not new transfer the work of managing ADC will only be done when the ATmegal28 normally would do a busy wait for SPI For this to work robustly it s important that all the other wait for SPI functions in the program has timeouts as described 7 2 3 This is because the A T megal28 will be unable to check the ADC conversions if it doesn t return to the the loop described here 8 1 ATMEGA128 FIRMWARE 59 8 1 2 am128io
151. onversion Table 9 4 shows that the analog input part of the I O card gives very accurate results On the prototype card the inductor of the LC filter was replaced with a short circuit bu it didn t seem like this affected the result Table 9 4 Results of ADC test with prototype card Voltage Multimeter voltage ADC result in voltage 2 5V 2 50V 2 47V 3 3V 3 27V 3 26V 5V 5 00V 5 00V 9 3 2 Buffering and Interrupt mode The design and implementation of the analog input was done in two ways and both gives correct values In 9 1 3 the time used by the two different modes was measured and the result was that with interrupts the command used about 120 longer This is just a bit more than the 1045 that an ADC conversion should take according to 7 2 2 and is as expected The advantage of using interrupts is that the returned result are a newly converted result When using buffering mode there is no way to know how old the result are If many channels are used the result might be almost 1775 old If few channels are used the result will be almost new The advantage of saving almost one third of the time used for getting an analog input value means that buffering mode will be used in the rest of the thesis Interrupt mode will be available in the code and can be used by changing the header files of both the AT mega128 code and the device driver 82 CHAPTER 9 TESTING WITH PROTOTYPE CARD Chapter 10 Final versio
152. or storing the channels that are enabled struct chanList struct chanList struct chanList char channel js struct chanList channeltab 8 Static decleration of list elements struct chanList channels Pointer to active element of the circular list char chCount Number of elements in the list tables for storing the latest value for each channel unsigned char dataH 8 dataL 8 Enable one analog channel if it s not already enabled Enabled means that the 128 will continuously convert analog values on this channel and store the digital values in a buffer void ADC_EnableChan char channel Disable one analog channel if it s not already disabled void ADC DisableChan char channel Check if the ongoing comversion is finished if so store the data and start a new one void ADC_CheckBuffer Starts conversion of the next channel in the array void ADC NewConversion Stops and ongoing conversions void ADC StopConversion ifdef INTERRUPT MODE Interrupt mode Starts a conversion of a given channel void ADC StartConversion char channel Checks if conversion is finished if so the result are stored and an interrupt is sent to the AVR32 signed char ADC_CheckConversion unsigned char endif Zinclude am128adc c endif 128 8 1 128 FIRMWA
153. ort as the time used to increase from 0V to 2V when the DAC increases from to 2 5V This are marked with red in the figure and is about 300 8 There are many factors that influence the ripple and response time of the DAC and these are explained below 22 CHAPTER 5 PRELIMINARY TESTS OF I O CARD 5 5 first order filter PWM Time x 10 Figure 5 1 PWM signal and PWM signal with first order low pass filter Volt x 10 Figure 5 2 PWM signal and PWM signal with first order low pass filter 5 3 ANALOG OUTPUT 23 Vin Vout Figure 5 3 First order low pass passive filter 5 small 4 5 large 4 4 3 5 1 4 x10 Figure 5 4 PWM signal filtered with filters with different Time constants RC 5 3 3 Time constant RC simple passive low pass filter consists of a resistor and capacitors as shown in figure 5 3 The time constant RC of the filter is the product of the resistance and capacitance of these two components and it describes how the filter works When using a low pass filter to convert a PWM signal to an analog signal the time constant defines the response time of the DAC A low time constant will give a fast filter while a high time constant will give slow filter A fast filter will increase
154. ost other processors increase their throughput by increasing the clock frequency The AVR32 microprocessor aims to give high throughput with a slow clock Since power consumption is directly related to clock frequency this means that it can do the same work with less power This will be an important characteristic in the future since we will use more and more gadgets that use battery as a power source like hand held music and video players Low power consumption is also important for control systems Many systems needs to have low weight low cost and a long battery time Since batteries normally are heavy and expensive both weight and cost will decrease if the power consumption decrease 2 2 1 5 1000 STK1000 8 is development board for AVR32 STK1000 has some standard I O tions like Ethernet RS 232 mouse and keyboard PS 2 It has an inboard LCD screen and general extension headers where it is possible to connect add on cards The STK1000 card comes with a SD flash card with a fully functional Linux system This is described in more details in 2 3 4 Figure 2 1 on the facing page is an image of the STK1000 board 2 2 2 AT32AP7000 The AT32AP7000 was the first microprocessor with the AVR32 architecture and it s also mounted on the STK1002 daughter board that can be connected to the STK1000 board The features of this processor are listed below o 32 KB on chip SRAM o 16 KB instruction and 16 KB data caches o M
155. ototyping tool This means that code can be generated from Matlab Simulink models and it runs on the control system This makes it easy to implement different control systems through the graphical interface of Simulink The I O card can be used in Real Time Workshop by using the developed Simulink S function blocks To make it easier to use the control system platform an user manual was written This contain information about how to install the needed tools and use the control system platform from a Linux distribution or Windows This is an important part of the thesis since one of the goals were to make an user friendly product The manual should give enough information to use the control system platform To develop the system further this report should be read CHAPTER 1 INTRODUCTION The chapters in this report are as follows Chapter 2 Background This chapter describes some of the technologies and concepts behind the thesis Chapter 3 AVR32 Linux on STK1000 This chapter Describes how to install and use AVR32 Linux on STK1000 Chapter 4 Preliminary tests of AVR32 This chapter performs tests to find out the capabilities of the STK1000 development board and the AVR32 processor architecture Chapter 5 Preliminary tests of I O card This chapter performs tests to find out if correct solutions have been chosen for the I O card Chapter 6 Prototype I O card This chapter describes the design and production of the prototype I O card
156. r Without a rectifier the voltage regulator might be broken if a negative voltage is applied This makes the card more fool proof Added a screw clamp power supply in addition to the ordinary power jack plug This makes it easy to connect different power sources On the new card all screw clamps and headers are marked with numbers that corre sponds to the number of pin on ATmegal28 Analog in channel 0 is the same as the 83 84 CHAPTER 10 FINAL VERSION OF I O CARD ADCO pin on ATmegal28 and so on Ordering these signals gives a slightly more complex routing but it s more practical and easy to use o new type of op amps were used to correct the flaw described in 9 2 3 These op amps are single supply op amps that are able to give output between GND and V 2V As V the rectified but unregulated power supply was used since the op amp don t need regulated power supply This means that the output range of the op amp are defined by the supply voltage of the I O card The disadvantage of this solution is that the op amps and therefor the analog output will not work when running on power from the STK1000 board o All three subchannels on the first channel channel 0 of the analog out was designed with two jumpers each One of these jumpers were used to bypass the filter meaning that the output will be a PWM signal instead of a analog signal This is useful when using components like servos The other jumper are used to ch
157. r periods The platform has some performance limitation The AVR32 processor isn t a fast processor compared to a normal computer and it lacks a FPU This means that floating point operations has to be software emulated and is less effective which limits the ability to control complex systems If a system is to complex the risk of breaking any real time constraints increases However the platform is well suited to controlless complex systems and the workload is logged and can be used to detect if the system is close to breaking a real time constraint The user manual was made to make it easy for users to install and use the control system platform For users the system will function as a black box where they don t need to know how the system works only that it can be controlled using Matlab Real Time Workshop 109 110 CHAPTER 14 CONCLUSION Chapter 15 Further Work This thesis has built a control system platform that uses the AVR32 architecture and further work would be to use this platform in a actual control system The platform may also be developed further to improve it by making it faster and more stable Below is a list of ideas for further development o Find ways to make sending commands to the I O card more effectively This can be done by making the AVR32 Linux SPI driver more efficient drop error detection or reduce the overhead introduced by it or by optimizing the interaction between the User Mode driver and the de
158. reading and writing three SPI specific registers The control register SPCR the status register SPSR and the data register SPDR How these registers are used in slave mode is described below o SPCR e Bit 0 SPRO and bit 1 SPR1 aren t used in slave mode e Dit 2 CPHA and bit 3 CPOL defines the SPI mode The different SPI modes have different timing between the clock signal and the data signals devices using the same SPI bus need to use the same mode Bit 4 MSTR selects slave mode when written to zero Bit 5 DORD selects if the LSB or MSB should be sent first during transfer devices using the same SPI bus should use the same data order or data needs to be reversed in software e Dit 6 SPE turns on SPI for this device e Bit 7 SPIE turns on SPLinterrupts for this device o SPSR e Dit 0 SPI2X isn t used in slave mode e Bit 1 to 5 are reserved bits e Bit 6 WCOL is set if the data register is written to during transfer e Bit 7 SPIF is set when a SPI transfer is completed Will trigger an interrupt if bit 7 of SPCR is high o SPDR is used both to send and receive data data in the register before transfer will be sent to the master while the data in the register after transfer is the data received from the master Writing or reading to this register clears bit 7 of SPSR The simple program below was used to test the SPI communication It waits for a SPI transfer initialized by a SPI master
159. riginal file if AVR32 Specific AVR32 compilator CC avr32 linux gcc Removes m32 OPT_OPTS O ffloat store fPIC Links with pthread LDFLAGS Ipthread enables comments ANSLOPTS The line starting with CC are used to specify the AVR32 compiler and the line with OPT_OPTS are used to remove the m32 flag causes an error as I discovered in 4 3 This flag specifies that the target is a 32 bit processor and is unknown for the AVR32 compiler With these two changes the compilation to AVR32 works and it produces a runnable executable The line starting with LDFLAGS means that the executable will be linked with the pthread library This is required for using pthread that are needed for using threads mutexes and 244 339 340 341 48 49 50 51 156 157 158 159 160 161 162 90 CHAPTER 11 MATLAB REAL TIME WORKSHOP other pthread functionality The last line was used to remove the flag This doesn t affect the compilation it will only make it possible to comment code with double slash The next issue that needs to be modified is the C file containing the main function used by the generated code This is done by replacing the grt_main c with avr32_main c in line 233 of the original file The new line should then look like this SRCS MODEL TARGET_LANG EXT avr32_main c rt sim c EXT SRC SOLVER Since the new AVR32 target files are in another directory tha
160. rror detection should be used It s also possible that the device driver could be more effective The User Mode driver opens and closes the device node each time it reads and writes from them since the device driver has mutexes that makes it only possible that one process has it open at the time This could possibly be made more effective 13 4 MATLAB REAL TIME WORKSHOP 107 13 4 Matlab Real Time Workshop Matlab Real Time Workshop was used in this thesis as a rapid prototyping tool It gen erates code from Simulink models that runs on the control system new system target was created to allow some modifications to the way code are generated This new system target was able to compile the code for AVR32 and make the code execute periodically The system target can easily be installed and are easy to use S functions were developed for the different features of the I O card and it gave Simulink blocks that was able to control the I O The S functions that uses the normal user mode drivers worked as planned and they were effective test concluded that a value sent through the I O card only was delayed with one time step When using the threaded user mode driver the results were a longer delay This means that the threading is a less effective solutions Optimizing the driver might help but it s more likely that the increased overhead of the threaded driver is bigger than the effectively gain of using threads 108 CHAPTER 13 DISC
161. ry this directory has to be in Matlabs path variable add the path use the following commands in Linux or similar if Matlab is installed somewhere else 7 addpath usr local matlab rtw c avr32 blocks 7 savepath add the path when using Windows the following commands should be used 7 addpath c Program Files Matlab rtw c avr32 blocks 7 savepath Now the S functions for the I O card are available in the library in the blocks directory and they can be used in other Simulink models 12 2 AVR32 I O card 12 2 1 Hardware description AVR32 I O card is an add on card for STK1000 It provides the following I O o 8 channel analog input with a resolution of 10 bits The analog value can be between OV 5V where OV equals ground o 6 channel analog output with a resolution between 8 and 12 bits 3 of the channels has output between 0V 5V where equals ground The 3 other channels have jumpers for selecting output type see 12 2 4 o 8 amp channel digital input o 8 amp channel digital output Figure 12 1 show the front side of the I O card below are a description of the different parts 1 Screw clamps for ground and Voc that gives easy access to these signals 2 Jumper for selecting if analog output channels 0 0 0 2 should have 5V or 10V output 3 Screw clamps for analog output signals 4 Connector or screw clamp for external power supply The supply should be between 9V and 18V and the po
162. s to all questions sudo aptitude update sudo aptitude install avr32 linux devel If this approach doesn t work or instructions for installing on other platforms check the AVR freaks wiki http www avrfreaks net wiki 3 1 1 Compiling Development Tools from Source It s also possible to compile the development tools from source and this was necessary during the start of this thesis Then the precompiled tools had a few bugs Compiling the development tools from source is still the only option if special features is needed Instructions for doing this can be found at http avr321inux org twiki bin view Main GettingStarted 10 CHAPTER 3 AVR32 LINUX ON STK1000 3 2 AVR32 Linux Kernel Versions Some of the early AVR32 versions of the Linux kernel had some problems Both the 2 6 16 2 6 18 and 2 6 19 versions were tested During these tests the following problems was encountered The 2 6 16 version had problems linking with the pthread library The SPI driver worked but had problems with stability and returned wrong data o The SPI driver did not work in the 2 6 18 version The 2 6 19 version also had problems linking with the pthread library It s also possible that the problems with the pthread library were because of uClibc the library used by AVR32 Linux After switching to the 2 6 20 kernel version and new precompiled development tools no kernel or library related problems were encountered 3 3 Configure booting o
163. ser mode programs or between the kernel and user mode programs and are described in chapter 11 of 20 kernel works as a layer between hardware devices and user mode programs and this is usually done with Device Drivers Which are described in 2 3 3 2 3 3 Linux Device Driver device driver is code that controls a device normally this is some kind of hardware How device drivers works are described in Linux Device Driver 21 and in chapter 13 of Understanding the Linux kernel 20 A device driver has to be either a part of the kernel or a kernel module that can be linked into a running kernel Devices are identified in the Linux kernel with a major and a minor number These are numbers that the device driver has allocated for the devices it controls Device drivers are often used to make it possible for user mode programs to use the devices controlled by the driver user mode program access the driver through special files in the file system called device nodes These are normally located in the dev directory user mode program can read write or do other file operations on a node just as if it was a normal file When accessing a node with the same major and minor number as a device the user space program is actually accessing the driver of this device There are two types of device nodes which corresponds to two different types of devices Character or char devices are devices that receive or send data serially while block
164. solution or enable disable functionality 7 5 Threaded User Mode Driver Since communicating with I O often includes waiting commands are often executed in threads To make this possible another layer of software was used on top of the user mode driver This layer uses threads to send and receive data from the I O card making the total system more effective This has only been designed for analog I O 7 51 Threaded Analog Input The analog input uses threads to sample the analog input values Each channel has its own periodic thread that gets an analog input value and store it in a buffer When a user mode application needs the value of an analog channel it can quickly get the buffered value 56 CHAPTER 7 DESIGN I O CARD SOFTWARE This solution works best when the I O card uses interrupt mode since the value the thread is putting into a buffer should be as new as possible If using buffering mode the data will be buffered twice and this should be avoided The main disadvantage of interrupt mode is that the command takes longer time is less of a problem when it s performed by a thread It will not slow down the rest of the program 7 5 2 Threaded Analog Output The analog output uses a worker thread This thread waits until it receives an analog output command from the main thread Then it executes this command and waits for the next This means that the main thread gives a short command to the worker thread and then it can co
165. t this image The NFS server are configured by sharing a directory with NFS This are done in the etc exportfs file and below is an example of a line that will share a directory home oyvindne master fs 129 241 187 1 24 rw no_root_squash async To restart the NFS server with new configuration the following commands are used 7 sudo etc init d portmap restart 7 sudo etc init d nfs kernel server restart 7 sudo exportfs a 3 3 22 Configure U Boot U Boot Universal Bootloader are the boot loader used on STK1000 To configure it the STK1000 has to be connected to a workstation with a serial cable The Workstation should use a serial terminal program like minicom to connect to the STK1000 During start up of the STK1000 board the space bar should be pressed to enter the U Boot command line Here the bootargs variable has to be changed and a tftpip variable has to be created The following commands modify these variables If used on other systems the IP addresses to the host computer and the path to the NFS server has to be changed setenv tftpip 129 241 187 212 setenv bootargs console ttyUSO ip dhcp root dev nfs nfsroot 129 241 187 212 home oyvindne master fs init sbin init fbmem 900k saveenv 12 CHAPTER 3 AVR32 LINUX STK1000 Chapter 4 Preliminary tests of AVR32 This chapter describes some preliminary tests performed on the STK1000 board before continuing the work It was important to reveal any w
166. t way to solve problems when a processor has to wait while another often I O computer component completes its task When the task is completed an interrupt is sent to the processor and the it can retrieve the result The second solution is to let the ATmega128 know which analog input channels that are in use It can then continuously convert the analog values of these channels into digital values and store them in a buffer in memory When the master wants to read an analog input channel the slave can just return the previously converted result This solution is possible to use since the analog to digital conversion is a separate part of the ATmega128 Meaning that the normal code will continue to run as usual during the analog conversion The only overhead is saving the results and start new conversions The two solutions called interrupt mode and buffering mode will both work but have some different advantages shown below o Interrupt mode will always return a newly converted result while buffering mode may return an older result 7 3 DEVICE DRIVER 51 m m m gH m m m B M program mode 8 i i SPI m Threaded gt 128 driver m User mode Device function call write a BH m gH NH NH NH NH NH NH NH NH NH NH k STK1000 Figure 7 4 Describing the different components Buffering m
167. ted and the results 6 7 Errors in Schematic During the assembly and test of the prototype the following errors was found in the design o of the JTAG interface wasn t connected to the of the board o operational amplifiers don t work as they should see 9 2 o 9 dsub connector for the RS 232 connection weren t connected correctly Pin number 5 should be connected to ground and the cable shield shouldn t Chapter 7 Design of I O card Software This chapter describes the design of the different parts of the system and how these should work togeter The system consists of firmware running on the I O card a device driver running in kernel mode in AVR32 Linux and a user mode driver that makes user mode programs able to use the I O card 7 1 Communication Protocol The communication between the AVR32 master and the ATmegal28 slave uses SPI and it s a very central part of the system Before designing the software a protocol was designed to define the rules of communication between the master and slave Below are some terms that are used in the description of the protocol o transfer is a single exchange of data between the master and the slave o command is a task the master wants the slave to do message is a set of transfers that makes sure that the slave receives a command and returns data if necessary o A message structure is the way the set of transfers are organized in
168. the Power circuit used for the I O card To the left are the power jack connector for connecting a AC DC adapter In the bottom right corner there is a linear voltage regulator 7805 7 that gives out a stable 5V voltage source This component needs a capacitor on both input and output to work properly On the top there is a 3 pin header jumper is used to choose what kind of voltage source the rest of the card will use either the output from the voltage regulator or the 5V signal from the STK1000 card 34 CHAPTER 6 PROTOTYPE I O CARD GND PF7 ADG7 TDI PF6 ADC6 TDO PF5 ADC5 TMS PF4 ADC4 TCK PF3 ADC3 PF2 ADC2 PF1 ADC1 PFO ADCO ANALOG IN2 4 ANALOG IN2 3 ANALOG IN2 2 ANALOG IN2 1 C ANALOG_IN1 2 1 Figure 6 3 JTAG header and analog input connectors 6 4 2 Reset Crystal and Analog Supply Circuit Figure 6 2 on the previous page shows the reset crystal and analog reference circuits for the ATmegal28 The reset circuit provides a button that will pull down the active low reset port of the microcontroller when pushed This will reset the processor This circuit also has a pull up resistor that makes sure the reset port is high when the button isn t pushed The crystal circuit was made to give the ATmegal28 a stable and high frequency clock source The main reason for this is that a higher clock frequency will make the PWM signal better suited as a
169. threaded version AVR32 includes include driver avr32io threads h include driver periodicTask h include driver stopwatch h The following lines are global structures and variables that are needed to make the time steps periodical and to measure the workload Global AVR32 Data struct sPeriodicTask matlabSimulationPeriode struct sStopWatch timerStopWatch workStopWatch long usecWork usecTimer int count 0 The following lines are added to make the time steps periodical These should be added twice in the file one time for single tasking and one for multitasking Both places where 227 228 229 230 231 232 233 234 235 236 636 637 638 639 640 713 714 715 11 3 S FUNCTIONS FOR I O CARD 91 this function should be added are marked in the original file with a comment saying that interrupts should be enabled here RO CK AVR32 Timing interrupt StartStopWatch amp timerStopWatch usecWork StopStopWatch amp workStopWatch WaitPeriodicTask amp matlabSimulationPeriode usecTimer StopStopWatch amp timerStopWatch StartStopWatch amp timerStopWatch StartStopWatch amp workStopWatch count The WaitPeriodicTask function is a function that wait until the next period before re turning This function is defined in the periodicTask library Two different stopwatches two differ
170. to the board The final version of the card should use more SMD components since it will allow a smaller layout lVias are small metal cylinders that can be placed inside a hole on the PCB This allows electrical connection between top and bottom layer Vias should be avoided when possible since they increase assembly time and noise 6 5 LAYOUT 39 Figure 6 9 Top layer of prototype card Not to scale Figure 6 10 Bottom layer of prototype card Not to scale 40 CHAPTER 6 PROTOTYPE I O CARD The analog signals were kept as isolated as possible from the digital signals This is because fast changing digital signals can induce noise on analog signals The analog signals was also placed directly above or below a ground plane to protect them These ground planes only had a minimal connection to the rest of the ground plane 6 6 Assembly and test The layout from 6 5 was used to etch a PCB card The rest of the card was assembled by soldering the components on to the PCB The assembly of the card should be done step by step and each step should be tested before moving to next step By doing this each part of the circuit can be tested as isolated as possible And it s also possible to know to a certain degree that the components that are assembled and tested are working as planned 6 6 1 to 6 6 6 describes the steps of he assembly and the tests done after completing each step Before soldering anything to the card the
171. topWatch watch StartStopWatch amp watch for i 0 i lt COUNT i 6434352342 Random integers usec StopStopWatch amp watch usecPerCalc float usec float COUNT ticksPerCalc usecPerCalc float CPU CLOCK printf total_time _ i n usec printf microseconds per calculation f n usecPerCalc printf clock tick_per calculation f n ticksPerCalc StartStopWatch amp watch for i 0 i lt COUNT i 4 b 234092098437498 249872398472398 209347802947239 290834732984723 Random doubles usec StopStopWatch amp watch usecPerCalc float usec float COUNT ticksPerCalc usecPerCalc float CPU CLOCK printf total_time _ i n usec printf microseconds per calculation f n usecPerCalc printf clock tick per calculation 96fNn ticksPerCalc 4 1 2 Result Table 4 1 shows how the STK1000 preformed on these tests compared to a Dell workstation with a Pentium 4 CPU Table 4 1 Results of floating point FP and fixed point tests Platform CPU cycles FP us fixed cycles fixed Dell PC with Ubuntu 2 4GHz 0 00273 6 55 0 00269 6 47 STK1000 140M Hz 0 492 68 8 0 123 17 2 The Pentium is considerable faster than the AVR32 as expected It uses the same time for both the floating point and fixed point operations This is because it has a floating point unit The AVR32 uses about
172. valid channel since the function from 8 2 2 will return an negative channel number if a wrong minor number was used The next part uses a function that synchronizes with the AT mega128 by sending the code until the ATmegal128 returns the correct ready code After synchronizing the function sends data to the ATmegal28 This is done by the function call on line 88 The arrays sent with this function contain the data that should be sent and the data it expects the ATmegal28 will return All three bytes are sent at the same time because it s faster than to send them individually If the data transfer was successful the function ends by sending a master OK code to the slave If it receives a slave OK signal the function returns successfully int SetAOut u8 fromUser int ch int sch int ret unsigned char tx 3 expectedRx 3 check for valid channel if ch lt 0 return EIO Synchronize with 128 ret Cmd WaitForAM128 CH TO CODE AOUT ch sch DEBUG code 96i count 96iNn CH TOCODE AOUT ch sch ret if ret 0 return ret 1 8 2 DEVICE DRIVER 71 Prepare to send several bytes tx 0 fromUser 0 tx 1 fromUser 1 tx 2 DUMMY expectedRx 0 TO CODE AOUT ch sch 1 expectedRx 1 fromUser 0 1 expectedRx 2 fromUser 1 1 Send data and check returns ret SPI_SendTableOfBytes tx expectedRx 3 if ret lt 0 retur
173. value tv_usec 1 rttimer it_interval tv_sec 0 rttimer it_interval tv_usec 1000 setitimer ITIMER REAL amp rttimer NULL Initialize a empty taks table root Task NULL initialized 1 Return zero return 0 void fTimer Variables static long count struct sPeriodicTask xtask Increase the counter Walks through the tasks and signal the ones that need to run task rootTask while task NULL if count task gt periode 0 Signal a task pthread_cond_signal amp task gt cond Nert task task task gt next int StartPeriodicTask struct sPeriodicTask pTask int periode Variables struct sPeriodicTask newTask previousTask The new task will be pointing to nothing pTask next NULL if rootTask NULL If rootTask doesn t point at anything this task is the first task rootTask pTask ERP RRP USER else 143 If rootTask point at something the first task that doesnt point at a next task has to be found previousTask rootTask newTask root Task next while newTask NULL Will quit when a empty next pointer is found previousTask newTask newTask newTask gt next The empty newTask will now point to pTask and the former newest task will point to the new
174. ver Network 2 3 4 explains that the STK1000 can be configured to boot over network and that this is a suitable solution during development 3 3 1 Workstation Configuration To boot the STK1000 over network it s required that the workstation has two different servers A TFTP server Trivial File Transfer Protocol are a simple protocol for transfer ring small files and are used by the boot loader on STK1000 to download the kernel image A NFS server Network File System are a standard UNIX server for sharing files and will be used to share a root filesystem with the STK1000 board For a Ubuntu workstation these two servers are installed by using aptitude and the following commands 7 sudo aptitude install tftpd xinetd nfs kernel server portmap The TFTP server are configured by adding the following text into etc xinetd conf service tftp protocol udp port 69 dgram dgram wait yes user nobody server usr sbin in tftpd server_args tftpboot disable no The following commands are used to start the server This is only necessary to do once afterwards the server starts by itself 7 sudo mkdir tftpboot 7 sudo chmod R 777 tftpboot 7 sudo chown nobody tftpboot 7 sudo etc init d xinetd start 3 3 CONFIGURE BOOTING OVER NETWORK 11 The TFTP server are now started and shares the directory tftpboot If a kernel image are copied to this directory the STK1000 are able to download and boo
175. verage Standard deviation Dell Workstation running Ubuntu 7 04 2 4GHz 10013 09us 20578 STK1000 running avr32 Linux 150M Hz 9994 01 8 7 255 E E S Sine Wave Gain Integrator Scope Figure 4 1 First order low pass passive filter how much the results differ from the expected value and it considerable lower for the STK1000 This is because the workstation computer has many programs running and these will disturb the timer 4 3 Test of Matlab Real Time Workshop Generated Code One of the goals of this thesis was to configure Matlab RTW to be used as a rapid prototyping tool for the control system This made it important to check that it was possible to run RTW code on AVR32 simple test system was created consisting of a gain block and an integration block and generated code from it The system target was used when generating code see 11 1 1 Figure 4 1 describes the simple test system To compile the code for AVR32 it was necessary to change the generated makefile Adding CC avr32 linux gcc to the Makefile see 11 2 2 for the exact location specifies that the AVR32 compiler should be used When running the Makefile with this addition the Makefile returned the following output avr32 linux gcc c O ffloat store fPIC m32 DUSERTMODEL ansi pedantic DMODEL test DRT DNUMSI 2 DTID01EQ 1 DNCSTATES 1 DUNIX DMT 0 DHAVESTDIO I I I usr local matlab simulink include I usr
176. vice driver o Increase the number of I O protocols that the I O card can use The existing SPI communication protocol may be extended to for new commands o Improve the I O protocols that are already present 111 112 CHAPTER 15 FURTHER WORK Appendix Digital appendix The digital appendix includes the code and other files from the thesis and have the following directories code Contains the code developed in the thesis e atmegal28 Firmware code for the ATmegal28 e avr32 Code used by Matlab to make the AVR32 Real Time target Contain drivers and blocks in subdirectories e kernel_module Code for the device driver as a kernel module eagle Schematics and layout of the two AVR32 I O card versions in eagle format file_system Files used in the AVR32 file system o linux Patches config files and other AVR32 Linux related files o report The report and the user manual Subdirectory contain graphics used in the report 113 Appendix Schematics B 1 Schematic for protoype card Figure B 1 on the next page is the total schematics for the prototype card B 2 Schematic for final card Figure B 2 on page 116 is the total schematics for the final card 114 115 SCHEMATIC FOR FINAL CARD B 2 38945 1 lt 1107901 2 lt 1107001 E 1n0 901vN Lino O01vN z 41no O01 YN 100 001vN ZOBZ ZT eieg ijequnN ijueun2orn
177. x php title Linux kernel amp oldid 137027739 Wikipedia contributors Porting Wikipedia The Free Encyclopedia Jun 2007 http en wikipedia org w index php title Porting amp oldid 136428272 Wikipedia contributors Porting Wikipedia The Free Encyclopedia May 2007 http en wikipedia org w index php title APT amp oldid 131003365 Wikipedia contributors Real Time Computing Wikipedia The Free Encyclopedia Jun 2007 http en wikipedia org w index php title Real time computing amp oldid 135997153 Wikipedia contributors Ring Wikipedia The Free Encyclopedia May 2007 http en wikipedia org w index php title Ring 428computer security 29 amp o1did 131608375 148 149 20 21 22 23 24 Marco Cesati Daniel P Bovet Understanding the Linux Kernel O Reilly 3rd edition Nov 2005 Greg Kroah Hartman Jonathan Corbet Alessandro Rubini Linux Device Drivers O Reilly 3rd edition February 2005 Lindergren pent marked for Linux Embedded Datarespons Interrupt 2006 http www datarespons com templates interrupt aspx id 1826 GNU Project The Free Software Definition GNU Project February 2007 http www gnu org philosophy free sw html yvind Netland Rapid prototyping with matlab real time workhsop on an embedded control system with atmel avr32 processor Master s thesis NTNU 2007
178. x02 OCRIAL 0x00 With a 10 bit PWM timer and a clock frequency of 8M Hz the PWM frequency are calculated in equation 5 2 on the next page When running this test the period of the PWM signal was measured to 1305 on an oscilloscope that according to equation 5 3 on the following page is almost the same as the theoretical value 26 CHAPTER 5 PRELIMINARY TESTS OF I O CARD 8MHz 710 7 81kHz 5 2 5 3 Ey Pe yu 1304s 5 4 SPI To be able to use the I O card the AVR32 needs a way to communicate with it SPI is a serial bus that s often used for communication between different integrated circuits on the same board It s an simple yet effective bus that is full duplex meaning that data are transferred in both directions at the same time Both AVR32 Linux and the ATmega128 supports SPI and this bus will be used for data transfer between the STK1000 board and the I O card Another serial bus called I2C Inter Integrated Circuit or TWI Two Wire Interface was also considered and was also supported by AVR32 Linux and ATmega128 This bus does about the same as SPI but the differences described in 5 4 1 made the SPI a better choice 5 4 1 SPI bus A SPI bus consists of one master and one or more slaves The master can communicate with one slave at the time by using the slaves chip select signal This is different than I2C that uses addressing to decide which device that should receive the messa
179. y and limits of the system Make a control system platform with AVR32 that users can build their control system on Make a user manual for the platform that contain the information a user needs to use it so it can be used with minimal effort Assignment given 08 January 2007 Supervisor Amund Skavhaug ITK Preface This thesis has been very interesting and a worthy end of my time at NTNU It has been a privilege to work with a new processor architecture and try to do something that nobody as far as I know have tried before I would like to thank Amund Skavhaug my supervisor and Haavard Skinnemoen from Atmel Norway Both of them have been helpful whenever I have needed some guidance Abstract AVR32 is a new processor architecture made by Atmel Norway and in this thesis it has been used to make a control system platform The hardware used in this platform is the STK1000 an AVR32 development board and an I O card The I O card were developed as a part of the thesis Software for the platform consists of I O card firmware Linux device driver for the I O card and user mode drivers platform supports usage of Matlab Real Time Workshop as a rapid prototyping tool that generates code from graphical visualization of mathematical models S functions were created so Matlab Real Time Workshop can control the I O card control system platform is documented in an user manual This manual describes how to install development
180. y be something like 2 3 times higher than the normal pause between SPI transfers 7 3 Device Driver The purpose of the device driver is to act as a link between a user mode program and the I O card The user mode program access the device driver through a device node and it access the I O card through SPI communication This is shown in figure 7 4 The Linux kernel is a complicated piece of software Hence to make a module make it react to device nodes use SPI configure interrupts is not a trivial task How to program 52 CHAPTER 7 DESIGN I O CARD SOFTWARE the device driver to carry out these tasks is described in 8 2 7 3 1 Device Nodes Device nodes are used by user mode programs to access the device through the device driver A simple device driver has often only one node associated with it More complex drivers may have several where each node represents a specific function Several nodes was used for this driver one for each of the analog channels one for digital input and one for digital output Notice that analog output only has two nodes so each node will control three analog output subchannels The reason for this choice was to have one node for each of the smallest controllable parts of the I O card For example the two analog output channels can have different resolutions but all the subchannels of one channel has to have the same Since the analog input channels aren t dependent on each other in the same way they

Download Pdf Manuals

image

Related Search

Related Contents

Ar6 User Guide - Reichert Technologies: Analytical Instruments  Jeunesse et Intercommunalité Bouquet d`expériences  Sony MZ-G755 MiniDisc Player User Manual  MANUAL DEL USUARIO  プレホスピタル用医療機器総合カタログ 2015  

Copyright © All rights reserved.
Failed to retrieve file