You are on page 1of 63

Continental Automotive Systems S.R.

L
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
• Who am I?
• What I do for a living?
• Why am I teaching?

Continental Automotive Systems S.R.L


2
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 1
Embedded Systems

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
 Microcontroller
 What is a CPU ?
 What is a microcontroller ?
 Differences between microcontroller and
microprocessor – PC vs uC
 Where do you find a microcontroller ?
 Architecture
 Function Units

Continental Automotive Systems S.R.L


4
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
What is a microcontroller ?
 Microcontroller (µC) is an Integrated Circuit (IC) chip that includes a microprocessor,
internal memory and some peripherals (I/O ports).
 Usually the microprocessor in a microcontroller is less powerful than the
microprocessors used in general-purpose computers. Similarly, size of the internal
memory is much smaller than that in general purpose computer.
 Microcontroller is the main IC used in an embedded system. Internal memory is used
for processing (application code and data storage). Input data comes through the input
ports and output goes to output port.

Continental Automotive Systems S.R.L


5
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Differences between microcontroller and microprocessor
 Microprocessors are ICs which have only the CPU
inside them
 Microcontrollers have a CPU, in addition with a fixed
amount of RAM, NVM and other peripherals all
embedded on a single chip. At times they are also
described as a mini computer or a computer on a single
chip
 A microcontroller is far cheaper than a microprocessor
 Microprocessors cannot be used stand alone

 Microprocessor are found in applications where tasks are unspecific like developing software, games,
websites
 Microcontrollers are found in systems designed to perform a specific tasks. Specific means applications
where the relationship of input and output is defined
 The processing performance of the Microprocessor is orders of magnitude higher than the
microcontroller

Continental Automotive Systems S.R.L


6
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Where do you find a microcontroller ?
 Cars
 engine ignition, emissions control, ABS brakes, security
 Entertainment systems, consumer multimedia
 front-panel displays, system functions
 video game decks
 • Appliances
 timers, user interfaces, regulation of appliance functions
 • Printers
 image rasterizers, printer language interpretation
 • Networking equipment
 Routers, gateways
 • Personal communications equipment
 cell phones, cordless phones, smart cards
 • Computers
 IDE/SCSI hard drives, modems, high-end storage (I2O), keyboard
 • Batteries
 controls charging, discharge, gas gauge

Continental Automotive Systems S.R.L


7
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Function Units

• CPU: Central Processor Unit (4,8,16,32 bit data bus)


• NVM: Firmware (Flash)
• RAM: Register area, Processor Stack, Temporary data
• PIO: Parallel I/O (relays, sensor)
• INT: INTerrupt inputs (external/internal sources)
• SIO: Serial I/O (SPI, I2C, CAN)
• UART: Universal Asynchronous Receiver Transmitter (e.g. RS232C)
• GPT: General Purpose Timer (optional event counter)
• PWM: Pulse Width Modulator (motor controller)
• WDT: Watch Dog Timer (automatic reset)
• AIO: Analog I/O (DAC & ADC)

Continental Automotive Systems S.R.L


8
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 2
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
 Microcontroller
 CPU
 Memories
 Interrupts
 Digital Inputs / Outputs
 Counters / timers

Continental Automotive Systems S.R.L


10
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller - CPU
Embedded Processor by Primary Attributes:

Continental Automotive Systems S.R.L


11
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Memory Types
Types of RAM
The RAM family includes two important memory devices:
 static RAM(SRAM) - SRAM retains its contents as long as electrical power is applied to
the chip. If the power is turned off or lost temporarily, its contents will be lost forever.
 dynamic RAM (DRAM) - DRAM, on the other hand, has an extremely short data lifetime-
typically about four milliseconds. This is true even when power is applied constantly.

Continental Automotive Systems S.R.L


12
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Memory Types
Types of ROM
 masked ROM - The contents of the ROM had to be specified before chip
production, so the actual data could be used to arrange the transistors inside
the chip

 PROM (programmable ROM) - The process of writing your data to the


PROM involves a special piece of equipment called a device programmer.
The device programmer writes data to the device one word at a time by
applying an electrical charge to the input pins of the chip. Once a PROM has
been programmed in this way, its contents can never be changed. PROMs
are also known as one-time programmable (OTP) devices.

 EPROM (erasable-and-programmable ROM) - Is programmed in exactly the


same manner as a PROM. However, EPROMs can be erased and
reprogrammed repeatedly. To erase an EPROM, you simply expose the
device to a strong source of ultraviolet light. By doing this, you essentially
reset the entire chip to its initial unprogrammed state. Though more
expensive than PROMs, their ability to be reprogrammed makes EPROMs
an essential part of the software development and testing process.

Continental Automotive Systems S.R.L


13
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Memory Types
Types of Hybrid
 EEPROM - are electrically-erasable-and-programmable. Internally, they
are similar to EPROMs, but the erase operation is accomplished
electrically, rather than by exposure to ultraviolet light. Any byte within an
EEPROM may be erased and rewritten. Once written, the new data will
remain in the device forever-or at least until it is electrically erased.

 Flash memory - combines the best features of the memory devices


described thus far. Flash memory devices are high density, low cost,
nonvolatile, fast (to read, but not to write), and electrically reprogrammable.
From a software viewpoint, flash and EEPROM technologies are very
similar. The major difference is that flash devices can only be erased one
sector at a time, not byte-by-byte.

 NVRAM (non-volatile RAM) - An NVRAM is usually just an SRAM with a


battery backup. When the power is turned on, the NVRAM operates just
like any other SRAM.

Continental Automotive Systems S.R.L


14
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Interrupts

Normal execution of a given software application is contained within the bounds of one
program, or instruction stream. However, system designers and implementers also
have to understand how breaks in program flow occur, and how they may affect the
running program. Flow breaks fall into two general classes:

 Exceptions and traps are predictable, synchronous breaks in program flow.


They are synchronous because they are caused by the execution of certain
instructions (divide by zero; illegal memory access; software interrupt).
 Note: not all Exceptions are synchronous. A write access via a store
buffer will generate an async buss error.

 Interrupts are asynchronous breaks in program flow that occur as a result of


events outside the running program. They are usually hardware related,
stemming from events such as a button press, timer expiration, or completion
of a data transfer. We can see from these examples that interrupt conditions
are independent of particular instructions; they can happen at any time.

Continental Automotive Systems S.R.L


15
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Interrupts
All CPUs, and many devices, have some mechanism for enabling/disabling interrupt
recognition and processing:
 At the device level, there is usually an interrupt control register with bits to
enable or disable the interrupts that device can generate.

 At the CPU level, a global mechanism functions to inhibit/enable (often called


the global interrupt enable) recognition of interrupts.

 Systems with multiple interrupt inputs provide the ability to mask (inhibit)
interrupt requests individually and/or on a priority basis. This capability may be
built into the CPU or provided by an external interrupt controller. Typically,
there are one or more interrupt mask registers, with individual bits allowing or
inhibiting individual interrupt sources.

 There is often also one non-maskable interrupt input to the CPU that is used to
signal important conditions such as pending power fail, reset button pressed, or
watchdog timer expiration.

Continental Automotive Systems S.R.L


16
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Interrupts
Hardware
• Power down Interrupt occurs
• External interrupts, etc.
• ADC conversion finished.
• Falling/rising edge detected.
• Timer overflow.
• ASC data received or transmitted, etc. instruction 1
instruction 2
instruction 3
instruction 4
USH instruction 5
P

….
Interrupt routine instruction n

POP
instruction 1
….

instruction n

Continental Automotive Systems S.R.L


17
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
DIO (Digital Input Output)

Every microcontroller pin organized in ports that can be configurable, except some pins that are dedicated to
some special functions (voltage, debug, clk, etc). Pins can be configured as DIO (digital pins inputs or
outputs) or to be configured to have alternate function (used by other module: timers, spi, UART, PWM, etc).

Input

Parallel
Digital input μC
port
Output

Parallel
Digital output μC
port

Continental Automotive Systems S.R.L


18
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Counters / timers
Counter/timer hardware is a crucial component of most embedded systems. In some
cases, a timer measures elapsed time (counting processor clock ticks). In others, we
want to count or time external events. The names counter and timer can be used
interchangeably when talking about the hardware. The difference in terminology has
more to do with how the hardware is used in a given application.

The timer shown consists of a loadable 8-bit count register, an input clock signal, and an output
signal. Software loads the count register with an initial value between 0x00 and 0xFF. Each
subsequent transition of the input clock signal increments that value.
When the 8-bit count overflows, the output signal is asserted. The output signal may thereby
trigger an interrupt at the processor or set a bit that the processor can read. To restart the timer,
software reloads the count register with the same or a different initial value.

Continental Automotive Systems S.R.L


19
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 3
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
 Microcontroller

 Watchdog Timer

 Analog to Digital Converters

 PWM

 DC Motors

Continental Automotive Systems S.R.L


21
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – Watchdog
A watchdog timer is a piece of hardware that can be used to automatically detect
software anomalies and reset the processor if any occur. Generally speaking, a
watchdog timer is based on a counter that counts down from some initial value to zero.
As shown, the watchdog timer is a chip external to the processor. However, it could
also be included within the same chip as the CPU.
Watchdog function can be disabled

The process of restarting the watchdog timer's counter is sometimes called "kicking
the dog." The appropriate visual metaphor is that of a man being attacked by a
vicious dog. If he keeps kicking the dog, it can't ever bite him. But he must keep
kicking the dog at regular intervals to avoid a bite. Similarly, the software must
restart the watchdog timer at a regular rate, or risk being restarted.

Continental Automotive Systems S.R.L


22
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – ADC
 A/D converters are electrical circuits that have the following characteristics:
 The input to the A/D converter is a voltage.
 A/D converters may be designed for voltages from 0 to 10v, from -5 to +5v, etc.,
but they almost always take a voltage input.  (Some rare exceptions occur with
current inputs!) 
 In any event, the input is an analog voltage signal for most cases.
 The output of the A/D converter is a binary signal, and that binary signal encodes
the analog input voltage.  So, the output is some sort of digital number.

ADC
Signal
generator
Analog signal
• mode
value
μC
• resolution

Continental Automotive Systems S.R.L


23
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – ADC
Example:

How many bits would you need to divide 10 v into .01 v intervals?
To get the answer to the question consider the following.

•If you divide 10 v into .01 v intervals you need 1000 intervals.
•If you need 1000 intervals you need to think about a power of 2 that is larger than
1000.
•The smallest power of 2 that is larger than 1000 is 210 which is equal to 1024.
•That means that you need 10 bits in the converter, and the count in the
counter/register will run from 0 to 1023.
•And that leads us to observe that real converters often go to 10.23v, not 10v because
that gives perfect .01v increments between resolvable voltages.
•And another converter might run from -5.12v to +5.11v for the same reason.

Continental Automotive Systems S.R.L


24
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – PWM
Pulse width modulation (PWM) is a powerful technique for controlling analog circuits
with a microprocessor's digital outputs. PWM is employed in a wide variety of
applications, ranging from measurement and communications to power control and
conversion.
Figure 1a shows a PWM output at a 10% duty cycle. That is, the signal is on for
10% of the period and off the other 90%. Figures 1b and 1c show PWM outputs at
50% and 90% duty cycles, respectively.

Continental Automotive Systems S.R.L


25
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – PWM
In the figure, a 9V battery powers an incandescent lightbulb. If we closed the switch
connecting the battery and lamp for 50ms, the bulb would receive 9V during that
interval. If we then opened the switch for the next 50ms, the bulb would receive 0V.
If we repeat this cycle 10 times a second, the bulb will be lit as though it were
connected to a 4.5V battery (50% of 9V). We say that the duty cycle is 50% and the
modulating frequency is 10Hz.

Continental Automotive Systems S.R.L


26
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Microcontroller – DC Motors
Electrical motors are everywhere around us. Almost all the electro-mechanical
movements we see around us are caused either by an A.C. or a DC motor.
This DC or direct current motor works on the principal, when a current carrying
conductor is placed in a magnetic field, it experiences a torque and has a tendency
to move.

Continental Automotive Systems S.R.L


27
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 4
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Table of Contents
Microcontroller

- Serial communication

- RS-232 Interface

- SPI Communication Protocol

- Endianness

Continental Automotive Systems S.R.L


29
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Serial vs Parallel

• A parallel port sends and receives data eight bits at a time over eight separate wires
or lines. This allows data to be transferred very quickly
• A serial port sends and receives data, one bit at a time over one wire. While it takes
eight times as long to transfer each byte of data this way, only a few wires are
required.
• Although this is slower than parallel communication, which allows the transmission
of an entire byte at once, it is simpler and can be used over longer distances
• The cabling between equipment for parallel communication can be no more than 20
meters total, with no more than 2 meters between any two devices;
• Serial communication can be extended up to 1200meters
• The serial port on your PC is a full-duplex device meaning that it can send and
receive data at the same time. In order to be able to do this, it uses separate lines for
transmitting and receiving data.

Continental Automotive Systems S.R.L


30
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Synchronous Serial Interfaces

In synchronous transmission, the stream of data to be transferred is encoded and


sent on one line, and a periodic pulse of voltage which is often called the "clock" or
"strobe" is put on another line, that tells the receiver about the beginning and the
ending of each bit (or byte). In general, such synchronous transmission protocols are
used for all the types of parallel communications..

Continental Automotive Systems S.R.L


31
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Asynchronous Serial Interfaces

Continental Automotive Systems S.R.L


32
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
The advantages & disadvantages

The only advantage of synchronous data transfer is the Lower overhead and thus,
greater throughput, compared to asynchronous one. But it has some disadvantages
such as,
1.Slightly more complex and
2.Hardware is more expensive

One of the main Disadvantage of asynchronous technique is the large relative


overhead, where a high proportion of the transmitted bits are uniquely for control
purposes and thus carry no useful information. But it holds some advantages like,
1.Simple and doesn't require much synchronization on both communication sides
2.The timing is not as critical as for synchronous transmission; therefore hardware
can be made cheaper.
3.Set-up is very fast, so well suited for applications where messages are generated at
irregular intervals, for example data entry from the keyboard

Continental Automotive Systems S.R.L


33
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
RS-232 interface

Continental Automotive Systems S.R.L


34
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
SPI Bus interface
An SPI protocol specifies 4 signal wires.
1. Master Out Slave In (MOSI) - MOSI signal is generated by Master, recipient is the
Slave.
2. Master In Slave Out (MISO) - Slaves generate MISO signals and recipient is the
Master.
3. Serial Clock (SCLK or SCK) - SCLK signal is generated by the Master to
synchronize data transfers     between the master and the slave.
4. Slave Select (SS) from master to Chip Select (CS) of slave - SS signal is generated
by Master to     select individual slave/peripheral devices. The SS/CS is an active low
signal.

Continental Automotive Systems S.R.L


35
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
SPI Bus interface
The communication is initiated by the master all the time. The master first configures
the clock, using a frequency, which is less than or equal to the maximum frequency
that the slave device supports. The master then select the desired slave for
communication by pulling the chip select (SS) line of that particular slave-peripheral to
"low" state. If a waiting period is required (such as for analog-to-digital conversion)
then the master must wait for at least that period of time before starting to issue clock
cycles.
The slaves on the bus that has not been activated by the master using its slave select
signal will disregard the input clock and MOSI signals from the master, and must not
drive MISO. That means the master selects only one slave at a time.

Continental Automotive Systems S.R.L


36
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
SPI Bus interface
1. Cascaded slaves or daisy-chained slaves
2. Independent slaves or parallel configuration

Continental Automotive Systems S.R.L


37
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
SPI Bus interface
Advantages of SPI
1. Full duplex communication
2. Higher throughput than I²C protocol
3. Not limited to 8-bit words in the case of bit-transferring
4. Arbitrary choice of message size, contents, and purpose
5. Simple hardware interfacing
6. Typically lower power requirements than I²C due to less circuitry.
7. No arbitration or associated failure modes.
8. Slaves use the master's clock, and don't need precision oscillators.
9. Transceivers are not needed.
10. At most one "unique" bus signal per device (CS); all others are shared

Disadvantages of SPI
1. Requires more pins on IC packages than I²C
2. No in-band addressing. Out-of-band chip select signals are required on shared busses.
3. No hardware flow control
4. No slave acknowledgment
5. Multi-master busses are rare and awkward, and are usually limited to a single slave.
6. Without a formal standard, validating conformance is not possible
7. Only handles short distances compared to RS-232, RS-485, or CAN.

Continental Automotive Systems S.R.L


38
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Endianness
Big Endian
• In big endian, you store the most significant byte in the smallest address.
Little Endian
• In little endian, you store the least significant byte in the smallest address.

Continental Automotive Systems S.R.L


39
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 5
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Table of Contents
Embedded software

- Preprocessor

- Preprocessor directives

- Compiler

- Linker

Continental Automotive Systems S.R.L


41
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
The Compilation Process

Compilation in general is split into roughly 4 stages: Preprocessor,


Compiler, Assembler, and Linker

Continental Automotive Systems S.R.L


42
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Preprocessor

The preprocessor modifies the text of the source code file via a variety
of text substitution and manipulation operations. That modified source is
subsequently passed to the C compiler for compilation.

Preprocessor commands are lines in program that start with “#” and are
not finished with “;”:
• #define
• #include
• #ifdef
• #endif

Continental Automotive Systems S.R.L


43
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Preprocessor - Examples

Before preprocessing: After preprocessing:

#define N 100 int main(int argc,const char* arg[])


int main(int argc,const char* arg[]) {
{ int A[100];
int A[N]; int n;
int n;

for(n = 0;n < 100;n++)


for(n = 0;n < N;n++) A[n] = n*n;
A[n] = n*n; }
}

Continental Automotive Systems S.R.L


44
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Preprocessor - Examples

Before preprocessing: After preprocessing:

For example, given a header file foo.h The preprocessor will convert main.c to
a file main.i that looks like
extern int group_size;
void do_stuff(int n); extern int group_size;
void do_stuff(int n);
and a source code file main.c
int main(int argc,const char* arg[])
#include "foo.h“ {
int main(int argc,const char* arg[]) group_size = 12;
{ do_stuff(20);
group_size = 12; }
do_stuff(20);
}

Continental Automotive Systems S.R.L


45
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Preprocessor - Examples
#define SQ(n) n*n
#define CUBE(n) n*n*n

Once defined, these macros can be used in code much as you would use any other function.

float f(float x)
{
return 3.2*CUBE(x)-4.2*SQ(x)+10.7*x+3.0;
}

The preprocessor will use a simple text substitution mechanism to replace the code above with
the expanded form of the macros:

float f(float x)
{
return 3.2*x*x*x-4.2*x*x+10.7*x+3.0;
}

Continental Automotive Systems S.R.L


46
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Compiler

Any source code can be compiled or interpreted


• What is the difference between compiler and interpreter?
– Compilers: the source code is translated by a program named Compiler in machine
code, and after that, can be executed
– Interpreters: a program is executed direct from the source code through an interpreter
• Any programming language can be compiled or interpreted
– language (development) != implementation of a programming language (Compiler,
interpreter)
• Many programming languages have both compilers and Interpreters: C, Lisp
– GCC (GNU Compiler Collection) - C, C++, Ada, Fortran compilers
– MSVC (Microsoft Visual C) - C, C++ compilers
– CommonLisp – Lisp interpretor

Continental Automotive Systems S.R.L


47
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Compiler

• Traditional compiled languages


– C, C++, Objective-C, Pascal, Java, Ada
• Traditional interpreted languages (scripting languages)
– Perl, PHP, Python, Lisp, Ruby, shell scripting (bash, csh, ksh)
• Advantages / Disadvantages
– Interpreter
• Are in general easily understood by the programmer
• Easy debugging
• Slow execution
– Compiler
• Very hard to debug (an external debugger must be used)
• Fast execution

Continental Automotive Systems S.R.L


48
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Linker

Links the compiled codes of application software, object codes from library and OS kernel
functions.
Linking necessitates because of the number of codes to be linked for the final binary file.
For example, standard codes for to program a delay task, must link with the assembled
codes.
The delay code sequential from a beginning address.
The assembly software codes also sequential from another beginning address.
Both the codes have to at the distinct addresses as well as at the available addresses in the
system. Linker links these
After linking, re-allocation of the sequences of placing the codes before actually placement of the
codes in the memory
Linked file in binary for run on a computer commonly known as executable file or simply '.exe'
file.

Continental Automotive Systems S.R.L


49
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 6
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Table of Contents
Embedded software

- Macros

- Memory allocation

- Data initialization

- Stack

Continental Automotive Systems S.R.L


51
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Macros
Macros are very handy for some applications, but do have a couple of downsides. One is that
since a macro is not a true function, using a macro in combination with a debugger can be
frustrating, because unlike a true function you can not step into a macro to see what it is doing.
A second, much more dangerous problem is that macros only provide a simple text substitution
mechanism, which can cause trouble when mixed with precedence rules in a compound
expression. Here is an example of this problem. Suppose we construct a simple macro that
returns its argument plus one:
#define INCR(n) n + 1 The simple fix for this problem is to add parentheses
to the macro definition:
Now consider this piece of example code:
#define INCR(n) (n+1)
return INCR(x)*x;
With this definition the statement
Unfortunately, the simple text substitution
mechanism that macros use will translate this return INCR(x)*x;
statement to
expands to
return x+1*x;
return (x+1)*x; as desired.
which is not the desired result.

Continental Automotive Systems S.R.L


52
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Memory Allocation

The C language supports two kinds of memory allocation through the variables in C programs:

• Static allocation is what happens when you declare a static or global variable. Each static
or global variable defines one block of space, of a fixed size. The space is allocated once,
when your program is started (part of the exec operation), and is never freed.

• Automatic allocation happens when you declare an automatic variable, such as a function
argument or a local variable. The space for an automatic variable is allocated when the
compound statement containing the declaration is entered, and is freed when that
compound statement is exited.

A third important kind of memory allocation, dynamic allocation, is not supported by C variables
but is available via GNU C Library functions.

Continental Automotive Systems S.R.L


53
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Data initialization

In C/C++, an initializer is an optional part of a declarator. It consists of the '=' character followed by an
expression or a comma-separated list of expressions placed in curly brackets (braces). The latter list
is sometimes called the "initializer list" or "initialization list", although the term "initializer list" is formally
reserved for initialization of class/struct members in C++. A declaration which includes initialization is
commonly called definition.
int i = 0;
int k[4] = {0, 1};
char tx[3]="fa";
char ty[2]="fa";
struct point {int x; int y;} p = { .y = 13 , .x = 7 };
Data initialization may occur without explicit syntax in a program to do so. For example, if static
variables are declared without an initializer, then those of primitive data types are initialized with the
value of zero of the corresponding type, while static objects of class type are initialized with their
default constructors.

Continental Automotive Systems S.R.L


54
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
The Stack

Local variables and parameters get stored on the User stack.


The stack is a flexible data structure that grows and shrinks as
functions are called and the program returns from those
functions.
The basic structure of the stack is a list of stack frames, with
one frame for each function that is currently active. At the base
of the User stack is a stack frame for the application's main
function, with storage set aside for each of the local variables in
main. Each time that program execution enters a function, a
frame is created at the top of the stack for that function,
providing a place to store the local variables that that function
will need.
Here is a more detailed diagram that illustrates some of the
things you will typically see on the User stack.

Continental Automotive Systems S.R.L


55
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Course 7
Embedded Software

Continental Automotive Systems S.R.L


Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Table of Contents
Embedded software

- Constants

- Pointers

- Functions

Continental Automotive Systems S.R.L


57
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Constants
There are two simple ways in C to define constants:
• Using #define preprocessor.
• Using const keyword.

#include <stdio.h> #include <stdio.h>

#define LENGTH 10 int main()


#define WIDTH 5 {
#define NEWLINE '\n' const int LENGTH = 10;
const int WIDTH = 5;
int main() const char NEWLINE = '\n';
{ int area;
int area; area = LENGTH * WIDTH;
printf("value of area : %d", area); area = LENGTH * WIDTH;
printf("%c", NEWLINE); printf("value of area : %d", area);
return 0; printf("%c", NEWLINE);
} return 0;
}

Continental Automotive Systems S.R.L


58
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Pointers - What Are Pointers?
As you know, every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator, which denotes an address in memory.
What Are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before you can use it to
store any variable address. The general form of a pointer variable declaration is:
type *var_name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Continental Automotive Systems S.R.L


59
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Pointers - How to use Pointers?
There are few important operations, which we will do with the help of pointers very frequently.
•we define a pointer variable
•assign the address of a variable to a pointer and
•finally access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.
Following example makes use of these operations:

#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );


/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}

Continental Automotive Systems S.R.L


60
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Functions
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.

Continental Automotive Systems S.R.L


61
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Functions - Calling a Function
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.

Continental Automotive Systems S.R.L


62
Str. Salzburg, nr. 8, 550018, Sibiu, Romania
Functions - Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
This method copies the actual value of an argument into the formal parameter of the
Call by value function. In this case, changes made to the parameter inside the function have no effect
on the argument.

This method copies the address of an argument into the formal parameter. Inside the
Call by reference function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example while
calling max() function used the same method.

Continental Automotive Systems S.R.L


63
Str. Salzburg, nr. 8, 550018, Sibiu, Romania

You might also like