Part4 Clang 28 12 2023
Part4 Clang 28 12 2023
• 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 .
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 >
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 .
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;
0000
00000000
00000000
00000000
00000000
00000000
00000011
0000
0001
00001000
1100
0000
0110
011
Here 0000 0000 0000 0000 0000 0000 0011 0000 = (3ul<<4)
1111 1111 1111 1111 1111 1111 1100 1111 =~(3ul<<4)
#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
expressions
}
if (a==5) y=x+2; else y=x-2;
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
Sample:
if (a>b) y=x-1;
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.
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
Format Example 1:
while (control statement) // while loop operation that performs a single
operation;
...
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]);
{ do
{
expressions printf (" Enter a number between 10 – 20:");
scanf ("%d", &a );
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 "" ).
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;
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
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
/*
* 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_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();
}
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);
}
#include <htc.h>
#include "lcd.h"
#include <stdlib.h> // we need this library for C standard itoa function (integer to ascii function)
__CONFIG(0x3ff9);
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
}
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)
{
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
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.)
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
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.
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()
• 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
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-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
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