CS计算机代考程序代写 cache assembly Java data structure compiler DT131B Embedded Systems Programming

DT131B Embedded Systems Programming
Course Review (Parts 1 and 2)
Dawit Mengistu (dawit.mengistu@hkr.se)

What is an Embedded System?
• Aspecialpurposesystemdesignedto perform a few dedicated functions.
• Doesnotexistprimarilytoprovidestandard computing services to a user, designed to perform one or a few dedicated functions
• Containsacomputerthatisnotvisibletothe user, as part of a larger system
• Hasoftenreal-timecomputingconstraints.
• Usuallycontainssensorsandactuators.

Review: Embedded Systems Arichtecture
Display
Information Processing System
A/D-converters sample-and-hold
D/A converters
Actuators
Sensors Environment Temp, pressure, etc
3

Review: Embedded System Architecture
Micro controller
I/O Unit
Peripherals
Memory
Program
Data
CPU
Comm I/O 123

Digital I/O 123

Comm Unit (BT, WiFi, LAN…)
Sensors 123

ADC 12 …
Human Interface
Display
Timers
Actuators 123

Remote

Required Attributes of Embedded Systems
• Reliability
• Real-timeoperation
• Performance(codeandresourceefficiency) • Energyefficiency
• Physicalsizeandweight
• Cost
• Maintainability
• Safety,security,etc.

Architecture & Organization
• Architectureisthoseattributesvisibletothe programmer
– Instruction set, number of bits used for data representation, I/O mechanisms, addressing techniques.
– e.g. Is there a multiply instruction?
• Organization is how features are implemented
– Control signals, interfaces, memory technology.
– e.g. Is there a hardware multiply unit or is it done by repeated addition?

Architecture & Org’ (cont’)
• AllIntelx86familyprocessorssharethesamebasic architecture but may have different organization
• Organizationdiffersbetweendifferentversions – Memory technologies
– CPU structure
– Address and data units, etc.
• Similarityanarchitecturecansupportcode compatibility
– At least backwards

Functions
All computer functions are:
• Data processing • Data storage
• Data movement • Control

Components of a Computer
• The Central Processing Unit: Consists of: – ALU,
– Registers and – Control Unit
• Input/output:Dataandinstructionsneedtogetinto the system and results out.
• Mainmemory:Temporarystorageofcodeand results is needed

Computer Components: (cont’)

The Instruction Cycle
Two steps:
• Fetch
• Execute
Fetch What?
• Instruction(Opcode) • Data(operand)

Registers
• CPU must have some working space (temporary storage) called registers
• Numberandfunctionvarybetweenprocessor designs
– Some registers are visible to the programmer, others are not.
– Some registers can be modified by code, others can only be read from.
• Toplevelofmemoryhierarchy
How many memory levels? (L1, L2, L3??)
12

User Visible Registers
• GeneralPurpose
• Data
• Address
• ConditionCodes(status)
A computer’s architecture is usually defined by:
• Thenumberandtypesofregisters;
• The data size of each register
• Theoperationsallowedontheregisters
13

AVR Architecture
Registers: Two types of registers
General Purpose Registers
32 general purpose registers having storage capacity of 8-Bits Named as R0,R1,R2 to R31.
Register 0 to 15 & 16 to 31 are different.
Can store both Data & Addresses.
SPECIAL Purpose Registers: Three registers Program counter
Stack Pointer Status Register

AVR Architecture
Pointer Register
Three 16-bit address registers pairs of registers 26 to 31 have extra meaning in AVR assembly.
X (r27:r26), y (r29:r28), z (r31:r30).
Pointer
Sequence
X
Read/Write from address X, don’t change the pointer

AVR Architecture
Status Register (SREG) that contains
It is 8-bit long each bit has a different meaning.
I: Global Interrupt Enable/Disable Flag, SREG7
T: Transfer bit used by BLD and BST instructions, SREG6 H: Half Carry Flag, SREG5
S: For signed tests Instruction Set, SREG4
V: Two’s complement overflow indicator, SREG3
N: Negative Flag, SREG2
Z: Zero Flag, SREG1
C: Carry Flag, SREG0
(More on this later)
I
T
H
S
V
N
Z
C

AVR Register Architecture
Example:
How to tell the machine to perform addition such as 5+6?

AVR Memory Architecture
Memory:
There are two separate memories
Program Memory (Flash Memory)
Data Memory

The Memory Unit
ROM vs RAM: • Differences • Purposes
9

SRAM v DRAM Summary
• Bothvolatile
– Power needed to preserve data
• Dynamiccell
– Simpler to build, smaller
– More dense
– Less expensive
– Needs refresh
– Larger memory units
• Static
– Faster
– Cache
15

I/O Modules: Functions
• Control&Timing
• CPUCommunication
• DeviceCommunication • DataBuffering
• ErrorDetection
21

I/O Modules: Challenges
• Wide variety of peripherals
– Delivering different amounts of data – At different speeds
– In different formats
• All slower than CPU and RAM
22

• Human readable/writable – Screen, printer, keyboard
• Machine readable/writable – Monitoring and control
• Communication
– Modem
– Network Interface Card (NIC)
External Devices
23

I/O Mapping
• Memory mapped I/O
– Devicesandmemoryshareanaddressspace
– I/Olooksjustlikememoryread/write – NospecialcommandsforI/O
• Large selection of memory access commands available
• Port mapped (Isolated) I/O – Separateaddressspaces
– NeedI/Oormemoryselectlines
– Supportforlimited,specialcommandsforI/O
24

I/O Module Operation Steps
• CPU checks I/O module device status
• I/O module returns status
• If ready, CPU requests data transfer
• I/O module gets data from device
• I/O module transfers data to CPU
• Variations: Interrupt, DMA, etc. (more about this later)
25

What is an Instruction Set?
• The complete collection of instructions that are understood by a CPU
• Machine Code
• Binary
• Usually represented by assembly codes because machine code is not ‘human readable’
26

Elements of an Instruction
• Operation code (Op code) – Do this,
• Source Operand reference – To this.
• Result Operand reference – Put the answer here
• Next Instruction Reference
– When you have done that, do this…
27

Instruction Types
• Data processing
• Data storage (main memory) • Data movement (I/O)
• Program flow control
28

Types of Operands
• Addresses • Numbers
– Integer/floating point • Characters
– ASCII etc.
• Logical Data
– Bits or flags
29

Simple Instruction Format
30

Number of Operands
• Number of addresses used in an instruction.
• Example:
• A 3 address machine uses 3 addresses – Operand 1, Operand 2, Result
– a = b + c;
– Not common
– Needs very long words to hold everything
31

Number of Operands (cont’)
• 2 addresses : (used in a 2 address machine) – One address doubles as operand and result –a = a + b
– Reduces length of instruction
– Requires some extra work
• Temporary storage to hold some results
32

Number of Operands (cont’)
• 1 address: (used in called 1 address machines) – Implicit second address
– Usually a register (accumulator)
– Common on early machines
33

Number of Operands (cont’)
• 0 (zero) addresses
– All addresses implicit – Uses a stack
– e.g. push a
push b add pop c
–c = a+ b
34

Types of Operations
• Data Transfer • Arithmetic
• Logical
• Conversion
• I/O
• System Control
• Transfer of Control
35

Introduction to C Programming

Reasons for using C
• Portability of code to different architectures
• Access to low level programming
• Availability of standard libraries
• Possibility of mixing with codes in assembly languages.
* (Also, C is a high level language supported by most of our embedded system development environments!)

Pros and Cons
• Pros:
– compiled code runs FAST
– allows low-level device control
– a foundation of the programming world
• Cons:
– strings are tricky/difficult
– awkward conventions (pointers can be difficult to learn)
– requires a compiler (vs interperter)

Overview of C Syntax
 Preprocessor directive  macro
 header file inclusion  Loop constructs
 for, while, do-while, break, continue, label–go;  Conditional statements
 If, else, else if, switch, break
 Function definition
 return type, parameter definition, parameter passing  Standard library and function calls

Preprocessor Directives
• #defineisusedtogiveameaningfulnametoa constant in your program.
E.g. #define rpm 1500;
• #ifdefallowsasectionofaprogramtobe compiled only if the specified parameter has been defined, no matter what its value is.
E.g. #ifdef rpm //if rpm is already defined #define vcc 5 // vcc will be replaced
#endif

Preprocessors (cont’d)
• Isatranslationphasethatisappliedtosourcecode before the compiler proper gets its hands on it.
• Performstextualsubstitutionsonsourcecode,in three sorts of ways:
– File inclusion: inserting the contents of another file into your source file, as if you had typed it all in there.
– Macro substitution: replacing instances of one piece of text with another.
– Conditional compilation: Arranging that, depending on various circumstances, certain parts of your source code are seen or not seen by the compiler at all.

Pointers
• A pointer is a variable that points at, or refers to, another variable.
• Indirection: the situation when one variable refers to another.
• Declaring a pointer: int *ip;
• Setting a pointer variable to point to another variable as a two-step process: first we generate a pointer to that other variable, then we assign this new pointer to the pointer variable.

Pointers (cont’d)
• Pointers(thatis,pointervalues)aregeneratedwith the “address-of” operator &, which we can also think of as the “pointer-to” operator.
• E.g.declareandinitializeanintvariablei,andthen set ip to point to it:
int i = 5; ip = &i;

Memory Allocation: malloc()
• Themalloc()functiongivesasmuchmemory requested of a certain data type if available. Otherwise, it returns a null pointer.
• The programmer can first test the result of the allocation operation before using the previous code.
• Themallocfunctionisdeclaredinstdlib.h

Freeing Memory
• Memory allocated with malloc() lasts as long as you want it to.
• It does not, however automatically disappear when a function returns, as local variables do. (This is true even if p is a local variable. )
• Dynamically allocated memory is deallocated with the free
function.
• If the variable p is a global variable or will otherwise stick around for a while, to be sure that it’s not used any more (by mistake) would be to set it to a null pointer:
free(p);
p = NULL;
free(p);

Reallocating Memory
• A programmer is not sometimes sure at first how much memory he will need.
• The realloc() function gets a new size of memory to an old variable.
• Inthefollowingexample,amemoryfor100integers was previously allocated to p. To store additional 100 integers,
int len = 200;
p = realloc(len * sizeof(int))
• Whatiftherequestedmemoryisnotavailble?
• (Again,unpredictableresults!)

Basic Input – Output in C
• Many (not all) input output functions are declared in . Allows to
– display text on the standard output device (usually screen).
– Read characters from standard input device (usually keyboard).
– ….

File Processing in C
• Like in Java, create a file stream via a pointer variable (file handle) as follows: (remember, in Java FILE is an object)
FILE *p;
• fopen ()- open a file- specify how its opened (read/write) and type (binary/text)
• fclose() – close an opened file
• fread() – read from a file
• fwrite () – write to a file
• fseek()/fsetpos() – move a file pointer to somewhere in a file.
• ftell()/fgetpos () – tell you where the file pointer is located.

File Open Modes
“r“: Opens a file for reading (from its beginning). The file must exist.
“w“: Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
“a“: Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
“r+“: Opens a file to update both reading and writing (from its beginning). The file must exist.
“w+“: Creates an empty file for both reading and writing.
“a+“: Opens a file for reading and appending.

Example
FILE *fp; int len;
fp = fopen(“myfile.txt”, “r”); if( fp == NULL ) {
printf (“Error opening file\n”);
return(-1); }
fseek(fp, 0, SEEK_END); len = ftell(fp); fclose(fp);
printf(“Total size of file.txt = %d bytes\n”, len); } return(0);
Result: Total size of file.txt = 27 bytes
#include int main () {

File Access
scanf(): Reads data from
the stream and stores them according to the parameter format into the locations pointed by the additional arguments.
fscanf (fp,“format specifier”,identifiers);
Example: FILE *fp; fp=fopen(“myfile.txt”, ”r”);
int i; int X[10]; For (i=0; i<10; i++) fscanf (fp,“%d",&X[i)]; fprintf() sends output to a file. The first argument is a pointer to file. Previous content of file are overwritten. Example: int i = 12; float x = 2.356; char ch = 's'; FILE *fp; fp=fopen(“out.txt”,”w”); fprintf (fp, "%d %f %c", i, x, ch); File Access (cont’d) Reading a character - fgetc() identifier = fgetc (file pointer); Example: FILE *fp; fp=fopen(“myfile.txt”,”r”); char ch; ch = fgetc (fp); Writing a character - fputc() Similar to fgetc(), but used for write operations. Writes a single character to the output file, pointed to by fp. Example: FILE *fp; char ch; fputc (ch, fp); to read a single character from a Usage: Used file. End of File • For text files, the end of file (eof) is marked by the symbol ^Z (ASCII 26) • Useful with read operations to know if the end of file is reached. Usage: 1. Using feof(): if (feof(fp)) { printf("\n End of file reached."); } 2. Using the predefined macro EOF. if(fgetc(fptr1)==EOF) { printf ("End-of-file reached.\n”) ; } Struct Data structures in C • Aggregate in that they hold multiple data items at one time • named members hold data items of various types • like the notion of class in Java • but without the data hiding features • C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.  Cannot be compared using == (rationale: too inefficient) Structure Declarations • Combined variable and type declaration struct tag {member-list} variable-list; • Any one of the three portions can be omitted struct { int a, b; char *p; } ds; – ds declared with members as described: int members a, b and char pointer p. typedef struct { int a, b; char *p; } ds; – ds is a new data type with members as described. Member access • Directaccessoperators.m – subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for arrays. E.g.sam.pets[0].species • Indirectaccesss->m:equivalentto(*s).m
– Dereference a pointer to a structure, then return a
member of that structure
– Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m
(*pet.owner).name or pet.owner->name

struct COST { int amount;
char currency_type[2]; }
struct PART { char id[2];
struct COST cost;
int num_avail; }
layout of struct PART:
currency_type
num_avail
Memory layout
amount
cost
id
Here, the system uses 4-byte alignment of integers, so amount and num_avail must be aligned
Four bytes wasted for each structure!

Bit Fields
• Ifspaceisaseriousconcern,youcanselectthe number of bits used for each member
struct CHAR { unsigned ch: 7; /*Bit field members must be ints */
unsigned font: 6;
unsigned size: 19; };
This won’t work on machines with 16-bit ints
Layout possibilities (machine-dependent):
ch
font
size
size
font
ch
(this does not work on machines with 16-bit int)

Unions
• Like structures, but every member occupies the same region of memory!
– Structures: members are “and”ed together – Unions: members are “xor”ed together
union VALUE {
float f;
int i;
char *s;
};
/* either a float xor an int xor a string */
59