Home
Anexo A. Estructura de los ficheros migrados.
Contents
1. 1 1 Status Figure 9 2 Timer operations A timer except the timer ch 5 has TCNTBn TCNTn TCMPBn and TCMPn TCNTBn and TCMPBn are loaded into TCNTn and TCMPn when the timer reaches 0 When TCNTn reaches 0 the interrupt request will occur if the interrupt is enabled TCNTn and TCMPn are the names of the internal registers The TCNTn register can be read from the TCNTOn register ELECTRONICS 9 3 PWM TIMER 53 44 RISC MICROPROCESSOR AUTO RELOAD amp DOUBLE BUFFERING S3C44B0X PWM Timers have a double buffering feature which can change the reload value for the next timer operation without stopping the current timer operation So although the new timer value is set a current timer operation is completed successfully The timer value can be written into TCNTBn timer counter buffer register and the current counter value of the timer can be read from TCNTOn timer count observation register If TCNTBn is read the read value is not the current state of the counter but the reload value for the next timer duration The auto reload is the operation which copies the TCNTBn into TCNTn when TCNTn reaches 0 The value written into TCNTBn is loaded to TCNTn only when the TCNTn reaches to 0 and auto reload is enabled If the TCNTn is O and the auto reload bit is 0 the TCNTn does not operate any further Write Write TCNTBn 100 TCNTBn 200 Start TCNTBn 150 Auto reload 4
2. Construcci n e instalaci n make make install Con ello MPFR quedar a correctamente instalada en el sistema El significado de las 2 opciones de configuraci n es exactamente el mismo que en el caso de la configuraci n de GMP Tanto el build como el host son detectados autom ticamente del mismo modo que en los pasos anteriores Al no estar especificados el script de configuraci n interpretar que ambos coinciden con la m quina actual Paso 3 configuraci n de la biblioteca est ndar de C Las extensiones de GCC que posteriormente usaremos para incluir Ada extensiones de GNAT requieren elementos definidos en la biblioteca est ndar de C En nuestro caso se ha empleado una versi n reducida y adecuada de la biblioteca est ndar denominada Newlib 20 Constituye una versi n min scula de la biblioteca Glibc dedicada exclusivamente a sistemas empotrados y lo m s importante puede usarse para compilar con o sin llamadas a un sistema operativo Dado que en nuestro caso se programar n llamadas desde funciones de MaRTE OS que deben ser traducidas directamente a c digo m quina de ARM esta biblioteca nos puede servir de mucha ayuda frente a otras como Glibc que solo genera llamadas a sistemas operativos La versi n de Newlib utilizada es la 1 18 0 y sus fuentes pueden descargarse de su p gina principal No es necesario ejecutar ning n script de instalaci n puesto que toda la configuraci n ser automatizada c
3. Requerimientos del Target en caso de implementaci n para ARM e Microcontrolador 53 44 o cualquiera compatible Placa de desarrollo S3CEV40 opcional para las pruebas Toma de corriente alterna para alimentaci n de la placa S3CEV40 e Puerto USB para alimentaci n y carga de aplicaciones por el JTAG Toma de corriente alterna para alimentaci n alternativa del JTAG opcional e Puerto USB para alimentaci n alternativa de la placa S3CEV40 opcional Paso 0 Instalaci n del compilador GNAT MaRTE OS est escrito en Ada Pese a que el programador no quiera compilar aplicaciones Ada bajo este sistema operativo por ejemplo aplicaciones escritas en C o C ser necesario obtener el compilador GNAT correspondiente para poder compilar el n cleo de MaRTE OS En nuestro caso la instalaci n del compilador no es un proceso trivial por lo que ha sido necesario incluir un anexo diferente del actual el anexo J con los pasos necesarios para configurar el compilador cruzado en Linux Para el caso de las implementaciones de MaRTE OS previas la instalaci n de GNAT es muy sencilla pudi ndose realizar en el propio directorio de trabajo sin afectar al resto del sistema Hay que tener en cuenta que cada versi n de MaRTE OS soporta un subconjunto de versiones del compilador por lo que el programador deber asegurarse de utilizar la versi n correcta Para instalar el compilador GNAT habr que descargarlo de la p gi
4. ARM7TDMI has a total of 37 registers 31 general purpose 32 bit registers and six status registers but these cannot all be seen at once The processor state and operating mode dictate which registers are available to the programmer The ARM State Register Set In ARM state 16 general registers and one or two status registers are visible at any one time In privileged non User modes mode specific banked registers are switched in Figure 2 3 shows which registers are available in each mode the banked registers are marked with a shaded triangle The ARM state register set contains 16 directly accessible registers RO to R15 All of these except R15 are general purpose and may be used to hold either data or address values In addition to these there is a seventeenth register used to store status information Register 14 is used as the subroutine link register This receives a copy of R15 when a Branch and Link BL instruction is executed At all other times it may be treated as a general purpose register The corresponding banked registers R14 svc R14 R14 fiq R14 abt and R14 und are similarly used to hold the return values of R15 when interrupts and exceptions arise or when Branch and Link instructions are executed within interrupt or exception routines Register 15 holds the Program Counter PC In ARM state bits 1 0 of R15 are zero and bits 31 2 contain the PC In THUMB state bit 0 is zero and bits 31 1 contain the
5. 4 gt a gt 4M 150 100 100 Interrupt 2111 0114 Figure 9 3 Example of Double Buffering Feature TIMER INITIALIZATION USING MANUAL UPDATE BIT AND INVERTER BIT Because an auto reload operation of the timer occurs when the down counter reaches to 0 a starting value of the TONTn is not defined at first In this case the starting value has to be loaded by the manual update bit The sequence of starting a timer is as follows 1 Write the initial value into TCNTBn and TCMPBn 2 Set the manual update bit of the corresponding timer It is recommended to configure the inverter on off bit 3 Set the start bit of the corresponding timer to start the timer At the same time clear the manual update bit Also if the timer is stopped by force the TCNTn retains the counter value and is not reloaded from TCNTBn If new value has to be set manual update has to be done NOTE Whenever TOUT inverter on off bit is changed the TOUTn logic value will be changed whether or not the timer runs Therefore it is desirable that the inverter on off bit is configured with the manual update bit 9 4 ELECTRONICS 53 44 RISC MICROPROCESSOR PWM TIMER PWM PULSE WIDTH MODULATION Write TCMPBn 60 TCMPBn 40 TCMPBn 30 Write Write Write TCMPBn 50 TCMPBn 30 TCMPBn Next PWM Value Figure 9 5 Example of PWM PWM feature can be implemented by using the TCMPBn PWM frequency is determined by TCNTBn A PWM value is determined
6. RTCCON RTCALM PMWKUP PWDN ALMINT Figure 14 1 Real Time Clock Block Diagram LEAP YEAR GENERATOR This block can determine whether the last date of each month is 28 29 30 or 31 based on data from BCDDAY BCDMON and BCDYEAR This block considers the leap year in deciding on the last date An 8 bit counter can only represent 2 BCD digits so it cannot decide whether 00 year is a leap year or not For example it can not discriminate between 1900 and 2000 To solve this problem the RTC block in S3C44BOX has hard wired logic to support the leap year in 2000 Please note 1900 is not leap year while 2000 is leap year Therefore two digits of 00 in S3C44B0X denote 2000 not 1900 READ WRITE REGISTERS Bit 0 of the RTCCON register must be set in order to read and write the register in RTC block To display the sec min hour date month and year the CPU should read the data in BCDSEC BCDMIN BCDHOUR BCDDAY BCDDATE BCDMON and BCDYEAR registers respectively in the RTC block However a one second deviation may exist because multiple registers are read For example when the user reads the registers from BCDYEAR to BCDMIN the result is assumed to be 1959 Year 12 Month 31 Date 23 Hour and 59 Minute When the user read the BCDSEC register and the result is a value from 1 to 59 Second there is no problem but if the result is 0 sec the year month date hour and minute may be changed to 1960 Year 1 Month 1 Date O Hour
7. arch dependent files contiene el fichero marte configuration parameters ads el cual especifica los par metros de configuraci n del sistema operativo En el desarrollo de este proyecto el fichero ha sido incluido para poder compilar la interfaz abstracta con el hardware conteniendo exactamente lo mismo que el de la versi n X86 En un futuro cuando la interfaz abstracta con el hardware est completa y sea integrada con el resto del sistema operativo deber modificarse include contiene cabeceras de los ficheros C que usan los drivers implementados Las cabeceras contienen algunas funciones y estructuras de los ficheros C usados para temporizaci n por el Rea Time Clock handlers contiene un paquete de manejadores b sicos de interrupci n Actualmente solo hay uno implementado el cual pone un 1 en el visualizador de 8 segmentos y al cabo de poco tiempo pone un O startup almacena los ficheros relacionados con el arranque del microcontrolador asi como ficheros para enlazado y bibliotecas con macros que definen los registros de los perif ricos del microcontrolador sobre posiciones de memoria El fichero 44binit flash s contiene los vectores de excepciones e interrupciones as como la programaci n de la excepci n de reset hwi contiene la implementaci n de la interfaz abstracta con el hardware que abstrae al kernel de MaRTE OS de la plataforma usada Adem s contiene los drivers de los 3 perif ricos utilizados el Rea
8. 1 16 01xx 1 32 MUX 1 7 4 Select MUX input for PWM Timer1 0000 1 2 0001 1 4 0010 1 8 0011 1 16 01xx 1 32 MUX 0 3 0 Select MUX input for PWM Timero 0000 1 2 0001 1 4 0010 1 8 0011 1 16 01xx 1 32 9 10 ELECTRONICS 53 44 RISC MICROPROCESSOR PWM TIMER TIMER CONTROL REGISTER TCON Timer 5 auto reload 26 This bit determines auto reload on off for Timer 5 on off 0 One shot 1 Interval mode auto reload Timer 5 manual 25 This bit determines the manual update for Timer 5 update note 0 No operation 1 Update TCNTB5 Timer 5 start stop 24 This bit determines start stop for Timer 5 0 Stop 1 Start for Timer 5 Timer 4 auto reload 23 This bit determines auto reload on off for Timer 4 on off 0 One shot 1 Interval mode auto reload Timer 4 output 22 e bit determines output inverter on off for Timer4 inverter on off Inverter off 1 Inverter on for TOUTA Timer 4 manual 21 This bit determines the manual update for Timer 4 update note 0 No operation 1 Update TCNTB4 TCMPB4 Timer 4 start stop 20 This bit determines start stop for Timer 4 0 Stop 1 Start for Timer 4 Timer 3 auto reload 19 This bit determines auto reload on off for Timer 3 on off 0 One shot 1 Interval mode auto reload Timer 3 output 18 Vi bit determines output inverter on off for Timer 3 inverter on off Inverter off 1 Inverter on for TOUT3 Timer 3 manual 17 This bit determine manual upda
9. Volatile gt True end STI pragma Inline Always STI En este caso la habilitaci n deshabilitaci n se realiza actuando directamente sobre el registro de estado del procesador Bastar con poner a 1 en el caso de CLI o deshabilitaci n los bits de enmascaramiento de interrupciones o ponerlo a O en el caso de STI o activaci n procedure Hardware Interrupt Controller Enable Interrupt Int in HW Interrupt is begin if Int Timer Interrupt then IC Enable IRQ Int end if end Hardware Interrupt Controller Enable Interrupt procedure Hardware Interrupt Controller Disable Interrupt Int in HW Interrupt is begin if Int Timer Interrupt then IC Disable IRQ Int end if end Hardware Interrupt Controller Disable Interrupt Las pr ximas subrutinas son los procedimientos de habilitaci n deshabilitaci n de interrupciones especificas Asumiremos que pueden ser afectadas todas las interrupciones salvo la interrupci n de tick devuelta por Timer_Interrupt La implementaci n est dada en el driver del controlador de interrupciones Septiembre 2010 95 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM void enable irq unsigned int interrupt number if interrupt number lt 25 4 Unmask the interrupt rINTMSK amp i interrupt number void disable irq unsigned int interrupt number if interrupt number lt 25 Mask the interrupt rINTMSK i lt lt i
10. and O Minute because of the one second deviation that was mentioned In this case user should re read from BCDYEAR to BCDSEC if BCDSEC is zero BACKUP BATTERY OPERATION The RTC logic can be driven by the backup battery which supplies the power through the RTCVDD pin into RTC block even if the system power is off When the system off the interfaces of the CPU and RTC logic should be blocked and the backup battery only drives the oscillation circuit and the BCD counters to minimize power dissipation 14 2 ELECTR NICS 53 44 RISC MICROPROCESSOR REAL TIME CLOCK ALARM FUNCTION The RTC generates an alarm signal at a specified time in the power down mode or normal operation mode In normal operation mode the alarm interrupt ALMINT is activated In the power down mode the power management wakeup PMWKUP signal is activated as well as the ALMINT The RTC alarm register RTCALM determines the alarm enable disable and the condition of the alarm time setting TICK TIME INTERRUPT The RTC tick time is used for interrupt request The TICNT register has an interrupt enable bit and the count value for the interrupt The count value reaches 0 when the tick time interrupt occurs Then the period of interrupt is as follow Period n 1 128 second n Tick time count value 1 127 This RTC time tick may be used for RTOS real time operating system kernel time tick If time tick is generated by RTC time tick the time related f
11. lez Harbour POSIX de tiempo real 2001 http www ctr unican es publications mgh 1993b pdf 5 Documentaci n de la placa S3CEV40 http www armkits com Product s3cev40 asp 6 GCC Project http gcc gnu org 7 Libre Adacore home page http libre adacore com libre 8 Planificaci n de Tareas en Sistemas Operativos de Tiempo Real Estricto para Aplicaciones Empotradas 2002 http marte unican es documentation tesis mario pdf 9 MaRTE OS Boot process x86 architecture http marte unican es documentation tutorials booting marte howto pdf 10 Barttomiej Horn Ada 05 compiler for ARM based systems 2009 http www zsk p lodz pl morawski Dyplomy Praca 20dyplomowa 20p 20Horna pdf 11 EmbestIDE Pro for ARM 2004 User Guide 2004 http www armkits com download UserGuide2004 pdf 12 Compartir carpetas entre Windows y Linux en VirtualBox http www islabinaria com compartir carpetas entre windows y linux en virtualbox 13 Florist project http www cs fsu edu v baker florist html 14 Ciclo de vida del Software http www ia uned es ia asignaturas adms GuiaDidADMS node10 html 15 Grub4Dos and WinGrub http sourceforge net projects grub4dos 16 GNU binutils http www gnu org software binutils 17 Repositorio oficial del proyecto GNU http ftp gnu org Septiembre 2010 108 Migraci n del sistema operativo de
12. y realizar n la compilaci n del ejemplo hola mundo con los 3 lenguajes soportados mgcc hello world c c for a C application mgnatmake hello world adb for an Ada application mg hello world cpp cc for a C application Las opciones que admite cada uno de los scripts son las mismas que admitirian los comandos originales de compilaci n Para continuar con el proceso de carga de programas compilados en el microcontrolador utilizado de cara a cuando MaRTE OS este completamente migrado a la nueva arquitectura puede consultarse el manual on line de EmbestIDE 11 En el caso de estar compilando para Linux versi n Linux o Linux_Lib bastar a con ejecutar el programa compilado para verificar su funcionamiento En el caso de la versi n para X86 ser a necesario incluir el programa compilado entre las opciones de arranque con aplicaciones como WinGrub 15 que permite configurar dicho arranque desde Windows y arrancar directamente con l Septiembre 2010 33 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo D Resumen del repertorio de instrucciones del ARM7tdmi Este anexo es un extracto del capitulo 3 INSTRUCTION SET del manual original del microcontrolador Septiembre 2010 34 53 44 RISC MICROPROCESSOR ARM INSTRUCTION SET INSTRUCTION SET SUMMARY This chapter describes the ARM instruction set in the ARM7TDMI core FORMAT SUMMARY The AR
13. 4 slave units and 2 interrupt sources Each slave unit has 4 programmable priority source SGn and 2 fixed priority sources kn The priority among the 4 sources in each slave unit is determined the PSLV register The other 2 fixed priorities have the lowest priority among the 6 sources The master priority generating unit determines the priority between 4 slave units and 2 interrupt sources using the I PMST register The 2 interrupt sources INT_RTC and INT ADG have the lowest priority among the 26 interrupt sources If several interrupts are requested at the same time the I ISPR register shows only the requested interrupt source with the highest priority R Curent IRO proviy of slave register ortbibtbie I GMST 0x01E0001C R Current IRQ priority of master register Current IRQ priority of master register 0x0000xx1 0x0000xx1b ISPR 0x01E00020 IRQ interrupt service pending register 0x00000000 Only one service bit can be set ISPC 0x01E00024 IRQ interrupt service clear register Whatever to be set INTPND will be cleared automatically IMPORTANT NOTE In FIQ mode there is no service pending register like ISPR users must check INTPND resister IRQ INTERRUPT SERVICE PENDING REGISTER I ISPR ISPR indicates the interrupt being currently serviced Although the several interrupt pending bits are all turned on only one bit will be turned on ISPR 0x01E00020 R IRQ interrupt
14. 5 count buffer 15 0 Setting count buffer value for Timer 5 0x00000000 register TIMER 5 COUNT OBSERVATION REGISTER TCNTO5 5 0x01D5004G R Timer 5 count observation register 0x00000000 observation register Timer 5 15 0 Setting count observation value for Timer 5 0x00000000 9 14 ELECTRONICS Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo I Migraci n de MaRTE OS con el S3C44BOX Este cap tulo analiza a nivel de c digo fuente como se han implementado cada una de las rutinas de la interfaz abstracta con el hardware de MaRTE OS Como se ha detallado en la memoria el hito a conseguir para asegurar la correcta migraci n de MaRTE OS a cualquier arquitectura es la correcta implementaci n de lo especificado en la interfaz del fichero marte hal ads As pues se ha partido del fichero marte hal adb inicialmente vac o Desde las rutinas de este fichero se realizar n una serie de llamadas a las rutinas de los diferentes drivers implementados a modo de manejadores de cada uno de los diferentes perif ricos reloj de tiempo real temporizador PWM y controlador de interrupciones y rutinas de manejo de registros del procesador De este modo se ha establecido una jerarqu a en la que el punto de entrada a la interfaz abstracta es siempre marte hal ads y su implementaci n y las diferentes salidas hacia el hardware son las dem s bibliotecas Las diferentes s
15. PC Register 16 is the CPSR Current Program Status Register This contains condition code flags and the current mode bits FIQ mode has seven banked registers mapped to R8 14 R8 fiq R14 fig In ARM state many FIQ handlers do not need to save any registers User IRQ Supervisor Abort and Undefined each have two banked registers mapped to R13 and R14 allowing each of these modes to have a private stack pointer and link registers ELECTRONICS 2 3 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR ARM State General Registers and Program Counter System amp User FIQ Supervisor Abort Undefined 23 1 31 0 1 0 5 100 R1 R2 R3 R4 R5 R7 JJ I R10 E E 15 PC __R15 PC RO RB RS Ra RS Rs R7 Ra ta PARO fa RIO fa Rt fg D R12 a D R13 fig RIA fig ARM State Program Status Registers DASPSR_svc PXSPSR NSPSR ira NSPSR und b banked register Figure 2 3 Register Organization in ARM State 2 4 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL The THUMB State Register Set The THUMB state register set is a subset of the ARM state set The programmer has direct access to eight general registers RO R7 as well as the Program Counter PC a stack pointer register SP a link register LR and the CPSR There are banked Stack Pointers Link Registers and Saved Process Status Registers SPSRs for each privileged mode
16. This is shown in Figure 2 4 THUMB State General Registers and Program Counter System amp User FIQ Supervisor Abort IRQ Undefined THUMB State Program Status Registers h banked register Figure 2 4 Register Organization in THUMB State ELECTRONICS 2 5 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR The relationship between ARM and THUMB state registers The THUMB state registers relate to the ARM state registers in the following way THUMB state RO R7 and ARM state RO R7 are identical THUMB state CPSR and SPSRs and ARM state CPSR and SPSRs are identical THUMB state SP maps onto ARM state R13 e THUMB state LR maps onto ARM state R14 The THUMB state Program Counter maps onto the ARM state Program Counter R15 This relationship is shown in Figure 2 5 THUMB state ARM state Lo registers NE AD Hi registers Figure 2 5 Mapping of THUMB State Registers onto ARM State Registers 2 6 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL Accessing Hi Registers in THUMB State In THUMB state registers R8 R15 the Hi registers are not part of the standard register set However the assembly language programmer has limited access to them and can use them for fast temporary storage A value may be transferred from a register in the range RO R7 a Lo register to a Hi register and from a Hi register to a Lo register using special variants of the MOV instruction Hi
17. by TCMPBn in figure 9 5 For a lower PWM output value decrease the TCMPBn value For a higher PWM output value increase the TCMPBn value If an output inverter is enabled the increment decrement may be reversed Because of the double buffering feature TCMPBn for a next PWM cycle can be written at any point in the current PWM cycle by ISR or something else ELECTRONICS 9 5 PWM TIMER 53 44 RISC MICROPROCESSOR OUTPUT LEVEL CONTROL Inverter off Inverter on 21411 Initial State Period 1 Figure 9 6 Inverter On Off The following methods can be used to maintain TOUT as high or low assume the inverter is off 1 Turn off the auto reload bit And then TOUTn goes to high level and the timer is stopped after TCNTn reaches to 0 This method is recommended 2 Stop the timer by clearing the timer start stop bit to 0 If TCNTn lt TCMPn the output level is high If TCNTn the output level is low 3 Write the TCMPBn which is bigger than TCNTBn This inhibits the TOUTn from going to high because TCMPBn can not have the same value as TCNTn 4 TOUTn can be inverted by the inverter on off bit in TCON The inverter removes the additional circuit to adjust the output level 9 6 ELECTRONICS 53 44 RISC MICROPROCESSOR PWM TIMER DEAD ZONE GENERATOR The dead zone is for the PWM control in a power device This feature is used to insert the time gap between a turn off of a switching device and a turn on
18. el numero mostrado en el visualizador de 8 segmentos test_ic_rtc_pwm adb pone a prueba el funcionamiento del driver controlador de interrupciones el reloj de tiempo real y el temporizador PWM Para verificar el correcto funcionamiento de las interrupciones se instala un manejador basico que act a sobre el visualizador de 8 segmentos poni ndolo a 1 y a O cada vez que salta la interrupci n salta cada vez que el reloj se desborda Asimismo cada 3 desbordamientos se desactiva la interrupci n si estaba activada o se activa en caso contrario verificando la correcta activaci n desactivaci n Puede verse un esquema de la m quina de estados que representa la ejecuci n de este programa en la figura A 1 test_ic_rtc_pwm_pr_i adb test_ic_rtc_pwm_pr_2 adb idem que el anterior pero las interrupciones se deshabilitan con distintas llamadas a la interfaz deshabilitando todas las interrupciones a la vez o actuando sobre el registro de estado Puede verse un esquema de la m quina de estados que representa las ejecuciones de estos programas en la figura A 1 utils carpeta que contiene los scripts de compilaci n autom tica N interrupci n interrupci n interrupci n Figura A 1 Diagrama de estados para las pruebas de habilitaci n deshabilitaci n de interrupciones Septiembre 2010 23 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM La estructura que siguen los fiche
19. es invocado debe programar el timer dado en el primer par metro que en este caso es ignorado puesto que solo habr un temporizador hardware para que expire en Interval ticks de sistema En Next Activation debe devolverse el n mero de ticks de sistema que habr en el total una vez expire el temporizador esto se consigue sumando directamente ese intervalo de ticks al numero de ticks actual La programaci n del temporizador se realiza Septiembre 2010 100 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM invocando al driver del temporizador PWM y deber transmitirse el par metro que indique el numero de ticks que deben pasar para que expire Obviamente este numero de ticks debe estar expresado en ticks PWM y el parametro Interval esta expresado en ticks del reloj de tiempo real Con la sencilla cuenta que aparece se consigue la transformaci n Veamos en que consiste la llamada al driver void program timer unsigned int interval rTCNTBS interval Timer 5 ticks rTCON amp OxFEFFFFFF Stop timer 5 rTCON 20x02000000 Manual update of TCNTBS rTCON amp xFDFFFFFF Manual update of TCNTBS rTCON 0x01000000 Start timer 5 La programaci n del timer en el driver se realiza llamando a una funci n C que recibe como par metro el n mero de ticks que deben ser introducidos en el registro contador del temporizador 5 el utilizado para la migraci n Una vez escrito el p
20. interrupt in all cases If source A and source B are in different master groups and the master group priority of source A is higher than the master group priority of source B the priority of source A is higher than source B If source A and source B are in the same master group and source A has higher priority than source B source A has the higher priority The priorities of SGA SGB sGC and sGD are always higher than those of SGKA and sGKB The priorities among sGA sGB sGC and sGD are programmable or are determined by the round robin method Between sGKA and sGKB sGKA has always the higher priority The group priority of mGA mGB mGC and mGD are always higher than that of mGKA and mGKB So the priorities of mGKA and mGKB are the lowest among the other interrupt sources The group priority among mGA mGB mGC and mGD is programmable or is determined by the round robin method Between mGKA and mGKB mGKA always has the higher priority VECTORED INTERRUPT MODE ONLY FOR IRQ 53 44 has a new feature the vectored interrupt mode to reduce the interrupt latency time If ARM7TDMI receives the IRQ interrupt request from the interrupt controller ARM7TDMI executes an instruction at 0x00000018 In vectored interrupt mode the interrupt controller will load branch instructions on the data bus when ARM7TDMI fetches the instructions at 0x00000018 The branch instructions let the program counter be a unique address corresponding to each inter
21. of another switching device This time gap prohibits the two switching devices turning on simultaneously even for a very short time TOUTO is the PWM output nTOUTO is the inversion of the TOUTO If the dead zone is enabled the output wave form of TOUTO and nTOUTO will be TOUTO DZ and nTOUTO_DZ respectively nTOUTO_DZ is routed to the TOUT1 pin In the dead zone interval TOUTO DZ and nTOUTO DZ can never be turned on simultaneously EE E Deadzone Interval TOUTO DZ Pl IJI FF Figure 9 7 The Wave Form When a Dead Zone Feature is Enabled gt lt ELECTRONICS 9 7 PWM TIMER 53 44 RISC MICROPROCESSOR DMA REQUEST MODE The PWM timer can generate a DMA request at every specific times The timer keeps DMA request signal low until the timer receives the ACK signal When the timer receives the ACK signal it makes the request signal inactive One of 6 timers can generate a DMA request The timer that generates the DMA request is determined by setting DMA mode bits in TCFG1 register If a timer is configured as DMA request mode the timer does not generate an interrupt request The others can generate interrupt normally DMA mode configuration and DMA interrupt operation DMA mode DMA TimerO INT Timer1 INT Timer2 INT Timer3 INT Timer4 INT Timer5 INT request MCLK Timer4 Int tmp DMA mode 101 nDMA ACK nDMA REQ Timer4 Int Figure 9 8 The Timer4 DMA mode operation 9 8 ELECTR
22. on Entering an Exception When handling an exception the ARM7TDMI 1 Preserves the address of the next instruction in the appropriate Link Register If the exception has been entered from ARM state then the address of the next instruction is copied into the Link Register that is current PC 4 or PC 8 depending on the exception See Table 2 2 on for details If the exception has been entered from THUMB state then the value written into the Link Register is the current PC offset by a value such that the program resumes from the correct place on return from the exception This means that the exception handler need not determine which state the exception was entered from For example in the case of SWI MOVS PC R14_svc will always return to the next instruction regardless of whether the SWI was executed in ARM or THUMB state Copies the CPSR into the appropriate SPSR Forces the CPSR mode bits to a value which depends on the exception Forces the PC to fetch the next instruction from the relevant exception vector It may also set the interrupt disable flags to prevent otherwise unmanageable nestings of exceptions If the processor is in THUMB state when an exception occurs it will automatically switch into ARM state when the PC is loaded with the exception vector address Action on Leaving an Exception On completion the exception handler 1 Moves the Link Register minus an offset where appropriate to the PC The offset will vary depe
23. prescaler Each timer except timers 4 and 5 has a clock divider which has 5 different divided signals 1 2 1 4 1 8 1 16 1 32 Timers 4 5 have 4 divided signals 1 2 1 4 1 8 1 16 and one input TCLK EXTCLK Each timer block receives its own clock signals from the clock divider which receives the clock from the corresponding 8 bit prescaler The 8 bit prescaler is programmable and divides the MCLK signal according to the loading value which is stored in TCFGO and TCFG1 registers The timer count buffer register TCNTBn has an initial value which is loaded into the down counter when the timer is enabled The timer compare buffer register TCMPBn has an initial value which is loaded into the compare register to be compared with the down counter value This double buffering feature of TCNTBn and TCMPBn makes the timer generate a stable output when the frequency and duty ratio are changed Each timer has its own 16 bit down counter which is driven by the timer clock When the down counter reaches zero the timer interrupt request is generated to inform the CPU that the timer operation has been completed When the timer counter reaches zero the value of corresponding TCNTBn is automatically loaded into the down counter to continue the next operation However if the timer stops for example by clearing the timer enable bit of TCONn during the timer running mode the value of TCNTBn will not be reloaded into the counter The value of TCMPBn is used f
24. riesgos enumerados en la tabla B 4 1 N mero de estrategia de mitigaci n Descripci n 1 Consulta con diferentes expertos en el tema con el fin de renovar las fuentes en uso 2 Consulta de la documentaci n disponible en la Web o los CD s del fabricante 3 Cambio del hardware que el proyectando tiene actualmente por otro igual Dedicaci n de m s tiempo al desarrollo 5 Mantener copias de seguridad del trabajo realizado en un dispositivo USB B 5 Herramientas B 6 Las herramientas Software empleadas en este Proyecto Fin de Carrera se enumeran a continuaci n Sistema operativo Windows XP Explorador Web Internet Explorer Paquete de ofim tica OpenOffice v3 1 0 Herramienta de dibujo Paint v5 1 Gestor Emulador de m quinas virtuales VirtualBox v3 1 4 Sistema operativo emulado Ubuntu Utilidades binarias Binutils 2 20 1 Librer as de operaciones matem ticas GMP 4 3 2 y MPFR 2 4 2 Librer a est ndar de C Newlib 1 18 0 Fuentes del compilador C con sus extensiones Ada GCC 4 4 4 Entorno de desarrollo carga y depuraci n de programas para la placa de desarrollo S3CEV40 Embest IDE Aplicaci n de carga de aplicaciones en la memoria RAM de la placa de desarrollo S3CEV40 Flash Programmer Aplicaci n auxiliar de analisis y mantenimiento de memoria dinamica Valgrind v3 5 Paquetes de trabajo 10000 Gestion del proyecto 11000 Reuniones con el tutor 12000 Pre
25. to pass through the synchroniser Tsyncmax if asynchronous plus the time for the longest instruction to complete the longest instruction is an LDM which loads all the registers including the PC plus the time for the data abort entry Texc plus the time for FIQ entry Tfiq At the end of this time ARM7TDMI will be executing the instruction at 0x1C Tsyncmax is 3 processor cycles Tidm is 20 cycles Texcis 3 cycles and Tfiq is 2 cycles The total time is therefore 28 processor cycles This is just over 1 4 microseconds in a system which uses a continuous 20 MHz processor clock The maximum IRQ latency calculation is similar but must allow for the fact that FIQ has higher priority and could delay entry into the IRQ handling routine for an arbitrary length of time The minimum latency for FIQ or IRQ consists of the shortest time the request can take through the synchroniser Tsyncmin plus Tfiq This is 4 processor cycles RESET When the nRESET signal goes LOW ARM7TDMI abandons the executing instruction and then continues to fetch instructions from incrementing word addresses When nRESET goes HIGH again ARM7TDMI 1 Overwrites R14 svc and SPSR svc by copying the current values of the PC and CPSR into them The value of the saved PC and SPSR is not defined Forces M 4 0 to 10011 Supervisor mode sets the and F bits in the CPSR and clears the CPSR s T bit Forces the PC to fetch the next instruction from address 0x00 Executi
26. usarse los siguientes comandos cd SHOME tar zxvf marte version tar gz cd marte minstall EI funcionamiento de minstall es muy sencillo Unicamente buscar la instalaci n de GNAT realizada en el paso 0 y realizar algunos enlaces simb licos desde el directorio de descompresi n de MaRTE OS Tras la instalaci n es recomendable incluir el directorio utils del directorio de MaRTE OS con el fin de emplear sus utilidades con mayor comodidad Usar el siguiente comando export PATH PATH SHOME marte utils Es recomendable incluir el comando anterior en el script de inicio del sistema HOME bashrc En caso de estar empleando la versi n binaria de MaRTE OS con el nucleo previamente compilado el proceso de instalaci n habr a sido completado Con la versi n de MaRTE actual pueden encontrarse dentro del directorio de descarga instalaci n las librer as para las 3 plataformas soportadas x86 Linux lanzamiento de MaRTE OS como proceso de Linux y Linux_Lib lanzamiento como proceso de Linux pero con acceso al sistema de ficheros y drivers del sistema operativo Cuando la versi n para ARM est completa esta plataforma aparecer tambi n entre las librer as En el caso de no estar empleando la versi n binaria de MaRTE OS ser necesario Septiembre 2010 32 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM compilar su kerne y previamente el runtime de GNAT Los s
27. 010 21 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Como puede verse los fuentes que ofrecen soporte a las distintas arquitecturas Linux Linux_lib y X86 estan distribuidos en distintos directorios cada uno con un nombre que identifica a la arquitectura Los ficheros implementados para el portado de MaRTE OS a ARM deben seguir esta nomenclatura con el fin de que en un futuro la carpeta que los almacene pueda ser integrada facilmente en los scripts actuales de MaRTE OS Por tanto la carpeta que contendr los ficheros del n cleo dependientes de la arquitectura ARM deber llamarse arm_arch Esta carpeta se dispondr dentro del directorio de la entrega junto con otros elementos que permitir n realizar pruebas de verificaci n de los fuentes contenidos Como se ha dicho arm_arch constituye la futura capa del n cleo que lo abstraer del hardware utilizado en este caso ARM Dentro de esta carpeta debe haber como m nimo 3 ficheros el fichero de configuraci n de MaRTE OS marte configuration parameters ads situado en la subcarpeta arch_dependent_files la cabecera de la interfaz abstracta con el hardware y su implementaci n marte hal ads y marte hal adb situados en el subdirectorio hwi siguiendo la nomenclatura original de las arquitecturas previas soportadas por MaRTE OS El total de subdirectorios del directorio arm_arch es el siguiente README contiene informaci n general del directorio
28. H REGISTER BCDMON BCDMON 0x01D70084 L R W BCD month Register Undef 0x01D70087 B by byte pe MONDATA BCD value for month 0 10 1 ea fremoes BCD YEAR REGISTER BCDYEAR BCDYEAR 0x01D70088 L R W BCD year Register Undef 0x01D7008B B by byte YEARDATA 7 0 BCD value for year from 00 to 99 TICK TIME COUNT REGISTER TICNT TICNT 0x01D7008C L R W Tick time count Register 0x00000000 0x01D7008F B by byte TICK INT ENABLE 7 Tick time interrupt enable 0 disable 1 enable TICK TIME COUNT Tick time count value 1 127 000000 This counter value decreases internally and users can not read this real counter value in working 14 10 ELECTR NICS Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo H El temporizador PWM del S3C44BOX Este anexo es un extracto del capitulo 9 PWM TIMER del manual original del microcontrolador Septiembre 2010 78 53 44 RISC MICROPROCESSOR PWM TIMER OVERVIEW The S3C44BOX has six 16 bit timers each timer can operate in interrupt based DMA based mode The timers 0 1 2 4 have the PWM function Pulse Width Modulation Timer 5 has an internal timer only with no output pins Timer 0 has a dead zone generator which is used with a large current device Timer 0 and timer 1 share an 8 bit prescaler timers 2 amp 3 share another 8 bit prescaler and timers 4 amp 5 share the other 8 bit
29. I b HandlerPabort b HandlerDabort b b IsrIRQ b HandlerFIQ IsrIRQ sub sp sp 4 stmfd sp r8 r9 ldr r9 ISPR ldr r9 r9 mov r8 0x0 0 movs r9 r9 lsr 1 bcs SF 1 add r8 r8 444 b BO 1 ldr r9 HandleADC add r9 r9 r8 ldr r9 r9 str r9 sp 8 ldmfd sp r8 r9 pc HandleADC 4 HandleRTC 4 HandleUTXD1 4 HandleUTXDO H 4 HandleEINT3 4 HandleEINT2 4 HandleEINT1 4 HandleEINTO 4 ELECTHONICS for debug handlerUndef SWlinterrupt handler handlerPAbort handlerDAbort handlerReserved reserved for PC Oxc1 c7 fff84 INTERRUPT CONTROLLER 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER SPECIAL REGISTERS INTERRUPT CONTROL REGISTER INTCON INTCON 0x01E00000 Interrupt control Register This bit disables enables vector mode for IRQ 0 Vectored interrupt mode 1 Non vectored interrupt mode This bit enables IRQ interrupt request line to CPU 1 0 IRQ interrupt enable 1 Reserved Note Before using the IRQ interrupt this bit must be cleared This bit enables FIQ interrupt request line to CPU 0 FIQ interrupt enable Not allowed vectored interrupt mode 1 Reserved Note Before using the FIQ interrupt this bit must be cleared NOTE FIQ interrupt mode does not support vectored interrupt mode INTERRUPT PENDING REGISTER INTPND Each of the 26 bits in the interrupt pending register INTPND corresponds to an interrupt source When an interrupt reques
30. ICINT 0x81 void initialize rtc unsigned int tiempo set interrupt handler for tick pISR TICK unsigned tick int rINTMSK amp BIT GLOBAL BIT total tiempo Enable tick rTICINT 0x81 update RTCCON rRTCCON amp OxFO0 R W disable for power consumption 1 32768 Normal merge No reset Init total time total 0 La gesti n del tiempo en ticks se realiza como se muestra en el c digo anterior En el proceso de inicializaci n del reloj de tiempo real se instala una interrupci n que incrementa una variable la de tick de sistema con una frecuencia de 128 Hz cada vez que el perif rico hace saltar la interrupci n TICK entre otras inicializaciones del perif rico Esta variable es la que es le da desde el c digo Ada del driver cuando se solicita el tiempo del sistema Septiembre 2010 99 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM function Safe Longest Timer Interval return HWUTime is begin pragma Assert Initialized return PUM Safe Longest Timer Interval HUT HZ PUM PUM HZ end Safe Longest Timer Interval La siguiente funci n devuelve al sistema el intervalo m ximo en ticks con el que puede ser programado el temporizador hardware implementado bajo el temporizador PWM Con la cuenta que se realiza en la funci n se consigue obtener el n mero de ticks del reloj de tiempo real en funci n del intervalo m ximo del temporizado
31. IQ UNDEF ABORT SWI etc if the exception was entered with the processor in THUMB state Entering ARM State Entry into ARM state happens e execution of the BX instruction with the state bit clear in the operand register e the processor taking an exception IRQ FIQ RESET UNDEF ABORT SWI etc In this case the PC is placed in the exception mode s link register and execution commences at the exception s vector address MEMORY FORMATS ARM7TDMI views memory as a linear collection of bytes numbered upwards from zero Bytes 0 to 3 hold the first stored word bytes 4 to 7 the second and so on ARM7TDMI can treat words in memory as being stored either in Big Endian or Little Endian format ELECTRONICS 2 1 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR BIG ENDIAN FORMAT In Big Endian format the most significant byte of a word is stored at the lowest numbered byte and the least significant byte at the highest numbered byte Byte 0 of the memory system is therefore connected to data lines 31 through 24 Higher Address Word Address Lower Address Most significant byte is at lowest address Word is addressed by byte address of most significant byte Figure 2 1 Big Endian Addresses of Bytes within Words LITTLE ENDIAN FORMAT In Little Endian format the lowest numbered byte in a word is considered the word s least significant byte and the highest numbered byte the most significant Byte 0 of the memory s
32. M instruction set formats are shown below 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 1211109876543210 Opcode S Rn Operand2 Data Processing PSR Transfer oolololofojajs Pd Rn ms Am 0 ojojo uja s Rao m Pm Wultply Long mn Rm single Data Swap An French and Exchange U 0 WIL Rn 1 lS H 1 Rm Halfword Data Transfer register offset Offset Offset Halfword Data Transfer immendiate offset bl Single Data Transfer Ug S unetned fold m Register List Block Data Transfer Offset Branch Opc 111 1 1 Ignored by processor Software Interrupt 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 161514131211109876543210 Figure 3 1 ARM Instruction Set Format NOTE Some instruction codes are not defined but do not cause the Undefined instruction trap to be taken for instance a Multiply instruction with bit 6 changed to a 1 These instructions should not be used as their action may change in future ARM implementations ELECTRONICS 3 1 ARM INSTRUCTION SET 53 44 RISC MICROPROCESSOR INSTRUCTION SUMMARY Table 3 1 The ARM Instruction Set Add with carry Rd Rn Op2 Carry AND Rd Rn AND Op2 fann R Bb CPSR flags Rn 2 Exclusive OR Rd Rn AND NOT Op2 OR Op2 AND NOT Rn Load coprocessor from memory Coproce
33. Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo A Estructura de los ficheros migrados Este anexo describe la estructura y el prop sito de cada uno de los ficheros importantes entregados dentro de la m quina virtual proporcionada como resultado de este Proyecto Fin de Carrera Se ha intentado seguir en la medida de lo posible la estructura de ficheros establecida en las versiones previas de MaRTE OS Cuando nos descargamos este sistema operativo ya sean los fuentes o los ficheros con el n cleo compilado y descomprimimos el fichero de descarga se genera un directorio con el siguiente contenido INSTALL instrucciones de instalaci n de MaRTE OS README informaci n general del contenido del directorio arch link al directorio dependiente del hardware de la arquitectura seleccionada para MaRTE OS Linux Linux lib o X86 Contiene los siguientes subdirectorios Drivers c digo fuente de drivers de dispositivo implementados para las arquitecturas previas de MaRTE OS Include cabeceras en C de la interfaz POSIX Implementaci n de la biblioteca est ndar de C libc examples programas de ejemplo para probar MaRTE OS Hay ejemplos en C C y Ada COPYING licencia de distribuci n del c digo de MaRTE OS kernel c digo fuente del n cleo de MaRTE OS Independiente del hardware Lib ink al directorio dependiente del hardware de los objetos y lib
34. ONICS 53 44 RISC MICROPROCESSOR PWM TIMER PWM TIMER CONTROL REGISTERS TIMER CONFIGURATION REGISTERO TCFGO Timer input clock Frequency MCLK prescaler value 1 divider value prescaler value 0 255 divider value 2 4 8 16 32 TCFGO 0x01D50000 Configures the three 8 bit prescalers 0x00000000 Dead zone length 31 24 These 8 bits determine the dead zone length The 1 unit time of 0x00 the dead zone length is equal to the 1 unit time of timer 0 23 16 These 8 bits determine prescaler value for Timer 4 amp 5 15 8 These 8 bits determine prescaler value for Timer 2 amp 3 7 0 These 8 bits determine prescaler value for Timer 0 amp 1 ELECTRONICS 9 9 PWM TIMER S3C44BOX RISC MICROPROCESSOR TIMER CONFIGURATION REGISTER1 TCFG1 TCFG1 0 01050004 6 MUX amp DMA mode selecton register 0x00000000 DMA mode 27 24 Select DMA request channel 0000 No select all interrupt 0001 TimerO 0010 Timer1 0011 Timer2 0100 Timer3 0101 Timer4 0110 Timer5 0111 Reserved MUX 5 23 20 Select MUX input for PWM Timer5 0000 1 2 0001 1 4 0010 1 8 0011 1 16 1 EXTCLK 4 19 16 Select MUX input for PWM Timer4 0000 1 2 0001 1 4 0010 1 8 0011 1 16 1 TCLK MUX 3 15 12 Select MUX input for PWM Timers 0000 1 2 0001 1 4 0010 1 8 0011 1 16 1 1 32 MUX 2 11 8 Select MUX input for PWM Timer2 0000 1 2 0001 1 4 0010 1 8 0011
35. SSOR RTC ROUND RESET REGISTER RTCRST RTCRST 0x01D7006C L R W RTC round reset Register 0x0 0x01D7006F B by byte SRSTEN 3 Round second reset enable 0 Disable 1 Enable SECCR 2 0 Round boundary for second carry generation Note 011 over than 30 sec 100 over than 40 sec 101 over than 50 sec NOTE Otherwise no second carry is generated BCD SECOND REGISTER BCDSEC BCDSEC 0x01D70070 L R W BCD second Register Undef 0x01D70073 B by byte m SECDATA 6 4 BCD value for second from 0 to 5 fa roms SSCS BCD MINUTE REGISTER BCDMIN BCDMIN 0x01D70074 L R W BCD minute Register Undef 0x01D70077 B by byte a MINDATA 6 4 BCD value for minute 0105 89 fremoes 14 8 ELECTRONICS 53 44 RISC MICROPROCESSOR REAL TIME CLOCK BCD HOUR REGISTER BCDHOUR BCDHOUR 0x01D70078 L R W BCD hour Register Undef 0x01D7007B B by byte p gt HOURDATA 5 4 BCD value for hour from 0 to 2 BCD DAY REGISTER BCDDAY BCDDAY 0x01D7007C L R W BCD day Register Undef 0x01D7007F B by byte gp EEN DAYDATA 5 4 BCD value for day from 0 to 3 fa AA BCD DATE REGISTER BCDDATE BCDDATE 0x01D70080 L R W BCD date Register Undef 0x01D70083 B by byte m Ss DATEDATA 2 0 BCD value for date from 1 to 7 ELECTRONICS 14 9 REAL TIME CLOCK 53 44 RISC MICROPROCESSOR BCD MONT
36. Time Clock el controlador de interrupciones y el temporizador PWM as como ficheros C con operaciones de bajo nivel La carpeta arm arch se proporciona junto con otras carpetas dentro del directorio workspace situado en el HOME del usuario proporcionado con la m quina virtual El contenido adicional de este directorio permite verificar el correcto funcionamiento de las pruebas implementadas y es el siguiente newProyect este script acepta un par metro como entrada Compila los fuentes de la interfaz abstracta crea una carpeta de proyecto sobre la que poder testear las pruebas y deposita los ficheros objeto de la interfaz dichas pruebas y scripts de compilaci n autom tica en ella Ver apartado A 1 arm objs carpeta temporal para ficheros objeto de la interfaz abstracta con el hardware de MaRTE OS Septiembre 2010 22 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM kernel contiene algunos ficheros del nucleo de MaRTE OS necesarios para compilar la interfaz abstracta con el hardware tests carpeta con las pruebas implementadas Contiene 6 pruebas 8led c prueba en C para el visualizador de 8 segmentos eight_led adb prueba en Ada para el visualizador de 8 segmentos test_ic_rtc adb pone a prueba el funcionamiento del driver controlador de interrupciones y el reloj de tiempo real Cada vez que el contador del reloj se desborda cada segundo aproximadamente avanza en 1 unidad
37. Timer 0 on off 0 One shot 1 Interval mode auto reload Timer 0 output Li bit determines the output inverter on off for Timer 0 inverter on off Inverter off 1 Inverter on for TOUTO Timer 0 manual This bit determines the manual update for Timer 0 update note 0 No operation 1 Update TCNTBO TCMPBO Timer 0 start stop This bit determines start stop for Timer 0 0 Stop 1 Start for Timer 0 NOTE This bit has to be cleared at next writing ELECTRONICS 53 44 RISC MICROPROCESSOR PWM TIMER TIMER 0 COUNT BUFFER REGISTER amp COMPARE BUFFER REGISTER TCNTBO TCMPBO TCNTBO 0x01D50000 Timer 0 count buffer register 0x00000000 TCMPBO 0x01D50010 Timer 0 compare buffer register 0x00000000 Timer 0 compare Setting compare buffer value for Timer 0 0x00000000 buffer register NOTE This value must be smaller than TCNTBO Timer 0 count buffer 15 0 Setting count buffer value for Timer 0 0x00000000 register TIMER 0 COUNT OBSERVATION REGISTER TCNTOO TCNTOO 0x01D50014 oR Timer 0 count observation register 0x00000000 observation register Timer 0 15 0 Setting count observation value for Timer 0 0x00000000 Note timer 0 registers are like timer 1 timer 2 timer 3 and timer 4 registers ELECTRONICS 9 13 PWM TIMER 53 44 RISC MICROPROCESSOR TIMER 5 COUNT BUFFER REGISTER TCNTB5 TCNTBS 0 01050048 Timer 5 count buffer register 0x00000000 TCNTB5 Description Initial State Timer
38. Vectors The following table shows the exception vector addresses Table 2 3 Exception Vectors address Exeon Abort prefetch Abort data 00000008 RR ELECTRONICS 2 13 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR Exception Priorites When multiple exceptions arise at the same time a fixed priority system determines the order in which they are handled Highest priority Reset Data abort FIQ IRQ Prefetch abort O MV Lowest priority 6 Undefined Instruction Software interrupt Not All Exceptions Can Occur at Once Undefined Instruction and Software Interrupt are mutually exclusive since they each correspond to particular non overlapping decodings of the current instruction If a data abort occurs at the same time as a FIQ and FIQs are enabled ie the CPSR s F flag is clear ARM7TDMI enters the data abort handler and then immediately proceeds to the FIQ vector A normal return from FIQ will cause the data abort handler to resume execution Placing data abort at a higher priority than FIQ is necessary to ensure that the transfer error does not escape detection The time for this exception entry should be added to worst case FIQ latency calculations 2 14 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL INTERRUPT LATENCIES The worst case latency for FIQ assuming that it is enabled consists of the longest time the request can take
39. ales no merece la pena comentar puesto que son sencillas y triviales Last HW Timer constant Integer 32 0 ARM type HW Timers is new Integer_32 range 0 Last HW Timer for HW Timers Size use 32 HW Timer 0 constant HW Timers 0 type HUTime is new Unsigned 64 A continuaci n se declaran una serie de constantes Last HW Timer y HW Timer 0 y un tipo de datos HW Timers Como nicamente vamos a tener un timer para programaci n de temporizadores hardware las 2 constantes valdran 0 HWTime se declara para a continuaci n disponer de un tipo que permita declarar variables que almacenen la cuenta de cuantos ticks de sistema han transcurrido Septiembre 2010 98 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM function Get HUTime Slow return HWTime is Ticks HWTime begin pragma Assert Initialized Disable Interrupts Ticks RTC Get Time In Ticks Enable Interrupts return Ticks end Get HWTime Slow La siguiente funci n retorna el tiempo en ticks que ha transcurrido desde el inicio de la aplicaci n deshabilitando las interrupciones antes de consultarlo y habilit ndolas posteriormente La funci n Get HWTime realiza lo mismo pero sin manipular las interrupciones La funci n invoca la lectura a partir del driver del reloj de tiempo real volatile unsigned int total void tick int _ attribute interrupt IRO void tick int rI_ISPC BIT_TICK total rT
40. ambios de contexto entre tareas pero en este Proyecto Fin de Carrera no se han implementado Finalmente aparecen 2 procedimientos generales de inicializaci n y finalizaci n de uso del hardware utilizado En la inicializaci n se invocan los procedimientos de inicializaci n de cada uno de los drivers implementados La inicializaci n del reloj de tiempo real y el controlador de interrupciones ya ha sido detallada anteriormente tan solo falta comentar la inicializaci n del Septiembre 2010 101 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM temporizador PWM void initialize pwm Enable timer 5 interrupt r INTMSK amp BIT GLOBAL BIT TIMERS Update TCFGO and TCFG1 Set tick to 62 06us frec 16113 Hz maximum interval 4 0672 sec rTCFGO prescaler Prescaler 255 rTCFGi1 2divider Divider 1 16 En la inicializaci n del temporizador PWM escrita como una funci n C nicamente se habilita la interrupci n correspondiente la del temporizador 5 En el registro de configuraci n deben modificarse los bits correspondientes al prescaler y el divisor de frecuencia del temporizador 5 para establecer su frecuencia de tick a 16113 Adem s de la inicializaci n de los perif ricos tambi n se escriben las variables que indican la frecuencia de la CPU y del tick del sistema esta ltima a partir de la inicializaci n del reloj de tiempo real Por ltimo la variable que i
41. an solo aparecen reflejados los registros utilizados en la migraci n de MaRTE OS los referentes a prioridades en la gesti n de interrupciones no se han incluido Septiembre 2010 55 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo G El reloj de tiempo real del 53 44 Este anexo es un extracto del manual original del microcontrolador y corresponde al cap tulo 14 REAL TIME CLOCK del mismo Septiembre 2010 67 53 44 RISC MICROPROCESSOR REAL TIME CLOCK OVERVIEW The RTC Real Time Clock unit can be operated by the backup battery while the system power is off The RTC can transmit 8 bit data to CPU as BCD Binary Coded Decimal values using the STRB LDRB ARM operation The data include second minute hour date day month and year The RTC unit works with an external 32 768 KHz crystal and also can perform the alarm function FEATURES BCD number second minute hour date day month year Leap year generator Alarm function alarm interrupt or wake up from power down mode Year 2000 problem is removed Independent power pin VDDRTC Supports millisecond tick time interrupt for RTOS kernel time tick Round reset function ELECTRONICS 14 1 REAL TIME CLOCK 53 44 RISC MICROPROCESSOR REAL TIME CLOCK OPERATION TIME TICK Time Tick Generator Leap Year Generator HOUR DATE DAY MON Control Register Alarm Generator
42. ar metro de entrada en el buffer de entrada de dicho registro ser necesario parar el temporizador para posteriormente proceder a la actualizaci n manual del registro a partir de dicho buffer Esto se realiza poniendo a 1 y a 0 el bit correspondiente del registro de control del perif rico Seguidamente puede ponerse en marcha el temporizador 5 el cual empezar a contar el tiempo establecido function Compulsory Timer Reprogramming return Boolean is begin return false end Compulsory Timer Reprogramming Aunque la siguiente funci n que aparece Compulsory Timer Reprogramming es trivial de implementar el valor true o false que devuelva implica la aplicaci n de distintas medidas a la hora de migrar MaRTE OS En caso de que se haya usado el mismo perif rico para implementar el tick de sistema y la temporizaci n hardware deber devolver True Como en nuestro caso se usan 2 perif ricos distintos reloj de tiempo real y temporizador PWM la funci n deber devolver False function RTC HlTime Since Epoch return HWTime is begin return Duration To HUTime Duration RTC RTC Time To Seconds Since Epoch end RTC HWTime Since Epoch La siguiente funci n devuelve el tiempo en ticks de sistema desde Epoch afio 1900 La lectura del tiempo se realiza en el driver del reloj de tiempo real mientras que su transformaci n a HWTime se realiza en la propia interfaz Seguidamente aparecen una serie de procedimientos referentes a c
43. babilidad estimada en porcentaje de que el riesgo de esa fila ocurra mientras que la columna descripci n indica en detalle en que consiste dicho riesgo La columna puntos indica la gravedad del riesgo en caso de ocurrir y la columna estrategia de mitigaci n indica el m todo de la tabla B 4 2 seguido para intentar reducir la posibilidad de que el riesgo se convierta en realidad y su gravedad Riesgo Descripci n Puntos Estrategia de mitigaci n 70 Proceso de configuraci n del entorno de 90 1 desarrollo cruzado en Linux no es trivial y documentaci n en la Web inconsistente 80 Dificultad de adaptaci n al entorno 30 2 proporcionado por el fabricante de la placa de desarrollo 5 El hardware utilizado no est en correcto 10 3 estado 60 La arquitectura del sistema operativo 30 2 MaRTE OS no es trivial o f cil de entender 100 Desconocimiento de los perif ricos 20 2 disponibles en el microcontrolador utilizado 20 EI modelo de interrupciones del 80 2 microcontrolador es muy complejo 5 La falta de experiencia los lenguajes de 15 4 programaci n C y Ada hacen retrasan el desarrollo Septiembre 2010 27 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM 40 El equipo sobre el que se guardan los 100 5 ficheros del proyecto se rompe o deteriora La tabla B 4 2 muestra las estrategias de mitigaci n empleadas sobre los
44. ble THUMB state registers Visible ARM state registers User R7 RO LR SP PC CPSR FIQ R7 RO LR fig SP fiq PC CPSR SPSR fiq aJ LR irg SP_irq PC CPSR SPSR irq Supervisor R7 RO LR_svc SP_svc PC CPSR SPSR svc Abort R7 RO LR_abt SP_abt PC CPSR SPSR_abt Undefined R7 RO LR_und SP_und PC CPSR SPSR_und R7 RO R14 fiq R8 fig PC CPSR SPSR fiq 12 R14 irq R13 irq PC CPSR SPSR irq R12 RO R14 svc R13_svc PC CPSR SPSR svc R12 RO R14_abt R13_abt PC CPSR SPSR_abt 12 R14_und R13_und PC CPSR R14 RO PC CPSR Reserved bits The remaining bits in the PSR s are reserved When changing a PSR s flag or control bits you must ensure that these unused bits are not altered Also your program should not rely on them containing specific values since in future processors they may read as one or zero ELECTRONICS 2 9 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR EXCEPTIONS Exceptions arise whenever the normal flow of a program has to be halted temporarily for example to service an interrupt from a peripheral Before an exception can be handled the current processor state must be preserved so that the original program can resume when the handler routine has finished It is possible for several exceptions to arise at the same time If this happens they are dealt with in a fixed order See Exception Priorities on page 2 14 Action
45. block only for IRQ interrupt request If the vectored mode is used and an interrupt source is configured as ISR in INTMOD register the interrupt will be processed by the interrupt priority generating block The priority generating block consists of five units 1 master unit and 4 slave units Each slave priority generating unit manages six interrupt sources The master priority generating unit manages 4 slave units and 2 interrupt sources Each slave unit has 4 programmable priority sources SGn and 2 fixed priotiry sources SGKn The priority among the 4 sources in each slave unit is programmable The other 2 fixed priorities have the lowest priority among the 6 sources The master priority generating unit determines the priority between the 4 slave units and 2 interrupt sources The 2 interrupt sources INT_RTC and INT_ADC have the lowest priority among 26 interrupt sources sGA B C D EINTO 1 2 3 mGA B C D sGKA B EINT4 5 6 7 ARM IRQ TICK mGKA B sGA B C D ZDMAQ ZD MA1 BRDMAO BRDMA1 WDT SGKA B UERRO 1 sGA B C D TIMERO 1 2 3 sGKA B TIMER4 5 RXDO 1 SGA BGD IIC SIO SGKA B TXDO 1 RTC ADC Figure 11 1 Priority Generating Block ELECTRONICS 11 3 INTERRUPT CONTROLLER 53 44 RISC MICROPROCESSOR INTERRUPT PRIORITY If source A is configured to FIQ and source B is configured to IRQ source A has higher priority than source B because a FIQ interrupt has higher priority than an IRQ
46. changed when an exception arises If the processor is operating in a privileged mode they can also be manipulated by software The T bit This reflects the operating state When this bit is set the processor is executing in THUMB state otherwise it is executing in ARM state This is reflected on the TBIT external signal Note that the software must never change the state of the TBIT in the CPSR If this happens the processor will enter an unpredictable state Interrupt disable bits The I and F bits are the interrupt disable bits When set these disable the IRQ and FIQ interrupts respectively The mode bits The M4 M3 M2 M1 and MO bits M 4 0 are the mode bits These determine the processor s operating mode as shown in Table 2 1 Not all combinations of the mode bits define a valid processor mode Only those explicitly described shall be used The user should be aware that if any illegal value is programmed into the mode bits M 4 0 then the processor will enter an unrecoverable state If this occurs reset should be applied Reserved bits The remaining bits in the PSRs are reserved When changing a PSR s flag or control bits you must ensure that these unused bits are not altered Also your program should not rely on them containing specific values since in future processors they may read as one or zero 2 8 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL Table 2 1 PSR Mode Bit Values M40 Visi
47. compresi n Configuraci n del compilador mkdir gcc build cd gcc build gcc 4 4 4 configur target arm elf prefix usr local arm enable languages c ada disable werror f Construcci n e instalaci n make make install Con estos pasos el compilador queda perfectamente generado El entorno quedar instalado en la ruta dada por el par metro prefix usr local arm y generar ejecutables para la arquitectura dada en target ejecutables para ARM en formato ELF Los comandos del compilador cruzado son similares y aceptan los mismos par metros que los compiladores nativos habituales Estos son los que m s nos interesan 1 arm elf gcc 4 4 4 compilador GCC cruzado Se recomienda no usar la versi n arm elf gcc que tambi n se genera pero provoca numerosos errores en la compilaci n Tampoco debe compilarse directamente con esta utilidad para generar ejecutables deben generarse objetos que despu s ser n ensamblados con otra utilidad Debe usarse esta utilidad para traducir tanto c digo C como Ada a c digo objeto 2 arm elf as ensamblador cruzado No es estrictamente necesario 3 arm elf Id linker cruzado Necesario para traducir el c digo objeto C a c digo m quina 4 arm elf gnatmake compilador de c digo Ada No usarlo usar en su lugar las utilidades anteriores junto con el inker propio de Ada Septiembre 2010 106 Migraci n del sistema operativo de tiempo real MaRTE OS al microp
48. d data available and retry the aborted instruction The application program needs no knowledge of the amount of memory available to it nor is its state in any way affected by the abort After fixing the reason for the abort the handler should execute the following irrespective of the state ARM or Thumb SUBS PC R14_abt 4 for a prefetch abort or SUBS PC R14_abt 8 for a data abort This restores both the PC and the CPSR and retries the aborted instruction 2 12 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL Software Interrupt The software interrupt instruction SWI is used for entering Supervisor mode usually to request a particular supervisor function A SWI handler should return by executing the following irrespective of the state ARM or Thumb MOV PC R14 svc This restores the PC and CPSR and returns to the instruction following the SWI NOTE nFIQ nIRQ ISYNC LOCK BIGEND and ABORT pins exist only in the ARM7TDMI CPU core Undefined Instruction When ARM7TDMI comes across an instruction which it cannot handle it takes the undefined instruction trap This mechanism may be used to extend either the THUMB or ARM instruction set by software emulation After emulating the failed instruction the trap handler should execute the following irrespective of the state ARM or Thumb MOVS PC R14 und This restores the CPSR and returns to the instruction following the undefined instruction Exception
49. de la Universidad de Zaragoza Septiembre 2010 25 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM B 2 El modelo de proceso El ciclo de vida seguido en este proyecto se ajusta a un ciclo en cascada clasico 14 ver figura B 2 1 Este ciclo de vida aboga por la simplicidad y dado que es un proyecto de corta duraci n 4 8 meses es el m s adecuado Figura B 2 1 Ciclo de vida en cascada cl sico Mediante el uso de este ciclo de vida ha sido posible identificar y reparar errores en la misma fase en la que aparecen con lo cual no se incurre en costes extra al identificar errores en una determinada fase del ciclo de desarrollo y tener que realizar modificaciones sobre la anterior La documentaci n y revisi n al final de cada una de las fases ha permitido identificar con facilidad todos los problemas y riesgos que han ido surgiendo facilitando el desarrollo del proyecto En nuestro caso la fase de mantenimiento no existe pero en un futuro es posible que las sucesivas ampliaciones que deban llevarse a cabo en el c digo fuente requieran modificar levemente elementos que han sido resultado de alguna de las otras fases Estas ampliaciones incluyen la migraci n completa de MaRTE OS a ARM incluyendo soporte para tareas o la migraci n a otros procesadores El tiempo en horas de dedicaci n a cada fase del proyecto viene dado en la figura B 2 2 42 Bi An lisis Pruebas 12 B Dise o e E D
50. de la estrategia de implementaci n 22320 Definici n de las operaciones de alto nivel 22330 Definici n de alto nivel de las pruebas finales 22331 Pruebas generales sobre la placa 22332 Pruebas especificas sobre los drivers dise ados 22400 Revisi n del dise o realizado 23000 Fase de implementaci n 23100 Interfaz abstracta con el hardware de MaRTE OS 23200 Drivers para perif ricos 23210 Driver para el controlador de interrupciones 23220 Driver para el reloj de tiempo real 23230 Driver para el temporizador PWM 23300 M dulos auxiliares 23310 Operaciones con a nivel de bit 23320 Operaciones con tiempos 23400 Ficheros de arranque del microcontrolador 23500 Revisi n de la implementaci n Septiembre 2010 29 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM 24000 Fase de pruebas 24100 Implementaci n de las pruebas definidas 24200 Script s auxiliares 24210 Compilaci n autom tica de los fuentes 24220 Compilaci n autom tica de las pruebas 24230 Generaci n de carpetas de trabajo independientes 24300 Verificaci n y validaci n de los resultados de las pruebas 24400 Revisi n de las pruebas realizadas 25000 Gesti n de la configuraci n 25100 Gesti n de la documentaci n 25110 Copias de seguridad semanales a USB 25200 Gesti n del c digo 25210 Copias de seguridad semanales a USB 25220 Control de versiones manual 25300 Impresi n de los elementos a entregar 25400 Preparaci n de la carpeta con l
51. devolviendo como par metro de salida el registro de estado anterior a la deshabilitaci n Bastar con guardar el valor del registro en una variable de salida y sobrescribir posteriormente los bits permiso de servicio de interrupciones IRQ o FIQ La funci n Save Flags realiza lo mismo salvo que no se deshabilitan interrupciones y el registro es devuelvo por la funci n en lugar de como par metro de salida Septiembre 2010 97 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM procedure Restore Flags CP5R in Integer is begin Asm 6 MSR CPSR 0 No Output Operands Integer Asm Input r CPSR Volatile gt True end Restore Flags pragma Inline Always Restore Flags La proxima subrutina realiza la operaci n inversa restaura el registro de estado con un par metro de entrada La operaci n es trivial basta con programar el c digo maquina que sobrescribe el registro con el valor de entrada La siguiente funci n que aparece es Get Stack Pointer Register y devuelve el valor del puntero a la pila alojado en uno de los registros del procesador Su programaci n est realizada en el fichero pr c unsigned int get esp register unsigned int temp asm volatile Yn mov 50 8 r temp return temp La implementaci n es trivial nicamente se lee el valor del registro y se devuelve Seguidamente aparecen 4 operaciones a nivel de bit las cu
52. efix usr local arm Construcci n e instalaci n make make install Con ello GMP quedar a correctamente instalada en el sistema El significado de las 2 opciones de configuraci n es similar al de las binutils host arm elf en este caso se especifica la arquitectura en la que esta librer a se ejecutar no confundir con el t rmino host referido a la arquitectura desde la que se compila adem s del formato de fichero objetivo del linkado prefix usr local arm especifica el directorio de destino de la instalaci n Tanto el build como el host son detectados autom ticamente del mismo modo que en el paso anterior Al no estar especificados el script de configuraci n interpretar que ambos coinciden con la m quina actual Paso 2 configuraci n de MPFR MPFR 19 es una biblioteca libre portable y estandarizada escrita en C que se basa en la biblioteca GMP Es necesario incluirla tambi n como parte del entorno de desarrollo debido a Septiembre 2010 104 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM la versi n de GCC utilizada La versi n de MPFR utilizada es la 2 4 2 y sus fuentes pueden descargarse de su pagina principal o del repositorio oficial de GNU Los comandos para instalarla desde el directorio de descarga y descompresi n de los fuentes son los siguientes Configuraci n de MPFR configur host arm elf prefix usr local arm
53. elementos entregados en el DVD adjunto a la memoria El formato de todos los ficheros con texto es pdf a excepci n del fichero README y el de los comprimidos rar Los ficheros entregados son los siguientes La memoria final id ntica la escrita La maquina virtual un fichero comprimido con una m quina virtual Ubuntu que dispone del entorno de desarrollo cruzado ya instalado as como todos los ficheros necesarios para generarlo una carpeta con los ficheros migrados y diversas utilidades para probarlos En el escritorio de dicha m quina hay un fichero README que informa del contenido exacto Para entrar en sesi n usar como nombre de usuario luis y contrase a luisluis Carpeta con fuentes para la instalaci n del entorno cruzado en Linux id ntica a la de la m quina virtual Carpeta con los fuentes migrados id ntica a la de la m quina virtual Carpeta con programas adicionales que deben ser instalados Carpeta con el fichero de configuraci n para la aplicaci n Flash Programmer y un proyecto de prueba para EmbestIDE Los ejecutables obtenidos en Linux deben copiarse a la subcarpeta debug y renombrarse con embest elf Fichero README informaci n general Adem s se realizar una exposici n oral del trabajo realizado en el Proyecto Fin de Carrera que tendr una duraci n m xima de 30 minutos Adicionalmente se proceder a la carga de la memoria del proyecto en el repositorio ZAGUAN
54. hen an interrupt request is generated So there must be the branch instruction to jump each corresponding ISR on it s own address as follows ENTRY b ResetHandler 0x00 b HandlerUndef 0x04 b HandlerSWI 0x08 b HandlerPabort OxOc b HandlerDabort 0x10 b 0x14 b HandlerIRQ 0x18 b HandlerFIQ Oxic ldr pc HandlerEINTO 0x20 ldr pc HandlerEINT 1 Idr pc HandlerEINT2 ldr pc HandlerEINT3 Idr pc HandlerEINT4567 Idr pc HandlerTICK 0x34 b b Idr pc HandlerZDMAO 0x40 Idr pc HandlerZDMA1 ldr pc HandlerBDMAO ldr pc HandlerBDMA1 ldr pc HandlerWDT Idr pc HandlerUERRO1 0x54 b b ldr pc HandlerTIMERO 0x60 Idr pc HandlerTIMER1 ldr pc HandlerTIMER2 ldr pc HandlerTIMER3 ldr pc HandlerTIMER4 ldr pc HandlerTIMER5 0x74 b b ldr pc HandlerURXDO 0x80 Idr pc HandlerURXD1 Idr pc HandlerlIC Idr pc HandlerSIO ldr pc HandlerUTXDO ldr pc HandlerUTXD1 0x94 b b Idr pc HandlerRTC Oxa0d b b b b b b dr pc HandlerADC Oxb4 11 6 ELECTRONICS 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER EXAMPLE FOR NON VECTORED INTERRUPT MODE USING I ISPR In the non vectored interrupt mode the IRQ FIQ handler will move the PC to the corresponding ISR by analyzing _ISPR F_ISPR register HandleXXX addresses hold each corresponding ISR routine start addresses The source code for an IRQ interrupt is as follows ENTRY b ResetHandler b HandlerUndef b HandlerSW
55. iguientes comandos realizan la compilaci n del runtime de GNAT para cada una de las versiones previas de MaRTE OS 5 mkrtsmarteuc march linux mkrtsmarteuc march linux lib 5 mkrtsmarteuc march x86 mproc 1386 pi pii Una vez compilado el runtime de GNAT deber ejecutarse uno de los siguientes comandos dependiendo de la plataforma de ejecuci n de MaRTE OS escogida con el fin de compilar el kernel mkmarte march linux mkmarte march linux lib mkmarte march x86 mproc i386 pi pii Paso 2 Compilaci n de aplicaciones con MaRTE OS Antes de pasar al proceso de compilaci n ser necesario establecer la arquitectura destino para los ejecutables que se generar n Los siguientes comandos establecen las librer as dependientes de la plataforma a utilizar en el proceso de compilaci n de aplicaciones con MaRTE OS 5 msetcurrentarch march linux msetcurrentarch march linux lib msetcurrentarch march x86 mproc i386 pi pii A partir de este punto podr n compilarse aplicaciones en C C y Ada de la misma forma que pod an compilarse aplicaciones nativas con compiladores tradicionales En el subdirectorio examples del directorio principal de marte hay diversos ejemplos que pueden usarse para comprobar la correcta instalaci n del sistema operativo Los siguientes comandos con nombre pr cticamente igual a los tradicionalmente utilizados invocar n los scripts de MaRTE OS ya inclu dos en el PATH
56. le 1 Enable Second alarm enable 0 Disable 1 Enable ELECTRONICS 14 5 REAL TIME CLOCK 53 44 RISC MICROPROCESSOR ALARM SECOND DATA REGISTER ALMSEC ALMSEC 0x01D70054 L R W Alarm second data Register 0x00 0x01D70057 B by byte e a SECDATA 6 4 BCD value for alarm second 0105 ALARM MIN DATA REGISTER ALMMIN ALMMIN 0x01D70058 L R W Alarm minute data Register 0x00 0x01D7005B B by byte mew a MINDATA 6 4 BCD value for alarm minute from 0 to 5 a ao ALARM HOUR DATA REGISTER ALMHOUR ALMHOUR 0x01D7005C L R W Alarm hour data Register 0x00 0x01D7005F B by byte rs HOURDATA 5 4 sa value for alarm hour from 0 to 2 En ao um 14 6 ELECTR NICS 53 44 RISC MICROPROCESSOR REAL TIME CLOCK ALARM DAY DATA REGISTER ALMDAY ALMDAY 0x01D70060 L R W Alarm day data Register 0x01 0x01D70063 B by byte e 7 DAYDATA 5 4 BCD value for alarm day from 0 to 28 29 30 31 from 0 to 3 89 mmoms ALARM MON DATA REGISTER ALMMON ALMMON 0x01D70064 L R W Alarm month data Register 0x01 0x01D70067 B by byte rs MONDATA unna value for alarm month from O to 1 fa ax ALARM YEAR DATA REGISTER ALMYEAR ALMYEAR 0x01D70068 L R W Alarm year data Register 0x00 0x01D7006B B by byte YEARDATA 7 0 BCD value for year 0x00 from 00 to 99 ELECTRONICS 14 7 REAL TIME CLOCK 53 44 RISC MICROPROCE
57. m Handler end Install HW Interrupt Handler pragma Inline Install HW Interrupt Handler La pr xima subrutina es la de instalaci n de interrupciones Una vez se ha comprobado que todos los perif ricos se han inicializado variable Initialized puesta a true una vez invocada la rutina de inicializaci n de la interfaz abstracta se llama al driver del controlador de interrupciones Este driver importa a su vez una funci n hecha en C cuya implementaci n se detalla a continuaci n void install irq handler int vector void handler Trap State unsigned ISR STARTADDRESS 4 vector 5 unsigned handler Aqu aparece una nueva constante que hasta ahora no hab amos detallado ISR STARTADDRESS Esta constante aparece en el fichero ensamblador en el que se definen las rutinas de arranque y los vectores de interrupciones Como se especific en el apartado 4 2 1 cada una de las interrupciones en el modo vectorizado generaba un salto a una direcci n especifica dentro del vector de interrupciones que comienza en la direcci n dada por la etiqueta VECTOR BRANCH en la direcci n 0x20 Cada una de las direcciones debia almacenar un salto configurable a la rutina de interrupci n establecida por el programador Precisamente esa configuraci n de la direcci n destino de salto se realiza a partir de la direcci n _ISR_STARTADDRESS Cuando salta una interrupci n el contador de programa se sob
58. na de Libre Adacore Septiembre 2010 31 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Tras descomprimir los ficheros y ejecutar un script el compilador estar listo para ser utilizado Los pasos a realizar en l nea de comandos son los siguientes S cd SHOME myapps 5 tar zxvf gnat gpl 2008 i686 gnu linux gnu libc2 3 bin tar gz 5 cd gnat gpl 2008 i686 gnu linux gnu libc2 3 bin doinstall Para que la instalaci n no afecte al resto del sistema escoger un directorio de instalaci n distinto al directorio por defecto por ejemplo HOME myapps Despu s de la instalaci n habra que incluir los binarios GNAT delante del PATH con el siguiente comando export PATH SHOME myapps gnat bin S PATH Para no tener que ejecutar este comando cada vez que se entre al sistema es recomendable incluirlo en el script de inicio del shell HOME bashrc Paso 1 Instalaci n de MaRTE OS En el caso de la arquitectura de MaRTE OS objetivo del actual PFC el sistema no est totalmente listo para ser compilado faltan determinadas funcionalidades por migrar Sin embargo para las arquitecturas previas y en un futuro para nuestra arquitectura objetivo el sistema operativo es muy facil de instalar Para instalar el sistema bastar con descargar y descomprimir los ficheros de MaRTE OS descargables desde la p gina de la Universidad de Cantabria y ejecutar un script de instalaci n Deber n
59. ndica que se ha inicializado todo el sistema se pone a True con lo que la inicializaci n queda completa Septiembre 2010 102 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo J Configuracion del compilador cruzado en Linux Este anexo trata la parte del ciclo de vida del tipo de aplicaciones empleado en este proyecto desde que se implementa un programa hasta que se obtiene el ejecutable para el S3C44BOX alojado en el sistema operativo Linux La configuraci n del entorno de desarrollo cruzado desde el cual poder compilar programas desde nuestro sistema operativo Linux no es tan trivial como la obtenci n de compiladores nativos tradicionales Los requisitos a cumplir por el entorno de desarrollo deben ser los siguientes Debe permitir trabajar con programas creados en Linux Debe generar programas ejecutables en el S3C44BOX Permitir compilar y enlazar programas escritos en C o Ada A la hora de ejecutar los pasos para la obtenci n del compilador cruzado se han tomado como base una gran cantidad de tutoriales de Internet pero la principal fuente de referencia ha sido la tesis de m ster de Bartlomiej Horn 10 de la Universidad T cnica de t dz dedicada exclusivamente a la obtenci n de dicho compilador Para mayor simplicidad en los sucesivos pasos que han de realizarse se recomienda encarecidamente que los directorios de descarga y descompresi n de los fuentes reque
60. nding on the type of exception Copies the SPSR back to the CPSR Clears the interrupt disable flags if they were set on entry NOTE An explicit switch back to THUMB state is never needed since restoring the CPSR from the SPSR automatically sets the T bit to the value it held immediately prior to the exception 2 10 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL Exception Entry Exit Summary Table 2 2 summarises the PC value preserved in the relevant R14 on exception entry and the recommended instruction for exiting the exception handler Table 2 2 Exception Entry Exit Return Instruction Previous State ARM R14_x THUMB R14 x MOV PG R14 MOVS PG R14_svc MOVS PC R14_und SUBS PC R14 fiq 4 SUBS PC R14 irq 4 SUBS PC R14_abt 4 SUBS PC R14_abt 8 NA A A A NOTES 1 Where PC is the address of the BL SWI Undefined Instruction fetch which had the prefetch abort 2 Where PC is the address of the instruction which did not get executed since the FIQ or IRQ took priority 3 Where PC is the address of the Load or Store instruction which generated the data abort 4 The value saved in R14_svc upon reset is unpredictable FIQ The FIQ Fast Interrupt Request exception is designed to support a data transfer or channel process and in ARM state has sufficient private registers to remove the need for register saving thus minimising the overhead of context switching FIQ i
61. nt reset 0 No reset 1 Reset CNTSEL 2 0 Merge BCD counters 1 Reserved Separate BCD counters CLKSEL 1 BCD clock select 0 XTAL 1 2 divided clock 1 Reserved XTAL clock only for test BCD count select RTC read write enable 0 Disable 1 Enable If RTC read write feature is enabled The STOP current will be consumed excessively To reduce STOP current this bit should be 0 while not accessing RTC Although this bit is 0 the RTC clock is still alive RTCEN NOTES 1 All RTC registers have to be accessed by byte unit using STRB and LDRB instructions or char type pointer 2 0 When the endian mode is little endian B When the endian mode is Big endian 14 4 ELECTR NICS 53 44 RISC MICROPROCESSOR REAL TIME CLOCK RTC ALARM CONTROL REGISTER RTCALM RTCALM register determines the alarm enable and the alarm time Note that the RTCALM register generates the alarm signal through both ALMINT and PMWKUP in power down mode but only through ALMINT in the normal operation mode RTCALM 0x01D70050 L R W RTC alarm control Register 0x00 0x01D70053 B by byte Alarm global enable 0 Disable 1 Enable RTCALM ALMEN YEAREN Year alarm enable 0 Disable 1 Enable NER ERES MONREN 4 Month alarm enable 0 Disable 1 Enable DAYEN 3 Day alarm enable O Disable 1 Enable HOUREN 2 Hour alarm enable 0 Disable 1 Enable MINEN Minute alarm enable 0 Disab
62. nterrupt number Puesto que son operaciones de bajo nivel han sido realizadas en C Tras comprobar que la interrupci n a habilitar deshabilitar es v lida solo hay 26 fuentes de interrupci n se actuar sobre el bit correspondiente del registro de enmascaramiento definido como una macro bajo rINTMSK poni ndolo a 1 procedure Enable Hardware Interrupt Controller is begin IC IC Enable end Enable Hardware Interrupt Controller pragma Inline Enable Hardware Interrupt Controller El siguiente procedimiento es el de inicializaci n del controlador de interrupciones su implementaci n esta dada en el driver correspondiente que a su vez importa una funci n C void initialize ic unsigned eflags rINTMSK OxOS3FFFFFF rINTMOD amp OxFCO00000 All interrupts are IRQs rINTCON amp OxFFFFFFFS Enable IRQs and IRQ vector mode asm volatile int mrs 0 CPSR n r eflags eflags amp OxFFFFFF3F asm volatile y mar CPSR O n r eflags Esta funci n realiza diversas tareas en el siguiente orden enmascaraci n de todas las interrupciones en el registro de m scara del controlador configuraci n de todas las interrupciones como IRQ en el registro de modo configuraci n de todas las IRQ como vectorizadas y la habilitaci n de IRQ FIQ en el registro de estado del procesador Septiembre 2010 96 Migraci n del sistema operativo de tiempo real MaRTE OS al microp
63. ocumentaci n implementaci n 128 82 Figura B 2 2 Tiempo de dedicaci n total de cada una de las fases del proyecto Septiembre 2010 26 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM B 3 Asunciones dependencias y restricciones La estrategia de desarrollo de este producto Software se ha planeado de acuerdo a las siguientes premisas Se dispone de una placa S3CEV40 sobre la que poder realizar las pruebas en perfecto estado y conectada correctamente a la corriente de alimentaci n La alimentaci n ser suministrada con un conversor anal gico digital a 5v o con un conector USB macho hembra la carga de programas ser necesario disponer de un conector USB adicional macho hembra o un cable Ethernet Ser necesario adem s un emulador JTAG UNETICE el cual deber ser conectado a la placa de desarrollo a trav s de un bus paralelo de 20 pines A trav s de l se realizar la carga de programas Se dispone de un PC el sistema operativo Linux Ubuntu instalado convenientemente refrigerado y conectado a la corriente el ctrica Al menos se necesita 1 GB de memoria RAM La aplicaci n VirtualBox debe estar instalada en el PC B 4 Gesti n de riesgos En la tabla B 4 1 se clasifican los diferentes tipos de riesgo encontrados a lo largo del proyecto y que han amenazado el proceso de desarrollo del mismo La columna riesgo indica cual es la pro
64. on resumes in ARM state ELECTRONICS 2 15 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER OVERVIEW The interrupt controller in 53 44 receives the request from 30 interrupt sources These interrupt sources are provided by internal peripherals such as the DMA controller UARTand SIO etc In these interrupt sources the four external interrupts EINT4 5 6 7 are OR ed to the interrupt controller The UARTO and 1 Error interrupt are OR ed as well The role of the interrupt controller is to ask for the FIQ or IRQ interrupt request to the ARM7TDMI core after making the arbitration process when there are multiple interrupt requests from internal peripherals and external interrupt request pins Originally ARM7TDMI core only permits the FIQ or IRQ interrupt which is the arbitration process based on priority by software For example if you define all interrupt source as IRQ Interrupt Mode Setting and if there are 10 interrupt requests at the same time you can determine the interrupt service priority by reading the interrupt pending register which indicates the type of interrupt request that will occur This kind of interrupt process requires a long interrupt latency until to jump to the exact service routine The 53044 may support this kind of interrupt processing To solve the above mentioned problem S3C44B0X supports a new interrupt processing called vectored interrupt mode which is a general feature of the CISC ty
65. or PWM pulse width modulation The timer control logic changes the output level when the down counter value matches the value of the compare register in the timer control logic Therefore the compare register determines the turn on time or turn off time of an PWM output FEATURES Six 16 bit timers with DMA based or interrupt based operation Three 8 bit prescalers amp Two 5 bit dividers amp One 4 bit divider Programmable duty control of output waveform PWM Auto reload mode or one shot pulse mode Dead zone generator ELECTRONICS 9 1 PWM TIMER 53 44 RISC MICROPROCESSOR Dead Zone Generator 8 Bit Prescaler TONES Clock Divider 8 Bit Prescaler Clock Divider 8 Bit Prescaler Clock TOUTS No Pin Divider ogic Figure 9 1 16 bit PWM Timer Block Diagram 9 2 ELECTRONICS 53 44 RISC MICROPROCESSOR PWM TIMER PWM TIMER OPERATION PRESCALER amp DIVIDER An 8 bit prescaler and an independent 4 bit divider make the following output frequencies 4 bit divider settings minimum resolution maximum resolution maximum interval prescaler 1 prescaler 255 TCNTBn 65535 1 2 MCLK 66 MHz 0 030 us 33 0 MHz 7 75 us 58 6 KHz 1 4 MCLK 66 MHz 0 060 us 16 5 MHz 0 485 us 2 06 MHz 125 us 7 32 KHz BASIC TIMER OPERATION dob Oa AA TCNTBn 3 TCNTBn 2 TCMPBn 1 TCMPBn 0 Manual Update 1 Manual Update 0 Auto reload 1 Auto reload 1
66. os elementos a enviar 26000 Documentaci n 26100 Memoria del proyecto 26200 Anexos 26210 Estructura de los ficheros migrados 26220 Plan de Gesti n del Proyecto Software 26230 Instalaci n de MaRTE OS y compilaci n de aplicaciones 26240 Resumen del repertorio de instrucciones del ARM7tdmi 26250 Registros principales y excepciones del ARM7tdmi 26260 Documentaci n especifica de los perif ricos utilizados 26270 Aspectos de bajo nivel de la implementaci n 26280 Configuraci n del compilador cruzado en Linux y carga de aplicaciones desde Windows Septiembre 2010 30 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo C Instalaci n de MaRTE OS y compilaci n de aplicaciones Este anexo contiene un extracto traducido y modificado del manual de instalaci n original de MaRTE OS alojado en la p gina de la Universidad de Cantabria Los requerimientos de instalaci n de MaRTE OS son los siguientes Requerimientos del Host requerido para las 2 implementaciones de MaRTE OS para Linux la de X86 y la de ARM Sistema operativo Linux Compilador GNAT nativo o cruzado seg n el caso Sistema operativo Windows con EmbestIDE para realizar la carga de los ejecutables generados en Linux solo para ARM Requerimientos del Target en caso de implementaci n para x86 PC i386 o superior Tarjeta Ethernet para carga remota opcional e Puerto serie para depuraci n opcional
67. pe micro controller to reduce the interrupt latency In other words the hardware inside the S3C44BOX interrupt controller provides the interrupt service vector directly When the multiple interrupt sources request interrupts the hardware priority logic determines which interrupt should be serviced At same time this hardware logic applies the jump instruction of the vector table to Ox18 or Ox1c which performs the jump to the corresponding service routine Compared with the previous software method it will reduce the interrupt latency dramatically INTERRUPT CONTROLLER OPERATION F bit and I bit of PSR program status register If the F bit of PSR program status register in ARM7TDMI CPU is set to 1 the CPU does not accept the FIQ fast interrupt request from the interrupt controller If I bit of PSR program status register in ARM7TDMI CPU is set 0 1 the CPU does not accept the IRQ interrupt request from the interrupt controller So to enable the interrupt reception the F bit or I bit of PSR has to be cleared to 0 and also the corresponding bit of INTMSK has to be cleared to 0 Interrupt Mode ARM7TDMI has 2 types of interrupt mode FIQ or IRQ All the interrupt sources determine the mode of interrupt to be used at interrupt request Interrupt Pending Register Indicates whether or not an interrupt request is pending When a pending bit is set the interrupt service routine starts whenever the I flag or F flag is cleared to 0 Inter
68. r PWM establecido en 65536 ticks por el tamafio de los registros y su frecuencia 16113 ticks por segundo function HWTime To Duration Th in HWTime return Duration pragma Inline HWTime To Duration function Duration To HWTime D in Duration return HiTime pragma Inline Duration To_HWTime Las funciones de conversi n de tipos entre Duration y HWTime no merece la pena destacarlas puesto que no se han modificado son independientes del hardware y no pueden optimizarse con c digo m quina ARM function Get HWClock Frequency return HUTime Ticks per second pragma Inline Get HWClock Frequency function CPU Frequency return HWTime Ticks per second Otras 2 funciones b sicas que aparecen son las de lectura de la frecuencia del sistema y de la CPU Esto se implementa mediante declaraci n de 2 variables HWT HZ ticks por segundo asignado a 128 en la inicializaci n de la interfaz abstracta y CPU Freq frecuencia del procesador asignado a 66MHz en la inicializaci n de la interfaz abstracta Estas funciones nicamente devuelven el valor de dichas variables procedure Program Timer Timer in HW Timers Interval in HWTimnme Next Activation out HWTime is begin pragma Assert Initialized PUM Program Timer Interval PUM PUM HZ HUT HZ Next Activation RTC Get Time In Ticks Interval end Program Timer El siguiente procedimiento es el encargado de gestionar la temporizaci n hardware Cuando
69. re are two types of abort e Prefetch abort occurs during an instruction prefetch e Data abort occurs during a data access If a prefetch abort occurs the prefetched instruction is marked as invalid but the exception will not be taken until the instruction reaches the head of the pipeline If the instruction is not executed for example because a branch occurs while it is in the pipeline the abort does not take place If a data abort occurs the action taken depends on the instruction type Single data transfer instructions LDR STR write back modified base registers the Abort handler must be aware of this e swap instruction SWP is aborted as though it had not been executed Block data transfer instructions LDM STM complete If write back is set the base is updated If the instruction would have overwritten the base with data ie it has the base in the transfer list the overwriting is prevented All register overwriting is prevented after an abort is indicated which means in particular that R15 always the last register to be transferred is preserved in an aborted LDM instruction The abort mechanism allows the implementation of a demand paged virtual memory system In such a system the processor is allowed to generate arbitrary addresses When the data at an address is unavailable the Memory Management Unit MMU signals an abort The abort handler must then work out the cause of the abort make the requeste
70. recci n 0 que coincide con la llamada a la rutina de reseteo inicializaci n En el manual on ine de EmbestIDE 11 se muestra como cargar en la placa de desarrollo un ejecutable Septiembre 2010 24 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo B Plan de Gestion del Proyecto Software Este anexo es un resumen del Plan de Gesti n del Proyecto Software empleado en el desarrollo de este Proyecto Fin de Carrera B 1 Elementos entregados Los elementos entregados como resultado de este Proyecto se clasifican en 2 grandes grupos la entrega escrita y la entrega en formato electr nico La entrega escrita la componen todos los documentos impresos en papel La propuesta del proyecto contiene los objetivos que el proyectando se compromete a completar ademas de informaci n personal Este documento fue entregado en cuanto el estado del proyecto permitid establecer un hito alcanzable El informe del director en espa ol e ingl s eval a y comenta brevemente el trabajo realizado por el proyectando La ficha de dep sito en espa ol e ingles incluye los elementos necesarios para poder clasificar el proyecto en la biblioteca adem s de un resumen de los objetivos y las conclusiones del mismo La memoria final recoge el trabajo realizado en este Proyecto Fin de Carrera Se seguir n las indicaciones de la gu a de estilo La entrega en formato electr nico la componen los
71. register values can also be compared against or added to Lo register values with the CMP and ADD instructions For more information refer to Figure 3 34 THE PROGRAM STATUS REGISTERS The ARM7TDMI contains a Current Program Status Register CPSR plus five Saved Program Status Registers SPSRs for use by exception handlers These register s functions are information about the most recently performed ALU operation e Control the enabling and disabling of interrupts e Set the processor operating mode The arrangement of bits is shown in Figure 2 6 Condition Code Flags Reserved Control Bits 7 6 5 4 3 2 1 0 Tr Joo eo 11 30 29 28 27 26 25 24 23 Overflow Mode bits Carry Borrow Extend State bit Zero FIQ disable Negative Less Than IRQ disable Figure 2 6 Program Status Register Format ELECTRONICS 2 7 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR The Condition Code Flags The N Z C and V bits are the condition code flags These may be changed as a result of arithmetic and logical operations and may be tested to determine whether an instruction should be executed In ARM state all instructions may be executed conditionally see Table 3 2 for details In THUMB state only the Branch instruction is capable of conditional execution see Figure 3 46 for details The Control Bits The bottom 8 bits of a PSR incorporating I F T and M 4 0 are known collectively as the control bits These will be
72. rer as de la arquitectura seleccionada para MaRTE OS gnat rts paquetes de modificados para soportar las arquitecturas previas para las que est implementado el soporte de MaRTE OS Linux Linux lib y X86 marte ug html Gu a de usuario de MaRTE OS minstall script de instalaci n de MaRTE OS misc algunos paquetes utiles objs directorio principal de ficheros objeto y bibliotecas a partir del cual hay un subdirectorio por cada arquitectura del soporte previo de MaRTE OS posix5 paquetes de POSIX5 basados en la implementaci n Florist 13 Sll bibliotecas de listas usadas por el n cleo de MaRTE OS tasks inspector herramienta que permite analizar gr ficamente el flujo de ejecuci n de una aplicaci n utils herramientas utiles para compilaci n de programas x86 arch parte del kernel dependiente del hardware que ofrece soporte para ejecutar aplicaciones con MaRTE OS en una arquitectura PC 386 o superior linux arch parte del kernel dependiente del hardware que ofrece soporte para lanzamiento de MaRTE OS como proceso de Linux linux lib arch parte del kernel dependiente del hardware que ofrece soporte para lanzamiento de MaRTE OS como proceso de Linux permitiendo el acceso directo a la biblioteca Glibc Permite acceder por tanto al sistema de ficheros tests tests para evaluaci n de MaRTE OS lang support bibliotecas para soporte de otros idiomas Septiembre 2
73. rescribe con una direcci n especifica dentro del vector de interrupciones que a su vez lee la direcci n espec fica de salto de una posici n espec fica del vector _ISR_STARTADDRESS las direcciones de las rutinas de interrupci n comienzan en _ISR_STARTADDRESS 32 y se incrementan de 4 en 4 El contenido de esta ltima posici n es la que es configurado en la rutina escrita en C la cual asigna a dicha direcci n el inicio de la rutina dada en el par metro handler Ver figura 1 1 YECTOR_BRANCH _ISR_STARTADDRESS 0x20 b EINTO handler 0x24 b EINT1 handler 0x28 b EINT2 handler Ox0C7FFFO0 32 0x0C7FFF00 36 Figura 1 1 Correspondencia entre vector de interrupciones y direcciones de salto Ox0C7FFFOO Septiembre 2010 94 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Las 2 subrutinas siguientes tienen que ver con la deshabilitaci n o habilitaci n de todas las interrupciones Se han implementado en el paquete marte hal processor_registers procedure CLI is Disable IRQ and FIQ interrupts begin Asm MRS RO CPSR amp ORR RO RO O0xOO00000CO0 r amp MSR CPSR RO i No Output Operands No Input Operands Volatile gt True end CLI pragma Inline Always CLI procedure STI is Enable IRQ and FIQ interrupts begin Asm MRS RO CPSR amp BIC RO RO 40 000000 0 5 MSR CPSR RO No Output Operands No Input Operands
74. ridos sean siempre el mismo Partiendo del sistema operativo Linux utilizado distribuci n Ubuntu versi n 10 04 los pasos a realizar serian los siguientes Paso 0 configuraci n de binutils Las binutils 16 son un conjunto de utilidades para manipular ficheros de c digo objeto Las herramientas proporcionadas son innumerables pero en nuestro caso destacan el linker Id el objdump herramienta que nos permite ver el contenido de un objeto en formato ensamblador muy Util para depurar y el readelf similar a objdump pero muestra adem s tablas de objetos ficheros empleados espacio usado etc El conjunto de utilidades binarias puede descargarse del repositorio oficial del proyecto GNU 17 La versi n de los fuentes utilizados es la 2 20 1 Los comandos a utilizar para su correcta configuraci n desde el directorio de descarga y descompresi n de los fuentes son los siguientes Creaci n de un directorio temporal para los fuentes compilados mkdir binutils build cd binutils build Configuraci n de las binutils binutils 2 20 1 configur target arm elf disable werror prefix usr local arm Construcci n e instalaci n Septiembre 2010 103 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM make make install Con estos comandos las binutils estar n perfectamente configuradas El significado de las opciones de configuraci n u
75. rocesador ARM arm elf gnatbind binder cruzado de Ada arm elf gnatlink inker cruzado de Ada arm elf readelf utilidad para volcar el contenido de ejecutables ELF Contiene secciones tablas de simbolos etc 8 arm elf objdump mas simple que el anterior permite volcar el contenido de un ejecutable en ensamblador para posible depuraci n Nou La compilaci n de un fichero C o Ada simple se realizaria de la siguiente manera FICHERO C Generamos c digo objeto arm elf gcc 4 4 4 c hola ARM c Linkamos arm elf ld o hola ARM elf opciones hola ARM o E Leemos el contenido del ejecutable ELF arm elf readelf a hola ARM elf E Fa Volcamos el ensamblador del contenido del ejecutable arm elf objdump S hola_ARM elf FICHERO Ada Generamos c digo objeto arm elf gcc 4 4 4 c hola ARM adb Encuadernamos arm elf gnatbind x hola ARM ali Linkamos arm elf gnatlink opciones hola ARM ali Septiembre 2010 107 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Bibliografia 1 J L Villarroel C Sagues y J D Tardos Pr cticas actuales de la asignatura sistemas empotrados http webdiis unizar es joseluis STR_PR pdf 2 P gina oficial de MaRTE OS http marte unican es 3 GNU General Public License http www gnu org licenses gpl html 4 Michael Gonz
76. rocesador ARM function re Interrupts Enabled return Boolean renames Processor Registers re Interrupts Enabled pragma Inline ire Interrupts Enabled La ultima subrutina referente al controlador de interrupciones es la consulta de si estas estan o no habilitadas Se realiza una llamada directa a la biblioteca de manejo de registros function Are Interrupts Enabled return Boolean is CPSR Unsigned 32 begin Asm amp MRS 3D CPSR Unsigned 32 Asm Output r CPSR No Input Operands Volatile gt True return Shift Right CPSR mod 2 0 end re Interrupts Enabled nicamente ser necesario consultar que el bit de habilitaci n de interrupciones FIQ del registro de estados valga 0 habilitadas o 1 deshabilitadas Posteriormente aparecen en la interfaz 3 subrutinas implementadas en la biblioteca de manejo de registros del procesador Save Flags And Disable Interrupts Save Flags y Restore Flags procedure Save Flags nd Disable Interrupts CPSR out Integer is begin Asm amp MRS 50 CPSR Integer sm Output r CPSR No Input Operands Volatile gt True Asm RO 50 0x000000C0 g MSR CPSR RO No Output Operands Integer Asm Input r CPSR Volatile gt True end Save Flags nd Disable Interrupts pragma Inline Always Save Flags nd Disable Interrupts La siguiente subrutina consiste en la deshabilitaci n de interrupciones
77. ros implementados puede verse en la figura A 2 Placa de desarrollo S3CEV40 A 2 Estructura de los ficheros implementados A 1 Estructura de los proyectos Una vez ejecutamos el script newProyect se genera una carpeta cuyo nombre es el primer parametro de la invocaci n con el siguiente contenido Examples carpeta con fuentes para las pruebas Include Lib carpeta con bibliotecas necesarias para la compilaci n Link carpeta con los ficheros para el linker Obj carpeta con los ficheros objeto de la interfaz abstracta con el hardware Src carpeta con programas C y Ada vac os Startup contiene los ficheros objeto de las rutinas de inicializaci n reseteo y definici n del vector de interrupciones Diversos scripts compileTestC ram compila la prueba en C para el visualizador de 8 segmentos para cargar en la RAM compileTestAda ram idem que el anterior pero para la prueba en Ada compileAda acepta un par metro que debe ser el nombre del fichero de cualquiera de las otras 4 pruebas implementadas eliminando la extensi n Se generar n 2 ficheros como resultado de la compilaci n startup flash para cargar en la Flash con la definici n del vector de interrupciones y dem s rutinas est ticas y otro que ser el resultado de concatenar el par metro introducido con ram para cargar en la RAM con el programa a ejecutar El programa debe comenzar a ejecutarse siempre desde la di
78. rupt Pending Register is a read only register so the service routine must clear the pending condition by writing a 1 to I ISPC or F ISPC Interrupt Mask Register Indicates that an interrupt has been disabled if the corresponding mask bit is 1 If an interrupt mask bit of INTMSK is 0 the interrupt will be serviced normally If the corresponding mask bit is 1 and the interrupt is generated the pending bit will be set If the global mask bit is set to 1 the interrupt pending bit will be set but all interrupts will not be serviced ELECTRONICS 11 1 INTERRUPT CONTROLLER 53 44 RISC MICROPROCESSOR INTERRUPT SOURCES Among 30 interrupt sources 26 sources are provided for the interrupt controller Four external interrupt EINT4 5 6 7 requests are ORed to provide a single interrupt source to the interrupt controller and two UART error interrupts UERRORO 1 are the same configuration Desenpnons Waster Group saven mate arc amina wc wotommm NOTE EINT4 EINT5 EINT6 and EINT7 share the same interrupt request line Therefore the ISR interrupt service routine will discriminate these four interrupt sources by reading the EXTINPND 3 0 register EXTINPND 3 0 must be cleared by writing a 1 in the ISR after the corresponding ISR has been completed 11 2 ELECTRONICS 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER INTERRUPT PRIORITY GENERATING BLOCK There is the interrupt priority generating
79. rupt source The interrupt controller generates the machine code for branching to the vector address of each interrupt source For example If EINTO is IRQ the interrupt controller must generate the branch instruction which branches from 0x18 to 0x20 So the interrupt controller generates the machine code 0xea000000 The user program code must locate the branch instruction which branches to the corresponding ISR interrupt service routine at each vector address The machine code branch instruction at the corresponding vector address is calculated as follows Branch Instruction machine code for vectored interrupt mode 0xea000000 lt destination address gt vector address gt 0x8 gt gt 2 For example if Timer 0 interrupt to be processed in vector interrupt mode the branch instruction which jumps to the ISR is located at 0x00000060 The ISR start address is 0x10000 The following 32bit machine code is written at 0x00000060 machine code 20x00000060 0xea000000 0x10000 0x60 0x8 gt gt 2 0xea000000 0x3fe6 0xea003fe6 The machine code is usually generated automatically by the assembler and therefore the machine code does not have to be calculated as above 11 4 ELECTRONICS 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER ELECTRONICS 11 5 INTERRUPT CONTROLLER 53 44 RISC MICROPROCESSOR EXAMPLE OF VECTORED INTERRUPT MODE In the vectored interrupt mode CPU will branch to each interrupt address w
80. s externally generated by taking the nFIQ input LOW This input can except either synchronous or asynchronous transitions depending on the state of the ISYNC input signal When ISYNC is LOW nFIQ and nIRQ are considered asynchronous and a cycle delay for synchronization is incurred before the interrupt can affect the processor flow Irrespective of whether the exception was entered from ARM or Thumb state a FIQ handler should leave the interrupt by executing SUBS PC R14 fiq t4 FIQ may be disabled by setting the CPSR s F flag but note that this is not possible from User mode If the F flag is clear ARM7TDMI checks for a LOW level on the output of the FIQ synchroniser at the end of each instruction ELECTRONICS 2 11 PROGRAMMER S MODEL 53 44 RISC MICROPROCESSOR IRQ The IRQ Interrupt Request exception is a normal interrupt caused by a LOW level on the nIRQ input IRQ has a lower priority than FIQ and is masked out when a FIQ sequence is entered It may be disabled at any time by setting the bit in the CPSR though this can only be done from a privileged non User mode Irrespective of whether the exception was entered from ARM or Thumb state an IRQ handler should return from the interrupt by executing SUBS PC R14 1 4 Abort An abort indicates that the current memory access cannot be completed It can be signalled by the external ABORT input ARM7TDMI checks for the abort exception during memory access cycles The
81. sentaci n ante tribunal 12100 Borrador 12200 Ensayos 12300 Realizaci n 20000 Desarrollo del proyecto Septiembre 2010 28 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM 21000 Fase de an lisis 21100 Sistema operativo MaRTE OS 21110 Estudio de la documentaci n Web 21120 Pruebas iniciales para comprender su funcionamiento 21200 Placa de desarrollo S3CEV40 21210 Estudio de la documentaci n del fabricante de la placa 21220 Pruebas iniciales para verificar su funcionamiento 21300 Entorno de desarrollo cruzado 21310 Estudio de la documentaci n Web 21320 Estudio de la documentaci n del fabricante de la placa 21400 Propuesta del PFC 21410 Especificaci n de objetivos 21420 Borrador de la propuesta 21430 Reuni n con el tutor 21440 Propuesta definitiva 21500 Revisi n del proceso de an lisis 22000 Fase de dise o 22100 Entorno de desarrollo cruzado 22110 Entorno cruzado en Ubuntu 22111 Configuraci n del entorno 22122 Pruebas para verificaci n 22220 Entorno de carga depuraci n en Windows 22221 Especificaci n de la carga de programas 22200 Placa de desarrollo S3CEV40 22210 Elecci n de los perif ricos a utilizar 22220 Especificaci n de drivers 22211 Especificaci n del driver para el controlador de interrupciones 22212 Especificaci n del driver para el reloj de tiempo real 22213 Especificaci n del driver para el temporizador PWM 22300 Sistema operativo MaRTE OS 22310 Especificaci n
82. service pending register 0x00000000 11 10 ELECTRONICS 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER IRQ FIQ INTERRUPT SERVICE PENDING CLEAR REGISTER I ISPC F ISPC _ISPC F_ISPC clears the interrupt pending bit INTPND _ISPC F_ISPC also informs the interrupt controller of the end of corresponding ISR interrupt service routine At the end of ISR interrupt service routine the corresponding pending bit must be cleared The bit of INTPND bit is cleared to zero by writing 1 on _ISPC F_ISPC This feature reduces the code size to clear the INTPND The corresponding INTPND bit is cleared automatically by _ISPC F_ISPC INTPND register can not be cleared directly NOTE To clear the _ISPC F_ISPC the following two rules has to be obeyed 1 The _ISPC F_ISPC registers are accessed only once in ISR interrupt service routine 2 The pending bit in I ISPR INTPND register should be cleared by writing ISPC register If these two rules are not followed _ISPR and INTPND register may be 0 although the interrupt has been requested ISPC 0x01E00024 IRQ interrupt service pending clear register F ISPC 0x01E0003C FIQ interrupt service pending clear register ELECTRONICS 11 11 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo F El controlador de interrupciones del S3C44BOX Este anexo es un extracto del cap tulo 11 INTERRUPT CONTROLLER del manual original del microcontrolador T
83. ssor load Load multiple registers Stack manipulation Pop Load register from memory Rd address d Move CPU register to coprocessor cRn rRn lt op gt cRm register Multiply Accumulate Rd Rm x Rs Rn Move register or constant Rd Op2 3 2 ELECTRONICS 53 44 RISC MICROPROCESSOR ARM INSTRUCTION SET Table 3 1 The ARM Instruction Set Continued Move from coprocessor register to Rn cRn lt op gt cRm CPU register omn frd moroe O RSB SBC STC STM Stack manipulation Push STR SWI SWP TEQ ELECTRONICS 3 3 ARM INSTRUCTION SET 53 44 RISC MICROPROCESSOR THE CONDITION FIELD In ARM state all instructions are conditionally executed according to the state of the CPSR condition codes and the instruction s condition field This field bits 31 28 determines the circumstances under which an instruction is to be executed If the state of the C N Z and V flags fulfils the conditions encoded by the field the instruction is executed otherwise it is ignored There are sixteen possible conditions each represented by a two character suffix that can be appended to the instruction s mnemonic For example a Branch B in assembly language becomes BEQ for Branch if Equal which means the Branch will only be taken if the Z flag is set In practice fifteen different conditions may be used these are listed in Table 3 2 The sixteenth 1111 is reserved and must not be used In
84. st If the global mask bit is set to 1 all interrupt requests are not serviced and the INTPND register is set to 1 If the INTMSK is changed in ISR interrupt service routine and the vectored interrupt is used an INTMSK bit can not mask an interrupt event which had been latched in INTPND before the INTMSK bit was set To clear this problem clear the corresponding pending bit INTPND after changing INTMSK The 26 interrupt sources and global mask bit are summarized as follows INTMSK 0x01E0000C R W Determines which interrupt source is masked The masked interrupt source will be serviced 0 Interrupt service is available 1 Interrupt service is masked IMPORTANT NOTES 1 INTMSK register can be masked only when it is sure that the corresponding interrupt does not be requested If your application should mask any interrupt mask bit INTMSK just when the corresponding interrupt is issued please contact our FAE field application engineer 2 If you need that all interrupt is masked we recommend that I F bits in CPSR are set using MRS MSR instructions The I F bit in CPSR can be masked even when any interrupt is issued ELECTRONICS 11 9 INTERRUPT CONTROLLER 53 44 RISC MICROPROCESSOR IRQ VECTORED MODE REGISTERS The priority generating block consists of five units 1 master unit and 4 slave units Each slave priority generating unit manages six interrupt sources The master priority generating unit manages
85. t is generated it will be set to 1 The interrupt service routine must then clear the pending condition by writing 1 to the corresponding bit of I ISPC F_ISPC Although several interrupt sources generate requests simultaneously the INTPND will indicate all interrupt sources that generate an interrupt request Even if the interrupt source is masked by INTMSK the corresponding pending bit can be set to 1 INTPND 0x01E00004 Indicates the interrupt request status 0x0000000 0 The interrupt has not been requested 1 The interrupt source has asserted the interrupt request INTERRUPT MODE REGISTER INTMOD Each of the 26 bits in the interrupt mode register INTMOD corresponds to an interrupt source When the interrupt mode bit for each source is set to 1 the interrupt is processed by the ARM7TDMI core in the FIQ fast interrupt mode Otherwise it is processed in the IRQ mode normal interrupt The 26 interrupt sources are summarized as follows INTMOD 0x01E00008 R W Interrupt mode Register 0x0000000 0 IRQ mode 1 FIQ mode 11 8 ELECTRONICS 53 44 RISC MICROPROCESSOR INTERRUPT CONTROLLER INTERRUPT MASK REGISTER INTMSK Each of the 26 bits except the global mask bit in the interrupt mask register INTMSK corresponds to an interrupt source When a source interrupt mask bit is 1 and the corresponding interrupt event occurs the interrupt is not serviced by the CPU If the mask bit is 0 the interrupt is serviced upon a reque
86. te for Timer 3 update note 0 No operation 1 Update TCNTB3 TCMPB3 Timer 3 start stop 16 This bit determines start stop for Timer 3 0 Stop 1 Start for Timer 3 Timer 2 auto reload 15 This bit determines auto reload on off for Timer 2 on off 0 One shot 1 Interval mode auto reload Timer 2 output 14 bit determines output inverter on off for Timer 2 inverter on off Inverter off 1 Inverter on for TOUT2 Timer 2 manual 13 This bit determines the manual update for Timer 2 update note 0 No operation 1 Update TCNTB2 TCMPB2 Timer 2 start stop 12 This bit determines start stop for Timer 2 0 Stop 1 Start for Timer 2 NOTE This bit has to be cleared at next writing ELECTRONICS 9 11 PWM TIMER 53 44 RISC MICROPROCESSOR TIMER CONTROL REGISTER TCON Continued Timer 1 auto reload 11 This bit determines the auto reload on off for Timer1 on off 0 One shot 1 Interval mode auto reload Timer 1 output 10 4 bit determines the output inverter on off for Timer inverter on off Inverter off 1 Inverter on for TOUT1 Timer 1 manual This bit determines the manual update for Timer 1 update note 0 operation 1 Update TCNTB1 TCMPB1 Timer 1 start stop This bit determines start stop for Timer 1 0 Stop 1 Start for Timer 1 Dead zone enable 4 This bit determines the dead zone operation 0 Disable 1 Enable Timer 0 auto reload 3 This bit determines auto reload on off for
87. tent generar el compilador realizando todas ellas y el resultado no fue exitoso daban errores de ausencia de bibliotecas entre otros Los cambios a realizar en los fuentes son los siguientes 1 Las modificaciones del apartado 5 2 de la tesis C Files pero tan solo las que se refieren a Adaint c y Adaint h Tres funciones deben suprimirse as como el include de dirent h y debe comentarse el contenido de las especificadas 2 Lo referente al apartado 5 4 de la tesis Algunas funciones provocan un error fatal de compilaci n por lo tanto ser necesario comentar su contenido o poner c digo in til para proseguir la compilaci n Son funciones no estrictamente necesarias relacionadas con c lculo matem tico muy avanzado n meros complejos 3 Es posible que en el proceso de compilaci n de los fuentes de GCC GNAT Newlib salgan otros errores por ejemplo el fichero s oscons ads generado en tiempo de compilaci n Sin embargo solo son errores sint cticos o warnings que el compilador trata como errores muy intuitivos de arreglar Estos errores se producen debido a que los scripts empleados para compilar los fuentes GCC GNAT Newlib hacen que el compilador usado sea case sensitive Por lo tanto algunas constantes como por ejemplo la constante NUL escrita a veces como Nul generan errores sint cticos Una vez hecho esto podemos configurar el compilador Deber n ejecutarse los siguientes comandos desde el directorio de descarga y des
88. the absence of a suffix the condition field of most instructions is set to Always suffix AL This means the instruction will always be executed regardless of the CPSR condition codes Table 3 2 Condition Code Summary Fas ignored 3 4 ELECTRONICS Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Anexo E Registros principales y excepciones del ARM7tdmi Este anexo es un extracto del manual original del microcontrolador y corresponde al cap tulo 4 PROGRAMMER S MODEL del mismo Septiembre 2010 39 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL OVERVIEW S3C44B0X has been developed using the advanced ARM7TDMI core which has been designed by Advanced RISC Machines Ltd PROCESSOR OPERATING STATES From the programmer s point of view the ARM7TDMI can be in one of two states e ARM state which executes 32 bit word aligned ARM instructions e THUMB state which can execute 16 bit halfword aligned THUMB instructions In this state the PC uses bit 1 to select between alternate halfwords NOTE Transition between these two states does not affect the processor mode or the contents of the registers SWITCHING STATE Entering THUMB State Entry into THUMB state can be achieved by executing a BX instruction with the state bit bit 0 set in the operand register Transition to THUMB state will also occur automatically on return from an exception IRQ F
89. tiempo real MaRTE OS al microprocesador ARM 18 The GNU Multiple Precision Arithmetic Library http gmplib org 19 The MPFR Library http www mpfr org 20 The Newlib Homepage http sourceware org newlib Septiembre 2010 109 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM Indice de figuras Placa de desarrollo 53 40 cece eee 4 Portabilidad ofrecida por POSIX nnn 7 Modelo de MaRTE OS para aplicaciones escritas en C y Ada 8 Elementos que intervienen en la compilaci n 11 Fuentes de interrupci n del controlador de 13 Tratamiento de interrupciones no vectorizado y vectorizado 14 Diagrama de bloques del reloj de tiempo 15 Diagrama de bloques del temporizador 16 Diagrama de estados para las pruebas de habilitaci n deshabilitaci n de 24 Estructura de los ficheros 25 Ciclo de vida en cascada d sico vasen ee cr ER ena s 27 Tiempo de dedicaci n total de cada una de las fases del proyecto 27 Correspondencia en
90. tilizadas se muestra a continuaci n target arm elf especifica la arquitectura objetivo en la que se ejecutar n los futuros programas as como el inkado en ejecutables ELF disable werror evita que los warnings generados en el momento de la construcci n se conviertan en errores prefix usr local arm especifica el directorio de destino de la instalaci n Tanto el build m quina desde la que se genera el entorno de desarrollo como el host m quina desde la que se utilizar el entorno de desarrollo son detectados autom ticamente Al no estar especificados el script de configuraci n interpretar que ambos coinciden con la m quina actual Paso 1 configuraci n de GMP GMP 18 GNU Multiple Precision Arithmetic Library no es m s que una biblioteca libre en C que ofrece funciones de operaciones entre n meros enteros reales o de coma flotante en principio con una precisi n arbitraria en realidad la precisi n m xima es la que permite la m quina en la que se aloja la biblioteca Debido a la versi n de GCC utilizada es necesario incluir esta librer a como parte del entorno de desarrollo versiones anteriores no lo requieren La versi n de GMP utilizada es la 4 3 2 y puede descargarse de su p gina principal o del repositorio oficial de GNU Los comandos para instalarla desde el directorio de descarga y descompresi n de los fuentes son los siguientes Configuraci n de GMP configur host arm elf pr
91. tre vector de interrupciones y direcciones de salto 40 Septiembre 2010 110
92. uando se ejecuten los scripts asociados a la construcci n de GCC GNAT Unicamente ser necesario linkar la librer a desde un directorio del modo especificado en el siguiente paso Paso 4 configuraci n de los fuentes GCC GNAT Una vez configurado todo lo anterior podr procederse a la construcci n del entorno de desarrollo cruzado Ser necesario descargar tanto los fuentes GCC con los que puede construirse un compilador cruzado de C como las extensiones para Ada GNAT con los que poder a adir Ada al soporte de lenguajes del compilador La versi n de GCC GNAT utilizada es la 4 4 4 y los fuentes pueden descargarse del repositorio oficial de GNU Una vez descomprimidos estos fuentes ser necesario descomprimir los de la Newlib y linkarlos desde el directorio de descompresi n de GCC con el fin de que la librer a est ndar se detecte en el proceso de configuraci n Esto puede hacerse con los siguientes comandos que deben ser lanzados desde el directorio de descompresi n de GCC GNAT Newlib cd gcc 4 4 4 In s newlib 1 18 0 newlib Septiembre 2010 105 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM cd Previamente a la configuraci n del compilador sera necesario realizar algunas modificaciones en sus fuentes ya que existen algunos bugs en los mismos Estas modificaciones han sido extraidas de la tesis de master usada como referencia pero alteradas ya que inicialmente se in
93. ubrutinas implementadas en la migraci n parcial en la que consiste este proyecto as como variables y constantes importantes de la interfaz abstracta se detallan a continuaci n Partiremos del fichero marte integer types ads perteneciente al n cleo de MaRTE OS en el que se definen diferentes tipos de datos a partir de los ya existentes function Timer Interrupt return HW Interrupt is begin return TICK end Timer Interrupt La primera subrutina de la interfaz abstracta es una funci n que debe devolver utilizando el tipo declarado en la propia biblioteca un HW_Interrupt similar a tipo entero indicando el n mero asignado a la interrupci n de TICK Tal y como est implementada la interfaz esto corresponder al n mero 20 fuente de interrupci n tick del microcontrolador utilizado Ver la declaraci n de constantes asignadas a las diferentes IRQ procedure Default HW Interrupt Handler State in Trap State is begin null end Default HW Interrupt Handler La segunda subrutina que aparece es el manejador por defecto de las interrupciones Se ha optado por una implementaci n sencilla en la que el manejador por defecto sea nulo Septiembre 2010 93 Migraci n del sistema operativo de tiempo real MaRTE OS al microprocesador ARM procedure Install HW Interrupt Handler Int Num in HW Interrupt Handler in HW Interrupt Handler is begin pragma assert Initialized IC Install IRQ Handler Int Nu
94. unction of RTOS will always synchronized with real time ROUND RESET FUNCTION The round reset function can be performed by the RTC round reset register RTCRST The round boundary 30 40 or 50 sec of the second carry generation can be selected and the second value is rounded to zero in the round reset For example when the current time is 23 37 47 and the round boundary is selected to 40 sec the round reset changes the current time to 23 38 00 NOTE All RTC registers have to be accessed by the byte unit using the STRB LDRB instructions or char type pointer 32 768 2 X TAL CONNECTION EXAMPLE The Figure 14 2 is an example circuit of the RTC unit oscillation at 32 768Khz 15 22 pF E 32 768 Hz EXTAL1 Figure 14 2 Main Oscillator Circuit Examples ELECTRONICS 14 3 REAL TIME CLOCK 53 44 RISC MICROPROCESSOR REAL TIME CLOCK SPECIAL REGISTERS REAL TIME CLOCK CONTROL REGISTER RTCCON The RTCCON register consists of 4 bits such as the RTCEN which controls the read write enable of the BCD registers CLKSEL CNTSEL and CLKRST for testing RTCEN bit can control all interfaces between the CPU and the RTC so it should be set to 1 in an RTC control routine to enable data read write after a system reset Also before power off the RTCEN bit should be cleared to 0 to prevent inadvertent writing into RTC registers RTCCON 0x01D70040 L R W RTC control Register 0x0 0x01D70043 B by byte CLKRST 3 RTC clock cou
95. ystem is therefore connected to data lines 7 through 0 Higher Address Word Address Lower Address Least significant byte is at lowest address Word is addressed by byte address of least significant byte Figure 2 2 Little Endian Addresses of Bytes whthin Words INSTRUCTION LENGTH Instructions are either 32 bits long in ARM state or 16 bits long in THUMB state Data Types ARM7TDMI supports byte 8 bit halfword 16 bit and word 32 bit data types Words must be aligned to four byte boundaries and half words to two byte boundaries 2 2 ELECTRONICS 53 44 RISC MICROPROCESSOR PROGRAMMER S MODEL OPERATING MODES ARM7TDMI supports seven modes of operation e User usr The normal ARM program execution state fiq Designed to support a data transfer or channel process e irq Used for general purpose interrupt handling e Supervisor svc Protected mode for the operating system e Abort mode abt Entered after a data or instruction prefetch abort e System sys A privileged user mode for the operating system e Undefined und Entered when an undefined instruction is executed Mode changes may be made under software control or may be brought about by external interrupts or exception processing Most application programs will execute in User mode The non user modes known as privileged modes are entered in order to service interrupts or exceptions or to access protected resources REGISTERS
Download Pdf Manuals
Related Search
Related Contents
FCB1010 UnO v.1.0.4 User Guide PR311 Installation Guide Rev. F Online Application Tool (OLAT) User Manual INSTRUCTIONS DE MONTAGE MICROPROP DC2 Bulletin juillet 2011 Manual de utilização RapidScat wind Product User Manual Copyright © All rights reserved.
Failed to retrieve file