0% found this document useful (0 votes)
50 views120 pages

Part4 Clang 28 12 2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views120 pages

Part4 Clang 28 12 2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Functions (Subroutines) in C

• main function is the entry point of a C program. There may be functions


called from within main or invoked by event triggers such as interrupt.
• Functions are defined just like variables, but their parameters must also be
defined.
• In C , at least one function is mandatory. It is the main function .
• The main function can call other functions to get certain jobs done . But
others cannot call main function.
• Each function can call another function from within itself. However, they
cannot call theirselves. If functions are not defined globally, they can only be
called by functions in a higher hierarchy.
• The called function inherits control from the caller.

• When the called function completes its work, it returns to the point where
the calling function was called and continues execution to the next
statement .

• The called function may or may not return a value to the calling function .

• main function is called automatically at startup and is the entry point of the
program.

• When main function completes its work, it returns to the operating system .
In embedded systems without OS, there is no return from main .

• Standart C Functions are called characteristic functions. User functions are


created using these functions and expressions.
Defining a function
• A function can take input parameters as well as return values at the output.
• A function return value is defined by the function name and parameters . Parameters are defined in
parentheses and separated by commas .
• int function(parameter1, parameter2,... parameterN )
• This function takes N input parameters , and returns an int value in its output

Sample:
intSum ( int number1, int number2 )
{
return (number1+number2 );
}

input parameters are defined in the line where the function is declared .

If the function is in another file, the header file containing the function proptotype must be included in
the file from which the function is called .
# include < actions.h >

function prototype must be defined in the Islemler.h file. for example


int Sum ( int , int )
# include < stdio.h >
int Sum ( int number1, int number2)
{
return (number1+number2);
}

int main( void )


{
int number1,number2, result ;
number1=1; number2=4;
result =Sum(number1,number2);
printf ("%d + %d = %d \n", number1, number2, result );
return (0 ); // not used in embedded systems. Used if operating system
}
• Some functions may not return values on the output. Such
functions are defined by the void statement.
void infogonder ( char info)
• Some functions may not take any parameters. When defining
such functions, void is written in the parameter part.
int DoWait ( void )
• Some functions neither take parameters nor return values.
void Calculate( void )
Use of special characters
• Some string symbols are used to write instead of some
characters which cannot be expressed directly in functions.
These;

printf ( " Data : % s\n ", Address );


Some ANSI C standard function libraries
• Character Library ( ctype.h )
• Math Library ( math.h )
• standard I/O Library ( stdio.h )
• standard Library ( stdlib.h )
• String Library ( string.h )
• Time Library ( time.h )

Availability of these libraries may differ according to Compilers. Many


functions in the stdio and time libraries are not supported. On the other
hand, some functions are undesirable for optimization reasons.

In order to use the functions in these libraries , header files must be added to the
program with the # include statement .

These files consist of function prototypes, library files, various constants, macros,
variables, and some other preprocessor definitions.
printf function ( defined in stdio.h )
• Although it is not used frequently in embedded system software , the printf function, which we
will use frequently in software training , is used to write the desired information in a defined
format on stdout (standard output unit: console screen in computers, serial port in embedded
systems).
• Syntax : int printf ( Format string , values ...)
• Format String It is a string of characters that specifies how the output and values will be written.
The character string is specified between the " " signs.
• The characters to be written in the character array will be displayed as they are , and some express
how the values will be displayed.
• Field Definitions It starts with the % character . Used to specify the display format of values.
• %[flag][width][.fraction]<format character >
• Flag: If +, numbers are always written with a sign.
• If the sign + is written as +12
• Flag – if the number is specified If less than width , the number is written left justified.
• If the flag is 0 , if the number is shorter than the specified width , it is prefixed with 0 .
• Width is used to specify how long the number will be written in a field. However, if the length
of the value to be written is longer, this value is ignored.
• The length of the fractional part if the number is of type float . is defined with .
The Format Character specifies the type of the variable.

d : decimal integer
x or X: number in hex format
s: strings from given address to all characters up to null character
f: double and float
c : character

{ Program output
Double x =6.265;
İnt y =100;
char *p="DENEME";
printf ("%f \n%5.2f\n / 5.1f\n", x,x,x );
printf ("/05d\n", y );
printf ("%10s\ n", p );
}
Logical data and Operators
• There is no logical data type in C. Int or char can be used for
this .
Data value Logical Meaning
zero (=0 ) FALSE
nonzero (>0, <0 ) TRUE

• Logical Operators
Operator Meaning Example x=0 , result for y= 1
Operand Example Result
-------------------------------------------------------------------------
! (not) !x 1
&& and x && y 0
|| or x || y 1
Manipulating logic values
• C uses the short-circuit method to handle logical expressions .
• For example , if the initial value of an and operation is 0 , it
returns 0 , regardless of the other value .

• Problems of the short-circuit method


x && y ++, if x =1 the y value increases by 1, if 0 the y value does
not.
It is necessary to pay attention to this.
Relational Operators
Operator Meaning Example result for x=10, y=20
< Smaller x<y 1
<= less than or equal x<=y 1
> greater x>y 0
>= greater or equal x >= y 0
== Equal x==10 1
!= Not Equal x!=5 1

 Relational operators are used in decision operations.


 Relational operators need two values to compare.

 is 0 or 1 .
Bit-Based operators
~ inversion
<< shift left
>> right shift
& and

| or
^ Exclusive Or (xor)
~ inversion process
unsigned char x,y ;
x=0x24 ; // is x=36 . In binary it is 0010 0100 .
y=~x; // y would be 1101 1011 , so 0xDB or y=219

Shifting operations
unsigned char x,y ;
x=0x24 ;

y= x<<2 ; // shift two bits to the left bits to the left are discarded enters a 0 from the right. 1001 0000
// added two 0's from the right.
// y = 0x90 . Each bit shift is like multiplying by 2.

y=x >>3; // 3 bit right shift enters 0 from left, right bits are discarded.
// Each bit shift is like an integer division by 2 . It became 00000100 y=4.
& and operation
unsigned char x,y x = 36 . In binary it is 0010 0100 .
; x=0x24 ; If the and operation is done with 0xf0
y= x & 0xf0; (1111 0000), y will be 0x20. with 0 and
its operation becomes 0.
| or process
unsigned char x,y x = 36 . In binary it is 0010 0100 .
; x=0x24 ; If 0xf0 (1111 0000) is used with or, y= 0xf4. With
1 or its operation becomes 1.
y= x & 0xf0;

^ Exlusive or process x = 36 . In binary it is 0010 0100 .


0xf0 (1111 0000) with or
unsigned char x,y
y will be 0xd4. If the special or processed bits are
; x=0x24 ; the same, the result is 0, if different, the result is
1 . Or exor operation with 1 gives the inverse of
y= x & 0xf0; the other bit, exor operation with o gives the other
bit itself.
Examples
• To set bits OR , to clear bits AND and to invert bits XOR operators are used.
• Let GPIOA-MODER = xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx . Where x stands for
0 or 1.
Lets set GPIOA-MODER register 4. and 5. bits
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
0000 0000 0000 0000 0000 0000 0011 0000 =0x00000030
----------------------------------------------------- or
xxxx xxxx xxxx xxxx xxxx xxxx xx11 xxxx

So, GPIOA->MODER |= 0x00000030

However , same operation can be done more understandable


way
GPIOA->MODER |= (3ul << 4)
3 can be written in 32 bit format as follows,
0000 0000 0000 0000 0000 0000 0000 0011
If we shift this number for times left(3ul<<4)

0000
00000000
00000000
00000000
00000000
00000000
00000011
0000
0001
00001000
1100
0000
0110
011

So, GPIOA->MODER |= 0x00000030

GPIOA->MODER |= (3ul << 4)

Similarly, if we want to clear 4. and 5. bits, we do the


following.
GPIOA->MODER &= ~(3ul << 4)

Here 0000 0000 0000 0000 0000 0000 0011 0000 = (3ul<<4)
1111 1111 1111 1111 1111 1111 1100 1111 =~(3ul<<4)

xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx


1111 1111 1111 1111 1111 1111 1100 1111 =~(3ul<<4)
-------------------------------------------------- and
xxxx xxxx xxxx xxxx xxxx xxxx xx00 xxxx
y=(( (0x24<<1) & 0xaa) | 0x22) ^ 0x18;
What is the result of your
operation?
Example: program to display a given decimal number in
binary

#include <stdio.h>
unsigned short sayi,sayac,vesayisi;
int main(void)
{
printf("lutfen ikili olarak gösterilecek sayıyı giriniz:");
scanf("%d",&sayi);
printf("\n%d (0x%x Hex) sayisinin İkili karşılığı:",sayi,sayi);
vesayisi=0x8000; //1000 0000 0000 0000
for (sayac=16; sayac>0;sayac--)
{
if (sayi & vesayisi) printf("1"); else printf("0"); vesayisi=vesayisi>>1;
}
printf(" dir.\n");
}
}
Question : Please convert a given decimal to a 4-digit hexadecimal
number.
two-way selection

If the result is
zero If the result is 1 ( true )
actions to be taken. Actions to take.
if .... else decision command
if (decision statement)
If there is only one statement, there
{ // actions if true is no need for block initializers { }
expressions

else

{ // actions to be taken if false

expressions

}
if (a==5) y=x+2; else y=x-2;

If it is wrong, the actions to be taken part do


not have to be used.

if (a==5) y=x+2;
if .... else decision command:
Examples , Compound expressions
if (a!=b) Compound statements are
processed as a single
{ statement.
x++; y–- ;
printf ("xy : % d\ n", x -y);
}
else else part if needed
used.
{
x--; y++ ;
printf ("xy : % d\ n", x -y);
}
Complementary if … else

if if
(!statement) (statement)
{ {

... ...

} }

else else

{ {

... ...

} }
Nested if - states

Using more than 3 will reduce readability.

Sample:

if (a==b) y=x+1; else

if (a>b) y=x-1;

else if (y==x) result =1; else result =0;


Example work : Numbers game : +/- game
• Game of finding a randomly generated number in the system. A randomly
generated number does not have the same digit value in any digit. The
number can start with 0 and has 4 digits.
• The similarity of the guessed number is indicated. If the given number and
the digit in each digit of the hidden numbers are the same, + is expressed as
the number of similar digits , if same digit number exists but not in the
same digit ,it – is expressed for each digit.
• Example :
• if Secret Number is 6410 and guessed number is 1475, Result of the
software will be as +1, -1.
• Because 4 exists in the secret number and it is at the same digit. This
makes +1
• Because 1 exists in the secret number and but it is not at the same digit.
This makes -1
• The other numbers not exist , so they will be zero.
• For same number the result will be +4
Multi-Path selection
 Multi-Path selection methods allow us to choose for more than
two alternatives.
 C has two methods for multi-path selection:
– switch expression
– else- if (non-nested if statements)
• switch The expression can only be used for integer types or
character types. Otherwise, else – if method should be used.
switch function
switch (value) *Each case is determined by a
constant that the value can take,
{ a : must be placed after the
constant.
case constant-1: expressions
•default part does not have to be
break;
used. It only works when no
case constant-2: condition is followed .

expressions • Each case break part


should be terminated with
break;
• If the break statement is not
case constant-N: expressions used , all operations are executed
until the break statement is found
break; or the block is finished .

default :expressions
break;
}
switch example
switch (selection)
{
case 1:printf ("Option 1 selected.\ n"); break; Switch – Case
statements are
case 2:printf ("option 2 selected.\ n"); break; especially important
case 3:printf (" 3rd option selected.\ n"); break; in state-machine
default : printf ("Incorrect option.\ n"); break; programming

If the expressions in Switch – Case are not integer or literal , else- if logic can be
used.

if ( score >= 90 ) grade = 'A';


else if ( score >= 80 ) grade = 'B';
else if ( score >= 70 ) grade = 'C';
else if ( score >= 60 ) grade = 'D ';
e lse grade = 'F';
Loops and Repetitions
 PreTest Loops
 In each iteration , the loop control expression is tested first.
 if true the loop continues
 If wrong the loop ends.

 Post-Test Loops
 At each iteration , the loop action is checked, and then the loop control expression is
tested.
 if true new iteration starts
 If wrong the loop ends.
Initializing and updating the loop
State Controlled Loops
Counter Controlled Loops
 If the number of repetitions is known, a counter-controlled loop is
used .
 The number of repetitions can be a fixed , variable, or calculated
value.
 The counter can count backward or forward .

Count up
counter
example
Loops in C

 while and do … while loops are event controlled


 for loop is counter controlled
While loop

Format Example 1:
while (control statement) // while loop operation that performs a single
operation;

Format Example 2: // more than one transaction


while (control expression) while loop doing
{
process1; transaction2

...
process N
}
for loop
 for loop is a test-before loop.
 Format : for ( expr1 ; expr2 ; expr3 )
process;
 Expr1 is the initial value of the counter.
 Expr2 is the boundary condition
expression of the counter.
 Expr3 is the update expression.
#include<stdio.h>
#include<string.h> // strlen string kütüphanesindedir.
void TumunuBuyukYap(char Bilgi[256]);

void TumunuKucukYap(char Bilgi[256]); //fonksiyon prototipi


void BasHarfiBuyukYap(char Bilgi[256]);
char Adres[256];
int main(int argc, char* argv[])
{
printf("Lutfen Adresinizi Giriniz:\n");
gets(Adres); //klavyeden string dizisi okur. Embedded sistemlerde özel kütüphane oluşturulmalıdır.
TumunuBuyukYap(Adres);
printf("Tumu buyukAdres:%s\n",Adres);
TumunuKucukYap(Adres);
printf("Tumu buyukAdres:%s\n",Adres);
BasHarfiBuyukYap(Adres);
printf("Bas Harfleri buyukAdres:%s\n",Adres);
return 0;
}

void TumunuBuyukYap(char Bilgi[256])


{
int uzunluk;uzunluk=strlen(Bilgi); // 0 raslayanakadar olan karakter sayısı
for( int i=0; i<uzunluk;i++)
if(Bilgi[i]>='a' && Bilgi[i]<='z') Bilgi[i]-=0x20; //ascii32 karakter geriye
}

void TumunuKucukYap(char Bilgi[256])


{
int uzunluk;uzunluk=strlen(Bilgi); // 0 raslayanakadar olan karakter sayısı
for( int i=0; i<uzunluk;i++) if(Bilgi[i]>='A' && Bilgi[i]<='Z') Bilgi[i]+=0x20; //ascii32 karakter geriye
}

void BasHarfiBuyukYap(char Bilgi[256])


{
int uzunluk;uzunluk=strlen(Bilgi); // 0 raslayanakadar olan karakter sayısı
if(Bilgi[0]>='a' && Bilgi[0]<='z') Bilgi[0]-=0x20;
for( int i=1; i<uzunluk;i++)
{
if(Bilgi[i]==' ') {if(Bilgi[i+1]>='a' && Bilgi[i+1]<='z') Bilgi[i+1]-=0x20;i++;}
}
}
For and while comparison
do .... while loop
do .... while loop is a post-test loop .
That is, operations are performed first, then the loop condition is
executed . It's not an overused loop.
Format: Example : When the number entered
is between 10 and 20, the program
Do continues to the next step.

{ do
{
expressions printf (" Enter a number between 10 – 20:");
scanf ("%d", &a );

} } while (a < 10 | | a > 20);

next actions
while (condition statement)
Jump phrases
There are 4 different jump expressions.

• break

• continue

• return

• goto
 break and continue We will examine the statements
 return statement is used to terminate a program, or subroutine.
 goto is not preferred for structured programming. It is an expression of
unconditional jump from any point . It should not be used.
break statement
The break statement causes a loop to end.
• If there are nested loops, it just terminates the current loop.
while (i<10)
{
expressions
...
for (j=0;j<100;j++)
{
expressions
.....
if (a==b) break; // only the for loop is terminated.
}
expressions
.....
}

The break statement can be used for for , while , do .. while . However, in a good
programming style, only switch – case is used.
Pointers
 A pointer value is a variable pointing to an address.
 Pointers have a name, value , and type.
 Pointers with no value have a NULL value (for example , an int variable takes
the value 0, or a char variable takes the value "" ).

 indicated by the value of p and the value of p

24

p
Declaration of pointers
 int * p, p1; pointer of type integer
 char *q; pointer of type char
 double **w; A pointer of type Double pointer pointing

 Here :
 p sizeof ( int ) byte Indicates a data block.
 q sizeof ( char ) bytes Indicates a data block.
 w sizeof ( double *) byte Indicates a data block.
Accessing the content of pointers ( Dereferencing )
 int *p;

 p is a pointer of type int ,


 *p indicates the contents of the memory pointer p.
 *p is like an int variable.

24

p *p
Address Operator
 int i;
 i is a variable of type int
 &i is an int pointer to the variable i .

24

&I I

scanf ("%d",&i); // statement shows the address of i.

either in
int *pntri; pntri=&i;
scanf(“%d”,pntri);
// is anchar
arraytext
of type
[i]; char
address of this directory is indicated with . To write the name of the array
without using the & operator in arrays is to show the address of that array. Or,
in other words, to use it as a pointer.
Example: the scanf function requests the address of the input variables.
Because
scanf (“%s”, text ) is used. Or scanf (“%s”,& text *0+); means the same . Here the
address of the text [0] is shown.
pointer assignments

 int i;
int *iPtr = &i; ?
int j = 3;
int *jPtr = &j; I
iPtr
 What happens to the
following?
3
 * jPtr = * iPtr ;
 i = 4; jPtr j
 * jPtr = i;
 iPtr = j; //incorrect
 iPtr =NULL;
Lab Experiments
• C language Experiments 1 and 2 on PIC16F877A Deney 1 .
• Necessary data can be foud on lab sheets

Experiment 1 Forward and Backward Counter in C language


Experiment This example demontrates the basic operations in C language. Hitech compiler will be
Objective used.

Description • Both Input and Output GPIO will be used.


• Pressing S1 decrease counter and value is displayed in LEDs ON portd
• XT oscillator will be selected , Port A will be used as inputs, PortD will be used as
outputs.
Experiment 2 LCD Driving
Experiment Name Displaying light level and a second timer on LCD
Experiment This example will demontrate how to drive an alphanumerical LCD with HD44780
Objective controller and how to use the ADC
Description • PORTD0 – PORTD3 will be used for 4 bir LCD data bus
• PORT E0- E2 will be used for LCD control signals.
• PORTA will be configured for ADC operation.
• XT oscillator will be selected

/*
* LCD interface example
* Uses routines from delay.c
* This code will interface to a standard LCD controller
* like the Hitachi HD44780. It uses it in 4 bit mode, with
* the hardware connected as follows (the standard 14 pin
* LCD connector is used):
* PORTD bits 0-3 are connected to the LCD data bits 4-7 (high nibble)
* To use these routines, set up the port I/O (TRISA, TRISD) then
* call lcd_init(), then other routines as required.
*/

#ifndef _XTAL_FREQ
// Unless specified elsewhere, 4MHz system frequency is assumed
#define _XTAL_FREQ 4000000
#endif

#include <htc.h>
#include "lcd.h"

#define LCD_RS RE0


#define LCD_RW RE1
#define LCD_EN RE2

#define LCD_DATA PORTD

#define LCD_STROBE() ((LCD_EN = 1),(LCD_EN=0)) //enable ucunu 1 yap, hemen sonra 0 yap.
/* write a byte to the LCD in 4 bit mode */
void
lcd_write(unsigned char c)
{
__delay_us(40); // bu fonksiyonlar htc.h üzerinddn tanımlanmıştır.
LCD_DATA = ( ( c >> 4 ) & 0x0F );
LCD_STROBE();
LCD_DATA = ( c & 0x0F );
LCD_STROBE();
}

/* Clear and home the LCD */


void lcd_clear(void)
{
LCD_RS = 0;
lcd_write(0x1);
__delay_ms(2);
}

/* write a string of chars to the LCD */


void lcd_puts( char * s)
{
LCD_RS = 1; // write characters
while(*s)
lcd_write(*s++);
}

/* write one character to the LCD */

void lcd_putch(char c)
{
LCD_RS = 1; // write characters
lcd_write( c );
}
/* Go to the specified position */
void lcd_goto(unsigned char pos)
{
LCD_RS = 0;
lcd_write(0x80+pos);
}

/* initialise the LCD - put into 4 bit mode */


/* please check Figure 24 4-Bit Interface in HD44780 data sheet */
void lcd_init()
{
char init_value;
ADCON1 = 0x85; // A0 analog giriş, A3 Ref , diğerleri digital
init_value = 0x3;
TRISE=0;
TRISD=0;
LCD_RS = 0;
LCD_EN = 0;
LCD_RW = 0;

__delay_ms(15); // wait 15mSec after power applied,


LCD_DATA = init_value;
LCD_STROBE();
__delay_ms(5);
LCD_STROBE();
__delay_us(200);
LCD_STROBE();
__delay_us(200);
LCD_DATA = 2; // Four bit mode
LCD_STROBE();

lcd_write(0x28); // Set interface length


lcd_write(0xF); // Display On, Cursor On, Cursor Blink
lcd_clear(); // Clear screen
lcd_write(0x6); // Set entry Mode
}
Write the code as below to main.c.

#include <htc.h>
#include "lcd.h"
#include <stdlib.h> // we need this library for C standard itoa function (integer to ascii function)

__CONFIG(0x3ff9);

unsigned int i,j=0;


char buffer[6];
unsigned int x;

void main(void)
{
lcd_init();
GIE=0; // we don't want interrupts
while (1)
{
for (i=0;i<45000;i++) continue; //wait for one sec approximately
j++; //seconds timer
itoa(buffer, j,10); // change value to ascii as decimal

lcd_goto(0); // select first line


lcd_puts("second:"); // write
lcd_puts(buffer); // write seconds value

}
ADC Usage
/************************************************************************/
/* Analog to Digital Converter initialization */
/************************************************************************/
void init_a2d(void)
{
// Right justified reading, Channel 0 Select, Fosc/2 select ADCON0=0;ADCON1=0x85;
ADCON0=0; // select Fosc/2; ADCCON1 =0x5 olmalı
ADCON1=0x85; // A/D port configuration 0
ADCON0|=0x1; // turn on the A2D conversion module
TRISA=0x0f; // make all input
}

/************************************************************************/
/* Analog to Digital Conversion */
/* This function returns 10 bit conversion result for selected channel */
/************************************************************************/
unsigned int read_a2d(unsigned char channel)
{

unsigned int conversiondata;

channel&=0x07; // truncate channel to 3 bits


ADCON0&=0xC5; // clear current channel select
ADCON0|=(channel<<3); // apply the new channel select
ADCON0|=1<<2; // initiate conversion on the selected channel
while(ADCON0 & 0x4 ) continue; //wait until conversion completed
// conversiondatah=ADRESH;
// conversiondatal=ADRESL;
// return(conversiondatal); // return 8 bits data
conversiondata = (ADRESH & 0x3) << 8 +ADRESL;
return (conversiondata);
}
Arm Processor Families Cortex-A73
Cortex-A72
Cortex-A57
Cortex-A53
• Cortex-A Familes(Application)High-performance Cortex-A35
processors capable of providing full Operating System Cortex-A32
Cortex-A17
(OS) supportApplications include smartphones, digital Cortex-A15
TV, smart books Cortex-A9 Cortex-A
Cortex-A8
• Cortex-R series (Real-time) High performance and Cortex-A7
Cortex-A5
reliability for real-time applications; Applications
Cortex-R8
include automotive braking system, powertrain. Cortex-R7

• Cortex-M series (Microcontroller)Cost-sensitive


Cortex-R5
Cortex-R4
Cortex-R
solutions for deterministic microcontroller applications Cortex-M7, Cortex-M23, Cortex-
M33
Applications include microcontrollers, smart sensors Cortex-M4
• SecurCore series for high security applications Cortex-M3 Cortex-M
Cortex-M0+
Cortex-M0
• Previous classic processors including Arm7, Arm9, SC000
Arm11 families SC300 SecurCore
Arm11
Arm9 Classic
Arm7
How to design an Arm-based SoC
• Select a set of IP cores from Arm and/or other third-party IP vendors
• Integrate IP cores into a single chip design
• Give design to semiconductor foundries for chip fabrication

IP libraries SoC
Cortex-A9 Cortex-R5 Cortex-M4 Arm
ROM RAM
processor
Arm7 Arm9 Arm11
System bus Arm-based
DRAM ctrl FLASH ctrl SRAM ctrl SoC
Peripherals
AXI bus AHB bus APB bus

GPIO I/O blocks Timer


External Interface

Licensable IPs SoC Design Chip


Manufacture
Cortex-M4 registers
Register bank R0
R1
R2
R3
Low
R4 Regist
ers
R5
General purpose
R6
register
R7
R8
R9
R10 High
Regist
R11 ers
R12 MSP
Stack Pointer (SP) R13(banked) Main Stack
Pointer
Link Register (LR) R14 PSP
Program Counter R15 Process Stack
(PC) Pointer

Special Program Status x PSR APSR EPSR IPSR


registers Registers (PSR)
PRIMASK Applica Executi Interru
tion on pt
Interrupt mask FAULTMASK PSR PSR PSR
register
BASEPRI
Stack CONTROL
definition
Arm Cortex-M4 Memory Map
0xFFFFFFFF
Reserved for other purposes Vendor specific ROM table
Memory 0xE0100000
512MB
Private peripherals Private Peripheral Bus 0xE00FFFFF External PPB
e.g. NVIC, SCS (PPB) External PPB
0xE0000000
0xDFFFFFFF
Embedded trace macrocell
Mainly used for external
peripherals External device 1GB
Trace port interface unit
e.g. SD card Reserved
0xA0000000
0x9FFFFFFF System Control Space, including
Mainly used for external Nested Vectored Interrupt
memories External RAM 1GB Controller (NVIC)
Internal PPB
e.g. external DDR, FLASH, LCD
0x60000000
Reserved
Mainly used for on-chip 0x5FFFFFFF
Fetch patch and breakpoint unit
peripherals Peripherals 512MB
e.g. AHB, APB peripherals 0x40000000 Data watchpoint and trace unit
Mainly used for data memory 0x3FFFFFFF
e.g. on-chip SRAM, SDRAM SRAM 512MB Instrumentation trace macrocell
0x20000000
0x1FFFFFFF
Mainly used for program code
e.g. on-chip FLASH Code 512MB
0x00000000
Deney 3. STM32F401 üzerinde buton, led ve seri haberleşme kullanımı
Experiment Name Using Uart Interrupt in STM32
Experiment Objective This example shows how to use the Keil environment with STM32 processors and
Nucleo board . Interrupt usage will be demonstrated for USART2. Debugging will also be demonstrated using
STLINK on board debugger/programmer.
Description In this experiment, Only nucleof401 board will be required. With board ,
USART2 port will be used through a virtual com port on STlink . Notice that USART2 is is connected to STLINK
internally. Example will use a Button connected to PC13 and Led Connected to PA5 , UART2 Serial port on
PORTA

Documents are in Lab sheet3

Please remember that printf function use putch function ot fputc in our case. fputc
function is modified in retarget.c file as below to divert stdout to serial port.
ST MICROELECTRONICS MCU's
STM32 ARM CORTEX – M MCU FAMILY
Processor Block Diagram and
pin out
STM32F Memory Map
STM32F4xx Family, Reset and Clock Control
• Three different clock sources can be used to drive the system clock
(SYSCLK):
• HSI oscillator clock (Internal HSI clock %1 max error)
• HSE oscillator clock (External Crystal-Resonator)
• Master PLL (PLL) clock (Used to increase the frequency.)

• The devices have the following two secondary clock sources:


• 32 kHz low-speed internal RC (LSI RC) running independent Watchdog
and,optionally RTC used for Automatic wake-up from Stop/Standby mode.
• 32.768 kHz low-speed external crystal (LSE crystal) optionally driving RTC
(RTCCLK)
• Each clock source can be turned on and off independently when not in
use to optimize power consumption
RCC Block Diagram: Max SYSCLK 84 MHz for
STM32F401

For STM32F401
SYSCLK = 48MHz
HCLK = 48MHz
PCLK1 (APB1) = 12 MHz
PCLK2 (APB2) = 24 MHz External Xtal
connection
Example RCC code for Clock Configuration
Experiment 3. LED, Button and serial port intefacing on STM32F4xx
processors

Experiment Name Using Uart Interrupt in STM32


Experiment Objective This example shows how to use the Keil environment with STM32 processors and
Nucleo board . Interrupt usage will be demonstrated for USART2. Debugging will also be demonstrated using
STLINK on board debugger/programmer.
Description In this experiment, Only nucleof401 board will be required. With board ,
USART2 port will be used through a virtual com port on STlink . Notice that USART2 is is connected to STLINK
internally. Example will use a Button connected to PC13 and Led Connected to PA5 , UART2 Serial port on
PORTA

Documents are in Lab sheet3

Please remember that printf function use putch function ot fputc in our case. fputc
function is modified in retarget.c file as below to divert stdout to serial port.
Using GPIO in STM32F4xx family
• GPIO is general purpose input and output
• STM32 has 6 independent GPIO (GPIOA... GPIOH) each has
configured as 16 pins
• Each GPIO pin can be configured as input or output with
• Pull up, pulldowns for input
• Push pull or open drain for outputs
• To use GPIO pin ; its registers have to be programmed.
important

important
important

important

İmportant

important

important

important

important
Interrupts
• Along with fixed interrupts for standard units, there are
interrupts for peripheral units. Therefore, the number of
interrupts supported varies depending on the peripherals
included.
• Interrupts start at address 0x0000 0004, including the reset
interrupt.
• Nested vectored interrupt controller (NVIC)
• F401
• 52 maskable interrupt channels (not including the 16 interrupt lines of
Cortex®-M4 with FPU)
• 16 programmable priority levels (4 bits of interrupt priority are used)
• F407 , F405, F417..
• 82 maskable interrupt channels for STM32F405xx/07xx and
STM32F415xx/17xx, and up to 91 maskable interrupt channels for
STM32F42xxx and STM32F43xxx (not including the 16 interrupt lines of
Cortex®-M4 with FPU)
• 16 programmable priority levels (4 bits of interrupt priority are used)
Using Interrupts
İnterrupt addresses can be used to use interrupts. However, names defined in the
startup_stm32f401xe.s software are used instead. When an interrupt is activated, program
flow will automatically jump to addresses defined by names. In interrupt procedures, content
storage is created by C in an appropriate way together with the hardwired context saving by
the processor itself.

To enable o disbale
interrupts interrupts and to
set their priorities,
Necessary NVIC structures
and functions are defined in
CMSIS.

NVIC_EnableIRQ(USART2_IRQn)
Etc.

On the other hand, the


necessary registers of the
relevant peripheral units
should also be configured
appropriately.
Interrupt Management
• Interrupt and subroutine call handling are similar.
• The processor automatically performs some operations before
jump to the interrupt address, and this is typically done in 16
cycles.
• These are related to automatic address and content saving for
returning to the interrupted function.
Context saving

Interrupts always
use the main
stack pointer.
The processor
goes into handler
mode.
The Program Counter value assigned from the
vector table depends on which interrupt is
occured.
General Interrupt Control
• CMSIS-CORE API
• Global interrup enable or disable
• void __enable_irq()
• void __disable_irq()

• Individual intterrupt enables and disables are managed by NVIC module.


Necessary CMSIS API'
• NVIC_EnableIRQ(IRQnum),
• NVIC_DisableIRQ(IRQnum)
SysTick Timer
• It is the default timing interrupt on ARM processors, used by the operating
system or for general purposes.
• It is usually set to 1ms.
• It is set as follows using CMSIS.
• SystemCoreClockUpdate(); // if changes have been made to RCC
• SysTick_Config(SystemCoreClock / 1000); // 1ms interrupt and interrupt
Example interrupt initialization code for Usart2

USART2->CR1 |=(uint32_t)((uint32_t)( USART_CR1_RXNEIE | USART_CR1_RE ));


NVIC_EnableIRQ(USART2_IRQn);

Example USART2 interrupt subroutine:


Things to consider when using interrupts
• When writing interrupt routines in the assembler language,
care must be taken to save contents.
• Care should be taken with interrupt timing because it delays
the execution of other codes. For this reason, operations other
than time-critical operations are not included in interrupts.
Operations that uses flexible timings are performed in threads
in the main loop.
• Care should be taken to use volatile keywords to define
variables that are used in main programs but modified in
interrupts.
Serial Port usage in STM32
• There are 6 USART serial ports in STM32F401
MCU
• We'll use USART2 and its interrupt
• USART 2 have to be initialized first
• Baud rate :115200
• 1 Start, 1 Stop, No Parity, No HW flow
control
• Initilalization requires PORTA initialization
• Necessary Clocks in RCC, GPIO and USART
Using ADC (Analog Digital Converter) in
STM32F4xx family
• STM32F4xx family has 12 bits SAR type ADC on it
• ADC resolution is 12 bits which maps analog signal
values to 4096 digital values
• ADC1 has 19 channel multiplexed inputs
• 16 external input channel, 3 internal channels:
temperature, Battery check,
• Input Voltage level can be between 0 to 3.3 Volts
• For modes of operations
• Single
• Continuous
• Scan
• Discontinued
BLOCK DIAGRAM OF ADC
ADC Initialization
• To use ADC several things have to be done
• Enable ADC Using RCC
• Enable Corresponding GPIO Clock (in this example we'll use GPIOC)

• Select desired input pin from GPIO channels using GPIO MODER register (
in this example, We'll select PC0)
• Set appropriate bits to select the pin as analog input
• Configure ADC Registers
ADC Registers in Brief
Enable scan mode
and select
resolution
We'll use SWSTART and
ADON
Set sampling speed to 3 cycles
Select number of channels to 1 by L(3:0) bits
Initialization of ADC
A part of the main application
Arm processor families Cortex-A73
Cortex-A72
Cortex-A57
Cortex-A53
• Cortex-A series (Application) Cortex-A35
Cortex-A32
• High performance processors capable of full
Cortex-A17
Operating System (OS) support Cortex-A15
Cortex-A9 Cortex-A
• Applications include smartphones, digital TV, smart Cortex-A8
Cortex-A7
books Cortex-A5
• Cortex-R series (Real-time) Cortex-R8
Cortex-R7
• High performance and reliability for real-time Cortex-R5 Cortex-R
Cortex-R4
applications;
Cortex-M7, Cortex-M23, Cortex-
• Applications include automotive braking system, M33
Cortex-M4
powertrains Cortex-M3 Cortex-M
Cortex-M0+
• Cortex-M series (Microcontroller) Cortex-M0
SC000
• Cost-sensitive solutions for deterministic
SC300 SecurCore
microcontroller applications Arm11
• Applications include microcontrollers, smart Arm9 Classic
Arm7
sensors
• SecurCore series for high security applications
• Earlier classic processors including Arm7, Arm9,
Arm11 families
How to design an Arm-based SoC
• Select a set of IP cores from Arm and/or other third-party IP
vendors
• Integrate IP cores into a single chip design
• Give design to semiconductor foundries for chip fabrication

IP libraries SoC
Cortex-A9 Cortex-R5 Cortex-M4 Arm
ROM RAM
processor
Arm7 Arm9 Arm11
System bus Arm-based
DRAM ctrl FLASH ctrl SRAM ctrl SoC
Peripherals
AXI bus AHB bus APB bus

GPIO I/O blocks Timer


External Interface

Licensable IPs SoC Design Chip


Manufacture
Arm Cortex-M series family

Arm Core Hardware Hardware Saturated DSP Floating


Processor Thumb® Thumb®-2
Architecture Architecture Multiply Divide Math Extensions Point

Von 1 or 32
Cortex-M0 Armv6-M Most Subset No No No No
Neumann cycle

Von 1 or 32
Cortex-M0+ Armv6-M Most Subset No No No No
Neumann cycle

Cortex-M3 Armv7-M Harvard Entire Entire 1 cycle Yes Yes No No

Cortex-M4 Armv7E-M Harvard Entire Entire 1 cycle Yes Yes Yes Optional

Cortex-M7 Armv7E-M
Harvard Entire Entire 1 cycle Yes Yes Yes Optional
Cortex-M4 registers
Register bank R0
R1
R2
R3
Low
R4 Regist
ers
R5
General purpose
R6
register
R7
R8
R9
R10 High
Regist
R11 ers
R12 MSP
Stack Pointer (SP) R13(banked) Main Stack
Pointer
Link Register (LR) R14 PSP
Program Counter R15 Process Stack
(PC) Pointer

Special Program Status x PSR APSR EPSR IPSR


registers Registers (PSR)
PRIMASK Applica Executi Interru
tion on pt
Interrupt mask FAULTMASK PSR PSR PSR
register
BASEPRI
Stack CONTROL
definition
Arm Cortex-M4 memory map
0xFFFFFFFF
Reserved for other purposes Vendor specific ROM table
Memory 0xE0100000
512MB
Private peripherals Private Peripheral Bus 0xE00FFFFF External PPB
e.g. NVIC, SCS (PPB) External PPB
0xE0000000
0xDFFFFFFF
Embedded trace macrocell
Mainly used for external
peripherals External device 1GB
Trace port interface unit
e.g. SD card Reserved
0xA0000000
0x9FFFFFFF System Control Space, including
Mainly used for external Nested Vectored Interrupt
memories External RAM 1GB Controller (NVIC)
Internal PPB
e.g. external DDR, FLASH, LCD
0x60000000
Reserved
Mainly used for on-chip 0x5FFFFFFF
Fetch patch and breakpoint unit
peripherals Peripherals 512MB
e.g. AHB, APB peripherals 0x40000000 Data watchpoint and trace unit
Mainly used for data memory 0x3FFFFFFF
e.g. on-chip SRAM, SDRAM SRAM 512MB Instrumentation trace macrocell
0x20000000
0x1FFFFFFF
Mainly used for program code
e.g. on-chip FLASH Code 512MB
0x00000000
Bit-band operations
• Bit-band operations allow a single load/store operation to access a
single bit in the memory, for example, to change a single bit of one 32-
bit data:
• Normal operation without bit-band (read-modify-write)
• Read the value of 32-bit data
• Modify a single bit of the 32-bit value (keep other bits
unchanged)
• Write the value back to the address
• Bit-band operation
• Directly write a single bit (0 or 1) to the “bit-band alias
address” of the data
• Bit-band alias address
• Each bit-band alias address is mapped to a real data address
• When writing to the bit-band alias address, only a single bit of the
data will be changed
Cortex-M4 endianness
• Endian refers to the order of bytes stored in memory
• Big endian: lowest byte of a word-size data is stored in bit 0 to bit 7
• Big endian: lowest byte of a word-size data is stored in bit 24 to bit 31
• Cortex-M4 supports both little endian and big endian
• However, endianness only exists in the hardware level

Address [31:24] [23:16] [15:8] [7:0] [31:24] [23:16] [15:8] [7:0]

0x00000008 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 3 Word 3

0x00000004 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 2 Word 2

0x00000000 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 1 Word 1

Little endian 32-bit Big endian 32-bit


memory memory
Some tips on embedded systems
• Fractional numbers should not be used as much as possible. They are not
effective in terms of location and speed. They limit the speed, especially in
multiplication and addition operations at high speeds.
• If not needed, stdio etc . libraries should not be used. They reduce efficiency
in terms of space and speed.
• pointers provides advantages, but should be used with caution.
• cpp Software like checker prevents critical errors. Spell checking systems
such as MISRA can be used for secure software . But writing will be difficult.
• Options for code optimizations should be well evaluated.
Fixed and dynamic memories, heap
• Fixed or dynamic memory can be defined for memory usage in processors.
• Fixed definition int memory[2048] ; // 2K memory. A fixed place in memory
is made available at compile time.
• Dynamic memories: Can be turned on and off at runtime. For this, functions
such as malloc , calloc and free in c are used.
• These are used from the field set as heap . STM32 can also be set from the
startup_stm32f401xe.s file.
• Stack size is also set in the same file.
state machine programming and examples
• A state machine is a programming architecture that allows dynamic flow to
states depending on values from previous states or user inputs
• it can be useful if dynamic behavior required in the same process
• it is also helpful to make multitasking applications without any OS.
• state machine mostly switch for programming The case structure is used.
Switching is made to the next state according to the state of the switch.

sampl
e
Ping – pong ( double buffer ) and ring buffers _
• Buffers of this type are used if there is constantly flowing information and this
information is processed at certain time intervals or is processed in blocks.
• ping pong Double memory regions are used in buffers . One is processed while the
other is filled.
• circular buffers, there is a read and write pointer on the buffer . When the end of the
buffer is reached, the write or read pointer returns to the beginning.

ping pong
buffer

circular buffer In this case, two pointers are


used, one for writing and one for reading.
Tasks called by polling method in Main and circular buffer usage

You might also like