Designing with Microcontrollers Ing. Davide Brunelli DEIS - Università di Bologna davide.brunelli@unibo.it Davide Brunelli 1 Embedded System y F t Features: Small S ll size i Low power Effi i t use off PCB space Efficient High performance in small size Hi h MIPS / power consumption High ti ratio ti High bus bandwidth Low interface bottlenecks Davide Brunelli 2 Applications pp development p stages g Prototype Goal: “Try it and see” “Rapid Rapid prototyping prototyping” Pilot Goal: “Unprecedented data” “Realistic Realistic study study” “Modest scale” “Modest investment” “Well-enough executed” Production “Reducing cost” “Optimizing p g performance” p “Improving manufacturability” “Obtaining high reliability” “Finalizing mechanicals” + Accrue = Learnings Artifacts Investments Davide Brunelli 3 What is a microcontroller ? A Microcontroller is a small CPU with many support devices built into the chip Self Contained (CPU, Memory, I/O) Application A li i or Task T k Specific S ifi (Not (N a general-purpose l computer)) Appropriately scaled for the job Small power consumption Low costs ( $0.50 to $5.00.) Davide Brunelli 4 Microcontrollers and Embedded Controllers Controls some process or aspect of the environment: Microcontrollers Vs. DSPs DSPs optimized for math [multiplies] (aÅa+b*c) Embedded controller may not be a microcontroller per se but is used for special purpose control application Typical applications: temperature control, smart instrument, GPS, digital lock, cell phone, etc. . Davide Brunelli 5 Key Design Elements Flash Storage proc data logs pgm images Data SRAM Sensor Interface timers pgm EPROM Wireless Net Interface WD Wired Net Interface Low-power St db & Wakeup Standby W k ADC analog sensors digital sensors RF transceiver antenna serial link USB,EN,… Efficient wireless protocol primitives Fl ibl sensor iinterface Flexible t f Ultra-low power standby Very Fast wakeup Watchdog and Monitoring Data SRAM is critical limiting resource Davide Brunelli 6 Examples Personal information products: Cell phone, pager, watch, pocket recorder, calculator Laptop components: mouse, keyboard, modem, fax card, sound card, battery charger Home appliances: door lock, alarm clock, thermostat, air conditioner, tv remote conditioner remote, hair dryer, dryer VCR, VCR small refrigerator, exercise equipment, washer/dryer, microwave oven Toys; video games, cars, dolls, etc. Davide Brunelli 7 Why Ultra-low Ultra low Power Is Important Longer battery life Smaller products Simpler power supplies Less EMI simplifies p PCB Permanent battery Reduced liability Davide Brunelli 8 Market & Families Microcontroller unit sales are 15x higher than Microprocessors and are much cheaper. Most M t manufacturers f t offer ff a wide id range off devices d i for f low l endd to t higher hi h end applications Out of scope Davide Brunelli 9 Performance Metrics Not easy to define. Metrics are mostly application depended Electrical: El ti l Power Consumptions Voltage Supply Noise Immunity Sensitivity Computation: Clock Speed MIPS ((instructions pper sec)) Latency (lateness of the response) - Lateness of the response g between the begin g and the - Lag end of the computation Throughput - Tasks per second - Byte per second Energy is a good metric for the Digital section of WSN node Davide Brunelli 10 Microcontroller MSP430 Ultra-low Power + High Performance High-Performance 0.1µA power down 0.8µA standby mode 250µA / 1MIPS <1µs clock start-up Zero-power BOR <50nA pin leakage Modern 16-bit RISC CPU 1K to 128KB+ ISP Flash 14- to 100-pin options Intelligent peripherals boost performance Embedded E b dd d emulation l i Davide Brunelli 11 MSP430 Roadmap p Device 5xx-Next Gen Production • 25 MIPS • 32-256 KB • USB-RF Sampling Development Perform mance Future F23x-F24x F563x USB F261x F241x F543x • 16 MIPS 120KB • 11-120KB • 500nA Stand By F22xx 1xx-Catalog • 8 MIPS • 1-60KB F21x1 F5xx RF 2xx-Catalog F23x0 F20xx F5xx F21x2 F15x-F16x F13x-F14x F12xx F/C11xx Fx42x F 42 0 Fx42x0 F/C41x F471x7 Fx43x F44x F47x4 CG461x FG461x 4xx-LCD • 8/16 MIPS • 4-120KB • LCD Driver F = Flash C = Custom ROM Integration Davide Brunelli 12 MSP430 main characteristics Flexibility: Up to 256 kB U kByte Fl Flash; h Up to 100 pins; USART, I2C, Timers; LCD driver; Embedded emulation; And many more peripherals modules… Microcontroller Mi t ll performance: f Instruction processing on either bits, bytes or words Reduced instructions set; Compiler efficient; Wide range of peripherals; Flexible clock system. Davide Brunelli 13 13 Microcontroller MSP430 16-BIT RISC with 27 core instructions,27 emulated instuction, 7 addressing mode. Modest clock speeds (8-16 (8 16 MHz) 16-bit bus(MAB E MDB), 16 GP 16bit registers fully addressable Intended as “single single chip” chip solutions In-circuit programmable Flash (~1000 cycles) Small amount of FLASH and SRAM Single-cycle execution of most instructions Several on-chip on chip peripherals (UART, SPI,I2C,IRDA, ADC(SAR & Σ−Δ), 12 BITS DAC,PWM, 16 AND 8 BITS TIMERS,DMA , CONTROLLER,WDT, LDO) Davide Brunelli 14 MSP430 architecture Davide Brunelli 15 MSP430X16X Architecture ADC ALU DAC I/O Port Registers Interrupts DMA TIMERs Davide Brunelli USARTx 16 Memory organization The MSP430 von-Neumann architecture has one address space shared with special function registers (SFRs), peripherals, RAM, and Flash/ROM memory. Data can be accessed as bytes or words. Th addressable The dd bl memory space is i 64 KB. KB 17 Davide Brunelli 17 Address Space Mapped into a single, contiguous address space: All memory, including RAM, Flash/ROM, information memory, special p function registers g (SFRs), ( ) and pperipheral p registers. g Memory Address 0FFFFh End: Start: 0FFE0h End: 0FFDFh Memory e o y Map: ap: Description Interrupt Vector Table Flash/ROM Start *: End *: Start: End: Start: End *: Start: End: Start: End: Start: End: Start: 0F800h 01100h 010FFh 0107Fh 01000h 0FFFh 0C00h 09FFh 027Fh 0200h 01FFh 0100h 00FFh 0010h 000Fh 0000h Davide Brunelli Information Memory (Flash devices only) Boot Memory (Flash devices only) RAM Access Word/Byte Word/Byte y Word/Byte Word/Byte Word/Byte 16-bit Peripheral modules Word 8-bit Peripheral modules Byte Special Function Registers Byte 18 18 Addressing modes 7 addressing modes for the source operand: 4 addressingg modes for the destination operand: p Register mode; Indexed mode; Symbolic mode; Absolute mode. For the destination operand, two additional addressing modes can be emulated. Davide Brunelli 19 19 Registers and IS 16 general-purpose 16-bit registers (R0 to R15). INSTRUCTION SET (f (for msp430f1612): 430f1612) 51(coreand emulated) INSTRUCTION WITH 3 FORMATAND 7 ADDRESS MODES. 20 Davide Brunelli 20 Internal Registers Program g Counter (PC) Points to the next instruction to be executed Stack Pointer (SP) Store the return addresses of subroutine calls and interrupts p Status Register (SR) Source or destination register Davide Brunelli 21 Interrupt vector table Mapped at the very end of memory space (upper 16 words of Flash/ROM): 0FFE0h - 0FFFEh (4xx devices); Priority of the interrupt vector increases with the word address. Copyright 2009 Texas Instruments All Rights Reserved Davide Brunelli www.msp430.ubi.pt 22 How to Read Datasheets Manufacturers of electronic components provide datasheets containing i i the h specifications ifi i detailing d ili the h part/device /d i characteristics; Datasheets give the electrical characteristics of the device and the pin out functions, pin-out functions but without detailing the internal operation; More complex devices are provided with documents that aid the development of applications, such as: Application notes; User's guides; Designer's guides; Package drawings, etc… Davide Brunelli 23 How to Read Datasheets MSP430 device datasheet: Device has a large number of peripherals; Each input/output p p ppin usuallyy has more than one function;; It has a table with the description of each pin function; Example Pin number 2 = P6.3/A3; Example, P6 3/A3; - Digital Input/Output Port 6 bit 3; - 3rd analogue input. Davide Brunelli 24 How to Read Datasheets MSP430 User’s Guide: Most peripherals are represented by Block Diagrams. Example: p Part of the MSP430F44x clock module block diagram: g Davide Brunelli 25 Clock System One DCO, internal digitally controlled oscillator ill t Generated on-chip RC-type frequency controlled by SW + HW One LF/XT oscillator LF: 32768Hz XT: 450kHz .... 8MHz Second LF/XT2 oscillator Optional XT: 450kHz .... 8MHz Clocks: ACLK auxiliary clock ACLK MCLK main system clock MCLK SMCLK sub b main i system t clock l k Davide Brunelli 26 Basic Clock System Basic Clock Module provides the clocks for the MSP430 devices Davide Brunelli 27 System Clock: details DIVA 2 LFXTCLK /1, /2, /4, /8 OscOff XTS ACLKGEN ACLK Auxiliary Clock SELM DIVM CPUOff High frequency 2 Vcc 0 P2.5 /R /Rosc 0,1 Low power Vcc LF oscillator, XTS=0 Rsel SCG0 1 DCOR DCGenerator DCGEN 2 3 XT oscillator, XTS=1 2 DCO MOD 3 5 /1 /2, /1, /2 /4, /4 /8, /8 off ff MCLK MCLKGEN Main System Clock SELS DIVS SCG1 DCOCLK 2 Digital Controlled Oscillator DCO 0 Modulator MOD 1 DCOMOD SMCLK /1, /2, /4, /8, off + SMCLKGEN Sub-System Clock The DCO-Generator is connected to pin P2.5/Rosc if DCOR control bit is set. The port pin P2.5/Rosc is selected if DCOR control bit is reset (initial state). Davide Brunelli 28 System Clock Internal clock signals: Both MCLK and SMCLK are sourced from DCOCLK at ~1.1 MHz but can be sourced up to 16 MHz; DCO frequency Calibration register Size Address 1 MHz CALBC1_1MHZ CALBC1 1MHZ CALBC0_1MHZ Byte Byte 010FFh 010FEh 8 MHz CALBC1_8MHZ CALBC0_8MHZ Byte Byte 010FDh 010FCh 12 MHz CALBC1_12MHZ CALBC0_12MHZ Byte Byte 010FBh 010FAh 16 MHz CALBC1_16MHZ CALBC0 16MHZ CALBC0_16MHZ Byte B t Byte 010F9h 010F8h Davide Brunelli 29 System Clock Internal clock signals: Electrical characteristics vary over the recommended supply voltage range of between 2.2 V and 3.6 V. Higher DCO frequencies require higher supply voltages. Typical characteristics in active mode supply current for the Davide Brunelli 30 Digital I/O Independently programmable individual I/Os • Up to 6 ports (P1 – P6) • Each has 8 I/O pins • Each pin can be configured as input or output • P1 and P2 pins can be configured to assert an interrupt request Port1 Port2 Port3 … Port6 Function Select Register PxSEL yes yes Interrupt Edge Select Register PxIES yes no Interrupt Enable Register PxIE yes no yes no Direction Register PxDIR yes yes Output Register PxOUT yes yes yes yes Interrupt Flag Register PxIFG Input Register PxIN P1. P2. 7 P3. 6 5 4 3 2 1 0 P4. P5. P6. Davide Brunelli 31 GPIO - Inputs p Avoid floating inputs!!! Use a pull-up/down resistor, GND, or internal programmable logic To Input p Logic g VCC Button 5.6KΩ Button produces either Vcc or Floating input. Adding a pull-down resistor fixes it. Davide Brunelli VCC Button Port Pin 5.6KΩ Some ports have internal programmable resistors 32 GPIO - Outputs p Open-collector Many logic chips, output pins, circuits use open-collector (open-drain) Simple logic-glue, signal bus Wired-OR Wired OR circuits Interface I t f different diff t voltage lt levels. l l I t f Interface between b t 5V CMOS logic l i andd a higher hi h voltage lt Davide Brunelli 33 Davide Brunelli 34 G O GPIO Inside Inputs/Outputs z Each pin is independent Ports (out) and Pins (in) are not the same thing!! z Output section Input section External Memoryy Access Davide Brunelli 35 Interrupts p Main Prog A way to respond to an external event (i.e., flag being set) without polling How it works: H/W senses flag being set Automatically A tomaticall transfers control to s/w s/ that “services” the interrupt When done, H/W returns control to wherever it left off ISR : : : : RETI Advantages: Transparent to user cleaner code μC doesn doesn’tt waste time polling Davide Brunelli 36 Interrupts: details 3 types System reset (Non)-maskable NMI Maskable Interrupt priorities are fixed and defined by the arrangement of modules Davide Brunelli 37 (Non) Maskable Interrupts (Non)-Maskable Sources S An edge on the RST/NMI pin when configured in NMI mode An oscillator fault occurs An access violation to the flash memoryy Are not masked by GIE (General Interrupt Enable), but are enabled by individual interrupt enable bits (NMIIE, OFIE, ACCVIE) Davide Brunelli 38 NMI Interrupt Handler Davide Brunelli 39 Maskable Interrupts Caused by peripherals with interrupt capability Each can be disabled individually by an interrupt enable bit All can be disabled by GIE bit in the status register Davide Brunelli 40 Interrupt acceptance 1)) Any y currentlyy executingg instruction is completed. p 2) The PC, which points to the next instruction, is pushed onto the stack. 3) The SR is pushed onto the stack. 4) The interrupt with the highest priority is selected if multiple interrupts occurred during the last instruction and are pending for service. 5) The interrupt request flag resets automatically on single-source single source flags. flags Multiple source flags remain set for servicing by software. 6) The SR is cleared with the exception of SCG0, which is left unchanged. This terminates any low-power mode. Because the GIE bit is cleared, further interrupts are disabled. 7) The content of the interrupt vector is loaded into the PC: the program continues with Takes 6 cc to execute the interrupt service routine at that address. Davide Brunelli 41 Return from Interrupt RETI - Return from Interrupt Service Routine 1) The SR with all previous settings pops from the stack. All previous settings of GIE, CPUOFF, etc. are now in effect, regardless of the settings used during the interrupt service routine. 2) The PC pops from the stack and begins execution at the point where it was interrupted. Takes 5 cc to execute Davide Brunelli 42 Interrupt Vectors /************************************************************ * Interrupt Vectors (offset from 0xFFE0) / ************************************************************/ #define PORT2_VECTOR 1 * 2 /* 0xFFE2 Port 2 */ #define UART1TX UART1TX_VECTOR VECTOR 2 * 2 /* / 0xFFE4 UART 1 Transmit */ / #define UART1RX_VECTOR 3 * 2 /* 0xFFE6 UART 1 Receive */ #define PORT1_VECTOR 4 * 2 /* 0xFFE8 Port 1 */ #d fi #define TIMERA1_VECTOR TIMERA1 VECTOR 5 * 2 /* 0 0xFFEA FFEA Ti Timer A CC1 CC1-2, 2 TA */ #define TIMERA0_VECTOR 6 * 2 /* 0xFFEC Timer A CC0 */ #define ADC_VECTOR 7 * 2 /* 0xFFEE ADC */ #define UART0TX_VECTOR 8 * 2 /* 0xFFF0 UART 0 Transmit */ #define UART0RX_VECTOR 9 * 2 /* 0xFFF2 UART 0 Receive */ #define WDT_VECTOR 10 * 2 /* 0xFFF4 Watchdog Timer */ #define COMPARATORA_VECTOR 11 * 2 /* 0xFFF6 Comparator A */ #define TIMERB1_VECTOR 12 * 2 /* 0xFFF8 Timer B 1-7 */ #define TIMERB0_VECTOR 13 * 2 /* 0xFFFA Timer B 0 */ #define NMI_VECTOR 14 * 2 /* 0xFFFC Non-maskable */ #define RESET_VECTOR 15 * 2 /* 0xFFFE Reset [Highest Pr.] */ Davide Brunelli 43 Interfaces Several pprotocols for inter-chipp communication UART, I2C, SPI, USB,… Serial communication protocols Meant for short distances “inside the box” Low complexity L cost Low Low speed ( a few Mbps at the fastest ) S i l communication Serial i ti is i employed l d where h it is i nott practical, ti l either in physical or cost terms, to move data in parallel between systems. Davide Brunelli 44 I2C Shorthand for an “Inter-integrated circuit” bus I2C devices include EEPROMs, thermal sensors, and realtime clocks Used as a control interface to signal processing devices that have separate data interfaces, e.g. RF tuners, video decoders and encoders, and audio processors. I2C bus has three speeds: Slow (under 100 Kbps) Fast (400 Kbps) High-speed (3.4 Mbps) – I2C v.2.0 Limited to about 10 feet for moderate speeds Davide Brunelli 45 I2C Bus Configuration 22-wire wire serial bus – Serial data (SDA) and Serial clock (SCL) Half-duplex, synchronous, multi-master bus No chip select or arbitration logic required Lines pulled high via resistors, resistors pulled down via open-drain open drain drivers (wired-AND) Davide Brunelli 46 I2C Features “Clock stretching” – when the slave (receiver) needs more time to process a bit, it can pull SCL low. The master waits until the slave has released SCL before sending the next bit. “General call” broadcast – addresses every device on the bus 10-bit extended addressing for new designs. 7-bit addresses all exhausted Start Direction Data bits Address bits Receiver Ack Stop Davide Brunelli 47 Davide Brunelli 48 Example p I2C bridge SPI Shorthand for “Serial Peripheral Interface” Defined by Motorola on the MC68HCxx line of microcontrollers Generally faster than I2C, C capable of several Mbps Applications: Like I2C, used in EEPROM, Flash, and real time clocks Better suited for “data streams”, i.e. ADC converters Full duplex capability, i.e. communication between a codec and digital signal processor Davide Brunelli 49 SPI Bus Configuration g Synchronous serial data link operating at full duplex Master/slave relationship 2 data signals: MOSI – master data output, slave data input MISO – master data input, slave data output 2 control signals: SCLK – clock /SS – slave l select l t (no ( addressing) dd i ) Davide Brunelli 50 SPI As the register transmits the byte to the slave on the MOSI signal i l line, li the th slave l transfers t f the th contents t t off its it shift register back to the master on the MISO signal line exchanging the contents of the two shift registers line, registers. Davide Brunelli 51 SPI vs. I2C For ppoint-to-point, p , SPI is simple p and efficient Less overhead than I2C due to lack of addressing, plus SPI is full duplex. SPI For multiple slaves, each slave needs separate slave select signal More effort and more hardware than I2C I2C Davide Brunelli 52 UART Shorthand for “Universal Asynchronous ReceiverTransmitter i “ A UART’s UART s transmitter is essentially just a parallel-to-serial parallel to serial converter with extra features. The essence of the UART transmitter is a shift register that is loaded in parallel, and then each bit is sequentially shifted out of the device on each p pulse of the serial clock. One of the problems associated with serial transmission is reconstructing i the h data d at the h receiving i i end. d Difficulties arise in detecting boundaries between bits bits. Davide Brunelli 53 UART Asynchronous serial devices, such as UARTs, do not share a common clock Each device has its own, own local clock. clock The devices must operate at exactly the same frequency. Logic (within the UART) is required to detect the phase of the transmitted data and phase lock the receiver’s clock to this. Bitrate: Bit t 2400, 2400 19200, 19200 57600,115200, 57600 115200 921600… 921600 Davide Brunelli 54 UART The transmission format uses one start bit at the beginning and one or two stop bits end of each character. h t Davide Brunelli 55 RS232C An old standard (1960), originally intended for connecting computer equipment (computers or terminals, referred to as DTE) to communication equipment (DCE). RS232C is are commonly used in conjunction with UART because they share the same protocol RS232 Voltages are +5..+25V for a logic 0, and -5V..-25V for a logic g 1 ((Reverse ppolarity) y) Davide Brunelli 56 USART Block Diagram: g UART mode Davide Brunelli 57 RS 232 Interface Standard RS-232 DB-25 connector is described in the book; let’s take a look at DB-9 Davide Brunelli 58 Implementing p g RS-232C Davide Brunelli 59 ADC conversion Sample and Hold Ve is a mapping R → R : Discretization of time Restriction to digital information processing. Known digital computers can only process discrete time series Sample and hold-devices. Ideally: width of clock pulse → 0 Vx is a sequence of values or a mapping Z → R Davide Brunelli 60 A/D-converters Flash A/D converter Digital computers require digital form of physical values )A/D-conversion; An Analog to Digital Converter (ADC) converts an analog input voltage to a digital number number. Many methods with different speeds. Example: 1. Flash A/D converter: Parallel comparison p with reference voltage Speed: O(1) Hardware complexity: O(n) with n= # of distinguished g voltage levels Davide Brunelli 61 A/D-converters Successive approximation Key idea: binary search: Set MSB MSB='1' 1 if too large: reset MSB Set MSB-1='1' if too t large: l resett MSB-1 MSB 1 Speed: O(ld(n)) Hardware d complexity: l i O(ld(n)) (ld( )) with n= # of distinguished voltage levels; slow, but high accurate Davide Brunelli 62 ADC on MSP430 The ADC12 module supports fast, 12-bit analog-to-digital conversions. Features: • G Greater t th than 200 kksps maximum i conversion rate • Monotonic 12-bit converter with no missingg codes • Sample-and-hold with programmable sampling periods controlled by software or timers • Software selectable on-chip reference voltage generation (1.5 V or 2.5 V) • Interrupt vector register for fast decoding of 18 ADC interrupts • 16 conversion-result storage registers Davide Brunelli 63 Davide Brunelli 64 Timer A Timer_A Timer_A is a 16-bit timer/counter with three capture/compare registers • Capture external signals • • Compare PWM mode SCCI latch for asynchronous communication Timer A 16-bit Timer_A 16 bit Counter 15 0 TACTL Input Select unused 160h rw(0) rw(0) rw(0) rw(0) rw(0) rw(0) rw(0) rw(0) SSEL1 SSEL0 0 0 0 1 1 0 1 1 Input p Divider rw(0) Mode Control rw(0) ID1 ID0 0 0 1 1 0 1 0 1 unTAIE TAIFG used CLR rw(0) rw(0) rw(0) MC1 MC0 0 0 1 1 0 1 0 1 (w)(0) rw(0) rw(0) Stop Mode Up Mode Continuous Mode Up/Down Mode 1/1, Pass 1/2 1/4 1/8 TACLK ACLK MCLK INCLK Davide Brunelli 65 Timer A - Counting Modes Timer_A Stop/Halt Mode UP/DOWN Mode Timer is halted with the next +CLK Timer counts between 0 and CCR0 and 0 0FFFFh UP/DOWN Mode CCR0 0h UP Mode Continuous Mode Timer counts between 0 and CCR0 Timer continuously counts up 0FFFFh Continuous Mode 0FFFFh CCR0 0h 0h Davide Brunelli 66 Timer A – Waveform generator Timer_A UP M Mode d Timer counts between 0 and CCR0 Davide Brunelli 67 Davide Brunelli 68 Comparator A Comparator_A Comparator_A Comparator A is an analog voltage comparator • Supports precision slope analog-to-digital g g conversions • Supply voltage supervision, and • Monitoring of external analog signals. Watchdog Timer General Th primary The i function f ti off the th watchdog-timer t hd ti module d l (WDT) iis tto perform f a controlledt ll d system restart after a software problem occurs. If the selected time interval expires, a system reset is generated. If the watchdog function is not needed in an application, the module can work as an interval timer, to generate an interrupt after the selected time interval. Features of the Watchdog g Timer include: ¾ Eight software-selectable time intervals ¾ Two operating modes: as watchdog or interval timer ¾ Expiration of the time interval in watchdog mode, mode which generates a system reset; or in timer mode, which generates an interrupt request ¾ Safeguards which ensure that writing to the WDT control register is only possible g a password p using ¾ Support of ultralow-power using the hold mode Watchdog/Timer two functions: ¾ SW Watchdog Mode ¾ Interval Timer Mode 69 Davide Brunelli 69 Davide Brunelli 70 Watchdog Timer WDT module performs a controlled system restart after a software ft problem bl occurs • Can serve as an interval timer (generates interrupts) • WDT Control register is password protected • Note: Powers-up active DMA Di t Memory Direct M A Access (DMA) The MSP430 has been designed for applications requiring low power; When the application requires data-handling, the direct memory access (DMA) capability bilit included i l d d in i some devices d i i useful: is f l DMA automaticallyy handles data;; DMA does not require CPU intervention; DMA helps reduce the power consumption (CPU remains sleeping). Davide Brunelli 71 DMA Concept of DMA: move functionality to peripherals: Peripherals use less current than the CPU; Delegating g g control to pperipherals p allows the CPU to shut down ((saves power); “Intelligent” te ge t peripherals pe p e a s are a e more o e capable, capab e, providing p ov d g a better bette opportunity oppo tu ty for o CPU shutoff; DMA can be enabled for repetitive data handling, increasing the throughput of peripheral modules; Minimal software requirements and CPU cycles. Davide Brunelli 72 DMA Block diagram: Davide Brunelli 73 Power as a Design g Constraint Why worry about power? Battery life in portable and mobile platforms Power consumption in desktops, server farms - Cooling costs, packaging costs, reliability, timing - Power density: 30 W/cm2 in Alpha 21364 (3x of typical hot plate) Wh Where d does power go iin CMOS? Dynamic power consumption Power due to shortPower due to circuit current leakage current during transition P = ACV 2f + τAVIshort f + VIleak Davide Brunelli 74 Dynamic y Power Consumption p C – Total capacitance seen by b th the gate’s t ’ outputs t t Function of wire lengths, transistor sizes, ... V – Supply pp y voltage g Trend: has been dropping with each successive fab ACV 2f A - Activity of gates How often on average do wires switch? f – clock frequency Trend: increasing ... Reducing Dynamic Power 1) Reducing V has quadratic effect; Limits? 2) Lower C - shrink structures, shorten wires 3) Reduce switching activity - Turn off unused parts or use design techniques to minimize number of transitions Davide Brunelli 75 Short circuit Power Consumption Short-circuit τAVIshort f Vin Ishort Finite slope of the input signal causes a direct current path b between VDD andd GND ffor a Vout short period of time during switching when both the NMOS CL and PMOS transistors are conducting Reducing Short-circuit 1) Lower the supply voltage V 2) Slope engineering – match the rise/fall time of the input and output signals Davide Brunelli 76 Leakage g Power VIleak Sub-threshold currentt Sub-threshold current ggrows exponentially p y with increases in temperature and decreases in Vt Davide Brunelli 77 How can we reduce power consumption? Dynamic power consumption Reduce the rate of charge/discharge of highly loaded nodes Reduce spurious switching (glitches) Reduce switching in idle states (clock gating) Decrease frequency Decrease voltage (and frequency) Static power Consumption Smaller area (!) Reduce device leakage through power gating Reduce device leakage through body biasing Use higher-threshold transistors when possible Power performance tradeoffs! Davide Brunelli 78 Operating Modes Davide Brunelli 79 C Examples - Operating Modes C – programming i msp430x14x.h 430 14 h /************************ * STATUS REGISTER BITS ************************/ #define C 0x0001 #define Z 0x0002 #define N 0x0004 #define V 0x0100 #define GIE 0x0008 #define CPUOFF 0x0010 #define OSCOFF 0x0020 #define SCG0 0x0040 #define SCG1 0x0080 /* Low Power Modes coded with Bits 4-7 in SR */ /* B Begin i #d #defines fi f for assembler bl */ #ifndef __IAR_SYSTEMS_ICC #define LPM0 CPUOFF #define LPM1 SCG0+CPUOFF #define LPM2 SCG1+CPUOFF #define LPM3 SCG1+SCG0+CPUOFF #define LPM4 SCG1+SCG0+OSCOFF+CPUOFF /* End #defines for assembler */ #else /* Begin #defines for C */ #define LPM0_bits CPUOFF #define LPM1 LPM1_bits bits SCG0+CPUOFF #define LPM2_bits SCG1+CPUOFF #define LPM3_bits SCG1+SCG0+CPUOFF #define LPM4_bits SCG1+SCG0+OSCOFF+CPUOFF … #include "In430.h“ #define LPM0 _BIS_SR(LPM0_bits) #define LPM0_EXIT _BIC_SR(LPM0_bits) #define LPM1 _BIS_SR(LPM1_bits) #define LPM1_EXIT _BIC_SR(LPM1_bits) #define LPM2 _BIS_SR(LPM2_bits) #define LPM2_EXIT _BIC_SR(LPM2_bits) #define LPM3 _BIS_SR(LPM3_bits) #define LPM3_EXIT _BIC_SR(LPM3_bits) #define LPM4 _BIS_SR(LPM4_bits) BIS SR(LPM4 bits) #define LPM4_EXIT _BIC_SR(LPM4_bits) #endif /* End #defines for C */ /*Enter LP Mode 0*/ /*Exit LP Mode 0*/ /*Enter LP Mode 1*/ /*Exit LP Mode 1*/ /*Enter LP Mode 2*/ /*Exit LP Mode 2*/ /*Enter LP Mode 3*/ /*Exit LP Mode 3*/ / /*Enter Enter LP Mode 4*/ 4 / /*Exit LP Mode 4*/ /* - in430.h Intrinsic functions for the MSP430 */ unsigned short _BIS_SR(unsigned short); unsigned short _BIC_SR(unsigned short); Davide Brunelli 80 What we mean by “Low Power” 2 AA Æ 1.5 amp hours (~4 watt hours) Cell Æ 1 amp hour (3.5 watt hours) C ll 500 -1000 Cell: 1000 mW W Æ few f hhours active ti WiFi: 300 - 500 mW Æ several hours GPS: 50 – 100 mW Æ couple days WSN: 50 mW active,, 20 uW passive p 450 uW Æ one year 45 uW Æ ~10 years Ave Power = fact * Pact + fsleep * Psleep + fwaking * Pwaking Davide Brunelli 81 Node Power States Active Active Sleep WakeUP Work Davide Brunelli Sleep WakeUP Work 82 Average power consumption Dynamic power supply current Set of modules that are periodically active Typical situation – real time cycle T Iave = ∫ Icc(t)dt /T In most cases Iave = Σ Ii*ti/T Icc (power supply current) Time T Davide Brunelli 83 Basic Conditions for Burst Mode The ee example a peo of the e heat ea cos cost allocator a oca o sshows o s that a the e cu current e o of the e non-activity o ac y pe periode ode dominates the current consumption. Measure IAVG = IMeasure Process data + ICalculate = IADC* t Measure/T + Iactive * tcalc /T Real-Time Clock LCD Display + IRTC + IDisplay + Iactive * tRTC /T + IDisplay = 3mA *200µs/60s + 0.5mA * 10ms/60s + 0.5mA * 0.5ms/60s + 21µA = 10nA + 83nA + 21µA + 4nA IAVG ≅ 21µA The sleep p current dominates the current consumption! p The currents are related to the sensor and μC system. Additional current consumption of other y p parts should be added for the total system y current system Davide Brunelli 84 Battery Life B Battery C Capacity i BC – [mAh] [ Ah] Battery Life BL = BC / Iave In the previous example, standard 750 mAh batteries will allow battery life of: BL = 750 mAh / 21 μA ≈ 4.2 years !!! Conclusion: Power efficient modes Interrupt I t t driven di system t with ith processor in i idle idl mode d Davide Brunelli 85 Minimizingg power p in SW: Basics • System clock to maximize the time in LPM3 (LPM3 power consumption is less than 2 µA typical with both a real-time real time clock function and all interrupts active) • 32-kHz watch crystal for ACLK; CPU clocked from the DCO • Interrupts to wake the processor and control program flow • Peripherals P i h l should h ld be b switched i h d on only l when h needed d d • Use low-power integrated peripheral modules in place of software driven functions. (i.e. example Timer_A and Timer_B can automatically generate PWM and capture external timing, with no CPU resources) • Branching and fast table look-ups in place of flag polling and long software calculations • Avoid frequent subroutine and function calls due to overhead Davide Brunelli 86 Programming g g a Microcontroller Davide Brunelli 87 Projecting j g flow Design Decisions Davide Brunelli How to read inputs? How often to read inputs? p Which order to read the inputs? How to compute p responses? How to generate the responses? How often to generate? 88 MSP430 programming IAR Embedded Workbench Integrated tools in this IDE are: Compiler C il IAR MSP430 C/C++; C/C Assembler IAR MSP430; IAR XLINK Linker™; The IAR XAR Library Builder™; Text editor; Project management; Command lines utility; IAR C-SPY™ debugger. Gives the user: A highly efficient IDE; Functional workspace methodology; Reduced development time. Copyright 2009 Texas Instruments All Rights Reserved Davide Brunelli 89 89 eZ430-F2013 eZ430 F2013 Development Tool Complete development tool that fits in your pocket Supports S t MSP430F20xx MSP430F20 devices d i only l MSP430F20xx devices available in DIP Unrestricted programming and debugging Fast, Fast easy to use operation Includes IAR Kickstart IDE Supported by CCE V2 Davide Brunelli 90 EZ430 RF2500 EZ430-RF2500 USB-based MSP430 wireless development tool to evaluate the MSP430F2274 microcontroller i ll andd CC2500 2.4-GHz 2 4 GH wireless i l transceiver; Able Abl tto remotely t l send d and d receive i ddata t ffrom a PC using i the th MSP430 Application UART. Copyright 2009 Texas Instruments All Rights Reserved Davide Brunelli www.msp430.ubi.pt 91 91 EZ430-RF2500 Device features and integrated peripherals: 16 MIPS performance; 16-MIPS f 200-kbps 10-bit SAR ADC; Two built-in Op-Amps; Watchdogg timer,, 16-bit Timer_A3 and Timer_B3;; USCI module supporting UART/LIN, (2) SPI, I2C, or IrDA; 5 low-power low power modes (700 nA in standby); 2.4-GHz radio-frequency (RF) transceiver; Programmable data rate up to 500 kbps; Low current consumption. Copyright 2009 Texas Instruments All Rights Reserved Davide Brunelli www.msp430.ubi.pt 92 92 USB Flash Emulation Tool (FET) MSP430 FET: real-time debug and programming tool Supports ALL MSP430 devices 44-wire wire JTAG 2-wire Spy Bi-Wire Available A il bl with ith socketed k t d target t t board b d Example: MSP-FET430U14 = FET Interface + 14-pin target board Supported by all MSP430 IDEs Davide Brunelli 93 Embedded Emulation Real-time in-system debug No application resources used Full speed execution H/W breakpoints Single g stepping pp g Complex triggering Trace capability Easy to use tools l Spy Bi-Wire 2-wire debug interface No pin function impact JTAG Davide Brunelli 94 Downloading Code The MSP430 uses internal flash memory for program storage. This can be programmed (reprogrammed) in-circuit. The MSP430 processors are programmed via a JTAG port on the chip . The pins TDI, TDO, TMS, TCLK and RST of JTAG interface are used for programming and testing ends. 95 Davide Brunelli 95 Data Representation 2-complement ! Davide Brunelli 96 Instruction Set • 27 core instructions and 24 emulated instructions • 3 core core-instruction instruction formats: (i) Dual-operand, Dual operand (ii) Single Singleoperand, (iii) Jump Davide Brunelli 97 Code structuring Typical T i l structure t t off a simple i l embedded b dd d Software S ft Initialize devices… (UART, SPI, TIMER, etc…) [Clear registers, g read values from f Eeprom] p … loop inputs/sensors; p response; p compute generate actuator outputs read Forever Davide Brunelli 98 System Reset / Initialization Init Cond After System Reset Software Initialization After a POR, the initial MSP430 conditions are: After a system reset initialize for application requirements: • RST/NMI pin in the reset mode • Initialize t a e the t e SP S to top of o the t e • I/O pins in input mode RAM • peripheral modules/registers as default • Initialize watchdog • Status register (SR) is reset. reset • Configure peripheral modules • Watchdog timer powers up in wd mode • Program counter (PC) loaded with address contained at reset vector location (0FFFEh). CPU execution begins at that address. Davide Brunelli 99 Which programming language…? Generally a high-level language like C will be the language of choice. choice developing software is much easier your code d is i also l portable t bl between b t different diff t target t t machines. So why use assembly? Davide Brunelli 100 Why use assembly? Assembly and machine code, because they are “hand-written”, can be finely tuned to get the most performance out of the processor and computer hardware. This can be particularly important when dealing with time-critical operations with I/O devices. Coding directly in assembly can often (but not always) result in a smaller code space. The drawback is that the software is harder to maintain and has zero portability to other processors. Davide Brunelli 101 Syntax - General Each line of a program is one of the following: an instruction an assember directive (or pseudo-op) a comment Whitespace and case (between symbols) are ignored. Comments (beginning with “;”) ; ) are also ignored. ignored An instruction has the following format: LABEL OPCODE OPERANDS ; COMMENTS optional mandatory Davide Brunelli 102 Syntax - Opcodes and Operands Opcodes O d reserved symbols that correspond to LC-3 instructions - ex: ADD, AND, LD,… Operands registers -- specified by Rn, where n is the register number numbers -- indicated by # (decimal) or x (hex) label -- symbolic name of memory location separated by comma number, order, and type correspond to instruction format - ex: Davide Brunelli 103 Syntax – Label and Comment Label placed at the beginning of the line assigns g a symbolic y name to the address corresponding to line Comment anything after a semicolon is a comment ignored by assembler used by humans to p g document/understand programs tips for useful comments: - avoid restating the obvious, as “decrement R1” - provide additional insight insight, as in “accumulate accumulate product in R6” R6 - use comments to separate pieces of program Step 3: Planning project and write code Davide Brunelli 104 How to organize the code 1 Header 1. H d 1. Include 1. Register 1 Interrupt 1. Davide Brunelli 105 C - Programming Issues C programming language: C is an algorithmic language; C was developed for operating systems; It is based on expressions; An expression can be the result of an operation or a function; The program flow Th fl control t l is i achieved hi d using i a sett off appropriate i t structures t t that enable the choice, based on a logic operation, of the sequence of operations to be performed by the CPU; These structures allow cyclic execution of expressions that compose a block g of pprogram. Davide Brunelli 106 Programming Issues Declaration of variables: Must always be made at the beginning of a program; Global G ob vvariables: b es: Accessible ccess b e throughout oug ou thee code; Local variables: declared within one function and are only accessible during the execution of this function; If a variable is declared within a program block, it is only accessible while the flow of the program is underway within the block. block Davide Brunelli 107 Programming Issues Identifiers names: const: - extern: - Used to declare a constant (content is not changed in the course of code implementation); Stored in program section memory. Used to make reference to variables declared elsewhere, for example in another module. register: - Used to store a variable in a processor’s register; Promotes faster access to the contents of the variable; Only used locally and depends on the register’s availability. Davide Brunelli 108 Programming Issues Identifiers names: static: - Function declared within a function or a program block; Resources occupied are released, and with them their contents; Preserves the variable even after a function or block has been executed. volatile: - Used if an event outside the program can change the content of a variable, for example an ADC; A statement using this descriptor informs the compiler that this variable should not be optimized. Davide Brunelli 109 Style Guidelines Use the following style guidelines to improve the readability and understandability of your programs : Provide a program header, with author’s name, date, etc., and purpose of program program. Start labels, opcode, operands, and comments in same column for each line. (Unless entire line is a comment.) Use comments to explain what each register does. Give explanatory comment for most instructions. Use U meaningful i f l symbolic b li names. - Mixed upper and lower case for readability. - ASCIItoBinary, InputRoutine, SaveR1 Provide comments between program sections. Each line must fit on the page -- no wraparound or truncations. - Long statements split in aesthetically pleasing manner. Davide Brunelli 110 Directives The Assembler supports a number of directives. directives The directives are not translated directly into opcodes. Instead, they are used to adjust the location of the program in memory, define macros, etc. Ex: Directive Description Example DEF Define a symbolic name on a register EQU Set a symbol equal to an expression INCLUDE Read source from another file Davide Brunelli 111 Macros Macro: Macros are very useful for doing something that is done often but for which a procedure can’t be use. Macros are substituted when the program is compiled to the code which they contain. ex: Step 3: Planning project and write code Davide Brunelli 112 Subroutines In co contrary a y too macros ac os a subroutine sub ou e does save program p og a sstorage o age space. The respective sequence is only once stored in the code and is called from whatever part of the code. To ensure continued execution of the sequence following the subroutine call you need to return to the caller. Name op #Clocks Ex. Ex For a delay of 10 cycles you need rcall 3 to write this subroutine: Nop 1 ret 4 Subroutines always start with a label, otherwise you would not be able to jump to it, here Delay10:. Three NOPs follow and a RET instruction. If you count the necessary cycles you just find 7 cycles (3 for the NOPs, 4 for the RET). The missing 3 are for calling that routine…: [...] [ ] somewhere in the source code: Davide Brunelli 113 Davide Brunelli 114 Subroutines Interrupts Interrupts p ((also known as traps p in some pprocessors)) are a technique q of diverting the processor from the execution of the current program so that it may deal with some event that has occurred. When Wh an interrupt i t t occurs, the th processor saves its it state t t by b pushing hi its it registers and program counter onto the stack. Thee processor p ocesso then t e loads oads an a interrupt te upt vecto vector into to the t e program p og a counter. cou te . The interrupt vector is the address at which an interrupt service routine (ISR) lies. The last instruction of an ISR is always a Return from Interrupt (reti) instruction. This causes the processor to reload its saved state (registers and program counter) from the stack and resume its original program. Interrupts are largely transparent to the original program. This means that the original program is completely “unaware” that the processor was interrupted, i t t d save for f a lost l t interval i t l off time. ti Davide Brunelli 115 Interrupts: an example Step 3: Planning project and write code Davide Brunelli 116 www ti com/msp430 www.ti.com/msp430 Davide Brunelli 117 Important Documents Datasheets Technical Documents for every device User U G Guide id How to use MSP430 guide Divided into families - 1xx - 2xx - 4xx Code Example Code examples by family products. Application Notes S Sample l applications li ti on interfacing i t f i an MSP430 Use it! Davide Brunelli 118 Tools Link • www.ti.com/msp430 www ti com/msp430 • www.ti.com/ez430 • www.sparkfun.com kf Davide Brunelli 119