Home

An Introduction to Computer Engineering using the Renesas Sakura

image

Contents

1. 45 digitalWrite PIN LEDO ON 46 digitalWrite PIN LED1 ON 47 digitalWrite PIN LED2 ON 48 digitalWrite PIN LED3 OFF 49 break 50 case 4 SA digitalwrite PIN LEDO ON 52 digitalWrite PIN LED1 ON 53 digitalwrite PIN LED2 ON 54 digitalWrite PIN LED3 ON DDU break 56 default STs digitalWrite PIN LEDO OFF 58 digitalWrite PIN LEDL OFF 59 digitalWrite PIN LED2 OFF 60 digitalWrite PIN LED3 OFF 61 break 62 63 Current LED 64 if Current LED 5 65 Current LED 1 66 67 68 69 void loop 70 InitTimer Tia while 1 72 if TMRO TCNT OxFF 13 Rotate LEDs 74 18 76 4 2 3 Using Interrupts as Event Counters Renesas provides us functions to setup interrupts generated by designated inputs The interrupts h includes function calls that allow us to enable and disable global interrupts Specify an interrupt service routine ISR function when an external interrupt occurs and to disable specific interrupts When we include interrupts h in our main program file the following functions become available to us CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 93 void interrupts void Enable global Interrupt void noInterrupts void Disable global interrupts void detachInterrupt unsigned char interrupt Stop the specific interrupt void attachInterrup
2. 145 AD ADDIAGR BYTE 0x0 116 AD ADCSR BIT ADST 1 117 118 void InitPWMs void 119 MSTP TMRO 0 Activate TMRO unit 120 121 TMRO TCCR BIT CSS 1 Count source is PCLK 122 TMRO TCCR BIT CKS 5 Adjust count source to PCLK 1024 42 ms 123 TMRO TCR BIT CCLR 1 Timer resets at compare match A 124 TMRO TCORA OxDE Frequency 42 ms period 125 TMRO TCORB 0x70 Duty cycle 50 126 TMRO TCR BIT CMIEA 1 compare match A interrupt enabled 127 TMRO TCR BIT CMIEB 1 compare match B interrupt enabled 128 129 IEN TMRO CMIAO 1 enable compare match interrupt A 130 IPR TMRO CMIAO 15 compare match interrupt A priority 131 TR TMRO CMIAO 0 clear compare match interrupt A flag 132 133 IEN TMRO CMIBO 1 enable compare match interrupt B 134 IPR TMRO CMIBO 14 compare match interrupt B priority 135i IR TMRO CMIBO 0 clear compare match interrupt B flag 136 137 void Excep TMRO CMIAO void 138 if startMotors 0 139 digitalWrite enableA OFF 140 digitalWrite enableB OFF 141 142 if startMotors 1 143 digitalWrite enableA ON 144 digitalWrite enableB ON 145 146 147 void Excep TMRO CMIBO void 148 digitalWrite enableA OFF 149 digitalWrite enableB OFF 150 4 151 void myEventCounterA void 152 if forward 0 153 motorCountA t 154
3. PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SClc SCId RSPI LQFP VO PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT 26 B22 EDREQO MTIOC3B MTCLKC SCKO USBO_DRPD TIOCC3 TMOO PO2 In this example we have set up a pulse output from timer 0 and observed the output wave In a more advanced example later we will cover how to calculate and control the exact fre quency of the wave and discuss how this relates to controlling external devices 4 2 5 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 101 Setting up Timer interrupts for Pulse Output Another way of generating a pulse output using a timer would be to utilize interrupts at compare match A and compare match B Instead of setting the OSA bit to generate an out put on compare match A and the OSB bit to generate an output on compare match B we enable the interrupt on compare match A and compare match B inside the peripheral mod ule by setting the CMIEA and CMIEB bit respectively The CMIEA Bit Compare Match Interrupt Enable A selects whether compare match A interrupt requests CMIAn that are issued when the value of TCORA corresponds to that of TCNT are enabled or disabled Similarly the CMIEB Bit Compare Match Interrupt Enable B selects whether compare match B interrupt requests CMIBn that are issued when the value of TCORB corresponds to that of TCNT are enabled or disabled To utilize the interrupt calls we will also need to enable TM
4. Value after reset 0 0 0 0 0 0 0 0 Figure 2 6 Port Output Data Register 1 page 662 The syntax to access the bits of the Data Registers DR is PORTx PIDR BIT Bn x 0 to 9 A to G J and n 0 to 7 for those port pins configured as inputs and PORTX PODR BIT Bn for those port pins configured as outputs To select a pin as an output pin first set the Port Output Data Register PODR to a known value preferably 0 so that changes in the output can be easily observed The char variable BYTE can be used to set multiple pins as output at the same time Set LEDO Port A bit 0 as Output 1 PORTA PDR BIT BO 1 2 PORTA PODR BIT BO 0 Line 1 sets LEDO as an output and line 2 switches on the LED Sets LEDs 1 2 3 and 4 Port A bit 0 1 2 and 3 as Outputs 1 PORTA PDR BYTE 0x47 2 PORTA PODR BYTE 0xB8 Line 1 sets LED1 2 3 and 4 as outputs and line 2 switches on the LEDs Port Input Data Register PIDR The Port Input Data Register is also defined as a union of variables inside the port structure in the iodefine gcc63n h file PORTx PIDR BIT Bn x 0 to 9 A to G J and n 0 to 7 is used to read the state of a pin and the state is stored in the Port Input Data Register re gardless of the value in the Port Mode Register PMR This register also has some re served bits These bits are read as 1 and cannot be modified b7 b6 bs b4 b3 b2 bl DO Value after r
5. 155 N 4 4 4 5 4 6 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 147 RECAP In this chapter we covered the capabilities of the 8 bit timer peripherals on the Renesas RX63N We started with a brief overview of the timer concepts Then we covered how to cascade two 8 bit timers into one 16 bit unit We also covered pulse output operation which allows us to generate a steady frequency square wave whose duty cycle and fre quency are maintained by the timer unit We have also seen how the ADC of the RX63N board can be programmed The meth ods discussed above have been using polling Polling is not very efficient An efficient method of using these features would be using interrupts REFERENCES 1 Renesas Electronics Inc February 2013 RX63N Group RX631 Group User s Manual Hardware Rev 1 60 2 Renesas Electronics Inc June 2012 RX63N Group RX631 Renesas MCUs Rev 1 00 3 Conrad James M 2013 Embedded Systems An Introduction using the RX63N Microcontroller Micrium Press 4 Digilent Inc August1 2012 Motor Robot Kit MRK Reference Manual Rev 5 Digilent inc February 28 2012 Digilent PmodHBS 2A H Bridge Reference Manual Circuit Rev D Document Rev 6 Shayang Ye April 2010 DC Carbon brush motors IG 22 Geared Motor Series IG 22GP Type 01 amp 02 7 Parallax Inc 11 2004 OTI Line Follow App Kit for the Boe Bot 8 Wakamatsu Tsusho Co Ltd Gadget Renesas Precedi
6. 34 pinMode enableA B OUTPUT Siom pinMode directionB OUTPUT 36 pinMode counterRst OUTPUT 37 pinMode Asa INPUT 38 pinMode counterRst OUTPUT 39 pinMode TMR1 CCLR INPUT 40 41 42 void ADC init void 43 void InitCounters void 44 void InitPWMs void 45 BK RK kok kok ko kok kok kok kok kok kok kok kok kok k ke RE ke kok k ee oe 46 main loop run the motors 47 48 J BK RK ko ko oko kok kok kok kok k kok ok kok kok kok kok kok kok kok kok k ke a eo 49 void loop 50 while digitalRead PIN SW HIGH DAL InitPWMs DA InitCounters 53s forward 1 54 backward 0 55 56 DD 58 59 60 61 62 63 64 65 66 67 68 69 70 Tis 12 73 74 75 76 WW 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 141 turn 0 counterReset 0 while 1 if AD ADCSR BIT ADST 0 ADC value AD ADDRA amp Ox03FF AD ADCSR BIT ADST 1 if ADC_value gt 0x310 amp amp forward TMRO TCSR BIT OSA 1 delay 200 TMRO TCORA OXEE Frequency 42 ms period digitalWrite directionA Abackward digitalWrite directionB Bforward turn 0 forward 0 backward 1 digitalWrite counterRst HIGH delay 200 digitalWrite counterRst LOW TMRO TCSR BIT OSA 2 if backward 1 TMRO TCSR BIT OSA 1 delay
7. 4 digitalWrite PIN LEDO ON Se digitalWrite PIN_LED1 OFF 6s digitalWrite PIN LED2 OFF Ls digitalWrite PIN LED3 OFF 8 break 90 RENESAS SAKURA MICROCONTROLLER BOARD 20 21 22 Adis 24 ASe 26 273 29 29 30 Bg 32 33 34 3 36 31 38 By modifying the count source of timer TMR1 we can change the speed at which the LEDs rotate We can also achieve this by polling for a different count on the TMRO TCNT regis ter Polling is a poor way to utilize timer functionality In fact our programming could po tentially miss the count This becomes even more likely as the program becomes larger and CO U OU K U ND F o o case 2 digi digi digi digi brea case 3 digi digi digi digi brea case 4 digi digi digi digi brea default digi digi digi digi brea Current LE if Current Current talWrite talWrite talWrite talWrite Ky talWrite PIN talWrite PIN talWrite PIN talWrite PIN Ky talWrite PIN_ talWrite PIN talWrite PIN talWrite PIN Ky talWrite talWrite talWrite talWrite K D the timer increments faster BW ND H GR SAKURA Sketch Template Version V1 08 LEDO _LED1 ED2 LED3 EDO EDI D2 ED3 EDO EDI ED2 ED3 LEDO _LED1 ED2 LED3 include lt rxdui
8. 4 3 3 RENESAS SAKURA MICROCONTROLLER BOARD Let us now look at an example of setting up the registers of the 10 bit ADC It is always better to write register setup as a function void ADC Init SYSTEM MSTPCRA BIT MSTPA23 0 AD ADCSR BYTE 0x07 AD ADCR BYTE 0x00 AD ADCR2 BYTE 0x00 AD ADDIAGR BYTE 0x0 The setting up of registers has been written as a function named ADC Init in line 1 The10 bit ADC has been released from stopped state using Module Stop Control Register A line 2 In line 3 the Control Status Register is set up one channel AN0 has been selected and A D Interrupt Enable has not been enabled b6 0 Next on line 4 One Cycle Single Scan mode PCLK and software trigger have been selected using the A D Control Register The format of the Data Register has been set to right alignment using line 5 In line 6 the A D self diagnostic function has been turned off as we are not trying to detect any faults 10 bit A D Conversion The following is an example of how you would set up and use an analog to digital con verter using the GR SAKURA I OU BK U ND FE Oo s o JI OU K WN H GR SAKURA Sketch Template Version V1 08 include lt rxduino h gt include lt iodefine gcc63n h gt Remember to Connect GND pin Vref and 5V pin Vref define ANALOG ANO 46 Port E pin 46 ADO define HIGH 1 define LOW 0 unsigned short ADC value void ADC Init void
9. 83 84 Timer constant register B TCORB 83 84 Timer control register TCR 85 86 100 108 Timer control status register TCSR 84 85 Timer count register TCNT 81 82 83 Timer counter control register TCCR 81 83 Timer mode 78 79 Timer pulse unit TPUa 41 Timers cascading 87 88 92 clock division characteristics 87 counting events with 81 86 description of 77 78 formulas for 78 frequency and period control 105 6 interrupts for pulse output 101 4 overflow detection of 79 pulse output 97 100 pulse width modulation 97 100 registers 81 86 INDEX 153 robotics application 106 17 139 42 of RX63N microprocessor 41 42 TMR unit 0 block diagram of 80 TMR see 8 bit timers TMR Top down design 27 TPUa 41 Traces 8 U Union of port 18 19 USB 10 35 37 42 V V model of software development 26 27 Void attachInterrupt 94 97 Void detachInterrupt 93 94 Void interrupts 93 Void noInterrupts 93 Voltage ADC 118 detection circuit of RX63N 40 embedded systems 16 sensors 63 Von Neumann Machine 15 W Warm up mode 4 Watchdog timer WDTA 42 Wave 97 100 WDTA 42 Workspace of HEW 24 X XBee mounting pattern 37 Z Zigbee XBee 37
10. Lastly let s identify the total time that we will need to enable the motors in forward mo tion by taking the total motor rotations and dividing it by the rated RPM and converting to milliseconds 265 636 motor rotations k 47 6700 rotations min 0 039647 min 1 0 039647 min x 22 sec 000 ms ge 1 min 1 sec We need to calculate the total distance that the wheels will need to rotate in opposite direc tions to make a 90 degree turn First calculate the distance from one wheel to the other This can be achieved by simply measuring the platform from the center of one wheel to the other To achieve a 90 degree turn each wheel will need to travel Va of the total circumfer ence in opposite directions Figure 3 39 shows a diagram of how we would expect the vehicle to move about its axis when the wheels are turning in opposite directions 6 61685 in 7 854 in rotation 53 motor rotations f 0 8425 wheel rotations X 44 65 motor rotations 1 wheel rotation 44 65 motor rotations 0 8425 wheel rotations i 41 6700 motor rotations min 0 00666418 min 60 1000 0100666418 min X Z x P 399 85 ms 1 min 1 sec 72 RENESAS SAKURA MICROCONTROLLER BOARD The design decisions that we make come with consequences For example consider our choice of the robot assembly The motor specifications limit us as to the total payload that our robot will be able to carry how fast or slow the robot will move and the size of the
11. RO TCORA RO TCORB RO TCR BIT RO TCR BIT OxF Ox7 N TMRO CMIAO R TMRO CMIAO IR TMRO CMIAO N TMRO CMIBO R TMRO CMIBO IR TMRO CMIBO TP TMR1 R1 TCCR BI1 R1 TCCR BI1 R1 TCR BIT R1 TCORA R1 TCORB R1 TCR BIT R1 TCR BIT 0 LCS T CK CCL OxF Ox7 CMI CMI N TMR1 CMIA1 R TMR1 CMIA1 IR TMR1 CMIA1 N TMR1 CMIB1 R TMR1 CMIB1 IR TMR1 CMIB1 CMII CMII p Ar 0 1 14 0 CCIR 1 Timer resets at compare match A Frequency 42 ms period Duty cycle 50 1 1 compare match A interrupt enabled compare match B interrupt enabled enable compare match interrupt A compare match interrupt A priority clear compare match interrupt A flag enable compare match interrupt B compare match interrupt B priority clear compare match interrupt B flag Activate TMRO unit S 1 S 5 R 1 gt EA E EB E 1 13 0 1 12 0 startMotors 0 digitalWrite enableA OFF startMotors 1 Count source is PCLK Adjust count source to PCLK 8192 42 ms Timer resets at compare match A Frequency 42 ms period Duty cycle 503 1 1 compare match A interrupt enabled compare match B interrupt enabled enable compare match interrupt A compare match interrupt A priority clear compare match
12. Set Reset pin as low when disconnecting lt Back Next gt Cancel Figure 3 16 Flash Development tool Kit Communication Port CHAPTER 3 GETTING STARTED WITH GR SAKURA 53 The FDT software should find one USB device When a secondary popup window pops up go ahead and click next on it to select that USB device When selecting the device the next window that pops up select RX600 Series LittleEndian and click ok When entering the CPU crystal frequency set the frequency to 12 MHz if it is not already and click next In the programming options window set it up to where Protection is Automatic Messaging is Advanced and Readback Verification is no Then click finish E Programming Options EJN What level of device protection would you like r Protection Automatic Interactive None When programming the device any blocks found to have been written previously will automatically be erased What level of messaging would you like r Messaging Automatic Interactive The Toolkit will display verbose messages whenever it is communicating with the Target device This mode is useful for interface hardware development and Kernel development Would you like to perform readback verification after programming r Readback Verification O Yes No lt Back Finish Cancel lt 4 Figure 3 17 F
13. o 121 122 123 124 125 126 127 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 115 TMR1 TCORA OxFE Frequency 42 ms period motorCountA 266 amp amp nextTurn 1 startMotors 0 delay 200 digitalWrite directionA Abackward digitalWrite directionB Bbackward TMRO TCORA OxFE Frequency 42 ms period TMR1 TCORA OxFE Frequency 42 ms period delay 200 motorCountA 0 motorCountB 0 nextTurn 0 nextForward 1 startMotors 1 motorCountA 36 amp amp nextForward 1 startMotors 0 delay 200 digitalWrite directionA Abackward digitalWrite directionB Bforward TMRO TCORA OxFE Frequency 42 ms period TMR1 TCORA OxFE Frequency 42 ms period delay 200 motorCountA 0 motorCountB 0 nextTurn 1 nextForward 0 itt startMotors 1 end segment loop end program void InitPWMs void MSTP 1 n r MRO 1 MRO 1 MRO 0 Activate TMRO unit CCR BIT CSS 1 Count source is PCLK CCR BIT CKS 5 Adjust count source to PCLK 8192 42 ms 116 RENESAS SAKURA MICROCONTROLLER BOARD 128 129 130 13l 132 133 134 135i 136 187 138 139 S O U K WN r 156 157 158 159 160 161 162 163 164 165 166 IE EP IE IP MS IE TP IE LP void if Lf RO TCR BIT
14. Bits 16 Bitwise operations 21 Bytes 16 C CAN 3 Cascading timers 87 88 92 Central processing unit CPU 14 15 38 Clock generation circuit 40 Clock oscillator 40 Clocks see also timers CMIEA Bit 101 112 CMIEB Bit 101 112 CMT 41 Code algorithm converting to code 31 33 algorithm starting with 30 coding standards 32 description of 30 design margins tracking of 32 principles when implementing 32 robotics application 72 74 Coding standards 32 149 Communication function of RX63N 42 43 Communications and networking 5 Compare match interrupt enable A CMIEA bit 101 112 Compare match interrupt enable B CMIEB bit 101 112 Compare match timer CMT 41 Compilation mechanism 22 23 Compiler for embedded systems 23 24 of GR Sakura 44 Component costs 3 Computer engineer role of 9 10 Computers architecture of 13 15 Const variable 32 Constraints of system requirements 29 Contact bounce 60 61 Continuous scan mode 10 bit converter 122 Control Area Network CAN 3 Control mechanism of computer 14 Control systems 4 Control unit 14 Controller Area Network CAN module 43 Conversion rate of ADC 118 Cost of embedded systems 1 2 3 6 CPU 14 15 38 Crank and start 4 Customer requirements 28 150 INDEX D DAC 43 Data movement block of computer 13 Data Registers DR 18 Data transfer controller 40 Data types of RX CPU
15. Both of these constraints must be taken into account when designing interfaces for the actuator Because of their large coils motors draw a lot of current For Direct Current DC mo tors simple transistor drivers or H bridges shown in Figure 3 26 can be used to interface them with a microcontroller If the left input of the circuit in Figure 3 26 is connected to Port A pin 0 and the right input of this circuit is connected to Port A pin 1 the code to turn the motor one direction would be 1 PORTA PDR BYTE 0x03 Sets pins 0 and 1 on Port A as outputs 2 PORTA PODR BYTE 0x02 Sets one pin as HIGH and the other as LOW VDD 2N3906 2N3906 W X Input Input A G 10 o B 2N3904 2N3904 W Z 1N4148 1N4148 1N4148 1N4148 P nem l Er 3 GND Figure 3 26 H bridge motor driver Two of the microprocessor s outputs are connected to the resistors 2 page 21 Note Both inputs should not be the same value for the motor to turn Stepper motors can use transistors or stepper motor driver ICs Some ICs such as the L293 or the 754410 are specifically designed to drive the DC motors and interface directly with a microcontroller Servos are gearboxes that have motor control circuitry built in These de vices can often connect their control pins directly to a microprocessor as their internal cir cuitry handles driving th
16. Bsa INPUT 110 56 ST 58 D9 60 61 62 63 64 65 66 67 68 69 70 71 12 73 74 75 76 TT 78 79 80 81 S O0 U ao U BU N RENESAS SAKURA MICROCONTROLLER BOARD pinMode counterRst OUTPUT pinMode TMR1 CCLR INPUT pinMode TMR2 CCLR INPUT InitPWMs InitCounters J BK RK k k kok ko kok kok kok k ke ok kok kok kok kok k ke ok k ke RE RE ee main loop run the motors J BRK KR KR KK RR kk k kok k kok k kok k kok k OK kok k kok RR void loop i 0 nextTurn 1 nextForward 0 while digitalRead PIN SW HIGH TMRO TCSR BIT OSA 2 TMR3 TCSR BIT OSA 2 while i lt 4 if TMR1 TCNT lt TMR2 TCNT amp amp nextTurn 1 TMRO TCORA OxFB TMR3 TCORA OxFE if TMR1 TCNT gt TMR2 TCNT amp amp nextTurn 1 TMRO TCORA OXFE TMR3 TCORA OxFB if TMR1 TCNT TMR2 TCNT amp amp nextTurn 1 TMRO TCORA OXFE TMR1 TCORA OXFE if TMR1 TCNT 266 amp amp nextTurn 1 TMRO TCSR BIT OSA 1 TMR3 TCSR BIT OSA 1 delay 200 digitalWrite directionA Abackward digitalWrite directionB Bbackward TMRO TCORA OXFE Frequency 42 ms period CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 111 82 TMR1 TCORA OXFE Frequency 42 ms period
17. Our first step is to choose a speed for our prescaler If we look at Figure 4 12 Clock division characteristics we see that PCLK 32 1 5625 MHz offers almost a 41 94 ms period between TCNT overflows We will choose this prescaler as choosing prescaler PCK 8 will only give us a 10 41 ms period and we require a minimum of 20 ms Now we must calculate the values for the timer counter registers First we will calculate the values to place in time constant register B to obtain a pulse of 1 ms and 2 ms Then we must calculate the value to place in time constant register A to obtain a 20 ms low signal after the pulse Note that when we change the value of TCORB the frequency of the wave still stays the same so the time our wave is low is affected However since 1 2 ms is small compared to 20 ms this is negligible and we don t have to worry about recalculating for TCORA To calcu late the value for TCORB we divide 1 ms and 2 ms by the length of time between timer counts 1 1 ms 2 ms 640 ns 1562 5 3125 50 MHz 32 640 ns 640 ns For the value in TCORA we add 20 ms to our maximum high period 2 ms to get 22 ms then divide this by the time for a clock tick 22 ms 640 ns 34375 In this case it gives us a value right in the middle of our range which is limited to 65535 Now we need to convert the value 34375 to hex which is 0x8647 This will be the value that we set TCORA to So in all practicality wh
18. SCI12 Overflow 1 l w K TMOO Overflow 0 TCNT i TCT KO TMO1 Counter clear 0 i Counter clear 1 ieee i i Compare match B1 i j I lt Compare match BO Comparator BO i Comparator B1 Control logic j i TMRIO ie A s TCORB ICT TOR kK gt A D conversion i oi A TCSR start request signal gt TER rs K TCR T TR KO lt te H Tecer K Channel 0 Channel 1 gt CMIAO oo TMRO TMR1 TCORA Time constant register A TCNT Timer counter TCORB Time constant register B CMIA1 gt CMIBO gt CMIB1 gt ovo OVI1 Interrupt signal TCSR Timer control status register TCR Timer control register TCCR Timer counter control register Note For the corresponding A D converter channels see section 40 12 Bit A D Converter S12ADa and section 41 10 Bit A D Converter ADb Figure 4 2 Block diagram of TMR Unit 0 1 page 1014 Internal bus CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 81 4 2 1 Setting Up a Timer for Counting Events Timer Count Register The TCNT Timer Counter register holds the current timer value at any time after the timer has been configured Whenever you want to know the value of the timer or counter you will read the value in this register Also when not currently operating the timer you can load a value into this register and the timer will begin counting from that value when restarted Note that in the 16 bit mode T
19. USBO_VBUSEN EDREQ1 TIOCB4 TMRI1 PO4 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 109 GR SAKURA Sketch Template Version V1 08 de de de de de de de de de de int defi defi defi defi defi defi fine ine ine ine ine ine ine fine fine fine fine fine fine fine fine fine i include lt rxduino h gt directionA 3 enableA 2 directionB 5 enableB 6 Aforward I Abackward 0 Bforward I Bbackward 0 Asa 10 Bsa 11 PAUSE 500 ON I OFF 0 counterRst TMR1 CCLR TMR2 CCLR 13 int nextTurn int nextForward include lt iodefine gcc63n h gt Port 2 pin Port 2 pin Port 2 pin Port 3 pin Port C pin Port C pin 3 motor A direction 2 PWM TMRO input to motor A 4 motor B direction 2 PWM TMR3 input to motor B TMR1 TMR2 4 input to counter 6 input to counter Pause between switching directions Port 2 pin Port 2 pin Port C pin void InitCounters void void InitPWMs void 7 clear TMR1 Count output TMR1 Count input TMR1 Count input 4 clear 5 clear J BR RK RK KK KK I I KK I Kk setup input output pins J BK RK RK KK KK I KK KK ok void setup pinMode directionA OUTPUT pin pin pin pin pin pin ode enableA OUT ode ode enableB OUT PUT directionB OUTPUT PUT ode PIN SW OUTPUT ode Asa INPUT ode
20. and desired hardware to be utilized A com pany s operating practices and maintenance concepts could also have an impact on re quirements being delegated to the designer Operational requirements define the interfaces between the user and each functional system Operational requirements consist of actions decisions information requirements and timing Both normal and abnormal circumstances need to be considered when defining operation requirements Performance requirements are attributes of the function or system that make it useful to the customer Some of the considerations taken into account when identifying perfor mance requirements include accuracy fidelity range resolution speed and response times Physical and installation requirements relate to the physical attributes of the system to the overall system environment These requirements include size mounting provisions power cooling environmental restrictions visibility access adjustment handling stor age and production constraints Maintainability requirements depend on factors such as the percent of failure detec tion or the percent of fault isolation Provisions for external test equipment signals and connections should be defined Interface requirements should be defined with all inputs having a source and all out put destinations defined These requirements are usually dictated down from interfacing components CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 2
21. 0 0 0 0 0 0 Figure 4 4 Timer Counter Control Register 1 page 1019 82 RENESAS SAKURA MICROCONTROLLER BOARD aor E TO TA b2 tobO CKS 2 0 Clock Select See table below b4 b3 CSS 1 0 Clock Source Select See table below R W b6 b5 Reserved These bits are always read as 0 The write RAN value should always be 0 b7 TMRIS Timer Reset 0 Cleared at rising edge of the external reset R W Detection 1 Cleared when the external reset is high Condition Select Note To use an external clock set the Pn PDR Bi bit for the corresponding pin to 0 and the PORTn PMR Bi bit to 1 For details see 1 section 21 VO Ports Figure 4 5 TCCR Timer Counter Control Register description 1 page 1019 TCCR REGISTER CSS 1 0 CKS 2 0 CHANNEL COCA DESCRIPTION TMRO 0 Clock input prohibited TMR2 1 Uses external clock Counts at rising edge 1 O Uses external clock Counts at falling edge 1 Uses external clock Counts at both rising and falling edges 0 1 0 0 O Uses internal clock Counts at PCLK 1 Usesinternal clock Counts at PCLK 2 1 O Uses internal clock Counts at PCLK 8 1 Usesinternal clock Counts at PCLK 32 1 0 O Uses internal clock Counts at PCLK 64 1 Usesinternal clock Counts at PCLK 1024 1 O Uses internal clock Counts at PCLK 8192 1 Clock input prohibited o Setting prohibited Counts at TMR1 TCNT TMR3 TCNT overflow signal Figure 4 6 Clock input to
22. 125 TMRO TCORB 0x80 Duty cycle 503 126 127 void InitCounters void 128 MSTP TMR1 1 do NOT activate TMR1 unit 129 TMR1 TCCR BIT CSS 0 uses external clock signal as count source LO TMR1 TCCR BIT CKS 1 Counts at rising edge of clock source 131 TMR1 TCR BIT CCLR 3 Timer resets at external output 132 TMR1 TCORA 0x62 calculated value for traveling 6 inches 133 4 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 4 3 4 2 Using Interrupts Pulse Output amp Counters The following example uses compare match A interrupt and compare match B interrupt on TMRO to generate a pulse output to control motor speed and interrupt h functions to count rising edges of the hall effect sensors SA on the left and right motor This application is another way to execute the requirements in the beginning of section 4 3 4 GR SAKURA Sketch Template Version V1 08 46 ADO 3 2 1 2 include lt rxduino h gt 3 include lt iodefine gcc63n h gt 4 include lt intvect63n h gt 5 include lt interrupt h gt 6 7 define ANALOG ANO 46 Port E pin 8 define directionA 3 Port 2 pin 9 define enableA 2 Port 2 pin motor A 10 define directionB 5 Port 2 pin 5 11 define enableB 4 Port 2 pin 4 12 13 define Aforward 14 define Abackward 0 15 define Bforward 16 define Bbackward 0 17 define ON 1 18 define OFF 0 19 20 unsigned short ADC value 21 int motorCoun
23. 200 amp amp TMR1 TCNT 0x37 digitalWrite directionA Aforward digitalWrite directionB Bforward turn 1 forward 0 backward 0 digitalWrite delay 200 digitalWrite counterRst LO TMRO TCSR BIT OSA 2 counterRst HIGH if turn 1 46 TMR1 TCNT 0x46 TMRO TCSR BIT OSA 1 delay 200 TMRO TCORA OxDE Frequency 42 ms period digitalWrite directionA Aforward digitalWrite directionB Bbackward 142 RENESAS SAKURA MICROCONTROLLER BOARD 96 turn 0 97 forward 1 98 backward 0 99 digitalWrite counterRst HIGH 100 delay 200 101 digitalWrite counterRst LOW 102 TMRO TCSR BIT OSA 2 103 104 105 while loop 106 end switch 107 end program 108 109 void ADC Init TOK SYSTEM MSTPCRA BIT MSTPA23 0 LTU AD ADCSR BYTE 0x00 112 AD ADCR BYTE Ox0C Las AD ADCR2 BYTE 0x00 114 AD ADDIAGR BYTE 0x0 Biber AD ADCSR BIT ADST 1 116 117 void InitPWMs void 118 MSTP TMRO 0 Activate TMRO unit 19 TMRO TCCR BIT CSS 1 Count source is PCLK 120 TMRO TCCR BIT CKS 6 Adjust count source to PCLK 8192 42 ms tal TMRO TCR BIT CCLR 1 Timer resets at compare match A 122 TMRO TCSR BIT OSA 2 1 output at compare match A 1234 TMRO TCSR BIT OSB 1 O output at compare match B 124 TMRO TCORA OxFF Frequency 42 ms period
24. 3 bits are reserved and upper 5 bits are used TCNT can be cleared by an external reset input signal compare match A or compare match B Which compare match to be used for clearing is selected by the TCR CCLR 1 0 bits When TCNT overflows its value changes from FFh to 00h an overflow interrupt low level pulse is output provided the interrupt request is enabled by the TCR OVIE bit Inter rupts can also be generated at compare match A and compare match B by enabling the CMIEA and CMIEB bits respectively We will discuss using interrupts to generate a pulse width output in Section 4 2 4 86 RENESAS SAKURA MICROCONTROLLER BOARD Address es TMRO TCR 0008 8200h TMR1 TRC 0008 8201h TMR2 TCR 0008 8210h TMR3 TRC 0008 8211h b7 b6 b5 b4 b3 b2 b1 DO CMIEB CMIEA OVIE CCLRI1 0 Value after reset 0 0 0 0 0 0 0 0 Figure 4 10 Timer Control Register TCR 1 page 1018 En SYMBOL BIT NAME DESCRIPTION EA b2 to bO b4 b3 b5 b6 b7 Reserved These bits are always read as 0 The write value should always be 0 CCLR 1 0 Counter Clear b4 b3 R W 0 0 Clearing is disabled O 1 Cleared by compare match A 1 0 Cleared by compare match B 1 1 Cleared by the external reset input Select edge or level by the TMRIS bit in TCCR OVIE Timer Overflow Interrupt 0 Overflow interrupt requests OVIn R W are disabled Enable 1 Overflow interrupt requests OVIn are enabled CMIEA Co
25. 69 motor robot kit assembly 63 67 payload 74 system requirements 29 30 timers use of 139 42 RTCa 41 42 RX63N microprocessor block diagram 39 clock generation circuit 40 communication function 42 43 converter A D and D A 43 CPU 38 43 direct memory access DMA 40 external bus extension 40 VO ports 40 memory 40 reset 40 temperature sensor 43 timers 41 42 voltage detection circuit 40 Safety requirements 28 Sakura ADC see analog to digital converter board design and features of 10 35 38 driving motors and coils 61 63 embedded systems 35 43 example project 46 50 firmware updating of 44 50 54 VO ports of 17 LEDs as outputs 58 LEDs switch controlled 57 61 microcontroller of 35 My Renesas setting up account with 54 57 peripheral blocks of 35 37 robotics application see robotics application software development 44 45 switches as inputs 58 61 Sample and hold circuit 119 Sample frequency of ADC 118 Scan mode 10 bit converter 122 Schmitt trigger 69 106 SClc 42 SCId 42 SD card 10 37 Sensor control 57 63 hall effect 69 106 voltage requirements 63 Sequencing 4 Serial communication interfaces 42 Serial peripheral interfaces SPD 43 Servo motor 98 105 Signal processing 5 Simple transistor drivers 62 Single channel mode 10 bit converter 122 Single precision of floating point operations 21 Single scan mod
26. 7 Since we have made the design decision to use the QTI sensor we have implied several de rived requirements 1 The surface of the environment will need to be white and 2 we will need to outline our borders in black Can you think of any other requirements that can be derived from the design decision of using the QTI sensor to meet our initial set of re quirements Note that the QTI sensor needs to be very close to the surface ground to get an appropriate reading Given the specification of the QTI sensor we know that our threshold voltage that will determine if the robot has reached the border will be 1 4V We also know that our board Vier 18 3 3V and Vet GND or OV Given this we can calculate the integer value for our threshold AVE 1 1 lint 434 0x1B2 3 3V 2 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 137 First we start by writing a program that will test the output of the QTI sensor The below example uses the on board LEDs to verify the output change of the QTI sensor IE 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 19 20 21 Ads 23 24 ZD 26 27 28 29 30 31 32 33 34 3D 36 37 38 39 GR SAKURA Sketch Template Version V1 08 include lt rxduino define ANALOG ANO define HIGH define LOW h gt include lt iodefine gcc63n h gt Remember to Connect GND pin Vref 46 1 0 Port E pin unsigned short ADC value void A
27. 83 digitalWrite counterRst HIGH 84 delay 200 85 digitalWrite counterRst LOW 86 nextTurn 0 87 nextForward 1 88 TMRO TCSR BIT OSA 2 89 TMR3 TCSR BIT OSA 2 90 91 if motorCountA 36 amp amp nextForward 1 92 TMRO TCSR BIT OSA 1 93 TMR3 TCSR BIT OSA 1 94 delay 200 95 digitalWrite directionA Abackward 96 digitalWrite directionB Bforward ITs TMRO TCORA OxFE Frequency 42 ms period 98 TMR1 TCORA OXFE Freguency 42 ms period 99 digitalWrite counterRst HIGH 100 delay 200 VO digitalWrite counterRst LOW 102 nextTurn 1 103 nextForward 0 104 i 105 TMRO TCSR BIT OSA 2 106 TMR3 TCSR BIT OSA 2 107 108 end segment loop 109 10 end program 11 void InitPWMs void LEZ MSTP TMRO 0 Activate TMRO unit 113 MSTP TMR3 0 Activate TMR3 unit 114 TMRO TCCR BIT CSS 1 Count source is PCLK 15 TMRO TCCR BIT CKS 6 Adjust count source to PCLK 8192 42 ms 116 TMRO TCR BIT CCLR 1 Timer resets at compare match A 117 TMRO TCSR BIT OSA 1 1 output at compare match A 118 TMRO TCSR BIT OSB 1 O output at compare match B 19 TMRO TCORA OxFF Frequency 42 ms period 0 TMRO TCORB 0x80 Duty cycle 50 112 RENESAS SAKURA MICROCONTROLLER BOARD 121 122 123 124 125 1264 127 128 129 130 181 132 133 134 139 136 TMR3 TCCR BIT CSS 1 Count source i
28. A D converter ANO to AN7 are the analog inputs to the 10 bit ADC and are pre configured GR SAKURA ports defined in file brd_grsakura h 1 define PIN PD6 42 lt brief PORTD 6 AN6 2 define PIN PD7 43 lt brief PORTD 7 AN7 3 define PIN PEO 44 lt brief PORTE 0 ANEXO 4 define PIN PE1 45 lt brief PORTE 1 ANEX1 5 define PIN PE2 46 lt brief PORTE 2 ANO 6 define PIN PE3 47 lt brief PORTE 3 AN1 7 define PIN PE4 48 lt brief PORTE 4 AN2 8 define PIN PE5 49 lt brief PORTE 5 AN3 9 define PIN PE6 50 lt brief PORTE 6 AN4 10 define PIN PE7 51 lt brief PORTE 7 ANS CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 123 ITEM SPECIFICATIONS One unit Number of units Input channels A D conversion method Resolution Conversion time A D conversion clock Operating modes Conditions of AD conversion start Function Interrupt source Low power consumption function Figure 4 19 8 channels one extended analog input Successive approximation method 10 bits 1 0 us per 1 channel when operating peripheral module clock PCLK 50 MHz 4 types PCLK PCLK 2 PCLK 4 PCLK 8 Single channel mode A D conversion is to be performed for only once on the analog input of the specified single channel or a single extended analog input Scan mode Continuous scan mode A D conversion is to be performed sequenti
29. Choice of LSB first or MSB first transfer Average transfer rate clock can be input from TMR timers for SCIS SCI6 and SCI12 Simple I2C Simple SPI The following functions are added to SCIc Supports the serial communications protocol which contains the start frame and the information frame Supports the LIN format FC bus interfaces RIC It has four channels one of them is FM The communication formats supported are IC bus format SMBus format and Master slave selectable The Maximum transfer rate is 1 Mbps on channel 0 IEBus IEB It has one channel It supports protocol control for the IEBus with two selectable modes differentiated by transfer rate with formats in cluding half duplex asynchronous transfer and Multi master operation 11 12 13 CHAPTER 3 GETTING STARTED WITH GR SAKURA 43 m CAN module CAN It supports three channels and 32 mailboxes m Serial peripheral interfaces SPI It supports up to three channels and MOSI master out slave in MISO master in slave out SSL slave select and RSPI clock RSPCK signals They enable serial transfer through SPI opera tion four lines or clock synchronous operation three lines It is capable of handling serial transfer as a master or slave and can switch between Most Sig nificant Bit MSB first and Least Significant Bit LSB first The number of bits in each transfer can be changed
30. GR SAKURA ON DEU gt E2 Data Flash WDTA IWDTa CRC SClc X 12 channels SCld X 1 channel DI USB 2 0 host function module USB 2 0 function module RSPI unit 0 RSPI unit 1 cr RSPI unit 2 Pano of gt CAN X 3 channels 2 Port 1 SE MTU2a X 6 channels 8 p JJ Port 2 a POE2a E SJ TPUa x 6 channels unit 0 Porta a Hi gt TPUa X 6 channels unit 1 Port 4 Em PPG unit 0 Port 5 k ETHERC EI PPG unit 1 ETE or TMR X 2 channels unit 0 IV TMR x 2 channels unit 1 Fort O CMT X 2 channels unit 0 Port 8 ICUb X CMT x 2 channels unit 1 Port 9 ma kake EI a ma RTCa Port A g 8 prea RIIC x 4ch K a c Port B EE 8 IEB Coens DMACA x arc K E 4 channels 12bit ADC X 21 channels E al FT 10 bit ADC x 8 channels Port D DI a 10 bit DAC x 2 channels Port E U E ED Temperature sensor Port F o sO gt Port G g Port H v F Port J Ethernet controller DMA controller for Ethernet controller Interrupt controller Data transfer controller DMA controller EXDMA controller Bus controller Watchdog timer Independent watchdog timer CRC cyclic redundancy check calculato
31. Letting go of the switch will trigger LED1 to light up and LEDO to go off Let s start by taking a closer look into how LEDs interface with the microprocessor 58 RENESAS SAKURA MICROCONTROLLER BOARD Using LEDs as Outputs LEDs require a current limiting resistor so that they do not draw too much current from the VO pin to which they are connected Most microcontrollers can sink more current than they can supply so generally LEDs are connected with the cathode to the microcontroller pin and a current limiting resistor between the anode and supply voltage Formula 3 1 shows how to calculate the value of the current limiting resistor Figure 3 24 shows one of the ways of connecting LEDs to a microprocessor R 2 Voupu VLEDVILED Formula 3 1 R5F211A1DD VSS AVSS V i P1 OJANS KIO1 CMPO 0 P1 1ANB KIO CMPO 0 P1 2 AN10 K12 CMPO 2 P1_3 ANN11 KI3 TZOUT P1_4 TXDO P1_5 RXDO CNTRO1 INI11 P1_6 CLKO SSIO1 P1_7 CNTROO INI10 P3_3 TCIN INI3 SSI00 CMP1_0 Figure 3 24 LED Hardware Schematic 2 page 16 The microprocessor is sourcing current for the LED Turning on the LED requires a logi cal HIGH on the output pin If the LED is attached to Port 1 Pin 0 and that pin is set to an output then the code needed to turn the LED on would be PORT1 PODR BIT BO 1 Using Switches as Inputs A simple interfacing design can include using a pull up resistor on a pin that is also con nected to ground through a button or switch Th
32. SYSTEM MSTPCRA BIT MSTPA23 0 AD ADCSR BYTE 0x00 AD ADCR BYTE 0x00 AD ADCR2 BYTE 0x00 AD ADDIAGR BYTE 0x0 AD ADCSR BIT ADST 1 A A A A 18 Toz AD Ad 22 28 24 25 26 2 28 29 30 31 32 38 34 io 36 37 38 39 40 UT U U O U U G U U U O O XY o U BK U ND F o S CO U o U B WN r DB Ne CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD O pinMode ANALOG ANO pinMode PIN LEDO PIN LEDL PIN void setup U U U U pinMode pinMode 2 pinMode PIN LED3 O O O O INPUT TPUT TPUT TPUT TPUT OW digitalWrite DO PIN LED1 digitalWrite U H gt digitalWrite ED r 2 d H z 5 digitalWrite ED 3 ADC Init void loop if ADC_value AD ADCSR BIT ADST 0V to 1V if ADC value lt 0x0 digitalWrite PIN digitalWrite digitalWrite PIN digitalWrite PIN 1V to 2V else if digitalWrite PIN digitalWrite PIN digitalWrite PIN digitalWrite PIN_ 2V to 3V else if digitalWrite PIN digitalWrite PIN digitalWrite PIN digitalWrite PIN 3V to AV else if digitalWrite PIN digitalWrite PIN W W OW r r r r AD ADCSR BIT ADST 0 AD ADDRA amp Ox03FF 1 CD EDO LOW _LED1 LOW ED2 LOW ED3 LOW A
33. all four LEDs will be turn on Remember that VREFL will need to be connected to ground and VREFH needs to be connected to a 5V source Using the GR Sakura data sheet and MCU data sheet identify the pins that are associated with VREFL and VREFH CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 135 4 3 4 A D Sensors Robotics Application Using the robot that was assembled in section 3 of this book let s design an application that will meet the following requirements 1 Design robot that shall not leave its designated environment a The environment will be a circle that is 5 meters in diameter b The circumference of the circle will be designated in black electrical tape 2 The robot shall continuously move forward until it detects its boundaries 3 When the robot detects the edge of its boundaries it shall a Move in reverse 6 inches at half speed b Rotate 120 degrees at half speed c REQ2 To meet the goal of the above requirements this sample program will use the QTI infrared sensor developed by Parallax The QTI sensor is designed for close proximity infrared IR detection Take a look at the small square black box just above the QTI label in Figure 4 27 It s nested below a capacitor and between two resistors That s a QRD1114 reflective ob ject sensor There s an infrared diode behind its clear window and an infrared transistor be hind its black window When the infrared emitted by the diode reflects off a surface and re t
34. if ADC value lt 0x300 amp amp forward 1 startMotors 1 if ADC value gt 0x310 amp amp forward 1 startMotors 0 delay 200 TMRO TCORA OXEE Frequency 42 ms period 74 75 76 71 78 79 80 81 82 83 84 85 86 87 88 89 90 9 92 93 94 95 96 OTs 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 145 digitalWrite directionA Abackward digitalWrite directionB Bforward turn 0 forward 0 backward 1 delay 200 startMotors 1 if backward 1 amp amp motorCountA 55 startMotors 0 delay 200 digitalWrite directionA Aforward digitalWrite directionB Bforward turn 1 forward 0 backward 0 motorCountA 0 delay 200 startMotors 1 if turn 1 amp amp motorCountA 60 startMotors 0 delay 200 TMRO TCORA OxDE Frequency 42 ms period digitalWrite directionA Aforward digitalWrite directionB Bbackward turn 0 forward 1 backward 0 motorCountA 0 delay 200 startMotors 1 end while 1 end switch loop end program void ADC Init void SYSTI AD A AD A AD A EM MSTPCRA BIT MSTPA23 0 DCSR BYTE 0x00 DCR BYTE 0x00 DCR2 BYTE 0x00 T 146 RENESAS SAKURA MICROCONTROLLER BOARD
35. insights about the timing of various operations happening inside the system Example of an Integrated Development Environment High Performance Embedded Workshop provides a GUI based integrated development environment on Windows operating systems for the development and debugging of em bedded applications for the Renesas microcontrollers It supports seamless integration and easy access to all tools for coding compiling linking debugging and downloading exe cutables All the tools in the package together offer a variety of functions and increase pro ductivity greatly HEW organizes your work with the concepts of workspaces and projects Workspace This is the largest unit which contains programs written in the HEW workshop It can have several projects A project is automatically created when we create the workspace Project The project is where you write your program In fact creating a new proj ect is making a new program You can also make hierarchical levels between sev eral modules It along with other projects will be included in the workspace CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 25 Title bar L tutorial High performance Embedded Workshop resetprg c Menu Bar File Edit view Project Build Debug Setup Tools Test Window Help Toolbars _ Di See kol JA s EELEE include typedefine h include stacksct h Workspace ifdef cplusplus Window extern C endif k void PowerON Reset
36. link GR SAKURA and GR SAKURA FULL Boards CHAPTER 3 GETTING STARTED WITH GR SAKURA 55 u EN ESAS Search by keyword or Part Name Search Products Applications Development Tools Support Design Buy Samples About Renesas Home Products Provide feedback TEXT SIZE Gadget Renesas Printthispage SMP L a 4 M The following page content corresponds to the products marketed in Japan d if you do not live in Japan please Select Your Region v What is Gadget Renesas 0 EEE UTEE Renesas Web Compiler Boards Distributor Information and Technical Support What is Gadget Renesas Figure 3 19 Renesas Products Website Home Page Users have the ability to login as registered users or as guests One downside with a guest login that we used from the example project is that your workspace will not be saved be tween logins Let s register with Renesas so that we can save our projects in the cloud and can always pick up from where we left off without having to re create projects and files each time GR SAKURA and GR SAKURA FULL Boards The GR Gadget Renesas project plans to produce a series of board solutions The first available board is the GR SAKURA board manufactured by Wakamatsu The GR SAKURA board using RX63N MCU offers an Arduino capatible board footprint and C template and libraries Two kinds of GR SAKURA board are offered GR SAKURA
37. of top down design or decomposition Each small problem is solved and the solutions are com bined into a software solution There are many approaches possible Do we design everything up front and then code it This is called a big up front design Do we have a prototype or a previous version which we can build upon Do we design and build a little at a time What do we work on first the easy or the hard parts Which model we should use depends on the types and severity of risks Some industries may be required to follow a specific development process in order for the product to re ceive certification At this point it is sufficient to understand that there are different ways to slice and dice the work to be done keeping in mind that we should develop each sub system in the order architect design implement For example don t start writing code if you haven t designed the algorithm yet This sequencing is quite important so we discuss it further Define System Requirements A system design begins with functional requirements Requirements identify how the fi nal product or system will perform Not developing requirements is often a reason many projects fail since the developers will not truly know when their development tasks are complete because they do not know in detail how the product or system is really supposed to operate There are many different types of requirements 3 Safety Requirements Functional
38. very flexible In fact most of the configured pins on the board can be reconfigured using the JTAG In fact an embedded systems engineer whose primary focus is to provide a solution for A D conversion of an external peripheral could configure the GR SAKURA to have twenty one A D input pins for the 12 bit A D converter unit which has twenty one data registers each corresponding to an input channel TABLE 4 4B GR Sakura 12 bit A D Converter Port Mapl8 PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SClc er RSPI CN15 LOFP I O PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT ADO P40 IRO8 DS AN000 AD1 9B P41 IRQ9 DS AN001 AD2 op P42 IRO10 DS AN002 AD3 91 P43 IRQ11 DS AN003 AD4 90 P44 IRO12 DS AN004 AD5 89 P45 IRO13 DS AN005 1020 88 P46 IRQ14 DS AN006 1021 87 P47 IRO15 DS AN007 1036 86 PDO DOIAO DOI IRQO AN008 1037 85 PD1 D1 A1 D1 MTIOC4B CTXO IRQ1 ANOO9 1038 84 PD2 D2 A2 D2 MTIOC4D CRXO IRQ2 ANO10 1039 83 PD3 D3 A3 D3 POES IRQ3 ANO11 1040 82 PD4 D4 A4 D4 POE3 IRO4 ANO12 1041 81 PD5 D5 A5 D5 MTICSW POE2 IRO5 ANO13 1046 76 PE2 D10 A10 D10 MTIOC4A PO23 RXD12 SMISO12 IRQ7 DS ANO SSCL12 RXDX12 SSLB3 MOSIB 1047 15 PE3 D11 A11 D11 MTIOC4B CTS12 RT S12 AN1 PO26 POES SS12 MISOB ET_ERXD3 1048 74 PE4 D12 A12 D12 MTIOCAD SSLBO ET_ERXD2 AN2 MTIOC1A PO28 1049 73 PES D13 A13 D13 MTIOC4C RSPCKB ET_RX_CLK IRQ5 AN3 MTIOC2B REF50CK 1050 72 PE6 D14 A14 D14 MOSIB IR
39. void Editor Window void main void ifdef _ cplusplus Output Window e Other component window e q Command line Status bar Ready Figure 2 12 HEW workspace showing various windows 2 page 2 The simple diagram below shows the relationship between a project and the workspace The HEW can be used for developing code with the GR SAKURA board For the ad vanced embedded developer the following link can be used to download a local debugging environment that has integrated the HEW with the GR SAKURA http www designspark com knowledge item resources for gr sakura local debuging environment for hew Figure 2 13 Relationship between the project and the workspace 26 2 5 2 5 1 RENESAS SAKURA MICROCONTROLLER BOARD BASIC SOFTWARE DEVELOPMENT We have tremendous flexibility when creating software we make many decisions going from an idea to a final working system There are technical decisions such as which com ponents we use to build a system their internal structure and how we interconnect them Some of the technical decisions will lead to a product that works but not all will There are also process decisions such as how we plan to build the system and how to select those components Similarly some process decisions can lead to an easier or more predictable development effort while others will lead to project delays or cancellation or can even bankrupt the company A good software proc
40. where logic signals are used to drive small to medium sized DC motors The HB5 works with power supply voltages from 2 5 V to 5 V but is normally operated at 3 3 V as this is the supply voltage which is also the standard voltage for the GR SAKURA board VM DIR M H BRIDGE eu CIRCUIT M o o eno velo alse GND ow od oft o lt J1 ea J2 O GND J3 4 Figure 3 35 PmodHB5 Circuit Board amp schematic 4 page 1 CHAPTER 3 GETTING STARTED WITH GR SAKURA 69 Motor power is provided via a two pin terminal block J3 that can accommodate up to 18 gauge wire The HBS circuits can handle motor voltages up to 12 V The HBS is con trolled by a system board connected to J1 The motor rotation direction is determined by the logic level on the Direction pin Current will flow through the bridge when the Enable pin is brought high The direction of the motor should not be reversed while the Enable pin is active If the direction is reversed while the bridge is enabled it is possible to create brief short circuits across the bridge as one leg will be turning on while the other leg is turning off This could damage the bridge transistors Two Schmitt trigger buffered inputs are provided on connector J2 to facilitate bringing motor speed feedback signals to the controlling system board SA and SB The Digilent motor gearboxes have Hall effect
41. 0 0 0 Figure 4 8 Timer Control Status Register 1 page 1021 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 85 eT sso onan ocscummon b1 bo OSA 1 0 Output b1 bo Select A O 0 No change when compare match A occurs O 1 0 is output when compare match A occurs 1 0 1 is output when compare match A occurs 1 1 Output is inverted when compare match A occurs toggle output b3 b2 OSB 1 0 Output b3 b2 RAN 1 Select B 0 No change when compare match B occurs 0 O 1 0 is output when compare match B occurs 1 0 1 is output when compare match B occurs 1 1 Output is inverted when compare match B occurs toggle output b4 ADTE A D Trigger 0 A D converter start requests by compare match A RAN Enable are disabled 1 A D converter start requests by compare match A are disabled b7 to b5 Reserved These bits are always read as an indefinite value The R W write value should always be 1 Notes 1 Timer output is disabled when the OSB 1 0 and OSA 1 0 bits are all 0 Timer output is O until the first compare match occurs after a reset 2 For the corresponding A D converter channels see 1 section 41 12 Bit A D Converter S12Ada and section 42 10 Bit A D Converter ADb Figure 4 9 TCSR Timer Control Status Register description 1 page 1021 Timer Control Register The Timer Control Register TCR is used to enable interrupt requests and counter clear ing It is an 8 bit register whose lower
42. 1 81 81 83 84 85 87 92 93 93 93 93 94 94 97 101 105 106 108 112 117 122 122 125 126 126 127 129 129 132 135 139 143 4 4 4 5 4 6 Recap References Exercises Index CONTENTS xi 147 147 147 149 Introduction to Embedded Systems 1 1 1 2 1 2 1 LEARNING OBJECTIVES In this chapter the reader will learn What an embedded system is Why to embed a computer What functions and attributes embedded systems need to provide m What constraints embedded systems have CONCEPTS An embedded system is an application specific computer system which is built into a larger system or device Using a computer system rather than other control methods such as non programmable logic circuits electro mechanical controls and hydraulic controls offers many benefits such as sophisticated control precise timing low unit cost low de velopment cost high flexibility small size and low weight These basic characteristics can be used to improve the overall system or device in various ways Improved performance More functions and features Reduced cost Increased dependability Because of these benefits billions of microcontrollers are sold each year to create embed ded systems for a wide range of products Economics and Microcontrollers Microcontrollers are remarkably inexpensive yet offer tremendous performance The mi croprocessor for a personal computer may cost 100 or more while microcont
43. 20 21 DC power jack 36 Debouncing solutions 60 61 Debugger 24 Decomposition 27 Delay method 49 Derived reguirements 29 Design margins 32 Detailed design of code development 30 Diagnostics 5 Digilent Motor Robot Kit MRK 63 64 106 Digilent PmodHBS 2A H Bridge Module HBS 68 Digital to analog converter DAC 43 DigitalRead function 59 60 DigitalWrite method 48 Direct current DC motors 62 Direct memory access DMA 40 42 Double precision of floating point operations 21 DR 18 Driving motors and coils 61 63 Duty cycle of a wave 98 E EDMAC 42 8 bit timers TMR 41 80 Embedded systems attributes of 5 benefits of use 2 4 computer engineer role of 9 10 constraints on 6 costs of 1 2 3 6 dependability of 4 description of 1 designing and manufacturing of 8 development description of 6 10 development product 7 8 economics of 1 2 example of 10 functions of 4 5 networks of 2 Sakura see Sakura Engineering design 7 Engineering Method of Creative Problem Solving 7 Estimation of code development 30 ETHERC 42 EtherNet connector 36 Ethernet controller ETHERC 42 Ethernet port 10 35 Event counter 78 79 see also timers interrupts as 92 97 Event counter mode 78 79 EXDMA controller 40 External bus clock BCLK 40 External bus extension 40 F Fault handling 5 FCLK 40 File inclusion 22 Firmware updating of 44 50 5
44. 25 150 Figure 3 38 Motor Characteristics 5 page 1 Based on the H bridge data sheet we know that the H bridge can handle motor voltages up to 12 V but no more So our voltage supply to the motors cannot be more than 12 V So if we look at Figure 3 37 we know that optimally with no load the motors will rotate 8000 times per minute rpm Let s use the Rated RPM to evaluate the time it will take for our ro bot to travel one meter From the MRK datasheet we know that the wheels are 2 5 inches in diameter and that depending the gear ratio of the motors it will either take 53 rotations of the motor for one rotation of the wheel or 19 rotations of the motor for one rotation of the wheel Let s evaluate based the 53 1 ratio First let s convert our forward distance from meters to inches 121 1 m is eguivalent to 3 2808 ft so 3 2808 ft X ae 39 37 in CHAPTER 3 GETTING STARTED WITH GR SAKURA 71 Calculate how many rotations of the wheels we will need to travel one meter To do this we will need to compute the circumference of the wheel then divide the forward distance by the circumference 2mr dr 2 5in X m 7 854 in 39 37 in 7 854 in rotation 5 012 rotations Now that we know how many rotations of the wheel we will need we can compute the to tal rotations of the motor by multiplying the wheel rotations by the gear ratio 53 motor rotations 5 012 wheel rotations X 265 636 motor rotations 1 wheel rotation
45. 4 Flash development tool kit communication port 52 device selection 52 install features 51 language 50 program flash 54 programming options 53 FlashIF clock FCLK 40 Floating point operations 21 Floating point unit FPU 38 Formulas 8 bit timer maximum time for 78 circumference of the wheel 71 digital value of analog value 119 duty cycle 98 frequency 98 motor total rotations of 71 motor total time enabled 71 timer counter registers values for 105 FPU 38 Frequency measuring method MCK 41 Frequency of a wave 98 105 6 Functional requirements 28 G Gadget Renesas board series 35 General purpose processors GPP 23 GPP 23 GR Sakura see Sakura GR SAKURA FULL board 35 37 38 H Hall effect sensors 69 94 106 Hardware debouncing 60 HB5 68 H bridge motor driver 62 70 98 99 HEW 24 26 Hexadecimal 16 Hierarchical systems 13 High level design 30 High Performance Embedded Workshop HEW 24 26 I I C bus interfaces 42 IAS computer 15 ICLK 40 ICR 18 Idle mode 5 IEBus IEB 42 1G 22GM 70 Independent watchdog timer IWDTa 42 Input Buffer Control Register ICR 18 Input output I O pins limits of 61 Integer 20 Interconnections of computer 15 Interface requirements 28 Interfacing of Renesas mircrocontroller see analog to digital converter event counter timers Interrupt service routine ISR 92 Interrupts as event counters 92 97 pu
46. 63 64 65 66 67 68 69 70 Tia 72 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 97 if motorCountA 600 digitalWrite PIN LEDO HIGH digitalwrite PIN LEDL HIGH digitalwrite PIN LED2 HIGH digitalwrite PIN LED3 LOW if motorCountA 800 digitalWrite PIN LEDO HIGH digitalwrite PIN LEDL HIGH digitalwrite PIN LED2 HIGH digitalwrite PIN LED3 HIGH if motorCountA 1000 digitalWrite PIN LEDO LOW digitalwrite PIN LEDL LOW digitalwrite PIN LED2 LOW digitalwrite PIN LED3 LOW motorCountA 0 end switch loop end while 1 loop end program Lastly we need to define function myEventCounterA When called the function will in crement motorCountA by 1 So essentially motorCountA will increment every time a ris ing edge occurs on port 1 pin 2 Toe 74 TDs void my mo EventCounterA void torCountAt Compile the sample code and download it to the robot to watch the LEDs switch and the motor rotates Setting Up a Timer for Pulse Output Before covering how the RX63N MCU s 8 bit timer peripheral handles pulse outputs we ll do a brief overview of pulse width modulation concepts There are three aspects of a wave we will concern ourselves with when dealing with pulse output operation the period frequency and duty cycle Any wave is bas
47. 9 Constraints define the limits on the system design such as cost and implementation choices Know the difference between constraints and reguirements Derived reguirements come from design choices For example if we choose to use board that reguires a 3 3V power supply then the derived reguirement shall be that 3 3V DC power shall be an input to the board Requirements should be written down This helps everyone have the same picture of what needs to be accomplished and makes omissions easier to spot m There are multiple ways to express requirements both in text and graphically The most appropriate and convenient method should be used Graphical methods such as state charts flow charts and message seguence charts should be used whenever possible because 1 they concisely convey the necessary information and 2 they often can be used as design documents m Requirements should be traceable to tests How will the system be tested to ensure that a requirement is met Requirements should be quantified and measurable The requirements should be stable Frequent changes to requirements churn often have side effects and disrupt the ideal prioritization of work tasks It is easy for the latest changed requirement to be interpreted as the most important require ment when in fact this is rarely the case Consider requirements for an embedded system N 1 that controls a motor N that con trols the flap position on a commercia
48. AKURA MICROCONTROLLER BOARD gt Port MAP ele ej le alo s He J Ex ns indicated white are 5V torelan ASE SY LUST KTS Figure 3 3 GR SAKURA Port Map front side For example CN8 pin 1 IO0 can be used as a general purpose I O pin as timer input or as an interrupt input Some pins have specific functions CN15 pins 1 through 6 ANO ANS are specifically configured to be used for A D 3 2 2 Basic Concepts of the RX63N Microprocessor As briefly stated in Section 3 2 1 the GR SAKURA MCU is based on the RX63N series 32 bit MCU which is a successor MCU of RX62N It has on chip flash memory and en hanced communication functions including an Ethernet controller and USB 2 0 Host Func tion The on chip flash memory of RX63N is programmable by USB mass storage mode and the on chip flash memory of RX63N is visible as a drive on your PC In detail the 63N microprocessor architecture has the following components 1 CPU The CPU contains two main modules or functions m CPU Itis a 32 bitRX CPU with maximum operating frequency of 100 MHz Floating Point Unit FPU This unit is a single precision 32 bit floating point unit which supports data types and floating point exceptions in confor mance with IEEE 754 standard ROM RX CPU MPU Clock generation circuit ETHERC EDMAC ICUb DTCa DMACA EXDMACa BSC WDTA IWDTa CRC SClc SCld MPU CHAPTER 3 GETTING STARTED WITH
49. An Introduction to Computer Engineering using the Renesas Sakura Microcontroller Board BY JAMES M CONRAD Micrium Press 1290 Weston Road Suite 306 Weston FL 33326 USA www micrium com Designations used by companies to distinguish their products are often claimed as trademarks In all instances where Micripm Press is aware of a trademark claim the product name appears in initial capital letters in all capital letters or in accordance with the vendor s capitalization preference Readers should contact the appropriate companies for more complete information on trademarks and trademark registrations All trademarks and registered trademarks in this book are the property of their respective holders Copyright 2014 by James M Conrad except where noted otherwise Published by Micrium Press All rights reserved Printed in the United States of America No part of this publication may be reproduced or distributed in any form or by any means or stored in a database or retrieval system without the prior written permission of the publisher with the ex ception that the program listings may be entered stored and executed in a computer system but they may not be repro duced for publication The programs and code examples in this book are presented for instructional value The programs and examples have been carefully tested but are not guaranteed to any particular purpose The publisher and content contributors do not offer any warranti
50. BLE 2 2 Input and Output to Each Processor PROCESSOR INPUT OUTPUT Preprocessor C source code file Source code file with processed preprocessor commands Compiler Source code file with processed Re locatable object code preprocessor commands Linker Re locatable object code and the Executable code in machine standard C library functions language Compilers for Embedded Systems Compilers for embedded systems differ from compilers for general purpose processors GPPs Minimizing code and data size is often critical for embedded systems since mem ory sizes are limited due to price pressures This makes compiler code and data size opti mizations extremely important The tongue in cheek Software Gas Law states that a pro gram will eventually grow to fill all available resources Embedded system software evolves as features are added and defects are fixed while the hardware changes much more slowly It is much easier to reprogram an MCU than to redesign the hardware As a result there is great value in compiler optimizations which can squeeze more code and data into the available resources Speed optimization is also often critical However it is done differently for embedded systems and GPPs First GPP instruction sets have evolved over time to enable extremely high clock rates gt 2 GHz and deep instruction processing pipelines Embedded proces sors with their lower clock rates do not need such deep pipelines which leads to different
51. C pin 5 We will use TMRO and TMR3 in pulse output mode to adjust the speed of each motor by connecting them to the enable pins on the left and right motor respectively If the count on TMRI is less than the count on TMR2 then we will increase the duty cycle at which a logic high is generated to TMO Port 2 pin 2 and decrease the duty cycle at which a logic high is generated on TMO3 Port 3 pin 2 If the count is greater on TMR1 than the count on TMR2 then we will decrease the duty cycle at which a logic high is generated on TMOO and increase the duty cycle at which a logic high is generated on TMO3 If the count on TMR1 and TMR2 are equal then we set the duty cycle on TMO0 to be equal to the duty cycle on TMO3 TABLE 4 2 GR Sakura TMRO TMR3 Port Map 8 PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SClc SCId RSPI CN15 LQFP I O PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT 102 26 P22 EDREOO MTIOC3B MTCLKC SCKO USBO_DRPD TIOCC3 TMOO PO2 106 18 P32 MTIOCOC TIOCCO TXD6 TXDO SMO SI6 IRQ2 DS TMO3 PO10 SMO SI0 SSDA6 SSDAO RTCOUT RTCIC2 CTXO USBO_VBUSEN 1011 MOSI 46 PC6 A22 CS1 MTIOC3C MTCLKA RXD8 SMISO8 SSCL8 IRQ13 TMCI2 PO30 MOSIA ET ETXD3 1010 SS 48 PC4 A20 CS3 MTIOC3D MTCLKC SCK5 CTS8 RTS8 SS8 TMCI1 PO25 POEO SSLAO ET TX CLK 1013 SCK 47 RCS A21 CS2 MTIOC3B MTCLKD SCK8 RSPCKA ET ETXD2 WAIT TMRI2 PO29 104 24 P24 CS4 MTIOC4A MTCLKA SCK3
52. CNT register Every time the TCNT incre ments it is constantly being compared against either of these registers When TCNT matches either of these registers a compare match event occurs Compare match events have many uses depending on what mode we are using the timer in 84 RENESAS SAKURA MICROCONTROLLER BOARD Address es TMRO TCORA 0008 8204h TMR1 TCORA 0008 8205h TMR2 TCORA 0008 8214h TMR3 TCORA 0008 8215h TMRO TCORA TMR2 TCORA TMR1 TCORA TMR3 TCORA b7 b6 b5 b4 b3 b2 bi bO b7 bE b5 b4 b3 b2 b DO Value after reset 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Figure 4 7 Time Constant Register A 1 page 1017 Timer Control Status Register The TCSR Timer Control Status Register register controls compare match output Each timer has an output port assigned to it which is controlled via compare match events This 18 one of many uses of the compare match events When a compare match event occurs this register can set the output of the timer s port to 1 or 0 or toggle it This register is used when we want the timer to control a pulse output Address es TMRO TCSR 0008 8202h TMR2 TCSR 0008 8212h b7 b6 b5 b4 b3 b2 b1 bo ADTE OSB 1 0 OSA 1 0 Value after reset x x x 0 0 0 0 0 Address es TMRO TCSR 0008 8203h TMR3 TCSR 0008 8213h b7 b6 b5 b4 b3 b2 b1 bo OSB 1 0 OSA 0 Value after reset X X X 1 0
53. D ADDRESS SYMBOL REGISTER NAME SYMBOL OF BITS SIZE ICLK PCLK ICLK lt PCLK FUNCTION 0008 9800h AD A D data register A ADDRA 16 16 2 SIAC elk ADb 0008 9802h AD A D data register B ADDRB 16 16 2 SIAC PG 0008 9804h AD A D data register C ADDRC 16 16 2 3 ROLE ZUCUS 0008 9806h AD A D data register D ADDRD 16 16 SA SSB Pel 0008 9808h AD A D data register E ADDRE 16 16 SAR SSB PIE 0008 980Ah AD A D data register F ADDRF 16 16 2 BPC PIEK 0008 980Ch AD A D data register G ADDRG 16 16 2 SIACUS ZULU 0008 980Eh AD A D data register H ADDRH 16 16 2 SIPC ZEUS 0008 9810h AD A D control status ADCSR 8 8 2 SIPC ZUCUS register 0008 9811h AD A D control register ADCR 8 8 2 SIAC ZULU 0008 9812h AD A D control register 2 ADCR2 8 8 2 3 IPCI ZEUS 0008 9813h AD A D sampling state ADSSTR 8 8 2 3 ROLE ZEUS register 0008 981Fh AD A D self diagnostic ADDIAGR 8 8 ZAS SB PG register The width of the ADDRn 16 bit is greater than the width of the ADC output 10 bit To avoid reading wrong data the output has to be aligned either to the right or left of ADDRn This can be done by setting the ADCR2 DPSEL bit This will be explained a little later 4 3 2 Initializing the 10 bit A D Converter Module Stop Control Register A MSTPCRA The module stop control registers is a 32 bit register and can be used to place modules in and release modules from the module stopped state The several modules that realize fre quency m
54. DC Init void SYSTEM MSTPCRA AD ADCSR BYTE AD ADCR BYTE AD ADCR2 BYTE AD ADDIAGR BYTE AD s zi 7 A A A A void setup pinMode ANALOG ANO pinMode PIN LED N LED pinMode pinMode PI PIN LED PI pinMode N LED digitalWri digitalWri digitalWri digitalWri ADC Init void loop if AD ADCSR BIT ADC_value AD ADCSR BIT BIT MSTPA23 0x00 0x00 0x00 0x0 0 DCSR BIT ADST 1 INPUT OUTPUT OUTPUT OUTPUT OUTPUT r r EDO W EDL W ED2 W ED3 LOW r r ADST 0 AD ADDRA Ox03FF ADST 1 and 5V pin Vref 46 ADO 138 RENESAS SAKURA MICROCONTROLLER BOARD 40 less than 2V 41 if ADC value lt 0x19A 42 digitalWrite PIN LEDO LOW 43 digitalWrite PIN LEDL LOW 44 digitalWrite PIN LED2 LOW 45 digitalWrite PIN LED3 LOW 46 47 greater than 2V 48 else if ADC value gt 0x19A 49 digitalWrite PIN LEDO HIGH 50 digitalwrite PIN LEDL HIGH 51 digitalWrite PIN LED2 HIGH 52 digitalWrite PIN LED3 HIGH DI 54 Similar to the ADC program in section 4 3 3 the above code sets the input pin for the 10 bit ADC and configures the 10 bit ADC to read the value on the respective pin The loop code will continuous
55. DC value gt 0x0CD amp amp ADC value lt 0x19A EDO HIGH EDI LOW ED2 LOW ED3 LOW ADC value gt 0x19A amp amp ADC value lt 0x267 HIGH HIGH LOW E E DO Di LOW ADC value gt 0x267 amp amp ADC value lt 0x334 HIGH HIGH 133 134 RENESAS SAKURA MICROCONTROLLER BOARD 60 digitalWrite PIN LED2 HIGH 6l digitalWrite PIN LED3 LOW 62 5 63 4V to 5V 64 else if ADC value gt 0x334 65 digitalWrite PIN LEDO HIGH 66 digitalWrite PIN LEDL HIGH 67 digitalwrite PIN LED2 HIGH 68 digitalwrite PIN LED3 HIGH 69 70 1 The rxduino h in line 1 includes the file brd grsakura h which defines the ports and the ADC registers which need to be set for the ADC operation Lines 3 through 7 are pre processor directives that give numbers a name For example the ADC pin that we are go ing to use has been defined as pin 46 In our program we use the name ANALOG ANO to de fine that numerical value The two variables have been used ADC value and i ADC_value is used to get the ADC value from the data register in line 31 The variable i is used to make sure that the A D converter takes one reading when the switch is pushed Lines 8 through 15 define the function that will initialize the ADC The A D Control Status register ADCSR is set to select channe
56. EDs on the board blink in sequence at a speed determined by how we set up our timers In this example we will use macros to control the LEDs The first thing to do in our main program is to declare our only global variable 1 int Current LED 1 We will use this variable to keep track of which LED is currently lit Then we need to in clude our function prototypes As you can see we will only use two function calls one to set up the timer and another to blink the LEDs 1 void InitTimer void 2 void Rotate LED void After our loop begins we will only need to include the timer initialization function call Our while 1 loop will poll for TMRO to reach OxFF 65535 counts and then execute the Rotate LED function each time the count is reached Note That this is generally bad programming practice and very uncommon however in some cases this is the correct solution 1 void loop 2 InitTimer 3 while 1 4 if TMRO TCNT OxFF Ds Rotate LEDs 6 7 8 First we need to define the setup function 1 void setup 2 pinMode PIN LEDO OUTPUT is pinMode PIN LED1 OUTPUT 4 pinMode PIN LED2 OUTPUT CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD Da pinMode PIN LED3 OUTPUT 6 digitalWrite PIN LEDO LOW Ta digitalWrite PIN_LED1 LOW 8 digitalWrite PIN_LED2 LOW 9 digitalWrite PIN LED3 LOW 10 89 Now comes the
57. ESAS SAKURA MICROCONTROLLER BOARD 14 digitalWrite PIN LED2 1 Los delay INTERVAL 16 digitalwWrite PIN LED3 1 17 delay INTERVAL 18 digitalwWrite PIN LEDO 0 19 delay INTERVAL 20 digitalwWrite PIN LEDL 0 21 delay INTERVAL 22 digitalwWrite PIN LED2 0 23 delay INTERVAL 24 digitalwWrite PIN LED3 0 25 delay INTERVAL 26 Let s first take a look at the predefined methods pinMode and digitalWrite Both of these methods are defined in our library and take two integers as parameters 1 void pinMode int pin int mode 2 void digitalWrite int pin int value When considering the pinMode method the first integer defines what pin we are trying to set the mode for and the second sets the direction of that pin The tkdn_gpio h file defines the pin numbers for the hardwired LED pins As you can see all of this has been predefined for us so that we can simply use the building blocks without having to define them ourselves 1 define PIN LEDO 100 2 define PIN LED1 101 3 define PIN_LED2 102 4 define PIN LED3 103 The direction of the pin can only be either an output or an input We always take it from the perspective of the MCU In this case we are sending a signal to either turn on or off an LED from the MCU to the pin that the LED is connected to So when we look at this from the perspe
58. IT OSA 2 1 output at compare match A 134 TMRO TCSR BIT OSB 1 O output at compare match B 14 TMRO TCORA 0x55 Frequency 15 TMRO TCORB 0x20 Duty cycle Les 4 As can be seen here we have no global variables to initialize and the only function we need is the function to set up the timer In the timer initialization we first enable the 8 bit timer unit on line 8 We set the count source for timer 0 as PCLK 8 on lines 9 and 10 On line 11 we set timer 0 to clear every time a compare match A occurs This allows us to alter how fast the timer resets with more control than just changing the count source On lines 12 and 13 we set the timer output to go high every time there is a compare match A and to go low when there is a compare match B This allows us to control the fre quency using time constant register A TCORA and the duty cycle using time constant register B TCORB On lines 14 and 15 we set the frequency and duty cycle by assigning a value to timer constant registers A and B These are randomly chosen we will worry about getting an ex act frequency and duty cycle in Section 4 2 4 When running this code the pulse will be output on pin TMOO The GR SAKURA supports output TMOO on Port 2 pin 2 The output will automatically generate once pin mode is set and the timer is activated and set to generate an output on the respective pin when compare match A and or compare match B occurs TABLE 4 1 GR Sakura TMRO Port Map 8
59. MRO TCNT and TMR1 TCNT TMR2 TCNT and TMR3 TCNT as well cascade into one 16 bit register This holds true for the timer constant registers as well Address es TMRO TCNT 0008 8208h TMR1 TCNT 0008 8209h TMR2 TCNT 0008 8218h TMR3 TCNT 0008 8219h TMRO TCNT TMR2 TCNT TMR1 TCNT TMR3 TCNT b7 b6 b5 b4 b3 b2 bi bO b7 bE b5 b4 b3 b2 b bO Value after reset 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Figure 4 3 Timer Counter TCNT Register 1 page 1017 The TCNT register is where the count is held After the timer is started this register will in crement every time a count is detected If you want to know the current count you can read this register If the timer is stopped you can write a value to this register and it will begin counting from the written value when re started Timer Counter Control Register The Timer Counter Control Register TCCR controls where the timers count source comes from Dependent on what value is set here it will be determined if the count comes from the internal peripheral clock a pre scaled peripheral clock an external count source or from an other timer overflowing This register also enables the timer s interrupts on the peripheral level Address es TMRO TCCR 0008 820Ah TMR1 TCCR 0008 820Bh TMR2 TCCR 0008 821Ah TMR3 TCCR 0008 821Bh b7 b6 b5 b4 b3 b2 b bo TMRIS CSS 1 0 CKS 1 0 Value after reset 0 0
60. Ms timers A2 8 A3 Read input SA L and SA R A0 and A1 Compare counter A0 and A1 every 15 pulses YES TURNCOUNT 4 Increase A2 by 1 bit Read AO continuously is count gt 280 Set direction DR L 1 and DR R 1 Increase turncount variable by 1 Read A0 continuously is count gt 90 Read turncount NO TURNCOUNT lt 4 Figure 4 16 Advanced motor control flowchart implemented 1 X 1 Meter square 108 RENESAS SAKURA MICROCONTROLLER BOARD 4 2 7 1 Using Timers Counters 8 Pulse Output Based on the above flowchart and the pin configuration for the GR SAKURA in our code we will use TMCI1 Port C pin 4 as the CLK input to timer TMR1 to count the motor ro tations of the left motor and TMCI2 Port C pin 6 as the CLK input to timer TMR2 to count the motor rotations of the right motor We are going to need to be able to clear the event counter each time our desired value is reached Because our timers are setup in event counter mode and our input is an external source we need to configure the counter clear as an external source However we will specify an output pin and generate logic high on that pin when we need to clear the counter The input to TMRI1 counter clear and TMR2 counter clear are defined as TMRI1 and TMRI2 respectively in the RX63 MCU datasheet The GR Sakura pin layout shows TMRI1 to be assigned to port 2 pin 4 and TMRI to be assigned to port
61. O6 AN4 1051 71 PE7 D15 A15 D15 MISOB IRQ7 AN5 1042 80 PD6 D6 A6 D6 MTIC5V POE1 IRQ6 AN6 122 4 3 1 RENESAS SAKURA MICROCONTROLLER BOARD Reconfiguring the pin layout is substantially complex and requires substantial changes to the pre defined I O and methods and requires an advanced knowledge of embedded sys tems design which is beyond the scope of this book However do not let this discourage you from attempting advanced embedded design Let s start by getting familiar with the 10 bit A D converter 10 Bit ADC The 10 bit A D converter unit allows up to 8 analog input channels ANO to AN7 and one extended analog input channel ANEX1 to be selected The 10 bit A D converter has three operating modes Single channel mode A D conversion is to be performed only once on the analog input of the specified single channel or a single extended analog input Scan mode Continuous scan mode A D conversion is to be performed sequentially on the analog inputs of the specified channels up to eight or the extended analog input 1 ANEX1 Single scan mode A D conversion is to be performed for one cycle on the analog inputs of the specified channels up to eight or the extended analog in put 1 ANEX1 Figure 4 19 lists the specifications of the 10 bit A D converter and Figure 4 20 shows the block diagram of the 10 bit A D converter Input Pins Figure 4 19 lists the input pins of the 10 bit
62. RO CMIAn and TMRO CMIBn IRQ in the Interrupt Control Unit Next we need to set the interrupt priority for CMIAn and CMIBn The default is 0 which also de activates the interrupt To set inter rupt priority we use IPR TMn CMIAn and IPR TMn CMIBn Interrupt priority is de fined from one to fifteen with one being the highest priority and fifteen being least priority Lastly we clear the interrupt bit just in case it was set previously by using IR TMRn CMIAn and IR TMRn CMIAn All of the other register configurations for the timer are set the same as they were in section 4 2 3 Now we will cover an example of setting up a timer for pulse output using interrupts First let s start with configuring TMRO to generate an interrupt at compare match A and compare match B 1 void InitPWMs void 2i SYSTEM PRCR WORD 0xA502 setting PRCR1 writes enabled Bx MSTP TMRO 0 Activate TMRO unit 4 SYSTEM PRCR WORD 0xA500 setting PRCR1 writes enabled 5 TMRO TCCR BIT CSS 1 Count source is PCLK 6 MRO TCCR BIT CKS 6 Adjust count source to PCLK 8192 42 ms Ta MRO TCR BIT CCLR 1 Timer resets at compare match A 8 MRO TCORA OxDF Frequency 42 ms period 9 MRO TCORB 0x70 Duty cycle 503 10 11 TMRO TCR BIT CMIEA 1 compare match A interrupt enabled 12 TMRO TCR BIT CMIEB 1 compare match B interrupt enabled 18 14 IEN TMRO CMIAO 1 enable compare match interr
63. RO CMIBO 1510 void Excep TMRO CMIBO void And change them to TMRO_CMIAO extern void Excep TMRO CMIAO void TMRO_CMIBO extern void Excep TMRO CMIBO void CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 103 Next we need to mask those functions in extern C in our c file Pp ifdef cplusplus extern C void Excep TMRO CMIAO void void Excep TMRO CMIBO void fendif Now that we have our timer and interrupts configured We need to choose which pin we would like to see our pulse output on For this example we will generate a pulse output on port 2 pin 2 void setup pinMode PIN P22 OUTPUT The loop function will be empty and only be used to keep the application running while the pulse is generated on the designated output pin We will also need to declare the functions which will be called when a compare match A or a compare match B occurs on TMRO Similarly to how we utilized OSA and OSB to trigger a digital high output when a compare match A occurred and a digital low output when a compare match B occurred we will use the interrupt on compare match A and the interrupt on compare match B to generate digital high and a digital low respectively void Excep TMRO CMIAO void digitalWrite PIN P22 0N void Excep TMRO CMIBO void digitalWrite PIN P22 0FF Remember that the organization of the function calls can determine whether your program compiles or not Putti
64. Requirements Customer Requirements Operational Requirements Performance Requirements Physical and Installation Requirements Maintainability Requirements Interface Requirements 28 RENESAS SAKURA MICROCONTROLLER BOARD Additional Certification Requirements m Derived Requirements For example consider an embedded system that notifies the pilot if he or she is flying too low to the ground An operational requirement could be that the system is able to perform its functional requirements in extremely low temperatures such as 50 degrees C Or that the system would be able to maintain its functional requirements in the event of a sudden spike in voltage such as a lighting strike Consider a child s toy that requires to be made of a metal alloy A safety requirement could be that these toys not contain lead which poses a health risk to young children Let s take a close look at each category of requirements Safety requirements are determined by identifying and classifying associated func tional failure conditions Functional Requirements specify the desired performance of the system under the associated conditions which consist of a combination of Customer desires Operational constraints Regulatory restrictions Implementation realities All functions should be evaluated for their safety related attributes Customer requirements vary with type of function type of system under considera tion desired features operating practices
65. Standard Version Renesas 32 bit RX63N Group MCU R5F563NBDDFP is on board RX63N Group Specifications Arduino UNO compatible pin headers ready for its shields GR SAKURA FULL Full Featured Version GR SAKURA board with LAN connector RJ 45 USB host connector DC power supply jack and MMC card shell For more detailed specifications of GR SAKURA and GR SAKURA FULL refer to Wakamatsu Tsusho s website Cy http akibanet kan com gr index_en htm Renesas Web Compiler Figure 3 20 MyRenesas GR SAKURA Web Compiler Home Page 56 RENESAS SAKURA MICROCONTROLLER BOARD After clicking on Login click on register when prompted to login Login Please login to proceed the process Email Address Password Cancel Close Forgot your password New user Click here to register now Figure 3 21 MyRenesas New User Choose your preferred language when the next window appears Choose Region and Language Americas English Maintand China Hong Kong Region ikp English Singapore South amp Southeast Asia Oceania English Asia South Korea Taiwan Region English REPL English Europe Middle East Africa English Japan Bae Figure 3 22 MyRenesas Language Selection STEP 2 CHAPTER 3 GETTING STARTED WITH GR SAKURA 57 Fill in the reguired information on the ne
66. TCNT and count condition 1 page 1020 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 83 CHANNEL B4 B3 B2 B1 BO DESCRIPTION 0 0 0 Clock input prohibited TMR1 0 TMR3 1 Usesexternal clock Counts at rising edge 1 O Uses external clock Counts at falling edge 1 Uses external clock Counts at both rising and falling edges Uses internal clock Counts at PCLK Uses internal clock Counts at PCLK 2 Uses internal clock Counts at PCLK 8 Uses internal clock Counts at PCLK 32 Uses internal clock Counts at PCLK 64 Uses internal clock Counts at PCLK 1024 Uses internal clock Counts at PCLK 8192 Clock input prohibited 1 O Setting prohibited 1 1 Counts at TMRO TCNT TMR2 TCNT overflow signal O O O O Notes 1 To use an external clock set the PORTn PDR Bi bit for the corresponding pin to O and the PORTn OPMR Bi bit to 1 For details see 1 section 21 VO Ports 2 If the clock input of TMRO TMR2 is the overflow signal of the TMR1 TCNT TMR3 TCNT counter and that of TMR1 TMR3 is the compare match signal of the TMRO TCNT TMR2 TCNT counter no incrementing clock is generated Do not use this setting Figure 4 6 Clock input to TCNT and count condition 1 page 1020 Continued Time Constant Register The TCORA Time Constant Register A and TCORB Time Constant Register B are used to store constants to compare against the T
67. TPUT pinMode PIN_LED1 OUTPUT pinMode PIN_LED2 OUTPUT PIN_LED3 OUTPUT r r r r pinMode digitalWrite PIN LEDO LOW digitalWrite PIN LED1 digitalWrite PIN LED2 PIN LED3 O O digitalWrite In our main loop our program will wait to be triggered by the press of the blue switch SW1 once SW1 is pressed we will enter a never ending loop In this loop we enable the motor to rotate and trigger LEDO to turn on once our interrupt has been triggered 200 times LEDO and LED1 when triggered 400 times LEDO through LED2 when trig gered 600 times and LEDO through LED3 when triggered 800 times Once the interrupt has been triggered 1000 times we turn off all of the LEDs and reset our motor count to 0 34 35 36 37 38 39 4 o S S S O O V OU B UO N H UI void loop motorCountA 0 while digitalRead PIN SW HIGH while 1 digitalWrite enableA HIGH if motorCountA 200 digitalwrite PIN LEDO HIGH PIN LED1 LOW PIN LED2 LOW PIN LED3 LOW digitalWrite digitalWrite digitalWrite if motorCountA 400 digitalWrite PIN LEDO HIGH PIN LED1 HIGH PIN LED2 LOW PIN LED3 LOW digitalWrite digitalWrite digitalWrite 4 2 4 Diles 52 53 54 D5 56 Deis 58 59 60 61 62
68. UTPUT 534 pinMode enableA OUTPUT 54 pinMode directionB OUTPUT DD pinMode enableB OUTPUT 26 initialize the counters and the Pulse width modulatators ST InitPWMs 58 interrupts 59 Port P12 IRQ2 function call RISING 3 Interrupt occurs for LOW to 60 HIGH state 61 attachInterrupt 2 myEventCounterA 3 62 Port P13 IRQ3 function call RISING 3 Interrupt occurs for LOW to 63 HIGH state 64 attachInterrupt 3 myEventCounterB 3 65 Start with getting ready to move forward by making sure the 66 motors are disabled and direction is set to move forward 67 digitalWrite directionA Abackward 68 digitalWrite directionB Bforward 69 70 void loop 71 i 0 72 startMotors 0 ese motorCountA 0 74 nextTurn 1 75 nextForward 0 76 while digitalRead PIN SW HIGH 71 startMotors 1 78 while i lt 4 79 if motorCountA lt motorCountB amp amp nextTurn 1 80 TMRO TCORA OxFB Frequency 81 TMR1 TCORA OxFE Frequency 82 83 if motorCountA gt motorCountB amp amp nextTurn 1 84 TMRO TCORA OxFE Frequency 85 TMR1 TCORA OxFB Frequency 86 87 if motorCountA motorCountB amp amp nextTurn 1 88 TMRO TCORA OxFE Frequency 89 90 91 92 23 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 N H o O0 JI Oo U B WN H
69. What is the difference between compilers used for embedded systems and com pilers used for desktops PCs 9 How does the linker differ from the compiler DU NS 34 RENESAS SAKURA MICROCONTROLLER BOARD 10 11 12 13 14 15 16 17 18 What are magic numbers List five example systems that would have safety requirements What are the primary tools for debugging code Create a set of requirements for a vending machine which accepts coins and one dollar bills and provides change Assume that each type of item has its own button Create a set of requirements for a controller for an elevator in a ten story building What are the ten types of requirements Describe the V model of software development What is a flowchart and how can it be useful in designing software Create a flow chart for an elevator in a ten story building TES si Chapter 3 Getting Started with GR Sakura 3 1 3 2 3 2 1 LEARNING OBJECTIVES In this chapter the reader will learn about m Basic Concepts and Architecture of the Renesas GR Sakura board and the RX63N Microprocessor Introduction and utilization of general digital inputs outputs Software development using the GR Sakura development tools amp Embedded System SAKURA EMBEDDED SYSTEM Sakura Board Design The GR Sakura is one of the Gadget Renesas board series It is based on RX63N series 32 bit MCU The MCU has on chip flash memory and enhanced communication func
70. ally on the analog inputs of the specified channels up to eight or the extended analog input 1 ANEX1 Single scan mode A D conversion is to be performed for one cycle on the analog inputs of the specified channels up to eight or the extended analog input 1 ANEX 1 Software trigger 6 synchronous A D conversion triggers from MTU TPU or TMR 1 asynchronous A D conversion trigger A D conversion can be started by the ADTRG pin Sample and hold function Number of sampling states is adjustable Self diagnostic functions of the 10 bit A D converter After the end of A D conversion an interrupt request ADIO is generated DMAC and DTC can be started by an ADIO interrupt Module stop state can be set Specifications of the 10 bit A D Converter 1 page 1686 124 RENESAS SAKURA MICROCONTROLLER BOARD Internal Module data bus 2 ae M 90 0 0 0 8 S 5 E m 3 VREFH ty Se lt mM O OU UL O I a a X 5 E 10 bit sal EE EE EEE o S5 E 5 lt i DA Pa 8 a aa 8 aa oa 80 ge Q VREFL gt 3 lt lt lt lt lt lt lt lt ESE SE Q o i OUUUL ANO gt AN1 10 bit A D converter N Synchronous AN2 gt p Control circuit gt D A conversion AN3 i enable signal AN4 gt T Compa
71. ames of integers CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 21 b7 bo Signed byte 8 bit Integer b7 bo Unsigned byte 8 bit Integer b15 bo Signed word 16 bit Integer b15 bo Unsigned word 16 bit Integer b31 bo Signed longword 32 bit Integer b31 bo Unsigned longword 32 bit Integer Figure 2 9 Integer 1 page 31 2 Floating Point The IEEE standard defines four different types of precision for floating point oper ations They are single precision double precision single extended precision and double extended precision Most of the floating point hardware follows IEEE 754 standard s single and double precision for floating point computations The RX Family supports single precision floating point computation b31 DO EN Figure 2 10 Floating point 1 page 31 Single precision Floating point S Sign 1 bit E Exponent 8 bits FL Mantissa 23 bits 3 Bitwise operations There are different types of bit manipulation instructions available in the RX63N to use with operations like AND OR or XOR 4 Strings The string data type consists of an arbitrary number of consecutive byte 8 bit word 16 bit or longword 32 bit units 22 RENESAS SAKURA MICROCONTROLLER BOARD 2 4 SOFTWARE DEVELOPMENT TOOLS 2 4 1 Compilation Mechanism There are several steps involved from the stage of writing a C program t
72. ams They complicate code maintenance because if a magic number is used in multiple places and if a change is needed then each location must be revised and it is easy to forget about one Similarly some magic numbers may de pend on others e g a time delay may depend on the MCU s clock rate It is much better to use a const variable or a preprocessor define to give the value a mean ingful name which can be used where needed It is important to track available design margin as you build the system up How much RAM ROM and nonvolatile memory are used How busy is the CPU on average How close is the system to missing deadlines The Software Gas Law states that software will expand to fill all available resources Tracking the resource use helps give an early warning Software configuration management should be used as the code is developed and maintained to support evolving code and different configurations as well 2 6 2 7 2 8 CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 33 We will explore how to code the algorithm from Figure 2 11 once we get a little more fa miliar with the GR SAKURA board and tools RECAP It should now be easier to understand how the embedded systems you encounter in your everyday life actually operate and communicate with the outside world It should also be easier to break some of these systems down into their component parts given the knowl ed
73. and robotics REFERENCES 1 Renesas Electronics Inc February 2013 RX63N Group RX631 Group User s Manual Hardware Rev 1 60 2 Conrad James M 2013 Embedded Systems An Introduction using the RX63N Microcontroller Mi crium Press 3 Digilent Inc August 2012 Motor Robot Kit MRK Reference Manual Rev 4 Digilent Inc February 28 2012 Digilent PmodHB5 2A H Bridge Reference Manual Circuit Rev D Document Rev 5 Shayang Ye April 2010 DC Carbon brush motors IG 22 Geared Motor Series IG 22GP Type 01 amp 02 76 3 11 RENESAS SAKURA MICROCONTROLLER BOARD EXERCISES uey A Write the Sakura code to light up all of the LEDs when the switch has been pressed What pins need to be set to turn LEDO and LED1 on What is the purpose of a debouncing circuit To turn 90 degrees in place which direction do the motors need to be moving Write the Sakura code to turn the motors of your robotic vehicle in a one meter circle Consider a robotic vehicle like the one from this chapter The motor has 1 19 gear ing and the wheel diameter is 9 cm a How many revolutions of each motor are needed for the vehicle to move 1500 cm in a straight line b How many seconds will it take if the motors rotate at 4500 rpm c Answer part a and b for a gear ratio of 1 53 Consider a robotic vehicle like the one that is used in this chapter The motor has 1 53 gearing and the wheel diameter is 7 cm The w
74. bat tery pack that will be required to power the robot Can you think of some more derived re quirements that would associate with our design choice of the Motor Robot Kit Assembly from Digilent Ro 6 1685 7 854 in Figure 3 39 Vehicle Rotation 3 8 3 Developing Code So now that we have an in depth understanding of what we will need to implement basic con trol of the vehicle let s create an algorithm that meets our reguirements and that we can code 1 2 3 Initialize variables and constants Setup the pin mode for the direction and enable to each H Bridge Initialize the direction of each motor so that both wheels will be turning in the forward direction Wait for the push button to be pressed SW1 Once the switch is pressed SW 1 enter a loop that will move the robot in a 1 X 1 meter square Enable the motors for 2 379 seconds to move the robot forward for one meter Disable the motors for 0 5 seconds to keep the H bridge from shorting prior mo tor direction change set enable pins 0 CHAPTER 3 GETTING STARTED WITH GR SAKURA 73 8 Update the direction of the left wheel to backward keep the right wheel direction forward 9 Enable the motors for 0 399 seconds to make a 90 degree turn 10 Disable the motors for 0 5 seconds keep H bridge from shorting 11 Update the direction of the left wheel to forward keep the right wheel direction forward 12 Repeat steps 6 11 three more times 13 Disable the moto
75. c SCId RSPI LOFP I O PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT ADO 95 P40 IRQ8 DS ANOOO AD1 93 P41 IRO9 DS ANOO1 AD2 92 P42 IRQ10 DS AN002 AD3 91 P43 IRQ11 DS AN003 AD4 90 P44 IRQ12 DS AN004 AD5 89 P45 IRO13 DS AN005 The 10 bit ADC cannot be utilize with the defined A D pins AN001 AN005 However the GR SAKURA does provide access to the 10 bit ADC using the pins shown in Table 4 4A TABLE 4 4A GR Sakura 10 bit A D Converter Port Map 8 PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SCIc SCId RSPI LQFP I O PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT 1044 78 PEO D8 A8 D8 SCK12 SSLB1 ANEXO 1045 UY PE1 D9 A9 D9 MTIOCAC TXD12 SMOSI12 ANEX1 PO18 SSDA12 TXDX12 SIOX12 SSLB2 RSPCKB 1046 76 PE2 D10 A10 D10 MTIOC4A RXD12 SMISO12 IRQ7 DS ANO PO23 SSCL12 RXDX12 SSLB3 MOSIB 1047 75 PE3 D11 A11 D11 MTIOC4B CTS12 RT S12 SS12 AN1 PO26 POES MISOB ET_ERXD3 1048 74 PE4 D12 A12 D12 MTIOCAD SSLBO ET_ERXD2 AN2 MTIOC1A PO28 1049 75 PES D13 A13 D13 MTIOC4C RSPCKB ET_RX_CLK IRQ5 AN3 MTIOC2B REF50CK 1050 12 PE6 D14 A14 D14 MOSIB IRO6 AN4 1051 al PE7 D15 A15 D15 MOSIB IRQ7 AN5 1042 80 PD6 D6 A6 D6 MTIC5V POE1 IRQ6 AN6 1043 79 PD7 D7 A7 D7 MTICSU POEO IRQ7 AN7 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 121 To accommodate the limited amount of pins to support the MCU functionality Renesas manufactured the GR SAKURA to be
76. can control them to meet the customer s requirements Based on what we have learned so far all we have to work with is a time Now that we know how to keep LEDs flashing for a certain amount of time or keep the motors enabled for a certain amount of time for how many seconds do we enable the motors so that they 70 RENESAS SAKURA MICROCONTROLLER BOARD travel a full meter To answer that guestion we need to take a look at the datasheet for the 1G 22GM and find out how quickly the Motors rotate From the datasheet we know that each IG 22GM motor s power source can be either 12 V or 24 V And Figures 3 37 and 3 38 tell us how quickly the motors will theoretically rotate given a 12 V or a 24 V source So which one should we consider SEFE MOTOR DATA EISER RH EROR HER RAO RATER EREN R Rated volt Rated torgue Rated speed Rated current No load speed No load current Rated output Weight v g cm rpm mA rpm mA W 9 12 22 6700 200 8000 70 1 5 32 0 24 22 7400 lt 110 9000 40 17 32 0 Figure 3 37 Motor Data 5 page 1 RSS MOTOR CHARACTERISTICS Po EF I N Po EF I N 3 0 100 1000 8000 01 TYPE 34 100 600 9000 R 02 TYPE 12V 24V EF 1 5 50 500 4000 1 7 50 300 4500 W mA rpm W mA rpm Tm 25 50 78 10 12 150 Tem 25 50 78 100 1
77. ccessfully resolve a signal of half this fre quency This frequency is known as Nyquist frequency If a signal of frequency greater than the Nyquist frequency is sent to the ADC to be converted the output will not be the correct binary value of the analog input This phenomenon is called Aliasing Usually to prevent frequencies higher than Nyquist fre quency from going to the ADC low pass filters are placed before the ADC Usually an ADC has a sample and hold circuit and a comparator The analog signal is first sampled according to the sampling frequency and then given to the sample and hold circuit The sampling rate or conversion speed of an ADC circuit is limited by the sam ple and hold but does not determine the sample rate The sample and hold circuit is a one time snapshot of the sampled input signal When A D conversion of a DC signal is to be performed conversion is simple but when the input changes within the conversion cycle of the ADC the digital representation of the analog input might be inaccurate To solve this problem a sample and hold circuit is placed in front of the ADC unit The sample and hold circuit usually consists of a switch and a capacitor CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 119 Sampling Switch oo Output Signal Input Signal ac QD Hold Capacitor Figure 4 18 Sample and Hold Circuit Signal from the sample and hold circuit is then given to the comparator The comparator compar
78. city of 2 Mbytes RAM capacity of 128 Kbytes E Data Flash of 32 Kbytes and operates at a maximum fre quency of 96MHz single precision FPU built in power divider 44 RENESAS SAKURA MICROCONTROLLER BOARD 3 3 SAKURA SOFTWARE DEVELOPMENT The compiler for GR Sakura is available in the cloud and is a GNU based compiler Rene sas has also developed an Applet on the Android smart phone which makes it possible to build an application with a module plug in In this way anyone can build a system without complex programming First we need to make sure that the GR SAKURA firmware is up to date Make sure that SW3 is in run mode as shown in the Figure 3 5 GR SAKURA 7 43 RESET Figure 3 5 Switch 3 Run Mode Connect the GR Sakura board to your computer with a USB to mini USB cable Figure 3 6 Connecting the GR SAKURA CHAPTER 3 GETTING STARTED WITH GR SAKURA 45 Press the red button to reset the board The PC will then register the GR SAKURA board as a memory drive also known as a USB drive d EE Er GR SAKURA Figure 3 7 Reset the GR SAKURA MCU The board s LEDs should be lit up blue and blink in unison this indicates that the board is ready for programming Go to computer by clicking Start gt Computer You should see the device show up here if the device does not show up it means that either the driver has not fin ished installing on your PC or your system does not support this har
79. code optimization trade offs Second a lower clock rate means that embedded systems have a smaller performance penalty than GPPs for accessing memory instead of registers 24 2 4 3 2 4 4 RENESAS SAKURA MICROCONTROLLER BOARD This has two interesting effects First the compiler makes different optimization trade offs with data allocation Second instruction sets for embedded systems can support memory memory and bit level operations rather than being forced into a load store model Debugger There are two primary tools for debugging embedded real time systems a Debugger The debugger allows a developer to observe and control a program s execution and data The execution can be started paused and stopped or advanced by a single instruction or program statement Breakpoints can typically be in serted Data stored in variables as well as raw memory and register values can be examined and modified Monitor The monitor allows a developer to examine the program s temporal be havior The most common monitors are oscilloscopes and logic analyzers con nected to the embedded system For instance while implementing interrupts in se rial communication one can measure useful information such as the duration of the transmit ISR and the receive ISR or the delay between sending a character and receiving a reply This information can be used to find maximum latency and max imum frequency Hence the monitor tool is helpful in giving
80. ction 1 page 1690 WHEN ADCR MODE 1 0 00B 0 0 0 0 1 1 1 0 Se 1 AN1 AN2 AN3 AN4 AN5 AN6 AN7 WHEN ADCR MODE 1 0 10B OR 11B 0 0 0 0 0 1 ANO AN1 ANO to AN2 ANO to AN3 ANO to AN4 ANO to AN5 ANO to AN6 ANO to AN7 Paes ea 0 0 ANO 0 0 ANO 128 RENESAS SAKURA MICROCONTROLLER BOARD The A D Start bit ADST is used to start or stop the ADC Setting this bit to 1 starts the ADC and setting it to 0 stops the ADC The A D Scan Conversion End Interrupt Enable ADIE is used to enable or disable the A D scan conversion end interrupt ADI When A D conversion is complete an interrupt is generated Setting the ADIE bit to 1 enables the interrupt and setting it to 0 disables the interrupt Figure 4 23 summarizes all of the possible configurations for the A D control status register Address es 0008 0810h b7 b6 b5 b4 b3 b2 b1 bo ADIE ADST CH 2 0 Value after reset 0 0 0 0 0 0 0 0 b2 b4 b5 b6 b7 tobO CH 2 0 Channel Select When ADCR MODE 1 0 00b When ADCR MODE 1 0 10b or 11b b2 bo b2 bo 0 0 0 ANO 0 0 0 ANO 001 AN1 00 1 ANO AN1 0 1 0 AN2 0 1 0 ANO to AN2 0 11 AN3 0 1 1 ANO to AN3 100 AN4 1 0 0 ANO to AN4 101 AN5 101 ANO to AN5 1 10 AN6 1 1 0 ANO to AN6 111 AN7 1 1 1 ANO to AN7 b3 Reserved These bits are read as 0 The write value should be 0 ADST A D Start 0 Stops A D conversion 1 Start
81. ctive of the MCU the signal is going out and therefore would be consid ered an output For the digitalWrite method we need to identify the pin we are trying to target The second integer reguires a value to set the state of the LED To turn on the LED we will need to define this integer as either a 1 or a 0 depending on whether our pin is active low or active high The board schematic defines the ON OFF state of the LEDs Or we can iden tify this by setting all of the LEDs to 0 and building our project If the LEDs are on then we know our LEDs are active low CHAPTER 3 GETTING STARTED WITH GR SAKURA 49 The delay method is defined in milliseconds Given that the constant INTERVAL has been defined to 100 we should expect that once LEDO turns on there will be a 100 millisecond delay before LED1 turns on and so on 1 void delay unsigned long ms Now if we put it all together we should expect that the LEDs will turn on in successive or der and then turn off in successive order and that this process will indefinitely repeat itself until we reset or turn off our microcontroller Now that we know what to expect let s see if it works Click on the build function in the top bar of the web compiler to build the project The project should build without er rors When the window in Figure 3 11 pops up go ahead and click ok Build The RX Arduino Labl has been compiled with no error Figure 3 11 Compilation Status pop up Yo
82. ctor Often a manu facturer will hire subcontractors to design and build individual sub systems This allows the manufacturer to pit potential subcontractors against each other keeping prices down There may be size and weight limits for portable and mobile applications An em bedded system for an automotive remote keyless entry transmitter must fit into a small fob on a key ring which fits easily into a pocket Similarly the receiver must not be too heavy A heavier car will have worse acceleration braking cornering and fuel efficiency Aircraft and spacecraft are especially sensitive to weight since a heavier craft requires more fuel to achieve the same range There may be limited power or energy available For example a battery has a lim ited amount of energy while a solar cell generates a limited amount of power High temperatures may limit the amount of cooling available which will limit the power which can be used The environment may be harsh Automotive electronics under the hood of a car need to operate across a wide range of temperatures 40 C to 125 C or 40 F to 193 F while withstanding vibrations physical impact and corroding salt spray Spark plugs generate broadband radio frequency energy which can interfere with electronics 1 7 DEVELOPING EMBEDDED SYSTEMS So who develops embedded systems There are many different people who contribute to a final embedded systems product These include engineers and scienti
83. d such as toggling an output signal trigger ing an interrupt Before covering how the timer works more specifically we will briefly de scribe the 8 bit timer device s registers and how they work Figure 4 2 is a block diagram of timer unit 0 unit 1 is identical except for naming dif ferences e g timer2 in place of timer0 and timer3 in place of timer1 We will start by first covering the registers that are used when setting up a timer channel The legend in the bottom left of Figure 4 2 lists the registers you need to consider when setting up the 8 bit timer unit For some registers we have an illustration included of the registers contents taken from the RX63N User s Manual Hardware Make note of the register parts as we will use these later when setting them up for specific features Further details are available in the hardware manual if needed 80 RENESAS SAKURA MICROCONTROLLER BOARD Freguency dividing clock PCLK PCLK 2 PCLK 8 PCLK 32 PCLK 64 PCLK 1024 PCLK 8192 Y Counter clock 1 TMCIO gt Counter clock 0 TMCI1 Clock select ESET vo areri fe ji r a 1 I It i TCORA HH TCORA on P Compare match A1 M i U Compare match A0 r Comparator A071 Comparator A1 TO SCI5
84. d a 16 bit counter there will be approximately 83 88 ms between each over flow interrupt 1 64 clock division s 65535 counts per interrupt 83 88 ms 50 MHz peripheral clock 1 1 To set up a timer unit in 16 bit cascaded timer mode set in TMRO TCCR CSS 1 0 bits to 11b This effectively sets the count source for timer 0 as timer 1 Whenever TCNT in timer 1 over flows timer 0 will count once In effect this makes TMRO TCNT and TMR1 TCNT combine into a single 16 bit register The speed at which timer 1 can count is still determined in TMR1 TCCR CSS and TMR1 TCCR CKS The settings for clearing the counter and inter rupts are now controlled by the TMRO TCR register any settings in TMR1 TCR are ignored Figure 4 12 lists the approximate time between overflow for each clock division TIME BETWEEN OVERFLOW CLOCK DIVISION TIMER PER COUNT IN 16 BIT MODE PCLK 20 ns 1 3107 ms PCLK 2 40 ns 2 6214 ms PCLK 8 160 ns 10 4856 ms PCLK 32 640 ns 41 9424 ms PCLK 64 1 28 us 83 8848 ms PCLK 1024 20 48 us 342275 PCLK 8192 163 84 us 1075373 s Figure 4 12 Clock division characteristics 88 RENESAS SAKURA MICROCONTROLLER BOARD For this demo we will be setting up the 8 bit timer TMRO in cascaded timer mode by cas cading timer TMRO and timer TMRI together We will poll for the cascading timer to reach OxFFFF Once the count reaches OxFFFF a function that rotates the LEDs on the board will be called The resulting program will make the L
85. data During processing the data needs a temporary or short term storage area After processing the data will be stored in a long term storage area The Data Movement Block provides a data path between the outside environment and the computer This block is also responsible for the data flow between various subcompo nents within the computer 13 14 RENESAS SAKURA MICROCONTROLLER BOARD Data storage facility Data ale 1 Data Control ei movement mechanism gt E destination Data processing facility Figure 2 1 A generalized view building blocks of a computer The Control Mechanism takes care of controlling and managing various subcomponents and their interactions with each other Computers have four basic structural components See Figure 2 2 CPU Processes the data and controls the operation of the computer Memory Stores data VO Moves the data between the computer and the external environment System Interconnection Provides a mechanism for transferring data or communi cating between components such as the CPU main memory and I O ADNa Figure 2 2 A top level view of computers System interconnection The Central Processing Unit CPU is the most complex component out of the four basic components The structure of the CPU is illustrated in Figure 2 3 The components that make up a CPU are 1 Control Unit Controls the ope
86. dware Updating the firmware could resolve this problem If you are not able to see the GR SAKURA folder then skip to section 3 4 2 If you do see the device then double click the GR SAKURA folder to open There you should see an html file SAKURA BOARD for Gadget Renesas Project Home Double click the file to go to the SAKURA board website Once on the website click the English link to show the website in English As you can see from the figure below this website will help guide you along in starting your development using the GR SAKURA SAKURA BOARD toe Roes rise RE Dpen the box and read kick start card Set Slide switch to RUN Connect your PO with a USB cable Check blue LEDs flashing Open GR SAKURA drive Try quest bein Create new project Type project name Build Check no compile error Download sketch bin Find downloaded tile Copy to GR SAKURA dr me Check program running Use editor View the source Modity the source Budd Check no compde error Figure 3 8 Home page of the GR SAKURA board website 46 3 4 RENESAS SAKURA MICROCONTROLLER BOARD SAKURA EXAMPLE PROJECT Let s go through the sample project to get better acclimated with the development tools for the GR SAKURA board From the SAKURA board website click on the Try Guest Login link When you first login a window will pop up asking you to create a project You will need to select a template and a project name as seen below L
87. e 10 bit converter 122 Single extended precision of floating point operations 21 Software debouncing 60 Software development code development see code development of compilation mechanism 22 24 computer organization and architecture of 13 15 debugger 24 decisions technical and process 26 development lifecycle overview 26 27 Software development introduction to compilers for embedded systems 23 24 integrated development environment example of 23 26 microcontrollers basics of 16 20 robotics application 29 30 Sakura software development see Sakura system requirements defining of 27 29 tools for development of 22 26 Software Gas Law 23 Source language 23 Speed optimization 23 SPI 43 Square wave 98 Static analysis 32 Stepper motors 62 Strings 20 Structure of port 18 19 Sub clock oscillator 40 Switches as inputs 58 61 of Sakura board 36 System clock ICLK 40 System interconnection 4 System requirements software development 27 29 T TCCR 81 83 TCNT 81 82 83 TCORA 83 84 TCORB 83 84 TCR see timer control register TCR TCSR 84 85 Technical decisions 26 Temperature sensor 43 10 bit A D converter block diagram of 124 description of 122 initialization of 125 32 input pins 122 125 registers of 125 32 126 registers setting up 132 set up and use of ex 132 34 specifications of 123 Terms definition of 43 Timer constant register A TCORA
88. e there and how are they connected What type of microcontroller and peripherals will be used What major pieces of software will there be How do they communicate What will make them run at the right time After we have decided upon an architecture for the system we can work on de signing the subsystems within it Again graphical representations can be quite useful 2 5 6 CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 31 especially if the corresponding requirements are graphical as in this and similar cases they can be reused Figure 2 15 shows a high level flowchart for the robot requirements from Section 2 5 3 Start Switch Turn Motors Forward No No End Right Turn Figure 2 15 Flowchart for a robot traveling in a square pattern Convert your Algorithms to Code Now that we have a detailed design it should be straightforward to proceed to the actual implementation of the code C is the dominant programming language for embedded systems followed by C and Java C is good enough for the job even though there are some languages which are much safer The risk with C is that it allows the creation 32 RENESAS SAKURA MICROCONTROLLER BOARD of all sorts of potentially unsafe code There are a few points to keep in mind as you de velop the code Three fundamental principles should guide your decisions when implementing code simplicity generality and clarity Simplicity is ke
89. e to understand what you are saying analog This is done with the help of the ADC The output of the ADC is a binary word 8 bits or 10 bits or 12 bits that represents the analog input The reference voltage of an ADC is the maximum analog voltage that can be converted by an ADC 118 RENESAS SAKURA MICROCONTROLLER BOARD Analog Input gt Digital Output bits Reference Voltage p Figure 4 17 Simple ADC The number of bits that the digital output of the ADC contains is called the Resolution of the ADC A 12 bit ADC produces an output containing 12 bits and a 10 bit ADC produces an output with 10 bits A 10 bit ADC will have 1024 2 different binary outputs Thus in a 10 bit ADC a range of input voltages analog will map translate to a unigue binary output range 0000000000b to 1111111111b A 12 bit ADC will have 4096 Cas unique binary output values to represent 0 to 100 of an analog input The RX63N MCU has a 10 bit and a 12 bit ADC The rate at which the outputs are calculated in an ADC is called the sampling fre quency or conversion rate The term sampling frequency indicates how often the value of the incoming analog signal is checked sampled to convert into a discrete signal A fast changing analog signal needs an ADC with high conversion rate since the incoming signal has to be checked sampled more often or else information will be missed Thus the ADC with a sampling frequency of 1 0 us can su
90. e Hardware 68 3 8 3 Developing Code 72 3 9 Recap 75 3 10 References 75 3 11 Exercises 76 CHAPTER 4 Interfacing with the Outside World 77 4 1 Learning Objectives 77 4 2 Event Counters and Timers 77 Event Counter 78 4 3 CONTENTS 4 2 1 4 2 2 4 2 3 4 2 4 4 2 5 4 2 6 4 2 7 Setting Up a Timer for Counting Events Timer Count Register Timer Counter Control Register Time Constant Register Timer Control Status Register Timer Control Register Cascading Timers Using Interrupts as Event Counters void interrupts void void nolnterrupts void void detachinterrupt unsigned char interrupt interrupt number 0 7 void attachinterrupt unsigned char interrupt void void func int mode interrupt numbers 0 7 Setting Up a Timer for Pulse Output Setting up Timer interrupts for Pulse Output Frequency and Period Control Advanced Motor Control Robotics Application 4 2 7 1 Using Timers Counters Pulse Output 4 2 7 2 Using Interrupts Pulse output Counters Analog To Digital Converters 4 3 1 4 3 2 4 3 3 4 3 4 10 Bit ADC Input Pins A D Data Registers ADDRn n A to H Initializing the 10 bit A D Converter Module Stop Control Register A MSTPCRA A D Control Status Register ADCSR A D Control Register ADCR A D Control Register 2 ADCR2 10 bit A D Conversion A D Sensors Robotics Application 43 4 1 Using Timers Counters amp Pulse Output 4 3 4 2 Using Interrupts Pulse Output amp Counters 8
91. e digitalRead function accepts an integer as an input in this case the integer is the defined integer value of the pin we are trying to read and returns that integer value The structure of the functions can determine whether or not the program compiles The pro gram structure reguires that the setup function be declared This function is used to setup any registers prior to running the main loop of the program For the below program we use the setup function to configure the pin mode The loop function should contain the main body of the program from which all function calls are made include lt rxduino h gt define HIGH 1 define LOW 0 void setup PIN LEDO OUTPUT PIN LED1 OUTPUT PIN SW INPUT pinMode pinMode YD U B WN r pinMode 60 RENESAS SAKURA MICROCONTROLLER BOARD void loop while digitalRead PIN SW HIGH digitalwrite PIN LEDO HIGH digitalWrite PI EDI LOW digitalWrite PIN LEDO LOW digitalWrite PIN LEDL HIGH Dn U B U ND HO OO OO Contact bounce is a worry with any mechanical switch When the switch is closed the me chanical properties of the metals in the switch cause the contacts to literally bounce off of one another This can cause false signals to be read as inputs Your design should take this into account with either a hardware or software debouncing solution Hardware debounc ing circuits often req
92. e motor itself Other large coils such as relay coils should be treated similarly to motors Figure 3 27 shows a basic coil driving circuit Code to drive the coil is the same as it is to drive an LED 3 8 3 8 1 CHAPTER 3 GETTING STARTED WITH GR SAKURA 63 Vout R5F211A1DD VSS AVSS P1_0 AN9 KI01 CMPO_0 P1 1 ANB KIO CMPO 0 P1 2 AN10 K12 CMPO 2 P1 3 ANN11 KI3 TZOUT P1_4 TXDO P1 5 RXDO CNTRO1 NI11 P1_6 CLKO SSIO1 P1_7 CNTROO INI10 T2 2N3904 NIE BON R16 W P3 3 TCIN INI3 SS100 CMP1 0 P3 4 SCS SCA CMP1 1 P3 5 SSCK SCL CMP1 2 P3_7 CNIRO SSO IXD1 G EUC ES alo a a a a o o olo o oo GND Figure 3 27 Simple Coil Driver 2 page 22 There are other methods of controlling large loads with a microprocessor such as using re lays or triacs The overall concept with all load driving circuits is to keep the source and sink currents of the microprocessor within the manufacturer s recommendations Some sensors may require different voltages than what the microprocessor requires Care should be taken when interfacing these sensors If the microprocessor runs at 5 V and the sen sor runs at 1 8 V the microprocessor will not be able to read a HIGH logic signal on the sen sor output Circuits for interfacing with higher voltage sensors can be designed using transis tors or by using level converter ICs which convert the signals between the microcontroller and the sensor either unidirectional or bidirec
93. e resistor will pull the voltage on that pin to logic HIGH until the button connects to ground When the button is pressed the voltage at that pin will drop to zero logic LOW Figure 3 25 shows a schematic of this approach If the switch in Figure 3 25 is connected to Port 1 pin 0 the code to check this switch would be 1 i PORT1 PIDR BIT BO 0 Di Conditional code goes here CHAPTER 3 GETTING STARTED WITH GR SAKURA 59 VCC O R5F211A1DD o 5 E VSS AVSS F P1 O ANS KIO1 CMPO 0 18 o P1 1ANB KIO CMPO 0 15 N P1 2 AN10 K12 CMPO 2 EVE P1 3 ANN11 KI3 TZOUT EEN lo P1_4 TXDO 12 P1_5 RXDO CNTRO1 INI11 EER P1 6 CLKO SSIO1 ETE P1 7 CNTROO NI10 V 19 GND P3 3 TCIN INI3 SS100 CMP1 0 20 P3 4 SCS SCA CMP1 1 Figure 3 25 Switch Hardware Schematic 2 page 17 Remember that on line 1 of our application file the file include lt rxduino h gt has been included It is a custom header file created by Renesas for easy access and manipula tion of data Renesas provides additional h files containing defined functions such as the digitalRead function This function executes the behavior described above Once again we are provided the building block without having to design it ourselves Note that these h files are included into the rxduino h file Knowing how to utilize the functions and defini tions provided for us is very important Make sure to get familiar with the h files 1 int digitalRead int pin Th
94. e the interrupts work correctly TMRO_CMIAO void Excep TMRO CMIAO void S S O CC V OU B WN H UI CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 113 UserTMR0InterruptFunction modified on 2013 9 20 3 extern v weak function oid Excep TMRO CMIAO void TMRO_CMIBO void Excep TMRO CMIBO void extern v include include include include define B define directionA define enableA define directionB define enableB define Aforward define Abackward define Bbackward define ON define OFF oid Excep TMRO CMIBO void lt rxduino h gt lt iodefine gcc63n h gt lt intvect63n h gt lt interrupt h gt Port 2 pin 3 motor A direction Port 2 pin 2 PWM TMRO input to motor A Port 2 pin 5 motor B direction Port 2 pin 4 motor B on off A 0 NU forward H O E H int motorCountA 0 int motorCountB 0 int startMotors 0 int i 0 int nextTurn 0 int nextForward 0 void InitPWMs void void myEventCounterA void void myEventCounterB void ifdef cplusplus extern C void void void void fendif Excep TMRO CMIAO void Excep TMRO CMIBO Excep TMR1 CMIA1 Excep TMR1 CMIB1 void void f r void f 114 RENESAS SAKURA MICROCONTROLLER BOARD 51 void setup D2 pinMode directionA O
95. easurement are all stopped in their initial state Releasing the modules from the stopped state makes operations for frequency measurement possible Before we can utilize the 10 bit A D converter we would need to release the module from the stopped state by configuring bit 23 of the MSTPCRA 31 0 register Address es 0008 0010h CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 127 Value after reset Value after reset b31 b30 b29 b28 b27 b26 b25 b24 b22 b21 b20 b19 b18 b17 b16 MSTPA MSTPA MSTPA MSTPA MSTPA MSTPA ACSE 29 28 27 24 mi 19 17 0 1 0 0 0 1 1 O 41 1 1 1 1 1 1 1 Di5 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 bi bo MSTPA MSTPA MSTPA MSTPA MSTPA MSTPA MSTPA MSTPA MSTPA 15 14 13 12 11 10 9 15 a 5 4 i 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 bit A D Converter Target module AD RAN b23 MSTPA23 Module Stop 0 The module stop state is canceled 1 Transition to the module stop state is made Figure 4 22 Module Stop Control Register A MSTPCRA Description 1 page 282 A D Control Status Register ADCSR The Control Status Register is used to select the input channels start or stop A D conver sion and enable or disable the ADI interrupt The CH 2 0 is used to select the analog chan nels which have to be A D converted The channels can be selected using the Table 4 6 TABLE 4 6 Channel Sele
96. eds to interact with Sakura hardware Striking a balance between breadth and depth it should prove equally useful and illuminating for both hardware and software engineers Whether you are a university student honing your design skills a design engineer look ing for leading edge approaches to time critical processes or a manager attempting to fur ther your risk management techniques you will find Jim s approach to embedded systems to be stimulating and compelling Peter Carbone Renesas Contents Preface Foreword CHAPTER 1 Introduction to Embedded Systems 1 1 Learning Objectives 1 2 Concepts 1 2 1 Economics and Microcontrollers 1 2 2 Embedded Networks 1 3 Typical Benefits of Embedded Systems 1 3 1 Greater Performance and Efficiency 1 3 2 Lower Costs 1 3 3 More Features 1 3 4 Better Dependability 14 Embedded System Functions 1 5 Attributes of Embedded Systems 1 6 Constraints on Embedded Systems 1 7 Developing Embedded Systems 1 7 1 Product Development 1 7 2 Designing and Manufacturing Embedded Systems 1 7 3 The Role of a Computer Engineer 1 8 An Example of an Embedded System The Renesas Sakura Board 1 9 Summary of Book Contents 1 10 Recap 1 11 References vii OO HO o u A AR R U UN NY PF PF gt a 8 m O O O viii CONTENTS CHAPTER 2 Introduction to Software Development 2 1 Learning Objectives 2 2 Computer Organization amp Architecture 2 3 Microcontroller Basics 2 3 1 Bi
97. ems are designed with a central microcontroller and other supporting elec tronic components mounted on a printed circuit board PCB PCBs provide the means to connect these integrated circuits to each other to make an operational system The PCB provides structural support and the wiring of the circuit The individual wires on the PCB are called traces and are made from a flat copper foil While many circuit designs may use the same standard components the PCB is often a custom component for a given design Designing a PCB requires a completed schematic for the circuit This schematic is sometimes different than the schematic seen in textbooks It often contains extra informa tion about the components and construction of the board For example a textbook schematic may only show a battery for the power supply while the production schematic would show the battery case the number of cells the rating of the battery and the manu facturers of the components From the schematic a designer will use their computer aided design tools to identify the size of the PCB and then place the electronic components on their board drawing The designer will also place the wiring between the components on the PCB The physical PCB is manufactured from a fiberglass resin material that is lightweight and inexpensive A manufacturer will add copper wiring traces to the surfaces of the board and the appropriate insulation and white silk screening The final manufacturi
98. en setting up a pulse output signal we are just calculating a timer length for the period of our wave and for each high duty cycle we desire and then programming it into the time constant registers Also keep in mind that with this example 1 ms and 2 ms are the maximum value pulses for our motor If this were a 180 de gree servo 1 ms would put it at 0 degrees and 2 ms at 180 degrees If we wanted any 106 4 2 7 RENESAS SAKURA MICROCONTROLLER BOARD position in between we would have to output a signal proportionally between 1 and 2 ms 1 5 ms would place the servo at 90 degrees 1 75 ms at 135 degrees and so on In the case of a continuous rotation servo 1 and 2 ms would be full forward and backward and any pulse length in between would speed up or slow down the rotation 1 5 ms would be a full stop Advanced Motor Control Robotics Application Now that we have an understanding of how to utilize pulse width modulation Frequency and period control of a signal Let s see if we can adequately meet the requirements from Chapter 2 Section 2 5 3 Remember that Two Schmitt trigger buffered inputs are provided on connector J2 of the PmodHBS H bridge circuit to facilitate bringing motor speed feedback signals to the controlling system board SA and SB The Digilent motor gearboxes have Hall effect sensors arranged as a quadrature en coder The quadrature encoder signals are a pair of square waves whose frequency is pro portional to motor
99. ents 28 PIDR 19 PinMode method 48 PmodHBSTM H Bridge 68 106 PMR 20 PODR 18 19 POE2a 41 Port direction register PDR 17 18 Port Input Data Register PIDR 19 Port Mode Register PMR 20 Port Output Data Register PODR 18 19 Port output enable 2 POE2a 41 Ports I O description of 17 direction of 17 microcontroller registers 17 19 of RX63N 40 Sakura ADC map 120 21 Sakura port map fig 38 Sakura TMRO map 100 Sakura TMRO 3 map 108 PPG 41 Precision of floating point operations 21 Preprocessor 22 24 Preprocessor define 32 Printed circuit board PCB 8 Process decisions 26 152 INDEX Programmable pulse generator PPG 41 Project of HEW 24 Pull up resistor 58 Pulse output mode 78 97 100 105 timer interrupts for 101 4 Pulse width modulation 108 Q QTI sensor 135 36 138 39 Quadrature encoder 106 R R5F563NBDDFP 10 43 Real time clock RTCa 41 42 Real time systems response times of 5 Recurring cost 2 Reduced media independent interface 42 Registers 10 bit ADC 125 32 126 of computers 15 description of 16 mircrocontroller ports 17 19 timers for counting events 81 86 Renesas Sakura see Sakura Reset for RX63N microprocessor 40 Resolution of ADC 118 RIIC 42 RMII 42 Robotics application A D sensors 135 47 advanced motor control 106 17 developing code 72 74 hardware understanding of 68 71 interrupts use of 112 17 143 46 motor power
100. eping the programs and functions short and manageable Generality is designing functions that can work in a broad sense for a variety of situations and that require minimum alterations to suit a task Clarity is the concept of keeping the program easy to understand while re maining technically precise Code should conform to your company s coding standards to ensure that it is easy to read and understand There are many coding standards examples available The rules we have seen broken most often and which have the biggest payoff are these Limit function length to what fits onto one screen or page Use meaningful and consistent function and variable naming conventions Avoid using global variables If you find yourself writing the same code with minor variations it may be worth parameterizing the code so only one version is needed Data sharing in systems with preemption including ISRs must be done very care fully to avoid data race vulnerabilities For this reason we do not introduce inter rupts in this book Static analysis should be used to ensure that your code is not asking for trouble Most if not all compiler warnings should be turned on to identify potential bugs lurking in your source code Tools such as LINT are also helpful and worth considering Magic numbers are hard coded numeric literals used as constants array sizes character positions conversion factors and other numeric values that appear di rectly in progr
101. erter This is used as the analog ground for each of the modules Set this pin to the same potential as the VSS pin Figure 4 21 Input pins of the 10 bit A D Converter 1 page 1688 ANEXO and ANEX1 are the extended analog inputs for the 10 bit ADC The ADTRG in put is used to start and stop the ADC conversion from an outside source VREFH is the Vers voltage input and VREFL is the V voltage input Figure 4 21 indicates the input pins of the 10 bit A D converter A D Data Registers ADDRn n A to H The 10 bit ADC has eight Data Registers corresponding to the designated input channels of the ADC A D data registers are 16 bit read only registers They store the A D conver sion results of pre configured SAKURA ports defined in file brd_grsakura h The 10 bit ADC registers are also presented as structures and unions for easy manipu lation just like the ports in the iodefine_gcc63n h file The registers can be accessed us ing the syntax lt Module Symbol gt lt Register Symbol gt WORD to set up an entire register or lt Module Symbol gt lt Register Symbol gt BIT lt bit location gt to set up a particular bit of a register For example we can set the sampling speed of the 10 bit A D converter as seen in reference Table 4 5 AD ADSSTR WORD 0x1FFF 126 RENESAS SAKURA MICROCONTROLLER BOARD TABLE 4 5 List of 10 bit A D Converter Registers 2 page 77 NUMBER OF ACCESS STATES MODULE REGISTER NUMBER ACCESS RELATE
102. es and does not guarantee the accuracy adeguacy or completeness of any information herein and is not responsible for any errors or omissions The publisher and content contributors assume no liability for damages resulting from the use of the information in this book or for any infringement of the intellectual property rights of third parties that would result from the use of this information Library of Congress subject headings 1 Embedded computer systems 2 Real time data processing 3 Computer software Development For bulk orders please contact Micrium Press at 1 954 217 2036 ISBN 978 1 935772 92 7 Please report errors or forward any comments and suggestions to jmconrad uncc edu Preface This book is the result of a long relationship the author has enjoyed with Renesas Electronics America Inc and one of its predecessors Mitsubishi Electronics I originally worked with this company because of their commitment to providing a low cost evaluation board and free development software that students could purchase and use in classes and senior design projects Over the years the boards have remained as affordable and popu lar as ever and the software development tools available have added more functionality while still available for free to our students I have been teaching embedded systems courses for over fourteen years and working in the field even longer I had not been able to find a book suitable for using in an Int
103. es the input signal with a reference signal and gives the digital output The refer ence voltage of an ADC is the maximum analog voltage that can be converted by an ADC The digital value for a particular analog value can be found mathematically This can be useful as a guide to see if the ADC output obtained is correct If Vi is the sampled input voltage V efis the upper end of input voltage range V_ f is the lower end of input voltage range and N is the number of bits of resolution in ADC the digital output n can be found using the following formula N _ M V 2 1 in Vref gt Vref 2 Per i m D n int 1 Vice 2 ref Let us assume that the analog voltage to be calculated is 2 7 V and the 12 bit ADC has to be used The digital value will be VEN D 1 spe 1 2 7 4095 1 n Vin Jim Since V 0 X jim EG in V 2 33 2 33 2 n 335210 The GR SAKURA has one 10 bit A D converter unit and one 12 bit A D converter unit However the GR SAKURA is designed specifically to use as little real estate as possible hence there are not enough designated pins on the board to support all of the RX63N MCU functionality at the same time There are six designated A D pins ANO to ANS that can only be used for the 12 bit A D 120 RENESAS SAKURA MICROCONTROLLER BOARD TABLE 4 3 GR Sakura 12 bit A D Converter Port Map 8 PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SCl
104. eset 0 0 0 0 0 0 0 0 Figure 2 7 Port Input Data Register 1 Page 663 20 2 3 3 RENESAS SAKURA MICROCONTROLLER BOARD Check State of Switch1 Port 4 bit 0 and Switch Off LED1 Port D bit 0 1 if PORTA PIDR BIT B7 1 2 PORTA PODR BIT BO 1 3 Port Mode Register PMR This register is used to buffer the input values for pins that have been configured as input from peripheral modules b7 b6 b5 b4 b3 b2 b1 bO Value after reset 0 0 0 0 0 0 0 0 Figure 2 8 Port Mode Register 1 Page 664 Before configuring a pin as an input from a peripheral the PMR must be enabled To en able the PMR set PORTx PMR BIT Bn x 0 to 9 A to G J and n 0 to 7 to 1 If a pin has to be configured as an output pin set PORTx PMR BIT Bn x 0 to 9 A to G J and n 0 to 7 to 0 Setting PMR to 0 disables the PMR While setting the PMR make sure that the corresponding pin is not in use It is necessary to follow the above steps to avoid unintended operations from taking place Data Types The RX CPU supports four types of data integer floating point bit and string 1 Integer An integer is a whole number of different sizes It can be stored as 8 bits 16 bits or 32 bits The larger the storage size the larger the range of values the integer can hold If an integer is unsigned it is a non negative number from 0 to 2N 1 where N is the number of bits Figure 2 9 shows the sizes and n
105. ess will evolve over time incorporating les sons learned from each project s successes and failures Hence a good process will make it easier to do the technical work The goal of this section is to show how both process and technical issues need to be considered to successfully create a product on time and on budget Development Lifecycle Overview The software process consists of multiple steps within the embedded product lifecycle One example process model is the V model shown in Figure 2 14 It consists of Defining system requirements m Creating an architectural or high level design deciding on the general approach to build the system and then creating appropriate hardware and software architectures Requirements Analysis Validation provided by testing EI 2 Review x p N onn Integration i Testing Review N s M PEN Integration i Testing Review S W Unit i Testing Review M Figure 2 14 The V model of software development emphasizes testing at each level of design detail 2 5 2 CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 27 Creating detailed designs Implementing code and performing unit testing Integrating the code components and performing integration testing Changing the code after completion to fit custom deployment requirements fix bugs add features etc The process breaks a problem into smaller easier problems through the process
106. et s use the name GR_SAKURA_Lab1 for this project Create Project GR SAKURA SA Sketch E0 50 zip GR SAKURA 3GShield V1 02 zip GR SAKURA 3GShield V1 03 zip GR SAKURA Sketch V1 06 zip GR SAKURA Sketch V1 07 zip Project template for GR SAKURA Ver 1 07 This is a standard template for GR SAKURA This includes SAKURA libraries compatible with Arduino libraries It allows to create application easily without Figure 3 9 Create a project from a template CHAPTER 3 GETTING STARTED WITH GR SAKURA 47 Your window should now look like this if it doesn t please try to recreate a project RX Arduino Lab1 No Renesas Web Compiler 5 Project Root m gr build m gr common gr reference e html gr reference j html gr sketch cpp Figure 3 10 GR SAKURA web compiler The project comes preloaded with a test program This program is designed to blink the LEDs on the board in a wave method To open the project double click on gr sketch cpp on the left panel of the web compiler Let s take a closer look at the code 1 include lt rxduino h gt 2 define INTERVAL 100 3 void setup 4 pinMode PIN LEDO OUTPUT Sis pinMode PIN_LED1 OUTPUT 6 pinMode PIN LED2 OUTPUT Te pinMode PIN _LED3 OUTPUT 8 9 void loop 10 digitalWrite PIN LEDO 1 Tis delay INTERVAL 12 digitalWrite PIN LED1 1 T2 delay INTERVAL 48 REN
107. f counter gt debounce count counter 0 current state reading time millis return current_ state Now make the following updates to our program file GO UP WN H DODO V OU KA UN H include lt rxduino h gt define HIGH 1 define LOW 0 void setup pinMode PIN LEDO OUTPUT PIN LED1 OUTPUT pinMode PIN SW INPUT pinMode void loop while DebounceButtonPress digitalWrite PIN LEDO HIGH digitalwrite PIN LEDL LOW digitalWrite PIN LEDO LOW digitalWrite PIN LEDL HIGH Build the program as before to make sure that it builds successfully If the program does not build successfully use the trace data to identify the issues in your code and review the above updates to make sure that you have made the correct updates to your application and h files Using the concepts we have identified so far update your application to flash the LEDs based on a time delay Can you make LEDO flash in 0 5 second intervals and LED1 flash every second while the switch is pressed Don t stop there test your knowledge Driving Motors and Coils Input Output I O pins on a microcontroller have specific limits to the amount of current each pin can sink or source These limits are found in the datasheet Voltage levels can also 62 RENESAS SAKURA MICROCONTROLLER BOARD be different between sensors and the microcontroller
108. fficiently at this ratio If there is too little air a rich mix then ex cessive carbon monoxide CO and hydrocarbons HC will be produced If there is too much air a lean mix then large amounts of oxides of nitrogen called NO will be cre ated So we would like for each fuel injector to add just the right amount of fuel This de pends on the mass of the air inside the cylinder which depends on factors such as air tem perature and air pressure These in turn depend on altitude and weather as well as whether the engine is warmed up or not Another factor is the timing of the sparkplug firing If it fires early then there is more time for combustion within the cylinder before the exhaust valve opens This raises the average temperature within the cylinder and changes the com bustion process affecting CO HC and NO concentrations It would be quite impractical to design a mechanical control system to consider all of these factors and squirt the fuel in jectors at just the right instant for the right amount of time Thankfully an inexpensive mi crocontroller is quite effective at these kinds of calculations and control Lower Costs There are various ways in which an embedded system can reduce the costs associated with a device Component costs Embedded software can compensate for poor signal quality al lowing the use of less expensive components For example a low cost pressure sensor may be very temperature dependent If ambie
109. from TMRO O 1 1 Trigger from ADTRG 1 0 0 Compare match input capture A from MTUO 1 0 1 Compare match input capture A from TPUO to TPU4 1 1 0 Compare match from MTU4 1 1 1 Compare match input capture A from TPUO Figure 4 24 10 bit A D Converter control Status Register ADCR description 1 page 1691 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 131 Address es 0008 9812h b7 b6 b5 b4 b3 b2 b1 DO I DPSEL EXOEN EXSELI1 0 l Value after reset 0 0 0 0 0 0 0 0 NO CO CA b3 to bO Reserved These bits are read as 0 The write value should be 0 b5 b4 EXSEL 1 0 Extended Analog b5 b4 RAN Input Select 0 0 Analog input channel ANxx 0 1 ANEX 1 1 0 Setting prohibited 1 1 Setting prohibited b6 EXOEN Extended Analog 0 Output is disabled RAN Output Control 1 Output is enabled b7 DPSEL ADDRy Format 0 A D data is flush right RAN Select 1 A D data is flush left Figure 4 25 10 bit A D Converter control Status Register 2 ADCR2 description 1 page 1692 ADCSR2 DPSEL bit 0 Flush right b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 b bO Value after reset 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ADCSR2 DPSEL bit 1 Flush left b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 bi bo Value after reset 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Figure 4 26 10 bit A D Converter data registers flush left versus flush right 1 page 1689 132
110. ge of sensor and actuator interfacing presented in this chapter Industry follows many and sometimes differing processes when developing software A process gives a directional path to developing software in an organized manner and al lows the people developing the software and using the software to maintain expectations from the development process at regular intervals Pseudo code and graphical methods to design solutions to a software programming problem allows understanding resolving and maintaining logical flow of a program They can also be directly included in the documen tation for the program REFERENCES 1 Renesas Electronics Inc February 2013 RX63N Group RX631 Group User s Manual Hardware Rev 1 60 2 Renesas Electronics Inc February 2011 RX63N Group High performance Embedded Workshop V 4 09 User s Manual Rev 1 00 3 Fultan Randall 2011 RTCA DO 254 Optimizing Requirements for Verification SoftwAir Assurance Inc EXERCISES What are the four basic structural components of computers What are the four basic functions that computers perform What is the hexadecimal representation of 1011011100111010 What is the binary representation of A3BF What is the Port Direction Register and how do you set it What are the four data types that the RX CPU supports What is the range of numbers that can be represented by an 8 bit unsigned inte ger An 8 bit signed integer A 32 bit signed integer 8
111. ge selection will determine the language of the installed help and user documentation International English O Asia Japanese O Asia English Release Notes InstallShield lt Back Next gt Cancel Figure 3 13 Flash Development tool Kit Language CHAPTER 3 GETTING STARTED WITH GR SAKURA 51 If not already done check every box so that every feature is installed onto the computer Renesas Flash Development Toolkit v4 08 InstallShield Wizard Lx Select Features Select the features setup will install REN ESAS Select the features you want to install and deselect the features you do not want to install Description 3 1V FDT Application H V Kernels Protocol B 8 C Flach Development Toolkit Kernels Protocol D applicaiton USB Drivers iv Release 01 Kernels H 7 Release 02 Kernels 89 11 MB of space required on the C drive 136558 20 MB of space available on the C drive InstallShield lt Back Next gt Cancel d Figure 3 14 Flash Development tool Kit Install Features Install the application in the pre determined installation directory and click next When the last window pops up click install The installation should take about three minutes or so dependent upon your machine Run the Flash Development Toolkit 4 08 Basic This is done by clicking on S
112. ght up and at compare match B only LED2 and LED3 will light up Design an application that will read the ADC value on from the 10 bit ADC when a compare match A is generated on TMRO Use a potentiometer to control the ADC value The application should light up LEDO if the voltage is between OV and 1V LED1 if the voltage is between 1V and 2V LED2 if the voltage is be tween 2V and 3V and LED3 if the voltage is greater than 3V A A D control register ADCR 129 130 A D control register 2 ADCR2 129 131 A D control status register ADCSR 127 28 A D converter see analog to digital converter A D data registers ADDRn 125 26 ADC see analog to digital converter ADCR 129 130 ADCR2 129 131 ADCSR 127 28 ADDRn 125 26 Algorithms code converting to 31 33 code development description 30 robotics application 72 Aliasing 119 ALU 14 Analog to digital converter 10 bit converter see 10 bit A D converter conversion rate 118 description of 117 19 digital value of analog value 119 Nyquist frequency 118 19 output of 126 resolution of 118 robotics application 135 47 of RX63N microprocessor 43 Sakura port map for 120 21 sample and hold circuit 119 sensors 135 47 voltage reference 118 Index Android system 44 Applet 44 Architecture of code development 30 Arduino 35 36 50 Arithmetic and Logic Unit ALU 14 B Baud rate clock 78 BCLK 40 Big up front design 27 Binary digit 16
113. gister A D Control Register 2 ADCR2 A D Control Register 2 ADCR2 is used to select extended analog input channel ex tended analog output channel and to select A D result format Setting the EXSEL 1 0 bits to 01b selects extended analog input channel The ex tended analog input channel should be input from an external operational amplifier Setting the EXSEL 1 0 bits to 00b isolates the extended analog input channel from the A D con verter circuit inside the chip Do not set the EXSEL 1 0 bits to 10b or 11b Setting the EXOEN bit to 1 enables Extended Analog Output Control Setting the DPSEL bit to 0 aligns the A D result to the right and setting it to 1 aligns the A D result to the left in the ADDRn register n A to H for 10 bit A D 130 RENESAS SAKURA MICROCONTROLLER BOARD Address es 0008 9811h Value after reset b7 b6 b5 b4 b3 b2 b1 DO I I I I TRGS 2 0 CKS 1 0 MODE 1 0 l l l i 0 0 0 0 0 0 0 0 EET SYMBOL BIT NAME DESCRIPTION Lid b1 bo MODE 1 0 b3 b2 CKS 1 0 ba b7 to b5 TRGS 2 0 Operation Mode Select Clock Select Reserved Trigger Select b1 bO 0 0 Single channel mode 0 1 Setting prohibited 1 0 Continuous scan mode 1 1 Single scan mode b3 b2 0 0 PCLK 8 0 1 PCLK 4 OAREN 1 1E CIC This bit is read as 0 The write value should be 0 R W br o5 0 0 0 Software trigger 0 0 1 Compare match input capture A from MTUO to MTU4 0 1 0 Compare match
114. h we will increment every time our interrupt service routine is called Also on line 14 we initialize the function that will be called when an interrupt occurs define Aforward 1 define Abackward 0 CO U a 9 define HIGH 10 define LOW 11 12 int motorCountA 0 L3 14 void myEventCounterA void Now we need to define our setup function The setup function is fairly similar to what we have done before We assign the motor control pins to be outputs as well as set the di rection of the pins controlling the LEDs and initialize all of the LEDs to be off We enable global interrupts by calling the interrupts function on line 19 Enable the ISR that we wish to use by defining the attachIntterupt function on line 22 In this function we set the port that will generate the interrupt as Port 1 pin 2 we set our interrupt to be gen erated on the rising edge of the input on port 1 pin 2 and upon the interrupt being trig gered we call a user defined function called myEventCounterA 15 void setup 16 pinMode directionA OUTPUT Li pinMode enableA OUTPUT 18 enable glogal interrupts 96 RENESAS SAKURA MICROCONTROLLER BOARD 19 20 Zl 22 23 24 25 26 2 28 29 30 3L 32 33 interrupts Port P12 IRQ2 function call RISING 3 Interrupt occurs for LOW to HIGH state attachInterrupt 2 myEventCounterA 3 digitalWrite directionA Aforward pinMode PIN LEDO OU
115. ically a repeating pattern in output over time 98 RENESAS SAKURA MICROCONTROLLER BOARD such as a sine wave square wave or sawtooth wave The period of the wave is defined as the time between repeats in the simplest form of the wave s pattern In the case of a square wave the period is the time between the rising edges of the positive output portion The frequency is determined by how many periods there are of a wave in a second We can determine frequency by the formula f number of periods Length of time yielding a value in Hertz Hz periods second If we want to determine the period using the fre quency we use the formula T period 1 f Hz Duty cycle is defined as the percentage of the period during which the waveform is high Duty cycle can be determined by the for mula D Time high T period X 100 Using the 8 bit timer peripheral we can output a square wave where the frequency and duty cycle are controlled by changing values in the registers we have already covered 1 5 T T Voltage lt Period gt 2ms 1 Duty Cycle 1 75 ms 87 5 05 F 0 m m m l sm mm mmm m mmm EE EER EE mmm m m nn o 0 5 i l i i 0 2 4 6 8 Time 10 Figure 4 13 Pulse width modulation signal attributes Pulse output mode is handy in applications such as interfacing the microcontroller to sev eral types of motors A servo motor usually uses a square wave input to determine the po
116. idth of the robot is 20 cm If the center of the robot is the point halfway between the wheels a How many revolutions of each motor are needed for the vehicle to turn 90 de grees in place b How many seconds will it take if the motors rotate at 5200 rpm c Answer part a and b for a 120 degree turn Consider you will design an autonomous robotic vehicle that can sense its envi ronment and move to perform a task The environment is underwater in a sea or lake with a minimum depth of three meters and a maximum depth if 30 meters The underwater vehicle will be one meter in length and 0 15 meters in diameter when stored although the device can deploy fins or expand when activated The vehicle will travel towards a pre placed underwater beacon at a specific frequency the beacon source is on the ocean or lake floor Once the vehicle is over the bea con it will attach itself to the cable chain holding a mine that is floating 1 5 meters under the surface of the water Once the vehicle is attached it will wait for another beacon at another frequency When it detects this new frequency it will self destruct It should be close to but not touching the mine a Write the requirements for the robotic vehicle The requirements should in clude the type of sensing and motion Also identify performance measures for the entire system Produce a minimum of 15 requirements b Draw a block diagram of how the robot is to be wired together I
117. inMode PIN SW INPUT digitalWrite directionA Aforward digitalWrite directionB Bbackward digitalWrite enableA OFF digitalWrite enableB OFF J BRR KR kok kok oko kok kok kok kok k kok ok k kok ok kok kok k ke ke ee ae a He main loop run the motors J BRR KR kok oko kok kok kok kok kok kok kok RE RE RE RE RE RE ee ae void loop Start with getting ready to move forward by making sure the motors are disabled and direction is set to move forward spin waiting until the button is pressed while digitalRead PIN SW HIGH Repeat a forward movement and a 90 degree turn 4 times to make a 1x1 meter square for i 07 a EA ay A delay PAUSE digitalWrite enableA ON digitalWrite enableB ON delay FORWARDTIME digitalWrite enableA OFF digitalWrite enableB OFF delay PAUSE digitalWrite directionA Aforward digitalWrite directionB Bforward delay PAUSE digitalWrite enableA ON digitalWrite enableB ON delay TURNTIME digitalWrite enableA OFF digitalWrite enableB OFF delay PAUSE digitalWrite directionA Aforward digitalWrite directionB Bbackward delay PAUSE end segment loop 3 9 3 10 CHAPTER 3 GETTING STARTED WITH GR SAKURA 75 66 67 end program Did the robot complete a 1 x 1 meter square If the answer is yes then consider yourself lucky If no then it should not be a surp
118. ing function Frequency Measuring Method MCK The MTU or unit 0 TPU module can be used to monitor the main clock sub clock HOCO clock LOCO clock and PLL clock for abnormal frequencies Port output enable 2 POE2a It controls the high impedance state of the MTU s waveform output pins Programmable pulse generator PPG It has two units each supporting four groups and each group has four bits It outputs the MTU pulse as a trigger The maximum output possible is 32 bit pulse output 8 bit timers TMR It has two units each supporting two channels and each channel has 8 bits The clock signal can be selected from seven counter input clock signals for each channel PCLK 1 PCLK 2 PCLK 8 PCLK 32 PCLK 64 PCLK 1024 PCLK 8192 These are capable of outputting pulse trains with desired duty cycles or of PWM signals Compare match timer CMT It has two units each supporting two channels and each channel has 16 bits The clock signal can be selected from among four internal clock signals PCLK 8 PCLK 32 PCLK 128 PCLK 512 Realtime clock RTCa Clock sources for the realtime clock include the Main clock and subclock The RTCa also includes clock and calendar 42 RENESAS SAKURA MICROCONTROLLER BOARD 10 functions interrupt sources alarm interrupt periodic interrupt and carry in terrupt battery backup operation and time capture facil
119. interrupt A flag enable compare match interrupt B compare match interrupt B priority clear compare match interrupt B flag Excep TMRO CMIAO void 4 3 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 117 167 digitalWrite enableA ON 168 169 170 void Excep TMRO CMIBO void K digitalWrite enableA OFF 2 N 173 void Excep TMR1 CMIA1 void Ly4 if startMotors 0 175 digitalWrite enableB OFF 176 LIT if startMotors 1 178 digitalWrite enableB ON 179 180 181 void Excep TMR1 CMIB1 void 182 digitalWrite enableB OFF 183 184 void myEventCounterA void 185 motorCountA 186 187 void myEventCounterB void 188 motorCountB 189 ANALOG TO DIGITAL CONVERTERS The microcontroller is a digital device and can be easily interfaced with other digital de vices However when the microcontroller has to be connected to an analog device inter facing becomes complex This is when analog to digital converters ADC and digital to analog converters DAC come into play An ADC is a device which converts or electronically translates analog signal into dig ital binary form Imagine you want to record your voice onto the computer There are many operations that have to take place in order to record your voice setup of the micro phone other software etc but the main operation is for the computer digital devic
120. itions m presence of the maximum voltage of the system we ll call this state 1 m absence of a voltage of the system most often 0 zero volts we ll call this state 0 This basic unit of information is the binary digit or bit Values with more than two states require multiple bits Therefore a collection of two bits has four possible states 00 01 10 and 11 A collection of eight bits is called a byte Often we group bits together to rep resent them in a larger number representation called hexadecimal A grouping of four bits is represented by one hexadecimal digit usually preceded by an x as represented in Table 2 1 As an example the binary number 1010 is xA in hexadecimal and 10 in deci mal Binary number 01011100 is hexadecimal x5C TABLE 2 1 Hexadecimal Representation BINARY HEXADECIMAL DECIMAL BINARY HEXADECIMAL DECIMAL x0 0 x8 8 0000 1000 0001 x1 1 1001 x9 9 0010 x2 2 1010 xA 10 0011 x3 3 1011 xB 11 0100 x4 4 1100 xC 12 0101 x5 3 1101 xD 13 0110 x6 6 1110 XE 14 0111 x7 7 lei xF 15 These values are moved around inside the microcontroller and stored in memory locations called registers Each register has a unique location which will be addressed These mem ory locations are in addition to larger stores of useable memory 2 3 2 CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 17 Ports Remember that embedded systems consist of computers embedded in larger systems The processor needs to se
121. ity for three values Watchdog timer WDTA It has one channel of 14 bits The clock signal can be selected from eight counter input clock signals PCLK 4 PCLK 64 PCLK 128 PCLK 512 PCLK 2048 PCLK 8192 It is switchable between watchdog timer mode and interval timer mode Independent watchdog timer IWDTa It has one channel of 14 bits It re quires a counter input clock which is available from the dedicated on chip oscillator Communication function For communicating with the outside world the MCU provides several controllers Ethernet controller ETHERC The data rate it supports is either 10 or 100 Mbps It supports both full and half duplex modes MII Media Independent Interface or RMII Reduced Media Independent Interface as defined in IEEE 802 3u DMA controller for Ethernet Controller EDMAC It supports transmission and reception of First In First Out FIFO of 2 Kbytes each USB 2 0 host function module USBa It includes a USB device controller and transceiver for USB 2 0 It incorporates 2 Kbytes of RAM as a transfer buffer and supports data rate of 12 Mbps Serial communication interfaces SCIc SCId It has 13 channels SCIc 12 channels SCId 1 channel The SCIc communication interfaces support several communications modes such as asynchronous clock synchronous and smart card interface SCIc also supports Multi processor function On chip baud rate generator allowing selection of the desired bit rate
122. l ANO and disable interrupt on that channel The A D Control Register ADCR is used to select single mode PCLK and software trig ger to start and stop the ADC The ADCR2 register is used to select right alignment The Self Diagnostic function is set to off And lastly the ADC is started by setting the ADST bit of the ADCSR register to 1 After conversion is complete the ADST bit of the ADCSR gets cleared to 0 Next we set up the pins that this program will utilize Line 17 sets the A D pin to be an input pin The remaining lines set up two LEDs to be outputs and a switch to be an input The LEDs are also initially set to OFF The program polls for the switch to be pushed Once the switch is pushed the program will check if the A D has finished its conversion and if the variable i is equal to 0 If both of these conditions are met the program will write the converted value to variable ADC value and increment variable i The data register was set to be right aligned Hence to avoid reading wrong bits the value 0x03FF is used to mask the upper 6 bits using zeros and read the lower ten bits right bits Based on the ADC value the program will deactivate all LEDs if the ADC value is less than 1V If the value is between 1V and 2V then LEDO will turn on if the ADC value is between 2V and 3V then LEDO and LED 1 will turn on if the ADC value is between 3V and 4V then LEDO LED1 and LED2 will turn on and lastly if the value is between 4V and 5V
123. l air craft Level N requirements in many cases interface requirements can be directly copied to level N 1 These requirements can change units or terminology at level N 1 m Tier 2 LRU The maximum flap position shall be limited to 45 degrees Tier 3 CCA The maximum flap output position command shall be 5V 0 05V Tier 3 Software The label FLAP_POSITION shall be output to DAO1 every 20 0 5ms 2 5 3 Requirements Robotics Applications We are tasked with designing a robotic vehicle that will travel forward then make a right turn and do this four times Of course this robot will travel in a square pattern Let s write the high level or Tier 1 requirements for this robot 1 The robot shall be activated with an ON OFF switch a When in the OFF position the robot shall not move b When in the ON position the robot shall move forward for 1 meter 30 2 5 4 2 5 5 RENESAS SAKURA MICROCONTROLLER BOARD 2 The robot shall make a 90 degree turn after traveling for 1 meter a The robot shall stop after four events of traveling forward then turning We will take a closer look at writing lower level requirements in later chapters Developing Code One of the most effective ways to reduce risks in developing software is to design before writing code We refer to high level design as the architecture and the low level design as the detailed design Writing code locks you into specific imple
124. l purpose I O pin as an A D converter input or as an interrupt input Depending on the purposes these pins serve they might have extra registers Certain other registers called Port Function Registers are also present These registers are associated with special features of the RX63N micro controller such as USB CAN etc Port Direction Register PDR This register as the name suggests is used to set the port direction input or output of a pin PDR is a read write register Each bit of the Port Direction Register represents a pin on the specified port B7 B6 BS B4 B3 B2 Bl BO Value after reset 0 0 0 0 0 0 0 0 Figure 2 5 Port Direction Register 1 page 661 The iodefine gcc63n h file has C code constructs that make it easy to access each port with C code Each port is defined as a structure and each register of the port is defined as a 18 RENESAS SAKURA MICROCONTROLLER BOARD union of variables within that structure An example of how the PDR is defined inside a port structure as follows 1 struct st port4 2 union 3 unsigned char BYTE 4 struct Dis unsigned char BO 1 6 unsigned char Bl l 7 unsigned char B2 1 8 unsigned char B3 1 Di unsigned char B4 1 10 unsigned char B5 1 11 unsigned char B6 1 12 unsigned char B7 1 13 BIT 14 PDR Li F Line 1 shows that port4 has been defined as a structure Lines 2 to 14 suggest that the Port Direction Regi
125. lash Development tool Kit Programming Options A connection should automatically be made between the FDT and the GR Sakura at this point To flash the board select the file NonOS_MscFw mot Once the file is selected click Program Flash 54 3 6 RENESAS SAKURA MICROCONTROLLER BOARD gt FDT Simple Interface Unsupported Freeware Version Options Exit BASIC FILE PROGRAMMING Device RX600 Series LittleEndi Port USB Direct r File Selection Download File v User Data Area C Users Harris Desktop RX_Arduino_Lab NonOS_MssFw mot L User Boot Area gt Program Flash Disconnect Line size received 1024 Clock Frequency External 12 0000MHz CKM 8 and CKP 4 FCF Settings Applied RX600 Series LittleEndian C Users Harris Attemping to finalize connection to Generic RX600 Series LittleEnd Connection complete lt N d Figure 3 18 Flash Development tool Kit Program Flash If no errors were received go ahead and Disconnect from the board and repeat section 3 4 1 You should be able to see the GR SAKURA under My Computer SETTING UP AN ACCOUNT WITH MYRENESAS The first step to getting started with developing your own software is to setup an account by visiting the compiler website http www renesas com products promotion gr index jsp Once on the website click on the
126. lse output 101 4 robotics applicaiton and 112 17 143 46 VO of computer 14 VO ports see ports VO Iodefine gcc63n h 17 18 125 IWDTa 42 L Least significant bit LSB 43 LEDs as outputs 58 of Sakura board 36 switch controlled 57 61 Linker 23 LINT 32 Low level design 30 LSB 43 M Macro expansion 22 Magic numbers 32 Maintainability requirements 28 Maintenance costs 3 Manufacturing costs 3 MCK 41 Media independent interface 42 Memory 14 40 Micro SD card 10 37 Micro USB port 10 35 Microcontrollers basics of 16 20 bits and bytes 16 data types 20 21 ports 17 19 RX63N microprocessor see RX63N microprocessor Sakura see Sakura MII 42 Module stop control register A MSTPCRA 126 27 Monitor as software development tool 24 Most significant bit MSB 43 Motors and coils 61 63 and sensor control 57 63 speed determination of 106 7 MRK 63 64 106 MSB 43 MSTPCRA 126 27 MTU2a 41 Multi function timer pulse unit 2 MTU2a 41 My Renesas setting up account 54 57 N Neumann John von 15 Non recurring engineering NRE cost 2 Nyquist frequency 118 19 o Object language 23 Operating costs 3 INDEX 151 Operation requirement 27 29 Operational requirements 28 P Parallax 135 PCB 8 PCLK 40 PDR 17 18 Performance reguirements 28 Period of a wave 98 105 6 Peripheral module clock PCLK 40 Physical and installation reguirem
127. ly and efficiently despite changes in loads due to air conditioning power steering and the electrical system Signal processing modifies input signals to eliminate noise emphasize signal components of interest and compensate for other factors For example a hands free speakerphone interface may use multiple microphones beam forming and active noise cancellation to filter out low freguency road noise Other sensors may have spark plug noise filtered out Communications and networking enable different devices on the same network to exchange information For example the engine controller may need to send a message indicating speed To do this the speed value must be formatted according to the communication protocol and then loaded into the network interface periph eral for transmission 1 5 ATTRIBUTES OF EMBEDDED SYSTEMS Embedded systems are designed so that the resulting device behaves in certain desirable ways Embedded systems need to respond to events which occur in the environment whether a user presses a button or a motor overheats A system which is not suffi ciently responsive is not likely to be a successful product For example when we press a channel select button for the radio we would like for it to respond within some reasonable time For real time systems the timing of the responses is critical because late answers are wrong answers Igniting the fuel in a cylinder is time critical because bad tim ing can damage or de
128. ly read the ADC value If the ADC value is less than 2V then all four LEDs will be off lines 41 through 46 If the ADC value is greater than 2V then all four LEDs will light up lines 48 through 53 Figure 4 29 shows how to configure a sin gle and multiple QTI sensors on a breadboard with a 10K ohm transistor Figure 4 29 Testing the QTI sensor 7 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 139 Now that you have confirmed the output attach the QTI sensor to the robot Note that the QTI sensor should be no more than 2 centimeters from the ground as the robot moves around The further away from the ground the QTI sensor is the less likely you are to get a valid reading 4 3 4 1 Using Timers Counters 8 Pulse Output Now that we have verified the output of the QTI sensor we are ready to implement the re quirements The below code configures two timers TMRO is configured in pulse output mode and TMRI is configured in event counter mode We are going to need to be able to clear the event counter each time our desired value is reached Because our timer is setup in event counter mode and our input is an external source we need to configure the counter clear as an external source However we will specify an output pin and generate logic high on that pin when we need to clear the counter The input to TMR1 counter clear is defined as TMRI1 in the RX63 MCU datasheet The GR Sakura pin layout shows TMRI1 to be assigned to por
129. mentations of an algorithm data structure object interface method and so forth If this happens before you under stand the rest of the system then you probably haven t made the best possible choice and may end up having to make major changes to the code you ve written or maybe even throw it away Designing the system before coding also gives you an early insight into what parts are needed and which ones are likely to be complex This helps prevent the sur prises which slow down development One of the best ways of reducing schedule risk is to understand the system in depth before creating a schedule and then add in extra time buffers for dealing with the risky parts Estimation is the process of predicting how long it will take to create the system Designs should include graphical documents such as flowcharts and state ma chines when possible The goal is to have a small and concise set of documents which define how the system should do its work Graphical representations are easier to understand than code because they abstract away many implementation details leaving just the relevant items This makes it easy for others to understand your design and identify risks It also helps bring new hires up to speed on the proj ect and reduces the chances they II break something when they start maintaining or enhancing the code Start with an Algorithm The system architecture defines your approach to building the system What pieces ar
130. mpare Match Interrupt 0 Compare match A interrupt RAN requests CMIAn are disabled Enable A 1 Compare match A interrupt reguests CMIAn are enabled CMIEB Compare Match Interrupt 0 Compare match B interrupt RAN reguests CMIBn are disabled Enable B 1 Compare match B interrupt reguests CMIBn are enabled Note To use an external reset set the Pn DDR Bi bit for the corresponding pin to 0 and the Pn ICR Bi bit to 1 Figure 4 11 TCR Timer Control Register description 1 page 1018 4 2 2 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 87 Cascading Timers Sometimes when using a timer for an application you need a delay longer than is allowed when only using 8 bits The RX63N MCU allows both timer channels in either time unit to be cascaded into one 16 bit channel Essentially every time the first timer overflows the next timer will count This multiplies the total time able to be counted by a factor of 2 256 Originally we could only count from 0 to 255 now we can count to 65535 So how do we calculate how long it will take for the timer to count to OxFFFF our max value First we consider the RX63N MCU main clock which is 50MHz This means every clock tick takes approximately 20 nanoseconds We multiply by what division of the pe ripheral clock we are using say 64 because the period for that clock is 64 times as long Then we multiply by the number of ticks which is OxFFFF or 65535 So when using PCLK 64 an
131. my children Jay Mary Beth and Caroline and my wife Stephanie for their understanding when I needed to spend more time on the book than I spent with them James M Conrad March 2014 Foreword For more than a decade the microcontroller world has been dominated by the guest for ultra low power high performance devices two goals that are typically mutually exclu sive The Renesas RX MCU quickly achieved market leadership by achieving both of these goals with a highly innovative architecture The RX family enables embedded designs that previously would have required some uncomfortable tradeoffs However there are no simple solutions to complex problems and mastering all of the RX63N s features is not a task to be undertaken lightly Fortunately in this book Dr Conrad has crafted a guidebook for embedded developers that moves smoothly from concepts to coding in a manner that is neither too high level to be useful nor too detailed to be clear It explains beginning software engineering techniques and shows how to implement them in RX63N based applications moving from a clear explanation of problems to techniques for solving them to line by line explanations of example code Modern embedded applications increasingly require hardware software co design though few engineers are equally conversant with both of these disciplines In this book the author takes a holistic approach to design both explaining and demonstrating just how soft ware ne
132. ng the various branches of engineering Because of this diversity there is no universal list of procedures that will fit every problem Not every engineer uses the same steps in his or her design process The following list includes most of the steps that engineers use 1 Identifying the problem Gathering the needed information Searching for creative solutions Overcoming obstacles to creative thinking Moving from ideas to preliminary designs including modeling and prototyping Evaluating and selecting a preferred solution Preparing reports plans and specifications Project Planning Implementing the design Project Implementation EE Ww o a Often steps five through eight are expanded into more detailed steps including m Requirements gathering and specification of the entire product High level design architecture of the system Low level design algorithms of the software modules and schematic capture of the electrical circuits 1 7 2 RENESAS SAKURA MICROCONTROLLER BOARD Coding and building the hardware implementation Unit testing of the individual software modules Functional testing build the entire software package Integration testing put the software in the hardware Verification and Beta testing make sure it is compliant Ship it Engineers developing an embedded system will use these steps to conceive plan design and build their products Designing and Manufacturing Embedded Systems Embedded syst
133. ng it all together the code in your cpp file should closely resemble the following Compile the following program and verify the output on port 2 pin 2 using an oscilloscope include lt rxduino h gt include lt iodefine gcc63n h gt include intvect63n h UB WN H define ON 1 104 RENESAS SAKURA MICROCONTROLLER BOARD 6 define OFF 0 hs 8 void InitPWMs void 9 10 ifdef cplusplus 11 extern C 12 void Excep TMRO CMIAO void Log void Excep TMRO CMIBO void 14 15 endif 16 17 void setup 18 pinMode PIN P22 OUTPUT 19 20 21 void loop end program 22 23 void InitPWMs void 24 SYSTEM PRCR WORD 0xA502 setting PRCR1 writes enabled 25 MSTP TMRO 0 Activate TMRO unit 26 SYSTEM PRCR WORD 0xA500 setting PRCR1 writes enabled 27 TMRO TCCR BIT CSS 1 Count source is PCLK 28 TMRO TCCR BIT CKS 6 Adjust count source to PCLK 8192 42 ms 29 TMRO TCR BIT CCLR 1 Timer resets at compare match A 30 TMRO TCORA OxDF Frequency 42 ms period Siz TMRO TCORB 0x70 Duty cycle 505 32 38 TMRO TCR BIT CMIEA 1 compare match A interrupt enabled 34 TMRO TCR BIT CMIEB 1 compare match B interrupt enabled 35 36 IEN TMRO CMIAO 1 enable compare match interrupt A Bhi IPR TMRO CMIAO 15 compare match interrupt A priority 38 IR TMRO CMIA0 0 clear compare match interru
134. ng overview of the GR SAKURA family information EXERCISES 1 What is the output code in decimal of a 10 bit ADC with a Vin 3 V b Vief 5 V C Vref 0 V 2 What is the output code in decimal of a 10 bit ADC with Given the following information of a particular analog to digital converter determine the value of the digitally represented voltage and the step size of the converter m The device is 10 bit ADC with a V reference voltage of 3 3 volts and a V r reference voltage of 0 volts The digital representation is 0100110010b 148 RENESAS SAKURA MICROCONTROLLER BOARD Write a subroutine to set up the registers for a 10 bit ADC operation of the follow ing specifications continuous scan mode on channels ANT and AN2 software triggered PCLK 2 and data aligned to the LSB end Write a program to display the percentage of light intensity given a light sensor circuit Record the darkness cover the sensor to make it dark and brightness shine a bright LED or other light on the sensor values Identify the correct cali bration such that the average room light lies between these values What registers would you use when setting up the 8 bit timer unit 0 in cascaded mode Give a sample code that will set up a basic 1 kHz square wave with a 40 duty cycle Design an application that will use TMRO compare match A and compare match B to generate interrupts At compare match A only LEDO and LED1 will li
135. ng steps are applying solder placing the components and heating cooling the solder Figure 1 1 shows an example of a finished board The completed boards are electrically tested for functionality Any board failing the test is inspected in more detail to find the problems These boards are repaired to in crease the passing rate acceptable to the manufacturer The boards are wrapped in anti static materials and shipped to the next location for the next stage of production or im mediately installed in a mechanical enclosure like the mechanical shell of a mobile phone 1 7 3 CHAPTER 1 INTRODUCTION TO EMBEDDED SYSTEMS 9 HOC eevee eo of u u GR SAKURA He Figure 1 1 Renesas Sakura Board 2 The Role of a Computer Engineer Computer engineers work on the interface between different pieces of hardware and strive to provide new capabilities to existing and new systems or products Computer engineers are concerned with the design development and implementation of computer technology into a wide range of consumer industrial commercial and military applications They might work on a system such as a flexible manufacturing system or a smart device or instrument The work of a computer engineer is grounded in the hardware from circuits to archi tecture but also focuses on operating systems and software Computer engineers must understand logic design microprocessor system design computer architecture computer inte
136. no h gt include lt iodefine gcc63n h gt CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 91 5 define ON 1 6 define OFF 0 7 8 int Current LED 1 9 10 void setup 11 pinMode PIN LEDO OUTPUT 12 pinMode PIN LED1 OUTPUT Loy pinMode PIN_LED2 OUTPUT 14 pinMode PIN LED3 OUTPUT I5 digitalWrite PIN LEDO OFF 16 digitalWrite PIN LEDL OFF 17 digitalWrite PIN LED2 OFF 18 digitalWrite PIN LED3 OFF 19 20 void InitTimer void 21h SYSTEM PRCR WORD 0xA502 setting PRCR1 writes enabled 22 MSTP TMRO 0 Activate TMRO unit 23 MSTP TMR1 0 Activate TMR1 unit 24 SYSTEM PRCR WORD 0xA500 setting PRCR1 writes disabled 25 26 TMR1 TCCR BIT CSS 1 use internal clock source PCLK for TMR1 Die TMR1 TCCR BIT CKS 5 Count source is PCLK 1024 for TMRI1 28 TMRO TCCR BIT CSS 3 Count source is TMR1 for TMRO 29 30 void Rotate LEDs void 31 switch Current LED 32 case 1 33s digitalWrite PIN LEDO ON 34 digitalWrite PIN LEDL OFF 354 digitalwrite PIN LED2 OFF 36 digitalwrite PIN LED3 OFF 35 break 38 case 2 DO digitalWrite PIN LEDO ON 40 digitalWrite PIN LED1 ON 41 digitalWrite PIN LED2 OFF 42 digitalWrite PIN LED3 OFF 43 break 44 case 3 92 RENESAS SAKURA MICROCONTROLLER BOARD
137. nse the state of the larger system and environment and control output devices The most basic way to do this is through one or more discrete signals each of which can be in one of two states on or off Microcontrollers have electrical pins which can be used to send electrical signals out from the device or can be used to accept electri cal signals These electrical pins can be grouped together and called ports General purpose digital I O ports are the hardware which can be used to read from or write to the system outside the microcontroller The data of a port can be read from the outside through a port data register Its direction is set in a port direction register Often a port is eight bits wide and is assigned a number i e Port 1 Some port pins are input only some are output only and some can be configured to be input or output If a pin is configurable then its direction is determined by a direction bit The GR Sakura has nine defined Ports PORT1 PORTS PORTC PORTE and PORTJ with fifty two I O pins Depending on the purposes these pins serve they might have extra registers Each port has a Port Direction Register PDR Port Output Data Register PODR Port Input Register PIDR Open Drain Control Register ODRy y 0 1 Pull up Resistor Control Register PCR Drive Capacity Control Register DSCR and Port Mode Register PMR The pins of a port may serve several purposes for example Port 4 pin 0 can be used as a genera
138. nt temperature information is already available then it is a simple matter to compensate for the temperature in duced error Manufacturing costs Many vehicles use the Control Area Network CAN pro tocol to communicate across an in car network The embedded network reduces assembly and parts costs because of the simpler wiring harness Operating costs As mentioned above an embedded system enables automobile engines to operate more efficiently reducing the amount of gasoline needed and hence lowering operating costs Maintenance costs Some vehicles predict oil life by monitoring engine use his tory notifying the driver when an oil change is needed 1 3 3 RENESAS SAKURA MICROCONTROLLER BOARD More Features An MCU running application specific software offers tremendous opportunities for fea tures and customization These features can make your company s products stand out from the competition Cruise control keeps the car running at the same speed regardless of hills wind and other external factors Smart airbags reduce injuries by adjusting inflation speed based on passenger weight Power seats move to each driver s preferred position automatically based on whose keyless entry fob was used to open the car Headlights and interior lights shut off automatically after a time delay if the car is not running and prevents the lights from draining the battery 1 3 4 Better Dependability 1 4 Embedded systems and ne
139. nterfacing with the Outside World 4 1 4 2 LEARNING OBJECTIVES Embedded systems are used to interface with analog and digital phenomena There are sev eral devices in the Renesas microcontroller that allow you to measure and control events in the outside world In this chapter we show how timers work as digital event counters as well as go into more advanced features It is possible to cascade timers together when one timer does not provide the range needed Using timers it is also possible to output a square wave with a controllable frequency and duty cycle Embedded systems also measure physical parameters such as light intensity and tem perature These parameters are analog but the embedded system s microcontroller requires digital values to work on An Analog to Digital Converter ADC is used to convert those parameters into a digital form In this chapter we will learn about Converting an analog value to digital mathematically m ADCs in the RX63N Setting up registers and using the 10 bit ADC EVENT COUNTERS AND TIMERS A timer in a microcontroller is a counter whose value can be read and written as a special function register When the timer is started the value in the register increases or decreases each time it is clocked and the rate at which the value changes is based upon the clock source provided to it If the clock source for the timer is 10 MHz then one count incre ment or decrement of the register would be eq
140. o the stage of exe cution Figure 2 11 shows these different steps In this process a program written in C lan guage gets translated into an assembly level program which the computer can understand It can be seen from Figure 2 11 that the program passes through several tools before it is ready to be executed The functions of each of these processors are m The preprocessor performs text replacement according to preprocessor directives There are two main preprocessor directives macro expansion e g define SIZE 30 and file inclusion e g include config h In other words the processor GC Source and Header Files hd l C Preprocessor Compiler Library Object Files Executable Image Figure 2 11 Compilation process for a C program 2 4 2 CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 23 understands that the word SIZE is actually the integer value 30 and it needs to in clude code and definitions from other header files that are included in the main source code file m The compiler transforms source code written in a programming language such as C or C source language into another target language object code which is of binary form m The linker is a program that takes one or more objects generated by a compiler and combines them into a single executable program The input and output to each of these processing stages is shown in Table 2 2 TA
141. om the RX Family of chips with 1024 K of flash memory 128 K of RAM and 32 K of data flash Fifty five I O pins are used to interface with external pins on the module This processor runs at 96 MHz 3 SUMMARY OF BOOK CONTENTS This book is structured as follows Chapter 2 shows how software is built At the low level it shows how programs are compiled and downloaded At the high level it shows software engineering con cepts and practices m Chapter 3 presents an introduction to embedded systems development through ba sic concepts such as LEDs switches and motor control using the GR Sakura Em bedded development board and associated tools These concepts are demonstrated using a simple robotic vehicle platform m Chapter 4 presents how to use peripherals to interface with the environment and simplify programs RECAP An embedded system is an application specific computer system which is built into a larger system or device Using a computer system enables improved performance more functions and features lower cost and greater dependability With embedded computer systems manufacturers can add sophisticated control and monitoring to devices and other systems while leveraging the low cost microcontrollers running custom software CHAPTER 1 INTRODUCTION TO EMBEDDED SYSTEMS 11 1 11 REFERENCES 1 Wright Paul H 2002 Introduction to Engineering Third Edition John Wiley amp Sons Inc New York 2 Renesas 2013 Gadge
142. ort P15 IRQS Port P16 IRO6 Port P17 IRQ7 E EE EE EEE NJUOVU BUWUW func Function to be called when an interrupt occurs mode Trigger condition to generate an interrupt LOW 0 When pins occurrence of LOW CHANGE 1 Interrupt occurs when the state of the pin changes FALLING 2 Interrupt occurs for HIGH to LOW state RISING 3 Interrupt occurs for LOW to HIGH state Return value none To create an event counter using interrupts we will need to activate global interrupts and trigger an interrupt service routine from an external source For this example we will use the Hall Effect sensor to generate an interrupt on port 1 pin 2 when a transition oc curs from a logic low to a logic high rising edge of the signal from the Hall Effect sensor CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 95 First we will need to include the interrupt h file in our main program file 1 GR SAKURA Sketch Template Version V1 08 2 include lt rxduino h gt 3 include lt interrupt h gt Next we will define the enable and direction output pins to one of the motor on our robot 4 define directionA 3 Port 2 pin 3 motor A direction 5 define enableA 2 Port 2 pin 2 input to motor A In this example we also have some definitions HIGH and LOW will control the state of the on board LEDs and Aforward and Abackward will be used to set the rotation direction of the motor We also define an integer motorCountA whic
143. part we are most concerned with the timer initialization In this function we will set the timer registers for 16 bit cascaded mode 1 void InitTimer void 2 MSTP TMRO 0 Activate TMRO unit 3 MSTP TMR1 0 Activate TMR1 unit 4 TMR1 TCCR BIT CSS 1 ase internal clock source PCLK for TMR1 Dis TMR1 TCCR BIT CKS 5 Count source is PCLK 1024 for TMR1 6 TMRO TCCR BIT CSS 3 Count source is TMR1 for TMRO We start on lines 2 to 3 by activating the timer units 0 and lin the Module Stop Control Register they are off by default On lines 4 to 5 we set the count source for timer 1 as the PCLK 1024 On line 6 we set the count source for timer 0 as timer 1 With the count source set this will make timer 0 count every time timer 1 overflows The timers TMRO and TMRI are now cascaded As we calculated earlier in our concepts this setup will take the main clock of 50 MHz and divide it by 1024 Then we poll TMRO for every 65535 counts Once TMRO reaches the count of 65535 the LED rotate function is called to switch the LEDs This is calculated to be approximately every 1 342 s The next function is used to light the LEDs on the board one at a time in a sequence It uses the Current_LED variable to hold which Led is currently lit Each time it is called it increments the value and as soon as it passes 4 it restarts at 1 1 void Rotate LEDs void 2 switch Current_LED 3 case 1
144. pin or on overflows of another timer For example an event counter can be set up in a place where you need to automatically keep track of the num ber of people entering a building using a particular entrance A person passing the en trance is tracked using an infrared sensor The sensor is set up such that a person enter ing the building breaks an infrared light beam directed at the sensor which changes its output from high to low as long as the beam is broken The event counter can be set up to increment on the high to low transition of the sensor output and in the end the count would give us the amount of people who entered the building using a selected en trance We can also use the event counter to calculate the time intervals between two events Event Counter The RX63N RX631 Group MCU has two units unit 0 unit 1 of 8 bit timers counters Each unit has 2 channels So there are a total of 4 channels of an 8 bit timer The 8 bit timer can be used in different operating modes timer mode event counter mode and pulse out put mode The timer mode can also be used to generate interrupts at particular intervals and two timers can be cascaded to use a 16 bit timer In this chapter we cover the basic concepts of an event counter mode The timer units can also generate a baud rate clock which can be used for serial communication CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 79 UNIT CHANNEL PINNAME vo DESCRIPTION TMRO TMOO Outp
145. pt A flag 39 4 IEN TMRO CMIBO 1 enable compare match interrupt B 4 IPR TMRO CMIBO 14 compare match interrupt B priority 4 IR TMRO CMIBO 0 clear compare match interrupt B flag void Excep TMRO CMIAO void italWrite enableA ON void Excep TMRO CMIBO void digitalWrite enableA OFF n O O JOU ARON FE O o F Q H 4 2 6 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 105 Frequency and Period Control For this example we will assume we are using the pulse output to control a servo motor Com mon servo motors use a pulse input to determine how or where it moves to Specifications vary by motor as per frequency and duty cycle required We will use specifications from an anonymously chosen motor for this example In the case of this motor we need a 1 ms pulse to turn full left and a pulse of 2 ms to turn full right Usually a frequency is not specified however you want to have adequate space between your pulses for smooth operation and also not have them spaced too far apart so that when the duty cycle is updated the servo re acts in a timely manner 50 Hz 20 ms period is a safe frequency for smooth operation For this example we will be using the timer in 16 bit cascaded mode as well as in pulse output mode This gives us more precise control over the duty cycle while still allowing for a wide period between pulses low frequency This is not much more complicated than 8 bit pulse output
146. r Serial communincations interface Memory protection unit RSP1 CAN CAN module MTU2a Multi function timer pulse unit 2 POE2a Port output enable 2 TPUa 16 bit timer pulse unit PPG Programmable pulse generator TMR 8 bit timer Serial peripheral interface CMT Compare match timer RTCa Realtime clock RIC I C bus interface IEB IEBus controller DEU Data encryption unit Figure 3 4 Block diagram 1 page 66 39 40 RENESAS SAKURA MICROCONTROLLER BOARD Memory The Memory contains three main modules ROM Its capacity is 2 Mbytes max as well as a ROM less version RX631 group ONLY It supports four on chip programming modes and one off chip programming mode RAM Its capacity is 128 Kbytes max Data Flash Its capacity is 32 Kbytes Clock generation circuit The clock generation circuit consists of two cir cuits namely a main clock oscillator and a sub clock oscillator The CPU and other bus masters run in synchronization with the system clock ICLK 8 to 100 MHz the peripheral modules run in synchronization with the peripheral module clock PCLK 8 to 50 MHz while devices connected to the external bus run in synchronization with the external bus clock BCLK 8 to 50 MHz Flash IF run in synchronization with the flashIF clock FCLK Up to 50 MHz Devices connected to the external bus run in synchronization with the external BCLK Reset There are various rese
147. ration of the CPU 2 Arithmetic and Logic Unit ALU Performs the computer s data processing functions CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 15 Figure 2 3 A top level view Registers of the CPU Interconnection 3 Registers Provides internal storage for the CPU They store ALU operands 4 Interconnections Provides a mechanism for transferring data or communicating between components such as the Control Unit ALU and registers The IAS computer which is a prototype of general purpose computers is based on the stored program concept This idea was developed by John von Neumann and is known as the von Neumann Machine As shown in Figure 2 4 the von Neumann machine has a main memory for storing the instructions and data the same as an IAS computer It also has an ALU which processes the binary data A control unit decodes the instructions and for wards them to the ALU for execution The Input Output unit interacts with the external en vironment and is controlled by the Control Unit CPU 4 4 VO Main ok Lf Control unit 7 Figure 2 4 Structure of a von Neumann machine 16 2 3 2 3 1 RENESAS SAKURA MICROCONTROLLER BOARD MICROCONTROLLER BASICS Bits and Bytes The basic concept of an embedded system is electricity If we ignore the underlying volt age value and just consider the maximum voltage of the system it is easy to recognize two cond
148. rator A n ANS 6 i re AN6 gt Sample and x 7 AN7 gt hold eircuit gt ADIO interrupt signal 5 4 Software trigger ANEXO E Synchronous triggers ANEX1 gt J o 4 F MTU TMR 5 H Synchronization Li Asynchronous trigger i 2 circuit ADTRG Internal n clock F PcLK Ep Clock T PCLK 2 ADCLK selection PCLK 4 4 rcLK8 ADDRA A D data register A ADCSR A D control status register ADDRB A D data register B ADCR A D control register ADDRC A D data register C ADCR2 A D control register 2 ADDRD A D data register D ADSSTR A D sampling state register ADDRE A D data register E ADDIAGR A D self diagnostic register ADDRF A D data register F ADDRG A D data register G ADDRH A D data register H Figure 4 20 Block Diagram of the 10 bit A D Converter 1 page 1684 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 125 PIN NAME INPUT OUTPUT FUNCTION ANO to AN7 Input Analog input pins ANEX1 Input Extended analog input pin ANEXO Output Extended analog output pin ADTRG Input Asynchronous trigger input pin for starting A D conversion VREFH Input Reference voltage input pin for the 10 bit A D converter and D A converter VREFL This is used as the analog power supply for each of the modules Connect this pin to VCC if neither 10 bit A D converter nor D A converter are used Input Reference voltage input pin for the 10 bit A D converter and D A conv
149. rfacing and continually focus on system requirements and design Computer Engineers must have strong analytical stills and be detail oriented In addi tion they must work well in team situations as they are often called upon to work in a group setting with other engineers and with others outside of engineering Communication abilities are important because engineers often interact with specialists in a wide range of fields outside engineering Computer Engineers are key contributors to the development of embedded systems since they have extensive knowledge of the hardware AND software of the system The can 10 1 8 1 9 1 10 RENESAS SAKURA MICROCONTROLLER BOARD perform many of the tasks needed such as designing the circuitry programming the oper ating system or writing the supplication software AN EXAMPLE OF AN EMBEDDED SYSTEM THE RENESAS SAKURA BOARD The Renesas Sakura Board Figure 1 1 is one example of a Renesas MCU based embedded system This device has fifty five digital I O lines that are controlled by the Renesas micro controller 2 Some of the main components to note are the 100 10 Mbps Ethernet port in the upper left a micro USB port right beneath the Ethernet port which is used to program the built in flash memory and at the bottom left a 5V DC power jack The Sakura also has a micro SD card slot located on the underside of the board The large chip in the center is a Renesas RSF563NBDDFP microcontroller fr
150. rise There are many variables that the above code does not consider We use the rated speed for the motors but it is more than likely that the RPM varies slightly from motor to motor In fact it could possibly be off by as much as 500 rpm We also did not accommodate for or considered the weight of the ro bot otherwise known as the payload The more weight on the motors the slower they will rotate How about the terrain It would make a substantial difference in the rpm of the motors from riding on a smooth wooden surface or on a grassy field How about slippage It is quite possible for one of the wheels to slip slightly or even rotate faster than the other To accommodate for our environment we will require feedback mecha nisms counters and pulse width modulators All this we will learn in Chapter 4 where we will attempt to utilize our knowledge to achieve the functionality dictated by our requirements RECAP The GR Sakura is one of the Gadget Renesas board series It is based on RX63N series 32 bit MCU The MCU has on chip flash memory and enhanced communication func tions including an Ethernet controller and USB 2 0 Host Function The on chip flash memory of RX63N is programmable by USB mass storage mode and the on chip flash memory is visible as a drive on your PC This chapter presented the tools and processes to use the Sakura embedded board The board is easy to program and use for many applica tions including sensing applications
151. roduction to Computer Engineering course that would lend itself to the theoretical and applied nature of the discipline and embedded systems design When Renesas released the GR SAKURA board I knew I have the perfect platform to use in the course This book was developed to augment the hands on exercises we use This book also has a radical fea ture not seen in many books currently on the market if any It is freely available for down load It is also available for purchase in hardcopy form for a modest price This book would not have been possible had it not been for the assistance of numerous people Several students and educators contributed to and extensively tested some of the chapters including Yevgeny Fridlyand 2 3 4 Adam Harris 1 2 3 Anthony Harris 3 Onkar Raut 2 4 Suganya Jebasingh 2 4 and Steven Erdmanczyk 4 Thanks go to the publisher Linda Foegen and especially June Harris Rob Dautel and Todd DeBoer of Renesas for their help in getting this book produced and published and for their patience Many many thanks go to the reviewers who offered valuable suggestions to make this book better especially David Brown and students from my UNC Charlotte Introduction to Engineering and Embedded Systems courses I would like to personally thank my parents the Conrads and my in laws the Warrens for their continued assistance and guidance through the years while I worked on books Also I would especially like to thank
152. rollers typi cally cost far less starting at under 0 25 Why is this so 1 2 2 1 3 RENESAS SAKURA MICROCONTROLLER BOARD Microcontrollers provide extremely inexpensive processing because they can leverage economies of scale MCUs are programmable in software so a chipmaker can design a single type of MCU which will satisfy the needs of many customers when combined with their application specific software This reduces the per chip cost by amortizing the de sign costs over many millions of units The cost of an integrated circuit such as a micro controller or a microprocessor depends on two factors non recurring engineering NRE cost and recurring cost The NRE cost includes paying engineers to design the integrated circuit IC and to verify through simulation and prototyping that it will work properly The recurring cost is incurred by making each additional IC and includes raw materials pro cessing testing and packaging The IC s area is the major factor determining this recurring cost The smaller the IC the more will fit onto a silicon wafer and the lower the recurring cost Microcon trollers are much smaller than microprocessors for personal computers so they will cost less given the same number of ICs sold The NRE cost must be divided across each IC sold As the number of ICs sold rises the NRE adder falls so each IC s price falls as well Because of this low volume chips are more expensive than high volume chip
153. rotation speed and which are 90 out of phase Motor speed can be de termined by the frequency and motor rotation direction can be determined by the phase relationship of the two signals ors H BRIDGE lt i O EN CIRCUIT M o o Jo vecls o SND os od oj od m GEM J2 gi GND Figure 4 15 PmodHB5 Circuit Board amp schematic 4 page 1 Previously we have calculated that it takes 265 636 motor rotations for our vehicle to travel one meter and 44 65 motor rotations to make a ninety degree turn 53 motor rotations 5 012 wheel rotations X 265 636 motor rotations 1 wheel rotation f 53 motor rotations 0 8425 wheel rotations X i 44 65 motor rotations 1 wheel rotation CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 107 The below flowchart utilizes the SA feedback as a control to move the vehicle in a one by one meter square and to attempt to adjust motor rotation when and if one motor is turning faster than the other Include all necessary special function files Setup timers counter mode AO and A1 Setup timers PWM mode A2 and A3 70 Duty Cycle EEE Output PWMzs EN L and EN R 4 Input Counters SA L and SA R Setup turncount variable 0 Enable Push button Enable all timers Push button pressed YES TURNCOUNT 4 Increase A3 by 1 bit Set direction DR L 1 and DR R 0 Start PW
154. rs Once we are done with our algorithm we can begin to code The below code example sat isfies the algorithm that we have created But does it satisfy the customer requirements Build the project using the code below and download it to the Sakura board Make sure to connect the connectors to the pins defined in the code GR SAKURA Sketch Template Version V1 08 include lt rxduino h gt 1 2 3 4 define directionA 2 Port 2 pin 2 motor A direction 5 define enableA 3 Port 2 pin 3 motor A on off 6 define directionB 4 Port 2 pin 4 motor B direction 7 define enableB 5 Port 2 pin 5 motor B on off 8 define Aforward 1 9 define Abackward 0 10 define Bforward 1 1 2 3 4 5 6 7 8 define Bbackward 0 define FORWARDTIME 2380 forward delay in milliseconds define TURNTIME 400 turn delay in milliseconds define PAUSE 500 Pause between switching directions define ON L define OFF 0 inte i7 counter variables J BRR KK ok oko kok kok kok kok kok kok kok kok kok I ee a k 19 setup input output pins 20 Z J BRR KR kok oko kok kok k kok oko kok kok k kee a ke a eH k 22 void setup 23 pinMode directionA OUTPUT 24 pinMode enableA OUTPUT 2E pinMode directionB OUTPUT 26u pinMode enableB OUTPUT 74 RENESAS SAKURA MICROCONTROLLER BOARD 27 28 29 30 31 32 33 34 35 36 3T 38 39 40 S U NF DS O0 U ao U A p
155. s Embedded Networks Some embedded systems consist of multiple embedded computers communicating across an embedded network and offer further benefits Each computer on the network uses a communication protocol to share the same set of wires to communicate rather than dedicating one set for each possible communication route Several advantages come from having fewer wires m Lower parts cost as fewer wires are needed Lower labor costs as it is faster to assemble m Greater reliability as it has fewer connections to fail Other advantages come from allowing separate nodes to share information New features may be possible or the system efficiency may be improved through better coordination of activities among different nodes TYPICAL BENEFITS OF EMBEDDED SYSTEMS As an example let s examine how embedded systems have affected automobiles A typical modern car has dozens of microcontrollers embedded within it Let s see why 1 3 1 1 3 2 CHAPTER 1 INTRODUCTION TO EMBEDDED SYSTEMS 3 Greater Performance and Efficiency Computer control of automobile engines lowers pollution and increases fuel efficiency re ducing operating costs Burning gasoline with air in spark ignition engines is a tricky business if we want to maximize efficiency yet minimize pollution The main factor affecting emissions is the ra tio of air mass to fuel mass The ideal ratio is 14 7 to 1 and the catalytic converter is de signed to operate most e
156. s A D conversion ADIE A D Interrupt 0 ADIO interrupt is disabled by completing A D conversion De 1 ADIO interrupt is enabled by completing A D conversion Reserved The read value is undefined The write value should be 0 RAN Figure 4 23 10 bit A D Converter control Status Register ADCSR description 1 page 1690 CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 129 A D Control Register ADCR The Control register is used to select the type of A D conversion mode clock and trigger MODE 1 0 sets the 10 bit A D in either Single mode Continuous Scan mode or One cycle scan mode Set the MODE 1 0 bits to 00b single channel mode 10b continuous scan mode or 11b single scan mode Do not set the MODE 1 0 bits to 01b The ADC clock can be set using the CKS 1 0 bits To select the peripheral module clock PCLK set the CKS 1 0 bits to 00b PCLK 8 01b PCLK 4 10b PCLK 2 or 11b PCLK The TRGS bits are used to select the type of trigger that will start the A D conversion process TABLE 4 7 Trigger Select for 10 bit ADC orc TE Software Trigger 0 1 Compare match input capture A from MTUO to MTU4 Compare match from TMRO 1 1 Trigger from ADTRG SOR Ska O Compare match input capture A from MTUO 1 Compare match input capture A from TPUO to TPU4 1 1 O Compare match from MTU4 1 1 1 Compare match input capture A from TPUO Figure 4 24 summarizes all of the possible configurations for the A D control re
157. s PCLK TMR3 TCCR BIT CKS 6 Adjust count source to PCLK 8192 42 ms TMR3 TCR BIT CCLR 1 Timer resets at compare match A TMR3 TCSR BIT OSA 1 1 output at compare match A TMR3 TCSR BIT OSB 1 O output at compare match B TMR3 TCORA OxFF Frequency 42 ms period TMR3 TCORB 0x80 Duty cycle 505 void InitCounters void MSTP TMR1 0 Activate TMR1 unit MSTP TMR2 0 Activate TMR2 unit TMR1 TCCR BIT CSS 0 uses external clock signal as count source TMR1 TCCR BIT CKS i Counts at rising edge of ext clock source TMR2 TCCR BIT CSS I o uses external clock signal as count source TMR2 TCCR BIT CKS 1 Counts at rising edge of ext clock source 4 2 7 2 Using Interrupts Pulse output amp Counters The following example uses compare match A interrupt and compare match B interrupt on TMRO to generate a pulse output to control motor speed and interrupt h functions to count rising edges of the hall effect sensors SA on the left and right motor This application is another way to execute the requirements in the beginning of section 4 2 7 ND H OV U e U co GR SAKURA Sketch Template Version V1 08 This program uses TMRO compare match A and compare match B to generate interrupts The interrupts are then used to generate a PWM on port 2 pin 2 the follow lines of code need to be modified in the intvect c file to mak
158. s to 00h again and the output goes back to 0 This process repeats pro ducing a square wave on the TCOn port n being the number of the timer used This is il lustrated in Figure 4 14 TMOn being the waveform of the output pulse TCNT o F ri Counter dear TE TCORA TCORB Pd TMOn n 0 to 3 Figure 4 14 An example of pulse output 1 page 1023 By altering the value of TCORA we change the frequency of the pulse output and by al tering TCORB without altering TCORA we alter the duty cycle of the wave Take note that by altering TCORA without altering TCORB the duty cycle does not remain the same be cause the output is going low at the same amount of time after TCNT resets but the time between when the pulse goes low and a compare match A occurrence has become longer Now we will cover an example of setting up a timer for pulse output This requires very little code to execute Once we have set up the timer it will begin to output our desired pulse without any further intervention void main void void InitTimer void void main void InitTimer while 1 nN U B WN F 100 CN15 102 RENESAS SAKURA MICROCONTROLLER BOARD 7 void InitTimer void 8 MSTP TMRO 0 Activate TMRO unit 9 TMRO TCCR BIT CSS 1 Count source is PCLK 8 10 TMRO TCCR BIT CKS 2 bie TMRO TCR BIT CCLR 1 Timer resets at compare match A be TMRO TCSR B
159. sensors arranged as a quadrature encoder These buffers have 5 V tolerant inputs when operated at 3 3 V Direction Enable Sensor A Sensor B GND Vec 3 3 5v HB5 6 Pin Header J1 Figure 3 36 HB5 6 Pin Header J1 4 page 1 For our basic motor control design we will need to assign four I O pins to control the H Bridge Two pins to control the direction of the motors one for the left motor and one for the right Motor A and B if you will We will also need two pins to control the enable of each motor Lastly we will need to supply a ground GND and a voltage 3 3 V to power each H Bridge Take a look at Section 3 2 1 do you know which pins we will need to use to supply GND and 3 3 V to each H Bridge Now that we understand how we can make our robot move forward or backward how do we know when the robot has moved one meter forward Or better yet how do we know if the vehicle has made a 90 degree turn To understand this we need to take a closer look at how the motors work As an engineer it is always important to have a strong under standing of how the peripherals that we decide to use work In fact it us up to the engineers to decide what peripherals they will need to satisfy the customers requirements Just like for the H Bridge the manufacture provides a datasheet for the motors that will give the en gineer the knowledge and understanding of not only how the motors function but also how they
160. sition or speed of the motor Varying the duty cycle will vary the speed or position When interfacing to a DC motor the microcontroller almost always lacks the power output to drive the motor A power amplifier must be used most often an H bridge The H bridge will take a square wave signal from the microcontroller and amplify it to whatever voltage and current levels are needed for the application By varying the duty cycle of the wave we vary the average power that is delivered to the motor making an efficient means of digi tally controlling an analog device CHAPTER 4 INTERFACING WITH THE OUTSIDE WORLD 99 Now we will go over how to set up pulse output mode First in pulse output mode TCR CCLR 1 0 bits are set to 01b This will make TCNT clear to 0x00 every time a com pare match A occurs Now we set TCSR OSA 1 0 to 10b and TCSR OSB 1 0 to O1b This will make the output from the timer channel change to 1 at the occurrence of compare match A and change back to 0 at the occurrence of compare match B Here is a brief overview of what happens on a single timer channel when set up in pulse output mode TCNT begins to count up Once it reaches the value of time constant register A the first time the pulse output becomes 1 and TCNT resets to 00h TCNT restarts counting and upon reaching the value of time constant register B the output goes to 0 TCNT continues to count until it reaches the value of timer constant register A again TCNT now reset
161. ster PDR has been defined as a union with the variable BYTE and a struc ture called BIT This organization helps in easy access of the bits of the PDR Unsigned char Bn 1 n 0 to 7 indicates that the character variable is assigned one bit To select a particular pin as the input pin the corresponding bit of the PDR has to be set to 0 and to select a pin as output the corresponding bit of the PDR has to be set to 1 The general syntax to set a bit of the PDR is PORTx PDR BIT Bn x 0 to 5 A to G J and n 0 to 7 since ports are defined as structures hence accessing structure members is done in this way To configure multiple pins at the same time the char variable BYTE can be used All pins are configured as inputs at reset by default Set Switch 1 Port A bit 7 as Input 1 PORTA PDR BIT B7 0 When a pin is selected as an input from a peripheral the Input Buffer Control Register ICR has to be enabled The ICR will be explained a little later Selecting a pin as an out put involves setting the Data Register DR and the Port Direction Register PDR Port Output Data Register PODR The Port Output Data Register PODR is also defined as a union of variables inside the port structure in the iodefine_gcc63n h file It is presented just like the PDR Unsigned char 1 is used to represent reserved pins CHAPTER 2 INTRODUCTION TO SOFTWARE DEVELOPMENT 19 B7 B6 B5 B4 B3 B2 B1 BO
162. stroy engine components to say nothing of reducing power or the efficiency and pollution concerns mentioned previously Embedded systems typically require sophisticated fault handling and diagnos tics to enable safe and reliable operation Often the fault handling code is larger and more complex than the normal operation code It is easy to design for the everything goes right and works fine case It is far more difficult to determine methods to handle the exceptional cases What is likely to fail Which failures can lead to dangerous conditions How should the system handle failures How will you test that the system handles the failures correctly Embedded systems may be expected to operate independently for years without operator attention such as adjustment or resetting The system is expected to oper ate robustly and always work Given that it is very difficult and expensive to write perfect bug free software developers build in mechanisms to detect faulty behav ior and respond perhaps by restarting the system RENESAS SAKURA MICROCONTROLLER BOARD 1 6 CONSTRAINTS ON EMBEDDED SYSTEMS Embedded systems often have constraints which limit the designer s options and can lead to creative and elegant solutions These constraints are typically different from those for general purpose computers Cost is a common constraint Many applications which use embedded systems are sold in very competitive markets in which price is a major fa
163. sts who create the basic technological advances in materials Scientists design the device enclosure Mechanical Engineers design the circuit boards and components on the circuit boards Electrical Engineers design and write code which interfaces with the user and performs the specific de vice application Software Engineers 1 7 1 CHAPTER 1 INTRODUCTION TO EMBEDDED SYSTEMS 7 design and write software to control the hardware Computer Engineers design the assembly lines which make the devices Manufacturing and Industrial Engineers m make sure the mechanical electrical and computer components of a device work together Systems Engineers It should be noted that many other people can be considered embedded systems develop ers There are countless students and hobbyist who create embedded systems used in ro bots and entrepreneurs who create the next hot electronic toy Product Development Engineering design is the creative process of identifying needs and then devising a solution to fill those needs This solution may be a product a technigue a structure a project a method or many other things depending on the problem The general procedure for com pleting a good engineering design can be called the Engineering Method of Creative Prob lem Solving Problem solving is the process of determining the best possible action to take in a given situation The types of problems that engineers must solve vary between and amo
164. t unsigned char interrupt void func void int mode Specify ISR function when external interrupt occurs void interrupts void Enable global interrupt Enable the interrupt that was stopped by the nolnterrupts function Argument none Return value none void nolnterrupts void Globally disable interrupt Argument none Return value none Note Used to such as to eliminate the disturbance of such timing by disable interrupts in a critical section Warning Interrupts are enabled by default and will process important background tasks Many features of RXduino will not be able to be used if interrupts are disabled such as USB and serial communication May result in a system crash so should be used with care void detachInterrupt unsigned char interrupt Stop the specified interrupt Argument interrupt number 0 7 0 port P10 is not in IRO0 TOFP100 pin 1 port P11 is not in IRQ1 TOFP100 pin 2 port P12 IRO 2 3 Port P13 IRQ3 4 port P14 IRO4 94 RENESAS SAKURA MICROCONTROLLER BOARD 5 port P15 IROS5 6 port P16 IRO6 7 Port P17 IRO7 Return value none void attachInterrupt unsigned char interrupt void void func int mode specify a function to execute when an external interrupt occurs Argument interrupt numbers 0 7 Port P10 is not in IRO0 TQFP100 pin Port P11 is not in IRO1 TOFP100 pin Port P12 IRQ2 Port P13 IRO3 Port P14 IRQ4 P
165. t 2 pin 4 PIN NUMBER TIMER COMMUNICATIONS 100 PIN BUS MTU TPU TMR ETHERC SClc SCId RSPI CN15 LOFP I O PORT EXDMAC PPG RTC POE RIIC CAN IEB USB INTERRUPT 104 P24 CS4 MTIOC4A MTCLKA SCK3 USBO_VBUSEN EDREO1 TIOCB4 TMRI1 PO4 1 GR SAKURA Sketch Template Version V1 08 2 include lt rxduino h gt 3 include lt iodefine gcc63n h gt 4 5 define ANALOG ANO 46 ANO input to the 10 bit ADC 6 define directionA 3 Port 2 pin 3 motor A direction 7 define enableA B 2 Port 2 pin 2 PWM TMRO input to motor A and B 8 define directionB 5 Port 2 pin 5 motor B direction 9 define counterRst 6 Port 2 pin 6 clear TMR1 Count output 10 define TMR1 CCLR 4 Port 2 pin 4 clear TMR1 Count input Ii 12 define Aforward 13 define Abackward 140 RENESAS SAKURA MICROCONTROLLER BOARD 14 define Bforward d 15 define Bbackward 0 16 define Asa 10 Port C pin 4 input to counter TMR1 ds 18 define PAUSE 500 Pause between switching directions 19 define ON 1 20 define OFF 0 21 22 unsigned short ADC value 23 int forward 0 24 int backward 0 25 int turn 0 26 2T J BRK RR RK kok RR kk RR kk kk kkk kkk kkk kkk kk kk 28 setup input output pins 29 7 30 J RRR KR RK kok RR kk RR RR Ek RR kk RE RR KK kkk 31 void setup 32 pinMode ANOLOG ANO INPUT 33a pinMode directionA OUTPUT
166. t Renesas Renesas Electronics America Inc Web Accessed at http www rene sas com products promotion gr index jsp board 3 Renesas Electronics Inc February 2013 RX63N Group RX631 Group User s Manual Hardware Rev 1 60 Chapter2 Introduction to Software Development 2 1 2 2 LEARNING OBJECTIVES This book cannot cover all of the concepts of embedded system design and microcontroller programming There are however some basic concepts that are important In this chapter the reader will learn about Basic organization of computers Basic representation of data in a computer Concepts of compiling code for an embedded system Concepts of developing software for an embedded system COMPUTER ORGANIZATION amp ARCHITECTURE A computer is a complex digital system The best way to look at it is by looking at its hier archical nature Hierarchical systems are best described as a series of subsystems that are interconnected at various levels to form a complete computer system At each level is a set of components whose behavior depends on the characteristics and functions of the next lower level A designer focuses on structure and function within each level The computer has four basic functions to perform see Figure 2 1 Data processing Data storage Data movement Data control Pew S Computers process data with the help of the data processing facility During and after pro cessing storage is required for this
167. t in pulse transformer JTAG terminal Used for debugging and can be connected to a JTAG debugger such as the Renesas E1 Arduino compatible terminal Note the difference of 5V to the standard opera tion voltage of 3 3V Can also be used as terminal extensions pull out the pre terminal of block 6 to expand Figure 3 3 shows the pin layout Pins indicated in white are 5V tolerant Switches a SW1 Red teset b SW2 blue user release c SW3 slide operation mode switching of RX63N LEDs Four LEDs are available on the GR Sakura board They are programma ble and sometimes can be quite helpful in debugging Figure 3 1 GR SAKURA FULL front view CHAPTER 3 GETTING STARTED WITH GR SAKURA 37 8 USB host connector A type Because of limited mounting space the USB host connector can be soldered to the substrate back The host connector can be used to implement Android ADK as well as other embedded operating sys tems on the GR Sakura Note that the Function and Host USB cannot be used simultaneously 9 XBee mounting pattern The Zigbee XBee is a wireless communication mod ule famous for its Wi Fi capabilities 10 Micro SD card slot Access the SPI mode eee bes R sf er a er ee ee WE EE Figure 3 2 GR SAKURA FULL back view The GR Sakura has fifty two I O pins and six analog to digital input pins Some pins are reserved The reserved pins cannot be configured as I O pins 38 RENESAS S
168. t sources available for different modules in the MCU such as pin reset power on reset voltage monitoring reset watchdog timer reset independent watchdog timer reset deep software standby reset and soft ware reset Voltage detection circuit When the voltage available on VCC falls below the voltage detection level Vz an internal reset or internal interrupt is generated External bus extension The external address space is divided into nine areas CSO to CS7 and SDCS The capacity of each area from CSO to CS7 is 16 Mbytes and for SDCS the capacity is 128 Mbytes A chip select signal CSO to CS7 SDCS can be output for each area Each area is specifiable as an 8 16 or 32 bit bus space the data arrangement in each area is selectable as little or big endian only for data The SDRAM interface is connectable Bus formats in clude Separate bus and multiplex bus Direct Memory Access DMA The DMA system consists of three different controllers which are explained below The activation sources for all three con trollers are software trigger external interrupts and interrupt requests from pe ripheral functions DMA controller It has four channels and three transfer modes These modes are normal transfer repeat transfer and block transfer EXDMA controller It has two channels and four transfer modes These modes are normal transfer repeat transfer block transfer and cluster transfer m Data transfer controller It has three
169. tA 0 22 int startMotors 0 23 int turn 0 24 int forward 0 25 int backward 0 26 void ADC Init void 27 void InitPWMs void 28 void myEventCounterA void 29 30 ifdef cplusplus 31 extern C 32 void Excep TMRO CMIAO void 33 void Excep TMRO CMIBO void Ww a motor A direction PWM TMRO input to motor B direction motor B on off 144 RENESAS SAKURA MICROCONTROLLER BOARD 35 36 37 38 39 50 Ss 52 DO 54 DO 56 STe 58 59 60 61 62 63 64 65 66 67 68 69 70 Ts 72 73 DS GO U M WN F IS co N endif void setup pinMode directionA OUTPUT pinMode enableA OUTPUT pinMode directionB OUTPUT pinMode enableB OUTPUT initialize the counters and the Pulse width modulators ADC Init InitPWMs interrupts Port P12 IRQ2 function call RISING 3 Interrupt occurs for LOW to HIGH state attachInterrupt 2 myEventCounterA 3 Start with getting ready to move forward by making sure the motors are disabled and direction is set to move forward Aforward Bbackward digitalWrite directionA digitalWrite directionB void loop startMotors 0 motorCountA 0 turn 0 backward 0 forward 1 while digitalRead PIN SW HIGH while 1 if AD ADCSR BIT ADST 0 ADC value AD ADDRA amp 0x03FF AD ADCSR BIT ADST 1
170. tart gt All Programs gt Renesas gt Flash Development Toolkit 4 08 gt Flash Development Toolkit 4 08 basic When the application opens up select Generic BOOT Device this option should be at the very bottom of the list as seen in Figure 3 15 Once it is selected click next 52 RENESAS SAKURA MICROCONTROLLER BOARD The FLASH Development Toolkit supports a number of Renesas FLASH devices Select the device you wish to use with this project from the list below Filter Type Full Name Kernel Version R32C R5F64600 ECC 1000 R32C R5F64601 R32C R5F64601 ECC R32C R5F6460E R32C R5F6461F R32C R5F64610 R32C R5F64610 ECC R32C R5F64611 R32C R5F64611 ECC R32C R5F6461E Generic BOOT Device Generic BOOT Device oo oo oo memu mn mm m m PPP cece oooooco ooo o amp oo 6 z gt i Figure 3 15 Flash Development tool Kit Device Selection On the next window change the select port to USB Direct and with the GR Sakura board still plugged into your computer in boot mode SW3 is to the back of the board Use this page to select your desired communications port interface All settings may be changed after the project is created Select port USER ad v Select an Interface type to connect to the target device with Normally this will be Direct Connection or simply left blank Select Interface Direct Connection v
171. tional in case the microprocessor needs to communicate to the sensor The use of a flyback diode is very important when interfacing in ductive loads to safely dissipate the voltage spike when the voltage to the load is removed BASIC ROBOTICS APPLICATION Let s develop our first application by starting with a basic set of requirements that were identified in Section 2 5 3 Motor Robot Kit Assembly To meet these requirements we are going to need some hardware The Digilent Motor Robot Kit MRK provides the perfect starting point for those new to robotics but has the 64 RENESAS SAKURA MICROCONTROLLER BOARD power to be used for advanced designs and applications as well The MRK boasts a rugged steel platform and all the motors wheels and other parts needed to build a complete robot The Digilent Motor Robot Kit MRK Assembly includes 3 Two PmodHB5 2A H bridge motor amplifiers with attachment clips and 6 pin cables m metal standoffs for microcontroller board rugged metal platform with holes on 1 2 center two 1 19 ratio motor gearbox drives with ABS plastic wheels 1 53 gear ratio mo tors also available m rugged plastic wheels and drag button rugged metal motor mount all wiring and assembly hardware included 1 Place the motor mount on the right side of the platform Attach it with two screws 3 Figure 3 28 Assembly Step 1 3 Page 2 CHAPTER 3 GETTING STARTED WITH GR SAKURA 65 2 Attach the mo
172. tions includ ing an Ethernet controller and USB 2 0 Host Function The on chip flash memory of RX63N is programmable by USB mass storage mode and the on chip flash memory is visible as a drive on your PC We will delve a little more into the GR Sakura MCU in section 3 2 3 The GR Sakura board is very flexible to a designer s needs Its features are compatible with not only host Renesas products such as the RX63N but the GR SAKURA board is compatible with Arduino as well The GR SAKURA FULL board comes with a LAN con nector RJ 45 a 5V DC Jack and a micro SD socket soldered on the board The USB host connecter is bundled in the box so you can solder it when needed To help get better acclimated with the peripherals of the GR SAKURA this section breaks them down into ten basic blocks Figure 3 1 and Figure 3 2 show the layout of these peripheral blocks 1 USB function connector Limited to USB mass storage compatible handsets via Android terminal or a PC connection a USB bus power supply power b Transfer speed 12M bits per second bulk interrupt control c Transfers compiled program to the internal Flash memory of the 63N MCU 35 36 RENESAS SAKURA MICROCONTROLLER BOARD w DC power jack 5V USB bus power is used in the case of capacity shortage Standard operating voltage of the MCU is 3 3V The voltage is converted from 5V to 3 3V by the regulator on the board to power the MCU EtherNET RJ45 connector 100 10Mbps buil
173. to any number of bits from 8 to 16 or to 20 24 or 32 bits Transmission and reception is buffered by 128 bit buffers A D converter MCU supports two A D converters specifically 12 bit and 10 bit The conversion time is 1 0 ws per channel The selectable operating modes are single mode and continuous scan mode age ranges from 0 V to Ver D A converter It supports two channels and 10 bit resolution The output volt Temperature Sensor The MCU supports a temperature sensor with precision of 1 C The voltage of the temperature is converted into a digital value by the 12 bit A D converter DEFINITION OF TERMS ENG ERGE EDMAC ICU DTC DMACA EXDMAC BSS CAN MTU POE PPG Ethernet controller DMA controller for Ethernet controller Interrupt control unit Data transfer controller DMA controller EXDMA controller Bus controller CAN module Multi function timer pulse unit Port output enable Programmable pulse generator WDT IWDT CRC MPU Sc USB RSPI TMR CMT RTC RIIC Watchdog timer Independent watchdog timer Cyclic redundancy check calculator Memory protection unit Serial communications interfaces USB 2 0 host function module Serial peripheral interfaces 8 bit timer Compare match timer Real time clock I C bus interface The specific chip that is used on the GR Sakura board is the RSF563NEDDFP The package for this chip is the 100 pin PLOPO1OOKB A package and has a ROM capa
174. tors to the motor mount with the miniature screws 3 Figure 3 29 Assembly Step 2 3 Page 2 3 Attach the battery holder to the platform near the motor mount using the shorter Velcro strip 3 Figure 3 30 Assembly Step 3 3 Page 3 66 RENESAS SAKURA MICROCONTROLLER BOARD 4 Attach the Pmod clips to the metal platform on both sides of the battery holder 3 Figure 3 31 Assembly Step 4 3 Page 3 5 Attach the drag button to the platform below the battery holder 3 Figure 3 32 Assembly Step 5 3 Page 4 CHAPTER 3 GETTING STARTED WITH GR SAKURA 67 6 Attach the two PmodHBS modules to the Pmod clips and connect them to the mo tors 3 Figure 3 33 Assembly Step 6 3 Page 4 7 Get the two wheels and the rubber traction bands Stretch the rubber band around the outside of the wheel Attach the wheels to the motors 3 Figure 3 34 Assembly Step 7 3 Page 5 68 3 8 2 RENESAS SAKURA MICROCONTROLLER BOARD Understanding the Hardware Now that the MRK is assembled let s take a closer look at how the motors should interact with the microcontroller To understand that interaction we will need to understand how the PmodHBSTM H Bridge controls the motors so that we know how we will need to con trol the H bridge from the microcontroller to get the vehicle to do what we want The Digilent PmodHBSTM 2A H Bridge Module the HB5 is an ideal solution for ro botics and other applications
175. transfer modes These modes are normal transfer repeat transfer and block transfer VO ports The main modules of I O ports are programmable I O ports There are several I O ports available on the 177 pin TFLGA 176 pin LFBGA 176 pin LOFP 145 pin TFLGA 144 pin LQFP and 100 pin LOFP CHAPTER 3 GETTING STARTED WITH GR SAKURA 41 9 Timers There are seven timer units available for controlling the seguence of events or processes Timer pulse unit TPUa It has two units each supporting six channels and each channel has 16 bits Each unit supports cascade connected operation 32 bits x 2 channels Multi function timer pulse unit 2 MTU2a It has one unit supporting six channels and each channel has 16 bits Time bases for the 6 16 bit timer channels can be provided via up to 16 pulse input output lines and three pulse input lines The clock signal can be selected from among eight counter input clock signals for each channel PCLK 1 PCLK 4 PCLK 16 PCLK 64 MTCLKA MTCLKB MTCLKC MTCLKD other than channel 5 for which only four signals are available Other characteristics of the MTU2a include Input capture function 21 output compare input capture registers Complementary PWM output mode Reset synchronous PWM mode Phase counting mode Generation of triggers for A D converter conversion Digital filter Signals from the input capture pins are input via a digital filter PPG output trigger can be generated Clock frequency measur
176. ts and Bytes 2 3 2 Ports Port Direction Register PDR Set Switch 1 Port A bit 7 as Input Port Output Data Register PODR Set LEDO Port A bit 0 as Output Sets LEDs 1 2 3 and 4 Port A bit 0 1 2 and 3 as Outputs Port Input Data Register PIDR Port Mode Register PMR 2 3 3 Data Types 2 4 Software Development Tools 2 4 1 Compilation Mechanism 2 4 2 Compilers for Embedded Systems 2 4 3 Debugger 2 4 4 Example of an Integrated Development Environment 2 5 Basic Software Development 2 5 1 Development Lifecycle Overview 2 5 2 Define System Requirements 2 5 3 Reguirements Robotics Applications 2 5 4 Developing Code 2 5 5 Start with an Algorithm 2 5 6 Convert your Algorithms to Code 2 6 Recap 2 7 References 2 8 Exercises 13 13 16 16 17 17 18 18 19 19 19 20 20 22 22 23 24 24 26 26 27 29 30 30 31 33 33 33 CONTENTS ix CHAPTER 3 Getting Started with GR Sakura 35 3 1 Learning Objectives 35 3 2 Sakura Embedded System 35 3 2 1 Sakura Board Design 35 3 2 2 Basic Concepts of the RX63N Microprocessor 38 3 3 Sakura Software Development 44 3 4 Sakura Example Project 46 3 5 Updating the GR Sakura Firmware 50 3 6 Setting Up an Account with MyRenesas 54 3 7 BASIC Motor amp Sensor Control 57 3 7 1 Switch Controlled LEDs 57 Using LEDs as Outputs 58 Using Switches as Inputs 58 3 7 2 Driving Motors and Coils 61 3 8 Basic Robotics Application 63 3 8 1 Motor Robot Kit Assembly 63 3 8 2 Understanding th
177. tworks offer many opportunities to improve dependability An engine controller and other controllers can provide various limp home modes to keep the car running even if one or more sensors or other devices fail A warning of an impending failure can be provided Diagnostic information can be provided to the driver or service personnel saving valuable trouble shooting time EMBEDDED SYSTEM FUNCTIONS There are several common functions which embedded systems typically provide Control systems monitor a process and adjust an output variable to keep the process running at the desired set point For example a cruise control system may increase the throttle setting if the car s speed is lower than the desired speed and reduce it if the car is too fast There is often sequencing among multiple states For example a car engine goes through multiple states or control modes when started During Crank and Start the fuel air mix is rich and depends on the engine coolant temperature Once the engine has started the controller switches to the Warm Up mode in order to raise the engine and exhaust system temperatures to their ideal levels Here the fuel air mixture and ignition timing are adjusted again based in part on the engine coolant CHAPTER 1 INTRODUCTION TO EMBEDDED SYSTEMS 5 temperature When the engine has warmed up it can switch into Idle mode In this mode the controller seeks to minimize the engine s speed yet still run smooth
178. ual to 0 1 us The timers may have a bit length of 8 bit 0 to 255 16 bit 0 to 65535 and 32 bit 0 to 4294967295 For an 8 bit timer with a clock source of 10 MHz the maximum time a timer can count depends on the maximum value a timer count register can hold i e the maximum value in an 8 bit regis ter is 255 FFh Therefore the maximum time for an 8 bit timer count is 77 78 RENESAS SAKURA MICROCONTROLLER BOARD 255 10 MHz 255 0 1usec 25 5 usec Therefore with an 8 bit timer you can measure a maximum of 25 5 usec But what if you want to measure 100 usec with an 8 bit register Should we count four times through an 8 bit timer The answer is no For this purpose the microcontroller has a prescaler which is used to divide the external or internal clock source by a fixed integer This increases the amount of time a timer can count without adding much hardware The general division factor for the prescaler would be multiples of two For example if we have a division fac tor of 32 then the maximum amount of time a timer can count with a 10 MHz clock source is 255 10 MHz 32 32 253 x asec 816 psec As aresult the maximum amount of time a timer can count increases as the prescaler divi sion factor increases A timer can also be used as an event counter The function of the event counter is the same as the counter but the event counter counts external events indicated by sig nal transitions on an input
179. uire digital logic as well as some resistors and capacitors Hardware debouncing circuits are very useful for interrupt pins Software debouncing is accom plished by setting up a timer to check the state of the switch at a set interval such as every 1 ms If the value of the input has been the same for the duration of the timer 1 ms in this case the input can be considered valid This method helps to ignore false input values Let s update our program to utilize a software debouncing solution Add the following dec larations below our constant declarations 1 int counter 0 now many times we have seen new valu 2 int reading the current value read from the input pin 3 int current state LOW the debounced input value 4 long time 0 the last time the output pin was sampled 5 int debounce count 10 number of millis samples to consider Add the following debounce function to the digitalio h file right above the digitalRead function 1 before declaring a debounced input 2 int DebounceButtonPress void 3 Tf we have gone on to the next millisecond 4 if millis time 5 reading digitalRead PIN SW 6 if reading current state amp amp counter gt 0 7 counter 8 9 if reading current_state 10 countert 11 3 7 2 DN HO V o U BU N CHAPTER 3 GETTING STARTED WITH GR SAKURA 61 T the Input has shown the same value for long enough let s switch it i
180. upt A 15 IPR TMRO CMITAO 15 compare match interrupt A priority 16 IR TMRO CMIAO 0 clear compare match interrupt A flag 102 RENESAS SAKURA MICROCONTROLLER BOARD eae 18 IEN TMRO CMIBO 1 enable compare match interrupt B 19 IPR TMRO CMIBO 14 compare match interrupt B priority 20 IR TMRO CMIBO 0 clear compare match interrupt B flag 21 3 j The interrupt functions that we will need to utilize are contained in the invect c file The file that we write our program in is a cpp file which is compiled as C Because we cannot add a C defined function to a C defined vector table we need to utilize Extern C to mask these functions Extern C affects linkage C functions when compiled have their names mangled By wrapping the C code with extern C the C compiler will not mangle the C code s names Now we need to set the interrupt functions that we will utilize to be extern functions To do this we will need to make a couple modifications in the invect c file Find lines 724 through 726 724 void Excep TMRO CMIOA void 725a UserTMROInterruptFunction modified on 2013 9 20 weak function 726 And change them to void Excep TMRO CMIOA void STOP Find lines 1504 through 1510 1504 TMRO CMIAO 1505 void Excep TMRO CMIAO void 1506 UserTMROInterruptFunction modified on 2013 9 20 weak function 1507 1508 1509 TM
181. ur project tree in the left panel has now changed to Renesas Web Compiler Project Root ia gr build ks gr common gr reference e html 9r reference j html gr sketch cpp B makefile sketch bin Figure 3 12 Renesas Web Compiler project tree 50 3 5 RENESAS SAKURA MICROCONTROLLER BOARD The sketch bin file is the file that you are interested in Right click on the file and se lect download files Find your downloaded file which should be located in the downloads folder within computer Drag and drop this file over to the GR Sakura drive Click the reset button and the board should now cascade through the LED s that were previously blinking at a constant rate UPDATING THE GR SAKURA FIRMWARE If the GR Sakura board does not show up within the drive window you will need to update the firmware Change the position of SW3 in the other location to enable it in boot mode This will allow you to modify the firmware on the GR Sakura Press the red switch to reset the board A new folder will appear on your desktop called RX_Arduino Click on the RX_Arduino folder on the desktop and run the executable application fdtv408r02 exe now Click next when the application opens up Choose the desired language that you would like to install the application in and click next Renesas Flash Development Toolkit v4 08 InstallShield Wizard Lx Select Language tENESAS Langua
182. urns to the black window it strikes the infrared transistor s base causing it to conduct current The more infrared incident on the transistor s base the more current it conducts W i 470 0 OR 0 01 uF WW 220 0 B D A A QRD1114 Figure 4 27 QTI sensor electrical characteristics 7 136 RENESAS SAKURA MICROCONTROLLER BOARD When used as an analog sensor the QTI can detect shades of gray on paper and distances over a short range if the light in the room remains constant The QTI sensor has 2 inputs and one output When W is connected to Vaa 5V and B is connected to V GND the R terminal s voltage will drop or rise based on the shade of the surface If all you want to know is whether a line is black or white the QTI can be converted to a digital sensor by adding a 10 KQ resistor across its W and R terminals After doing so the QTI behaves sim ilarly to the circuit in figure 4 28 When W is connected to Vdd and B is connected to Vs the R terminal s voltage will drop below 1 4 V when the IR transistor sees infrared re flected from the IR LED When the IR LED s signal is mostly absorbed by a black surface the voltage at R goes above 1 4 V 7 MEd 0 01 pF 08 tka S 4700 W R O MM i n i 2200 i B vy vy QRD1114 gt aTi Figure 4 28 QTI sensor electrical characteristics using a 10K resistor
183. ut Outputs compare match TMCIO Input Inputs external clock for counter TMRIO Input Inputs external reset to counter TMR1 TMO1 Output Outputs compare match TMCI1 Input Inputs external clock for counter TMRI1 Input Inputs external reset to counter 1 TMR2 TMO2 Output Outputs compare match TMCI2 Input Inputs external clock for counter TMRI2 Input Inputs external reset to counter TMR3 TMO3 Output Outputs compare match TMCI3 Input Inputs external clock for counter TMRI3 Input Inputs external reset to counter Figure 4 1 Pin Configuration of the TMR 1 page 1016 The event counter mode is used to detect the overflow of the timer After detecting the over flow another timer can be made to start counting For example TMRO can be made to start counting once TMR1 overflows and TMR2 can be made to start counting once TMR3 overflows This feature is mainly used to cascade two timers The overflow function can be used by setting the TCCR CSS 1 0 bits to a value of 3 In timer mode each timer can be used as an independent timer to count an external event or as a pulse output device The timer works by incrementing a register each time there is a count within the device The count is either triggered by a pulse from the inter nal peripheral clock a scaled version of the clock or an external source When this count overflows from its maximum value to zero and or there is a compare match with one of the timer constant registers an action is performe
184. xt screen as seen To register please provide the following information indicates reguired fields Receive registeration Email STEP 3 v Given Name First Name Enter personal information Family Name Last Name from URL in Email STEP 4 Email Address Confirm entered information STEP 5 Email Address confirm v RE DAS Cancel Close Clear all Submit content service 3 7 3 7 1 Figure 3 23 MyRenesas Registration An E mail will be sent to the desired E mail address you used This will reguire you to have access to that e mail account so that you can access the confirmation e mail Once you receive this e mail click on the link within the e mail that will allow you to finish set ting up your account with a password address and further information Congratulations Now you are fully registered with MyRenesas BASIC MOTOR amp SENSOR CONTROL Switch Controlled LEDs Now that we have setup our Renesas account go ahead and login to the web compiler and let s create our first project Since we are already familiar with the sample project that Renesas has provided for us we can use the sample project as our starting point The GR Sakura board has two push buttons and four LEDs Switches like LEDs are simple I Os and in the following program we will see how to set up a switch as an input to the LEDs According to this program when the blue switch is pressed LEDO will light up and LED1 will be off

Download Pdf Manuals

image

Related Search

Related Contents

広報つわの7月号vol.105 (PDF文書)  M - DSpace  Pyle® Single DIN AM/FM-MPX PLL Tuning Radio Users Manual  Abocom WR404 User's Manual      5.信頼される企業としての取り組み  Samsung NP-R528CE User Manual (FreeDos)  Zebra Image Lock Resin  design makes objects timeless, fashion corrupts  

Copyright © All rights reserved.
Failed to retrieve file