Vous êtes sur la page 1sur 105

Microcontrollers Training

IBS 2011

IBS Timisoara
1 2011 Viorel Deparateanu/ Continental AG, All rights reserved

References & Bibliography


(ref1) 78K0R User's manual: R01UH0007EJ0500_78K0RFX3.pdf (ref2) - MPC5607B Microcontroller Reference Manual: MPC5607BRM_Rev7.1_cut2.pdf O'Reilly Programming embedded systems in C and C++

Byte Craft Limited - First step with embedded systems


I BS SWP documentation

IBS Timisoara
2 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Agenda
Microcontrollers Training

1. 2 3 4 5 6. 7. 8 9

Introduction (Embedded systems, Microcontrollers general view) Software in Embedded Systems Design considerations CPU Memory (incl DMA) OS+Interrupts Timers (incl pwm) IO COM

10

Other sw considerations

IBS Timisoara
3 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Embedded systems


An embedded system is a computer system (hw / sw / md) designed to do one or a few dedicated and/or specific functions often with real-time computing constraints.

The design of an embedded system is influenced by technical constraints (this requires advanced components), and on the other side by cost constraints. The compromise should lead to minimal characteristics of components that still respect the specifications => limited resources.

Aspects to ve considered during Embedded Systems Development: -Reliability -Efficiency -Cost

IBS Timisoara
4 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


A microcontroller (C, uC or MCU) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. Platform the device on which the finished program will be run.

Focus on: - Renesas 78K0R - Freescale MPC 5607

IBS Timisoara
5 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


-1971: First microprocessor: Intel 4004
4 bit CPU, 740 khz

-1972: Intel 8008


8 bit CPU, 16 k Memory, clock max 800 khz

-1971-1974: First microcontroller: TI TMS1000


4bit CPU, 1kB address space, clock 300khz, 32 B RAM

-1977: Intel 8048


8bit CPU, 2kB ROM, 128 B RAM, 27 I/O ports clock max 11Mhz, but15 internal phases => 0.73 MIPS

- 1980: Intel 8051


8bit CPU, 64 k address space, 4kB ROM, 128 B RAM, 32 I/O ports, UART, 2 timers clock max 12Mhz, 12 machine cycles => 1 MIPS, 2 level interrupts, power saving.

- 1993: Microchip PIC16C84 using EEPROM - 1993 first microcontroller with flash (from ATMEL, based on 8051 core)

IBS Timisoara
6 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


Microcontroller architecture von Neumann architecture: instructions and data use the same bus system

Harvard architecture: separate storage and signal pathways for instructions and data

IBS Timisoara
7 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


Microcontroller architecture Modified Harvard architecture: it relaxes the strict separation between instruction and data while still letting the CPU concurrently access two (or more) memory buses. The most common modification includes separate instruction and data caches backed by a common address space. While the CPU executes from cache, it acts as a pure Harvard machine. When accessing backing memory, it acts like a von Neumann machine (where code can be moved around like data, a powerful technique).

IBS Timisoara
8 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


Internal view

Intel 8742 - die

IBS Timisoara
9 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


Internal view 16F84 - die

IBS Timisoara
10 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers General View


Package Package technology: - PTH (pin through hole) - SMT (Surface Mounted Technology)

PTH Package types - DIP ( or DIL:Dual In Line):

SMT

- QIL (Quad In Line)


PQFP: Plastic Quad Flat-Pack

- GA (grid array)
BGA: Ball Grid Array

IBS Timisoara
11 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers uC in I BS

Autosar
FS MPC551x

MPC564x FS MPC560x

NEC 78K0R

NEC 78K0 Fx2

SWP HE/LE
NEC V850 Fx2 / Cargate + NEC V850 Venus

NEC V850 Fx3 Freescale S12XE

Motorola 68HCS12

BSW

SGS Thomson ST7 Motorola 68HC08 Infineon C164

1997
IBS Timisoara
12 2011 Viorel Deparateanu/ Continental AG, All rights reserved

2000

2003

2006

2009

2012

Introduction Microcontrollers Main Features


A micro-controller is a single integrated circuit, commonly with the following features:

CPU (central processing unit) ranging from small and simple 4-bit processors to complex 32- or 64-bit processors Memory: RAM - volatile memory for data storage ROM, EPROM, EEPROM or Flash memory for program and operating parameter storage

DMA (Direct Memory Access Controller)


clock generator - often an oscillator for a quartz timing crystal, resonator or RC circuit in-circuit programming and debugging support Power management functions

Interrupts: Microcontrollers must provide real time (predictable, though not necessarily fast) response to events in the embedded system they are controlling. When certain events occur, an interrupt system can signal the processor to suspend processing the current instruction sequence and to begin an interrupt service routine (ISR, or "interrupt handler"). The ISR will perform any processing required based on the source of the interrupt before returning to the original instruction sequence.

IBS Timisoara
13 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Introduction Microcontrollers Main Features


GPIO (General Purpose Inputs / Outputs): discrete input and output bits, allowing control or detection of the logic state of an individual package pin ADC/DAC (analog to digital, digital to analog convertors): ADC is often used, some includes also DAC converters Timers. Programmable Interval Timer (PIT). A PIT may either count down from some value to zero, or up to the capacity of the count register, overflowing to zero. Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting. Time Processing Unit (TPU) is a sophisticated timer. In addition to counting down, the TPU can detect input events, generate output events, and perform other useful operations. Watchdog: timer used to detect software abnormal behavior PWM: Pulse Width Modulation UART: Universal Asynchronous Receiver/Transmitter block makes it possible to receive and transmit data over a serial line with very little load on the CPU. Dedicated on-chip hardware also often includes capabilities to communicate with other devices (chips) in digital formats such as I2C and Serial Peripheral Interface (SPI). Other communication channels: LIN, CAN, FlexRay, Ethernet

IBS Timisoara
14 2011 Viorel Deparateanu/ Continental AG, All rights reserved

78K0R General View

IBS Timisoara
15 2011 Viorel Deparateanu/ Continental AG, All rights reserved

78K0R General View


78K0R 100pin case datasheet, p31 78k0R 100pin internal structure datasheet, p39 78K0R functions datasheet, p48

IBS Timisoara
16 2011 Viorel Deparateanu/ Continental AG, All rights reserved

MPC560x general view


32-bit CPU core complex (e200z0h) CPU clock: up to 64 MHz Enhanced instruction set allowing variable length

encoding (VLE)
Up to 1.5 MB on-chip code flash memory 64 (4 16) KB on-chip data flash memory with ECC Up to 96 KB on-chip SRAM 16-channel eDMA controller 2 ADC: one 10-bit and one12-bit Up to 6 enhanced full CAN Up to 10 serial communication interface Up to 149 configurable general purpose pins up to 8 PIT , 32 bit counter package: 100/144/176 LQFP or 208 BGA The internal logic operates from 1.2 V (nominal) supplies that are supplied by the on-chip voltage regulator from a 5 V or 3.3 V supply.

IBS Timisoara
17 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


- Machine code - Assembler - C: is a "low-level" high level language - Instruction sets: - CISC: (Complex Instruction Set Computer) One complex instruction encapsulates several simple instructions - RISC

- C++, Linux
- MoBaDe

IBS Timisoara
18 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Kernighan and Ritchie, The C Programming Language: C is a relatively ``low-level'' language. This characterization is not pejorative; it simply means that C deals with the same sort of objects that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines. C provides no operations to deal directly with composite objects such as character strings, sets, lists or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is no heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions. Similarly, C offers only straightforward, single-thread control flow: tests, loops, grouping, and subprograms, but not multiprogramming, parallel operations, synchronization, or coroutines.

Although the absence of some of these features may seem like a grave deficiency, (You mean I have to call a function to compare two character strings?), keeping the language down to modest size has real benefits. Since C is relatively small, it can be described in small space, and learned quickly. A programmer can reasonably expect to know and understand and indeed regularly use the entire language.

IBS Timisoara
19 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Compilers translate high level programming language instructions into machine language (object files) These three components are: 1) Preprocessor 2) Compiler 3) Linker Preprocessor: The preprocessor goes through a program and prepares it to be read by the compiler (defines, includes, pragma). Identifiers (variables) in memory: the compiler allocates memory for all identifiers. As the compiler reads a program, it records all identifier names in a symbol table. The compiler uses the symbol table internally as a reference to keep track of the identifiers: their name, type and the location in memory which they represent. When the compiler finishes translating a program into machine language, it will have replaced all the identifier names used in the program with instructions that refer to the memory addresses associated with these identifiers.

IBS Timisoara
20 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


- Objects: starts with a header that described the sections that follow. Each section contains blocks of code or data. Symbol table: names and locations of all variables and functions. Sections: text (code), data (init global variables), bss (uninit global variables).Some of the symbols are unresolved (to be resolved by linker). - Linker: combines the object files to resolve the unresolved symbols. Relocatable: program without allocation of memory addresses. - Locating: the locator uses the information provided (through config ) to assign physical memory addresses to code and data sections.

C
Compiler

C
Compiler

Assembly
Assambler

Object

Object

Object

Linker

Relocatable
Locator

Executable

IBS Timisoara
21 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Libraries: Technically, a library in C is simply a collection of C functions. Libraries usually contain functions which serve a common purpose,

IBS Timisoara
22 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Hardware and software initialization: 1) reset code 2) Hardware initialization

3) startup code

IBS Timisoara
23 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Emulators / Simulators. OCD (On chip debugger , debug monitor) An OCD emulator can be used to download, execute, and debug embedded software over a serial port (usb / network connection) between the host and target. Active Emulators (ICE) It is itself an embedded system, with its own copy of the target processor, RAM, ROM, and its own embedded software. With it it is possible to monitor and control the state of the processor in real time. Other features: hw breakpoints, trace, profiling. Simulators A simulator is a computer program that simulates the functionality and instruction set of the target processor. Using a simulator you can step through your code while the program is running. You can change parts of your code in order to experiment with different solutions to a programming problem. Simulators do not support real interrupts or devices.

IBS Timisoara
24 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems

IBS Timisoara
25 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems Debuggers 78K0R


To use OCD on 78K0R (MInicube2) there are areas in memory reserved for placing the debug monitor program. When using the on-chip debug function, these spaces must be secured so as not to be used by the user program. Moreover, this area must not be rewritten by the user program. Details (ref1) p1189

IBS Timisoara
26 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software in embedded systems


Programming Environment Language: - assembly language,

- high-level programming languages (C)


- Others

IDE: Eclipse, Codewrite, CodeWarrior, Embedded Workbench

Compilers / interpreters

Simulators / Emulators : OCE / ICE

IBS Timisoara
27 2011 Viorel Deparateanu/ Continental AG, All rights reserved

System design
The embedded design process follows the next steps: - Product / functional requirement definition: defines what the product has to do. - processor selection

- Hardware / software specifications


- System evaluation - Hardware design - Software design - Integration - Verification (test)

IBS Timisoara
28 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Processor selection
Following items must be considered: - Number of IO pins - Interfaces required (PWM, Uart, CAN,)

- Memory requirements (RAM, ROM/Flash, EEPROM)


- Real-Time consideration - Processing speed - development environment

IBS Timisoara
29 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Hardware design
Reset circuit to assure that the microcontroller runs only during valid environmental conditions. A microcontroller requires an timebase (from internal / external oscillator), using either: - quartz (freq accuracy 0.1%) / ceramic rezonator (0.5%)

- RC (5-10%)
- external clock

Instruction cycle is not the same as a clock cycle.

IBS Timisoara
30 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Clock setting 78K0R


Types: - Main system clock external - 2 to 20 MHz, connecting external respnator on X1/ X2 - internal high speed - 4 or 8 MHz. This is used after reset.

- PLL clock: main system clock multiplied by 1, 6, or 8 (see ref1 p327)


- Subclock (external) - Internal low speed 30kHz

There are few registers used to configure and the clock (details ref1 p 328) Clock supply to the peripherals that are not used is also stopped so as to decrease the power consumption and noise (according to reg PER0 and PER1). Clock monitor: hw block used to check the main system clock and PLL. It generates a reset if the main system clock stops. The prescaler divides the main system clock and internal low-speed oscillation clock. Crystal /ceramic oscillator

IBS Timisoara
31 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Clock setting Bolero


Types: - System clock: - External oscillator

- FMPLL (Frequency modulated phase-locked loop)


- 16MHz fast internal RC oscillator (default clock source out of reset, back-up clock in the event of FMPLL or external oscillator clock failure, independent clock source for the watchdog timer) - low power oscillators

- 128kHz slow internal RC oscillator (SIRC for low power mode and self wakeup)
- 32 khz slow external oscillator

Loss of clock detection can be done with a Clock Monitor Unit

IBS Timisoara
32 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Software design
Software architecture: - single polling loop (idle loop) - state machine (the sw is in one state at a time)

- Multiple State Machines / Polling Loop (states for each process)


- Incremental State Machine

Code formats: - Machine code - Assembly - high level (C)

IBS Timisoara
33 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Debugging
Debugger: monitor program Emulator Debug functions: trace, profiling, memory dumps

78KoR: Renesas Minicube 2, Renesas IECube (ICE), iSystem JTAG, iSystem ICE Bolero: iSystem JTAG, Nexus (supported on 208 BGA package), ICE C

IBS Timisoara
34 2011 Viorel Deparateanu/ Continental AG, All rights reserved

RTOS
A task is a piece of the software that can be separated from and run independently of the rest. A set of embedded software requirements can usually be decomposed into a small number of such independent pieces. Considering tasks as isolated pieces reduces the complexity of a system. A RTOS manages the processes (tasks/ interrupts/ events) iso that they can run in a pseudoparallel manner. The OS is responsible for deciding which task gets to use the processor at a particular moment, and maintains information about the state of each task (tasks's context). The context records the state of the main registers just before another task is taking control. The OS maintains some information about each taskin a Task Control Block. Task states: suspended / ready / running. There will never be more (or less) than one task in the running state at any time! Scheduler - the part of the operating system that decides which task to run-can promote a task to the running state.

- Preemptive scheduling: a task runs until it is finished or until a task with higher priority preempts it.

Task stack

IBS Timisoara
35 2011 Viorel Deparateanu/ Continental AG, All rights reserved

scheduling algorithms: Basic scheduling algorithms: first-in-first-out, shortest job first, round robin. first-in-first-out scheduling: each task runs until it is finished, and only after that the next task is started

Shortest job first : the only difference is that each time the running task completes or suspends itself, the next task selected is the one that will require the least amount of processor time to complete.
Round robin is the only scheduling algorithm of the three in which the running task can be preempted, that is, interrupted while it is running. In this case, each task runs for some predetermined amount of time. After that time interval has elapsed, the running task is preempted by the operating system and the next task in line gets its chance to run. The preempted task doesn't get to run again until all of the other tasks have had their chances in that round.

RTOS utilize a priority-based scheduling algorithm that supports preemption. Scheduling points: os events when the scheduler function is called. Scheduling points: task creation, task deletion, clock tick (OS tick). Idle task is executed if no other tasks are in the ready state.

IBS Timisoara
36 2011 Viorel Deparateanu/ Continental AG, All rights reserved

The tasks should not disable interrupts, but sometimes other mechanisms might be needed to share resources (e.g.: semaphores, mutex) Probllems with OSs: (in regards to resources usage):

- deadlock: can occur whenever there is a circular dependency between tasks and resources
Priority inversion occurs whenever a higher-priority task is blocked, waiting for a resource that is held by a lower-priority task.

IBS Timisoara
37 2011 Viorel Deparateanu/ Continental AG, All rights reserved

OSEK, AR

IBS Timisoara
38 2011 Viorel Deparateanu/ Continental AG, All rights reserved

CPU
A CPU executes a sequence of stored instructions called a program. A program is represented by a series of numbers in memory. Instruction cycle: fetch, decode, execute, and store (writeback).

Fetch: involves retrieving an instruction from program memory.


The location in program memory is determined by PC (program counter). After an instruction is fetched, the PC is incremented by the length of the instruction word in terms of memory units. Often, the instruction to be fetched must be retrieved from relatively slow memory, causing the CPU to stall while waiting for the instruction to be returned. This issue is largely addressed in modern processors by caches and pipeline architectures. In the decode step, the instruction is broken up into parts that have significance to other portions of the CPU. Execute: various portions of the CPU are connected so they can perform the desired operation. After the execution of the instruction and store the resulting data, the entire process repeats.

If the completed instruction was a jump, the PC will be modified to contain the address of the instruction that was jumped to, and program execution continues normally.

IBS Timisoara
39 2011 Viorel Deparateanu/ Continental AG, All rights reserved

CPU
ALU (arithmetic logic unit) is responsible for performing calculations and executing instructions Registers are used to store the state of the CPU, to reflect results from the instruction just executed, to control the options available on the device, or to enable access to certain areas of memory.

IBS Timisoara
40 2011 Viorel Deparateanu/ Continental AG, All rights reserved

CPU 78K0R

IBS Timisoara
41 2011 Viorel Deparateanu/ Continental AG, All rights reserved

CPU - Bolero
Core: e200z0h (details ref2 p283) 32-bit Power Architecture CPU, 32 bit GPRs Variable length encoding (VLE), allowing mixed 16-bit and 32-bit instructions

Results in efficient code size footprint


Minimizes impact on performance Branch processing acceleration using lookahead instruction buffer Separate instruction bus and load/store bus Harvard architecture The e200z0h processors integrate an integer execution unit, branch control unit, instruction fetch and load/store units, and a multi-ported register file capable of sustaining three read and two write operations per clock. Most integer instructions execute in a single clock cycle. Branch target prefetching is performed by the branch unit to allow single-cycle branches in some cases. 4-stage pipelined in-order execution: 1) Instruction Fetch 2) Instruction Decode/Register file Read/Effective Address Calculation 3) Execute/Memory Access 4) Register Writeback

IBS Timisoara
42 2011 Viorel Deparateanu/ Continental AG, All rights reserved

CPU - Bolero
Main registers: see ref2 p289

IBS Timisoara
43 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts
is an input to microcontroller that redirects the program flow. It is used to increase the response speed to external events. Operations at interruption:

- save context on stack (the current program counter, stack pointer, register contents)
- get the interrupt vector - branch to a predetermined address (ISR) - run ISR

- retrieve the return address and context from stack


- resume execution Interrupt priority: when nested interrupts are enabled, an IST could be interrupted by a higher priority device. Could be external (Inputs, could be level and edge sensitive) or internal (timers, dma, uart,)

Interrupt could be enabled or disabled , or could be maskable and non-maskable (NMI)

IBS Timisoara
44 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts
a mapping must exist between interrupts and ISRs. This mapping usually takes the form of an interrupt vector table. The vector table is usually just an array of pointers to functions, located at some known memory address. It is important to initialize the interrupt vector table correctly - (If it is done incorrectly, the ISR might be executed in response to the wrong interrupt or never executed at all. It is helpful to use the interrupt map. When the processor acknowledges an interrupt synchronously, it finishes executing the current instruction and, before it performs a fetch for the next instruction, it services the interrupt. Servicing Interrupts could be done in two ways:

- Vectored arbitration system: an area in the memory is reserved for interrupt vectors. Each interrupt vector contains the address of that interrupts service routine. When the compiler allocates program memory for interrupt handlers, it places the appropriate address for the handler in the appropriate interrupt vector.
- Non vectored priority system: when an interrupt occurs, the PC branches to a specific address. At this address the interrupts must be checked sequentially to determine which one has caused the interrupt. This scheme can be very slow and there can be a large delay between the time the interrupt occurs and the time it is serviced.

IBS Timisoara
45 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts
Specific Interrupts: - Reset: The reset vector contains the address of the first instruction that will be executed by the CPU. The contents of volatile memory, typically data memory, can remain intact. A RESET can occur because of a manual reset, a WDT time out, low voltage, initial power on, or an attempt to execute an instruction from an illegal address. - Software Interrupt / Trap: Some chips that support interrupts provide an instruction in the instruction set which the programmer can use to halt program execution. This instruction name is different for different devices. - IRQ: pins or ports on the chip which generate an interrupt when they are sent a signal. -- Timer: A TIMER interrupt occurs when a timer overflow is detected

IBS Timisoara
46 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts
When to use interrupts: see p136 - to generate a regular, repeatable event (timer interrupt) - peripherals to be served immediately (e.g. uart)

Critical section: part of a program that must be executed atomically => interrupts are disabled at the beginning of the section, and enabled at the end. It might be useful for the protection of shared resources (global variables, memory buffers, or device registers that are accessed by multiple tasks). The tasks should not disable interrupts.

IBS Timisoara
47 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts
Do's and Dont's: - shared memory or I/O trap. ex pag129, poate gasesc mai bun

Could be solved by disable/ enable interrupts


- race condition: appears when a process tries to use data before data is available. - multiple reads: see pag 133

IBS Timisoara
48 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts 78K0R
Types: - maskable interrupts: external (up to 12) / internal (up to 49), divided into 4 priority groups - software interrupts: vectored interrupt generated by executing the BRK instruction

Interrupt sources: see ref1 p1050


Main registers: - interrupt request flag - interrupt mask flag - priority - used to enable/disable the corresponding maskable interrupt servicing - 2 bits, 0 highest prio, 3 lowest prio

- external interrupt rising/ falling edge - external interrupt pin selection - program status word (PSW) - config for IE (interrupts enable) and priorities

The interrupt request flags are set to 1 when the corresponding interrupt request is generated or an instruction is executed. When an interrupt is acknowledged, the interrupt request flag is automatically cleared and then the interrupt routine is entered.

IBS Timisoara
49 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts 78K0R
Multiple interrupt servicing: occurs when another interrupt request is acknowledged during execution of an interrupt. For this IE should be set during interrupt servicing, and priority level is also important.

Multiple interrupt servicing occurs twice

Multiple interrupt servicing does not occur due to priority control

IBS Timisoara
50 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Interrupts Bolero
Bolero provides priority-based preemptive scheduling of interrupt service requests (ISRs). Details: ref2 p345 9-bit vector for each of the 231 separate interrupt sources 8 software triggerable interrupt sources

16 priority levels with fixed hardware arbitration within priority levels for each interrupt source
Interrupt sources: see ref2 p346 2 operation modes, depending on the value of the HVEN register - software vector mode: common interrupt, software must read a register (INC_IACKR) to obtain the vector associated with the interrupt request. Reading the INTC_IACKR negates the interrupt request - hardware vector mode: specific interrupts for the specified sources registers: see ref2 p349

IBS Timisoara
51 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Peripherals
Control and status registers Usually these registers are memory mapped, and can be made to look just like ordinary variables. To access the value, it is declared as pointer to the register:

volatile unsigned short * pP2LTCH = (unsigned short *) 0x7205E;


Usage: void toggleLed(void) { *pP2LTCH ^= LED_GREEN; /* Read, xor, and modify. */ } /* toggleLed() */

The keyword volatile should be used when declaring pointers to device registers, to avoid compile optimizations.

IBS Timisoara
52 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Peripherals
Communication with the peripherals There are two basic communication techniques: polling and interrupts. Polling:

do
{ // Anything ... // Poll to see if we're there yet. status = areWeThereYet(); } while (status == NO); Interrupts: the processor issues commands to the peripheral exactly as before, but then waits for an interrupt to signal completion of the assigned work. the use of interrupts generally decreases the complexity of one's overall code by giving it a better structure.

IBS Timisoara
53 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Peripherals
Device drivers The purpose of the device driver is to hide the hardware. device driver module to be the only piece of software in the entire system that reads or writes that particular device's control and status registers directly.

IBS Timisoara
54 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory - General
Types: RAM: DRAM, SRAM ROM: Mask, EPROM, PROM

Hybrid: NVRAM, EEPROM, Flash

ROM (read only memory) is non-volatile memory used for program information and permanent data. RAM (random access memory) volatile,

Methods to verify data: Checksum: used to check if the data or program stored in a memory is still valid.CRC. Stack: A stack is a LIFO structure which records the chronological ordering of information. It is used mainly in subroutine calls and interrupt servicing. The stack pointer contains the address of the next free location on the stack.

IBS Timisoara
55 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory
Flash Memory - The primary function of the flash memory module is to serve as electrically programmable and erasable nonvolatile memory.

- may be used for instruction and/or data storage.


The module is a nonvolatile solid-state silicon memory device consisting of: - Physically separate units (arrays) of blocks (also called sectors) of single transistor storage elements - An electrical means for selectively adding (programming) and removing (erasing) charge from these elements

- A means of selectively sensing (reading) the charge stored in these elements


Using the Flash memory: Reading is easy, as any memory (provide the address, and the memory returns the data stored at that location). Writing is more difficult, as:

- each memory location must be erased before it can be rewritten. If the old data is not erased, the result of the write operation will be some logical combination of the old and new values, and the stored value will usually be something other than what you intended.
- one sector (block) of the device can be erased at a time Most of the time a Flash Drive is used (software module provided by device supplier). The user uses the APIs for erase or write.
IBS Timisoara
56 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory
Microcontrollers can have different methods for storing 16 bit integer values. Some hardware stores long data with a higher address for the low byte. This is called big endian because the big end comes at the end. Other hardware stores the high byte at the higher address. This is called little endian because the little end comes last. The results returned from extracting 8 bits from a 16 bit value will differ depending on the hardware storage method.

Poza big/ little endien poate si alta explicatie, ca asta e ciudata

IBS Timisoara
57 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory
The near and far keywords are common extensions to standard C. They allow different size pointers to address different areas of computer memory.
Near: creates a pointer which points to objects in the bottom section of addressable memory. These pointers occupy a single byte of memory, and the number of memory locations to which they can point is limited to the first 256 locations, or from $0000 to $00FF. For efficient RAM access, most microcontrollers place user RAM in the low memory addresses. Thus, near pointers usually point to data stored in user RAM such as user defined variables. int near * myNIntptr; The far keyword creates a pointer which can point to any data in memory. These pointers take two bytes of memory which allows them to hold any legal address location from $0000 to $FFFF. far pointers usually point to objects in user ROM, such as user defined functions and constant variables.

int far * myFIntptr;


Near and far pointers: Each microcontroller has different memory usage and the specific implementation of near and far pointers will vary depending on the target platform. Regardless of machine architecture, the compiler uses near pointers to point to commonly referenced data such as variables. The far pointers are harder to manipulate and are used for less common pointing tasks such as pointing to functions and constants.

IBS Timisoara
58 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory
Security function (censorship): prohibits rewriting the user program written to the code flash memory, so that the program cannot be changed by an unauthorized person. Can control the acces via debugger or boot. Often this is done by setting a configuration bit during programming. 78K0R: supported (see ref1 p 1171); operations: disable chip erase, disable block erase, disable write Bolero: (ref2 p85): after censorship is active, to re-gain the access a 64 bit password must be entered. For this there are 2 password registers.

Boot:

IBS Timisoara
59 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory 78K0R
Memory Map: see ref1 p127 The code flash memory is divided into 1k blocks (max 256 blocks) Program memory space is divided into:

- vector table area: see p132


- CALLT instruction table - store the subroutine entry address of a 2-byte call instruction (CALLT) - option byte when the boot swap is used - On-chip debug security ID setting - program area Mirror area: The 78K0R/Fx3 mirrors the code flash area of 00000H to 0FFFFH or 10000H to 1FFFFH, to F0000H to FFFFFH (the data flash area to be mirrored is set by the processor mode control register (PMC)). Data area (RAM): The internal RAM can be used as a data area and a program area where instructions are written and executed. Contains GPR (general purpose registers). SFR (Special Function Registers): are allocated in the area FFF00H to FFFFFH. SFR list see ref1 p 151 Extended special function register (second SFR): are allocated in the area F0000H to F07FFH - other than those in the SFR area. An instruction that accesses the extended SFR area, however, is 1 byte longer than an instruction that accesses the SFR area. ESFR list see ref1 p 158

IBS Timisoara
60 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory 78K0R
Addressing modes- see ref1 p144, 172 Instructions: - relative addressing: displacement (8/16 bits, from instruction) + PC -> PC - immediate addressing: Addr (16 /20 bits, from instruction) -> PC

- table indirect addressing (CALLT instruction)


table address (5b, from instruction)->CALLT table (16b) -> PC - register direct addressing: Data CS(8b)and GPReg (16b, from instruction) -> PC

- Implied addressing : instruction is addressing a register (e.g. accumulator), without mentioning it - register addressing: - direct addressing - short direct addressing - SFR addressing operand from GPRegister (from instruction) The instruction specifies the address of the operand (16b) For FFE20H to FFF1FH space, address on 8b. Operand from SFR (8b, from instruction)

- register indirect addressing : Register (16b, from instruction) specifies the address of the operand - based addressing: Operand address: Reg as base (16b) + 8/16b immediate data as offset Operand address: Reg as base (16b) + Reg (8b) as offset Indirect add using SP (Stack pointer) for Push, Pull instructions

- based indexed addressing: - stack addressing

IBS Timisoara
61 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory 78K0R

Main registers see ref1 p 145

- PC Program Counter
- PSW Program Status Word - SP Stack Pointer ES/ CS registers: The ES register is used for data access and the CS register is used to specify the higher address when a branch instruction is executed. The default value of the ES register after reset is 0FH, and that of the CS register is 00H. Stack: ref1 p 147 how different info is saved in stack

IBS Timisoara
62 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory 78K0R
Flash memory: can be written - via OCD - with dedicated flash memory programmer via serial interface

- Rewriting code flash memory by user program (application) (self programming)


2 types: - code flash - data flash: 8 x 2kB blocks, write access in 32 bit units

IBS Timisoara
63 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory - Bolero
Flash (details: ref2 p833) Up to 1.5 MB code flash memory (3 arrays of 512 KB). Sectors of 16k /32k (see ref2 p836) 4x 128-bit page buffers

64-bit ECC with single-bit correction, double-bit detection for data integrity
Censorship protection scheme 16 KB sector is available as Shadow space usable for user option bits and censorship settings. 4 x 16kB Data Flash Hardware managed flash memory writes, erase and verify sequence A TestFlash block is available in both the CFlash and DFlash modules. The TestFlash block exists outside the normal address space and is programmed and read independently of the other blocks. The independent TestFlash block is included to also support systems which require nonvolatile memory for security or to store system initialization information, or both.

Memory map: see ref2 p49

IBS Timisoara
64 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Memory - Bolero
SRAM (Static RAM) details ref2 p933 - Up to 96kB

- User transparent ECC encoding


- In order to reduce leakage a portion of the SRAM can be switched off/unpowered during standby mode. See p933 for details - Access: system bus is a two-stage pipelined bus, which makes the timing of any access dependent on the access during the previous clock cycle.

Register Protection module restricts write accesses for the module under protection to supervisor mode only.

MPU (Memory Protection Unit): provides hardware access control for all memory. Memory references that have sufficient access control rights are allowed to complete, while references that are not mapped to any region descriptor or have insufficient rights are terminated with a protection error response.

IBS Timisoara
65 2011 Viorel Deparateanu/ Continental AG, All rights reserved

DMA
The DMA controller moves the data from memory to a peripheral device or viceversa. It contains counters that automatically increment the next address after each transfer, so blocks of memory can be moved. It permits the microcontroller to perform other operations while a data transfer happens in the background. The micro just sets up the DMA and process the block of data when the transfer is complete.

IBS Timisoara
66 2011 Viorel Deparateanu/ Continental AG, All rights reserved

DMA 78K0R
Up to 4 DMA channels - data can be automatically transferred between the peripheral hardware supporting DMA, SFRs, and internal RAM without via CPU. Details: ref1 p1027 Maximum transfer unit: 1024 times

Transfer request: Selectable from the following peripheral hardware interrupts: A/D converter, Serial interface, Timer, LIN-UART, Multiplier/divider
Examples of functions using DMA. - Successive transfer of serial interface - Batch transfer of analog data - Capturing A/D conversion result at fixed interval - Capturing port value at fixed interval

IBS Timisoara
67 2011 Viorel Deparateanu/ Continental AG, All rights reserved

DMA 78K0R
Configuration: - address registers: DMA SFR (8b), DMA RAM (16b) transfer source or destination address - count register (10b) - Each time DMA transfer has been executed, this register is automatically decremented.

- control registers: mode, operation, forced wait

- Mode control register sets transfer mode, direction (SFR to RAM or RAM to SFR), data size (8/16b), start source. Bit 7 (STGn) is a software trigger that starts DMA.

- Operation register: enable/disable DMA transfer on channels, transfer status indication (completed / under execution).
- Forced wait: used to force DMA transfer on all channels to wait. It can also be used to change the priority order of the transfer channels.

IBS Timisoara
68 2011 Viorel Deparateanu/ Continental AG, All rights reserved

DMA - Bolero
Enhanced Direct Memory Access controller 16 channels to support independent 8-, 16-, or 32-bit single value or block transfers Support of variable sized queues and circular queues

Source and destination address registers independently configured to post-increment or remain constant
Peripheral DMA request sources possible from SPIs, I2C, 10-bit ADC, 12-bit ADC, eMIOS and GPIOs DMA transfers possible between system memories and all accessible memory mapped locations including peripheral and registers

IBS Timisoara
69 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers
A timer is a counter that is incremented at a fixed rate with the system clock. By loading in an initial count, a specific time interval can be timed, the overflow indicating when the interval has been reached.

Prescaler: a hw block in front of the timer to allow longer intervals to be measured. This hardware will only allow the timer itself to be incremented when a specific count is reached.

Used for: - To provide a constant delay - PWM

IBS Timisoara
70 2011 Viorel Deparateanu/ Continental AG, All rights reserved

WatchDog Timer (WDT)


is a special piece of hardware that protects the system from software hangs The watchdog timer is counting down from some large number to zero. In the meantime, the application software resets its counter to the original large number. If the counter ever does reach zero, the watchdog timer will assume that the software is hung. It then resets the embedded processor and, thus, restarts the software. On some controllers / applications the WDT does not perform a reset, but monitors a peripheral or signal, and calls an interrupt in case the parameters are out of normal values.

IBS Timisoara
71 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
Up to 3 timer units: with 4 or 8 x 16 bit timers Configuration: - Timer counter register mn (TCRmn) - 16-bit read-only register used to count clocks. The value of this counter is incremented or decremented in synchronization with the rising edge of a count clock. - Timer data register mn (TDRmn) -16 bit w/r, used for capture / compare

- Timer control registers, for unit or for each channel (details ref1 p377) - used for: peripheral enable/ disable, select clock, timer mode (TMRmn), overflow status (in capture mode), channel enable/disable, channel start, channel stop, timer output (enable, buffer register, level register, mode register, noise filter), Timer Input select, Timer output select, Port mode (PM0 PM15)

IBS Timisoara
72 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
Functions for Timer units: 1) Interval timer:
- reference timer that generates an interrupt (INTTMmn) at fixed intervals. TCRmn operates as a down counter Generation period of INTTMmn (timer interrupt) = Period of count clock (Set value of TDRmn + 1)

2) Square wave output

- performs a toggle operation is performed each time INTTMmn is generated and a square wave with a duty factor of 50% is output from a timer output pin (TOmn). Period of square wave output from TOmn = Period of count clock (Set value of TDRmn + 1) 2

Interval Timer/ Square Wave Output

IBS Timisoara
73 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
3) External event counter:
- generates an interrupt when the number of the valid edges of a signal input to the timer input pin (TImn) has reached a specific value. TCRmn operates as a down counter. Specified number of counts = Set value of TDRmn + 1

4) Frequency Divider function: - a clock input from a timer input pin (TImn) is divided and output from an output pin
(TOmn). Could be configured on rising/falling edge or both edges.

External event counter

Frequency divider

IBS Timisoara
74 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
5) Input pulse interval measurement
- It counts the value between two valid edges of a pulse signal (capture mode). TCRmn counts up from 0000H in synchronization with the count clock. When the TImn pin input valid edge is detected, the count value is transferred (captured) to TDRmn, the counter (TCRmn) is cleared to 0000H, and the INTTMmn is output. In case of overflow, the OVF bit is set at the end of measurement.

6) Measurement of high-/low-level width of input signal

Pulse interval measurement

High Level width measurement

IBS Timisoara
75 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
7) PWM output: Two channels are used as a set to generate a pulse
with a specified period and a specified duty factor. Pulse period = {Set val. of TDRmn (master) + 1} Count clock period Duty factor [%] = {Set val. of TDRmp (slave)}/{Set val. of TDRmn (master) + 1} 100
0% output: Set value of TDRmp (slave) = 0000H 100% output: Set value of TDRmp (slave) {Set value of TDRmn (master) + 1}

The master channel operates in the interval timer mode and counts the periods. TCRmn counts down from set TDRmn -> 0. When TCRmn = 0000H, INTTMmn is output. TCRmn loads the value of TDRmn again, and continues the similar operation.
TCRmp of a slave channel operates in one-count mode, counts the duty factor, and outputs a PWM waveform from the TOmp pin. TCRmp of the slave channel loads the value of TDRmp, using INTTMmn of the master channel as a start trigger, and stops counting until the next start trigger (INTTMmn of the master channel) is input. The output level of TOmp becomes active one count clock after generation of INTTMmn from the master channel, and inactive when TCRmp = 0000H.

IBS Timisoara
76 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
8) One-shot pulse output: - Two channels are used as a set to generate a one-shot pulse with a specified delay time
and a specified pulse width. Delay time = {Set value of TDRmn (master) + 2} Count clock period Pulse width = {Set value of TDRmp (slave)} Count clock period

9) Multiple PWM output

- using one master channel and two or more slave channels, up to seven types of PWM signals that have a specific period and a specified duty factor can be generated. Example for 2 slave channels: Pulse period = {Set value of TDRmn (master) + 1} Count clock period Duty factor 1 [%] = {Set value of TDRmp (slave 1)}/{Set value of TDRmn (master) + 1} 100 Duty factor 2 [%] = {Set value of TDRmq (slave 2)}/{Set value of TDRmn (master) + 1} 100

10) LIN bus supporting functions: wakeup detection, sync break field detection, sync pulse width measurement. These functions can only be configures on certain channels.

IBS Timisoara
77 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers 78K0R
16 bit Wake-up timer (WUTM, p493) works as Interval Timer mode. if the 16-bit counter and WUTM compare
register (WUTMCMP) values match, the counter is cleared and starts again, and an interrupt signal (INTWUTM) is output. As it can have the int. low speed clock as input, could be used in Low Power modes, and a good option as timer for OS scheduler (used by SWP).

Watchdog Timer (WDT, p501) generates an internal reset signal in case of program abnormal function. Writing
ACH to WDTE register clears the watchdog timer counter and starts counting again. Reset is generated in case of WDT counter overflow, or if data is written in WDTE register out of window open period. WDT operates on the internal low-speed oscillation clock.

The window open (interval that accepts WDT clear) can be configured as 25%, 50%, 75%, 100%. Example below for 25%

IBS Timisoara
78 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers Bolero
Types (see details ref2 p691) System Timer Module (STM) - 32-bit free running up-counter clocked by the system clock with a configurable 8-bit clock pre-scaler.

- 4 x 32-bit compare channels. Each channel can generate a unique interrupt on an exact match event with the free running counter.
- The STM is often used to analyze code execution times. By starting the STM and reading the timer before and after a task or function, you can make an accurate measurement of the time taken in clock cycles to perform the task. - The STM can be configured to stop (freeze) or continue to run in debug mode and is available for use in all operating mode where the system clock is present (not STANDBY or certain STOP mode configurations) - There are no external pins associated with the STM. Enhanced Modular Input Output System (eMIOS) used for IO capture / compare / pwm

- Up to 64 timed I/O channels with 16-bit counter resolution


- Support for shifted PWM outputs to minimize occurrence of concurrent edges - Supports configurable trigger outputs for ADC conversion for synchronization to channel output waveforms

IBS Timisoara
79 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers Bolero
Periodic Interrupt Timer (PIT) - 8 general purpose timers, 32 bit resolution - Interrupts: up to 2 ADC trigger, 4 DMA transfer, 2 CTU trigger

- including ADC trigger


- the user must first program an initial value into the LDVAL register. The timer will then start to count down and can be read at any time. Once the timer reaches 0x0000_0000, a flag is set and the previous value is automatically re-loaded into the LDVAL register and the countdown starts again. The flag event can be routed to a dedicated INTC interrupt if desired. 1 Real-Time Counter (RTC) timer - Real Time Clock / Autonomous Periodic Interrupt (RTC/API) - free running counter used for time keeping applications. The RTC may be configured to generate an interrupt at a predefined interval independent of the mode of operation - Supports continued operation through all resets except POR (power-on reset)

- Selectable clock sources, optional prescaler, 32 bit counter

IBS Timisoara
80 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Timers Bolero
Software Watchdog Timer (SWT) details see ref2 p957 - 32 bit counter, fixed clock source: internal RC oscilator

- normal or windowed mode


- Configurable response on timeout: reset, interrupt, or interrupt followed by reset - 3 operation modes: - normal: the counter runs continuously - debug: the counter is stopped in debug mode, otherwise it continues to run. - stop: counter is stopped in STOP mode - The software watchdog is not available during standby.

IBS Timisoara
81 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO
Digital IO Is the basic external interface between a microcontroller and the outside world The pins are selectable between input and output, using configuration registers.

Open drain output: the pin remains at the bus state unless it is set to output and the bit value is 0.
Ports usually consist of 8 or fewer bits which often support tristate logic with three states: input, output or high impedance. High impedance mode is the state of being undefined or floating.

Analog IO
In many models of the different microcontroller families there are analog-to-digital convertors (ADCs) and digital-to-analog convertors (DACs). Analog to Digital Conversion:

- Successive Approximation Converter: The converter works with one bit at a time from the MSB (mostsignificant bit) and determines if the next step is higher or lower. This technique is slow and consumes power. It is also cheap and has consistent conversion times.

IBS Timisoara
82 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO 78K0R
IO 78K0R IO structure see ref1 p117, p192 15 ports, with multiple functions, configurable by software. For alternate functions, the IO must have certain modes see ref1 p316 Input/output can be specified in 1-bit units. Use of an on-chip pull-up resistor can be specified by a software setting.

IBS Timisoara
83 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO 78K0R
Port functions are controlled by the following types of registers (see ref1 p290) - Port mode registers (PMxx) - specify input (1) or output mode (0) for the port in 1-bit units. FFh after reset . - Port registers (Pxx) - input: pin level; output: data that is output from the chip. 00h after reset.

- Pull-up resistor option registers (PUxx) - usage of the on-chip pull-up resistors (1-yes, 0-no). 00h after reset.
- Port input mode registers (PIMxx) - normal (0)/ TTL (1) input buffer of port .

- Port output mode registers (POMxx) - set the output mode of port: normal (0)/ N-ch open-drain output. - Port output slew rate select register (PSRSEL) - selects the output slew rate - A/D port configuration register (ADPC) - switches the ANI00/P80 to ANI07/P87, ANI08/P90 to ANI15/P97 and ANI16/P100 to ANI23/P107 pins to analog input of A/D converter or digital I/O of port (details p311)

IBS Timisoara
84 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO 78K0R
A/D Converter (see ref1 p514): 10-bit resolution, configured to control up to 24 channels analog inputs (ANI00 to ANI23). Each time an A/D conversion operation ends, an interrupt request (INTAD) is generated. Conversion modes (p545): - continuous select: A/D conversion of the voltage of one analog input pin specified by the ADS register. -continuous scan mode: sequentially selects pins from the ANI00 pin to the analog input pin specified by the ADS register, and performs A/D conversion successively. - One shot select/ scan mode The trigger can be software (setting ADCS = 1) and hardware (external) trigger mode (signal on ADTRG pin)

When conversion ends, the conversion result is stored in the ADCR and ADCRn registers.
Conversion time see ref1 p531

IBS Timisoara
85 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO Bolero
System Integration Unit Lite (SIUL) - controls the MCU pad configuration, ports, general-purpose input and output (GPIO) signals and external interrupts with trigger event configuration, offering flexibility in the allocation of device functions. Details:see ref2 p406 SIUL Features: - Up to 4 levels of internal pin multiplexing - Centralized general purpose input output (GPIO) control of up to 149 input/output pins - All GPIO pins independently configurable to support pull-up, pull down, or no pull

IBS Timisoara
86 2011 Viorel Deparateanu/ Continental AG, All rights reserved

IO Bolero
Analog-to-Digital Converter (ADC) details: ref2 p761 - 2 ADC modules, one 10-bit resolution and one 12-bit resolution supporting synchronous conversions on channels.

- Up to 5 dedicated 12-bit ADC channels, and up to 29 dedicated 10-bit ADC channels


- Conversions times of < 1 s available - injected conversion possible (normal conversion is interrupted temporary for a conversion of another channel ) - One Shot/Scan Modes (scan: conversion continuously performed) - 6 + 3 (6 on 10-bit ADC, 3 on 12-bit ADC) configurable analog comparator channels, offering alarms in case of: greater than, less than, out of range - Supports DMA transfer of results based on the end of conversion

Cross Trigger Unit (CTU) - enables the synchronization of ADC conversions with a timer event (triggers ADC conversions from any eMIOS, or from up to 2 dedicated PITs)

IBS Timisoara
87 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM
Communication peripherals embedded on microcontrollers (ex: CAN, LIN and SPI) requires important CPU resources for communication management. Even a 32-bit microcontroller is overloaded if its peripherals do not provide high-level features to autonomously handle the communication. To minimize the CPU load in Master mode, the communication peripherals required only seldom intervention from processor (software), for example to process the data received, or to provide the next message to be transmitted.

IBS Timisoara
88 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM - ASC
Serial communication: ASC / Synchronous ASC (asynchronous serial communication) a data byte is sent as a packet along with data start and stop information and error detection information. The first bit (start bit) is indicating that a data packet is being sent and is following. This is used by the receiver to synchronize the reading of the data which follows (least significant bit first). A parity bit can optionally be sent after the data to ensure that the receiver has received the correct data. Could be odd or even. After the parity bit, there is 1 or 2 stop bits that are used by the receiver to store and process the data byte just read in from the packet. Usual format is 8N1 - 8 data bits, no parity, and one stop bit as the packet format The most popular type of ASC is RS-232, RS 485 (differential). UART (Universal Asynchronous Receiver Transmitter) is used mainly as a serial to parallel and parallel to serial converter. In automotive: CAN ASC could be half duplex or full duplex Manchester encoding used for RF transmission. Start D0 D1 D2 D3 D4 D5 D6 D7 Parity Stop

IBS Timisoara
89 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM
Synchronous a clock signal is sent along with serial data. Protocols: Microwire, SPI, I2C

SPI (Serial Peripheral Interface) : is a threewire (Data IN, Data Out, Clk) synchronous serial port which allows several microcontrollers to be interconnected. In the configuration there must be at least one microcontroller master while the remaining microcontrollers can either be masters or slaves.

SPI Function

I2C: multi-master, multislave network interface with collision detection. 2 lines : SCL (clock) and SDA (data). Speed: 100 400 kbps. Every component has its own unique address.

IBS Timisoara
90 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM - LIN
LIN - Local Interconnect Network Cheaper than CAN Transfer up to 19200 kbit/s
Synch Break 13 bit (min) Identifier Field 1 byte next Synch Break

Byte field format

Synch Field 1 byte

Header (from Master) In-frame Space

Checksum Field 1 byte Data Field 2, 4 or 8 bytes Inter-frame space / break

LIN Frame Format

Response (from Master/ slave)

IBS Timisoara
91 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM 78K0R
Serial Array unit has two serial channels per unit and can use two or more of various serial interfaces (3wire serial (CSI), UART, and simplified I2C) in combination. Functions:

- 3 wire serial SCK (clock), SI, SO (transmission / reception data)


Config: Data length of 7 to 16 bits, MSB/LSB first selectable, Master/slave selection, Phase control of I/O clock, Transfer end interrupt/buffer empty interrupt, Overrun error detection, SPI. - UART: transmission on 2 lines (RxD, TxD), using start-stop synchronization. Config: Data length of 7 to 9, or 16 bits, Select the MSB/LSB first, Level setting of transmit/receive data and select of reverse, Parity bit appending and parity check functions, Stop bit appending, Transfer end interrupt/buffer empty interrupt, Framing error, parity error, or overrun error detection - Simplified I2C (only as master)

Registers:
- Shift register - 8-bit register that converts parallel data into serial data or vice versa. It cannot be accesed directly. - Serial data register (SDRmn): SDRmn is the transmit/receive data register (16 bits) of channel n

- Control registers: Peripheral enable, clock select, mode, status, serial start/stop, slave select, Port Mode,

IBS Timisoara
92 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM 78K0R
Asinchronous serial Interface LIN-UART (UARTF) can use different data format Start bit ................... 1 bit

Character bits.......... 7 bits/8 bits


Expansion bit .......... 1 bit (if ebabled) Parity bit .................. Even parity/odd parity/0 parity/no parity Stop bit.................... 1 bit/2 bits

IBS Timisoara
93 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM - Bolero
DSPI Module (Deserial Serial Peripheral Interface Module): provides a synchronous serial bus for communication between the MCU and an external peripheral device. - 6 DSPI modules

- supports full duplex, synchronous, master/ slave operations


- data frames from 4 to 16 bits - programable baud rate - For queued operations (4 entries depth) the SPI queues reside in internal SRAM. Data transfers between the queues and the DSPI FIFOs are accomplished through the use of the eDMA controller or through host software. Operation modes: - Master mode allows the DSPI to initiate and control serial communication. In this mode the SCK, CS n and SOUT signals are controlled by the DSPI and configured as outputs. - Slave mode allows the DSPI to communicate with SPI bus masters. In this mode the DSPI responds to externally controlled serial transfers. The DSPI cannot initiate serial transfers in slave mode. In slave mode, the SCK signal and the CS0_x signal are configured as inputs and provided by a bus master. - Module disable mode: is used for MCU power management. The clock is stopped.

- Debug mode - used for system development and debugging

IBS Timisoara
94 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM - Bolero
Serial communication interface module (LINFlex) - details: see ref2 p459 - Supports LIN master mode, LIN slave mode and UART mode - Up to 10 LINFlex modules supported

- Advanced LIN error detection


- 3 operating mode for power saving The software uses the control, status and configuration registers to: - Configure LIN parameters (for example, baud rate or mode) - Request transmissions - Handle receptions - Manage interrupts - Configure LIN error and timeout detection - Process diagnostic information The message buffer stores transmitted or received LIN frames.

IBS Timisoara
95 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM - CAN
CAN: controller area network differential serial bus, multiple nodes speed 125kbps 1Mbps 0 is known as a dominant bit and a 1 is known as a recessive bit.

devices are not given specific names or addresses. Instead, the message is identified (using the 11- or 19bit message identifier, for Standard or Extended frames). This method of addressing can provide you with very flexible messaging (which is what CAN is all about).

Standard Frame Format (CAN 2.0A): 11-bit Identifier


211 = 2048 (in reality only 2032) identifiers possible

Bus Idle

Arbitration Field

Control Field

Data Field

CRC Field

Ack Field

End of Frame Field

Interframe Space

Bus Idle

recessive

Bus Idle
dominant

S O F

11-bit Identifier

R I r TD 0 RE

DLC

0..64 Bit Data

15-bit CRC

DAD ECE L KL

7-bit EOF IFS Bus Idle

IBS Timisoara
96 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM CAN 78K0R


1-channel CAN (Controller Area Network) controller (details see ref1 p872) 16 message buffers, in RAM A receive completion interrupt is generated each time a message is received and stored in a message buffer. supports CAN sleep / stop mode (sleep: can be woken up by CAN bus, stop no wakeup on CAN) Registers (p898): - Control: clock select, pin select, port, port mode

- CAN global registers: CAN global control, clock select, automatic block transmission control,
- CAN module registers: mask 1-4 registers, control, error code, error counter, Interrupt enable, status - Message buffer registers Mask function: By using the mask function, the message ID comparison can be reduced by masked bits, herewith allowing the reception of several different IDs into one buffer. Multibuffer receive block - used to store a block of data in two or more message buffers sequentially with no CPU interaction, by setting the same ID to two or more message buffers with the same message buffer type.

IBS Timisoara
97 2011 Viorel Deparateanu/ Continental AG, All rights reserved

COM CAN Bolero


Supports up to 6 Can modules 64 mailboxes per FlexCAN module - Mailboxes configurable while module remains synchronized to CAN bus

- Each mailbox configurable as transmit or receive


- Individual programmable filters for each mailbox - DMA support is not provided - the Message Buffers are stored in an embedded RAM dedicated to the FlexCAN module. Modes of operation: - 4 functional modes: Normal (User and Supervisor), Freeze, Listen-Only and Loop-Back - 1 low-power mode (Disable mode) Message buffer structure see ref2 p595

IBS Timisoara
98 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Power Management
Power management: Current consumption can be reduced by: - reduce clock frequency

- disable peripherals
- Disable parts of memory Low Power Management (sleep mode/ standby mode) applies some of these reductions.

For PICMicro 16C73A

FREQUENCY 1.0 MHz 2.0 MHz 3.0 MHz 4.0 MHz

CURRENT 550 uA 750 uA 1 mA 1.25 mA

IBS Timisoara
99 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Power Management 78K0R


2 modes: - Halt - after HALT instruction - the CPU operation clock is stopped, but not stopping the clock oscillation. This mode is effective for restarting operation immediately upon interrupt request.

- Stop - after STOP instruction - the clock is stopped => current consumption is reduced. After an interrupt request a wait time is needed for clock stabilization
In both modes all the contents of registers, flags, data memory, I/O port output latches and output buffer statuses just before the standby mode is set are held. The STOP mode can be used only when the CPU is operating on the main system clock (not possible while the CPU operates with the internal low-speed oscillation clock). The HALT mode can be used when the CPU is operating on either the main system clock or the internal low-speed oscillation clock.

IBS Timisoara
100 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Power Management Bolero


Power Control Unit (MC_PCU) is used to reduce the overall power consumption. Power can be saved by disconnecting parts of the uC from the power supply via a power switching device, parts called power domains. Maximum power saving is reached by entering the STANDBY mode. All memories which are not powered down during STANDBY mode automatically enter a power saving state. No software configuration is required to enable this power saving state. While a memory is residing in this state an increased power saving is achieved. Data in the memories is retained. Wakeup Unit (WKPU) 2 internal sources and up to 27 external sources that can generate interrupts or

wakeup events

IBS Timisoara
101 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Optimizing the code


Compilers can optimize either speed or size, not both. To reduce the execution time: Things should be made as simple as possible, but not any simpler. Albert Einstein

- inline functions: request to the compiler to replace all calls to the indicated function with copies of the code that is inside. Suitable for very often called, short functions.
- switch statement optimization: put the individual cases in order by their relative frequency of occurrence (improves the average execution time, not the worst-case time) - table lookup: replace the switch statement with a table of pointers to functions - use assembly - use global variables instead of parameter to functions (disadvantage: less modular)

To reduce the code size:


- by compiler: dead code elimination - use functions - use local variables instead of global, near instead of far ()

An optimized program will not necessarily behave the same as the unoptimized one.

IBS Timisoara
102 2011 Viorel Deparateanu/ Continental AG, All rights reserved

To reduce the RAM usage: - move constants into ROM (use const)

- use reasonable stack size

IBS Timisoara
103 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Table lookup

enum NodeType { NodeA, NodeB, NodeC };

int processNodeA(void); int processNodeB(void); int processNodeC(void);

switch (getNodeType())
{ case NodeA: . case NodeB: . case NodeC: . }

/* Establishment of a table of pointers to functions. */

int (* nodeFunctions[])() = { processNodeA, processNodeB, processNodeC };


.

/* The entire switch statement is replaced by the next line. */ status = nodeFunctions[getNodeType()]();

IBS Timisoara
104 2011 Viorel Deparateanu/ Continental AG, All rights reserved

Exercitii
LED care sa lumineze intermitent cu 1 Hz (poate fi led bicolor)
1244.5 1480.0 1661.2 1864.7 1217.5 2489.0 2960.0 3322.4 3136.0 3520.0 3729.3 3951.1
A 7 #
or

semafor
1046.5

1108.7

lumina dinamica

1318.5

1396.9

1568.0

1760.0

1975.5

2093.0

2349.3

2637.0

2793.0

Buzzer

C 6 #
or

D 6 #
or

F 6 #
or

G 6 #
or

A 6 #
or

C 7 #
or

D 7 #
or

F 7 #
or

G 7 #
or

D 6 b

E 6 b

G 6 b

A 6 b

B 6 b

D 7 b

E 7 b

G 7 b

A 7 b

B 7 b

C6 D6 E6 F6 G6 A6 B6 C7 D7 E7 F7 G7 A7 B7 C8

IBS Timisoara
105 2011 Viorel Deparateanu/ Continental AG, All rights reserved

4186.0

1174.7

Vous aimerez peut-être aussi