EMBEDDED SYSTEMS STUDY GUIDE

¡Supera tus tareas y exámenes ahora con Quizwiz!

Arrow operator

"->" Dereference operator is a prefix (e.g. *thisPtr) So, (*thisPtr).member is a bit verbose Arrow Operator equivalent to dereference and member access thisPtr->member == (*thisPtr).member

What is information?

"Any entity or form that provides the answer to a question or resolves uncertainty"

What does Shannon's theorem mean for sampling a given frequency?

"If a function x(t) contains no frequencies higher than B hertz, it is completely determined by giving its ordinates at a series of points spaced 1/(2B) seconds apart." If a sampling rate is 2 times faster than fastest analog signal, the original signal can be reconstructed from the sampled signal

What is the compilation flow?

(Pre-processor, compiler, assembler, linker)

I2C (Inter-Integrated Circuit (I-squared-C))

- Address-based 2-wire communication interface - has only 2 data lines - Uses addresses to specify which chip listens - Address is 7 bits followed by a write bit - Write bit specifies if action is to read or write at register address

Linker

- Combines all object files and resolves addressing issues

What is a sensor? What type of signal typically comes out of a sensor (i.e. analog or digital)

- Component that measures physical phenomena Usually provides an Analog signal - Need to convert to digital Raw analog signals carry information Signal processing enables understanding of that information

Sampling?

- Converting Analog to Digital Values

Initial State

- Defines the behavior of the system on startup Initializes variables, sets outputs, prepares for input - Typically depicted as S0 or with external arrow pointing in

What is signal bias? How do you remove signal bias?

- Signal average is not centered at center of ADC value i.e. For ADC with range [-1,1], if ˆx != 0, biased in some direction For periodic signals (e.g. Alternating Current) removing bias often referred to as removing the DC (Direct Current)

What is a sample?

- Single Measurement in time

Test Vectors

- input combinations for testing Test each of the state transitions at least once Make sure border cases are represented Include additional test vectors of each type

What is a Task Control Block?

- structure containing tasks/processes

Gain

1 - buffer

What is scheduling? Name 2 and explain advantages/disadvantages for RTOS

Arrange to plan to take place at a particular time" Scheduling (Computing) - "Method by which work specified is assigned to resources to complete the work"

UART (Universal Asynchronous Receiver-Transmitter)

Asynchronous - No shared clock Data transfer is unidirectional Transmission Speed - Usually given in baud (bits per second) Receiver & transmitter have foreknowledge of transmission speed Data frame - Data transferred byte-by-byte Each frame is bordered by start & stop bit(s)

Serial Interfaces

Bits transferred one after another

Black Box vs. White Box

Black-box testing - Only check for valid output from test vector White-box testing - Examine proper state transitions & internal variables during operation White-box testing more likely to find issues Requires higher overhead in developing test mechanisms

Concurrent State Machines

Block Diagram - Used to demonstrate systems composed of concurrent SMs Each state machine has its own set of states (including initial state) Each state machine controls separate output

Dynamic Memory

C allows allocation of dynamic memory during execution Useful for: • Allocation of arrays • Allocation of memory to hold data in structures

AtoI

C function to convert from ascii to integers

Why is C the most predominant language?

C/C++ are built into development environments and compilers, industry standard, not likely to go away!

What is the most predominant language for embedded systems?

C/C++ are still the dominant languages

What are two philosophes for RTOS design?

Event-Driven - Context switch on event of higher priority • Time-Sharing - Context switch on regularly clocked interrupt

What is the trade off between precision and speed of an ADC? Why are they inversely related?

For instance, while you can get successive approximation ADCs that range from 8 to 16 bits, you won't find the 16-bit version to be the fastest in a given family of parts. The fastest flash ADC won't be the 12-bit part, it will be a 6- or 8-bit part.

Attenuator

Gain < 1

Variable Quantifiers - register

Hint to compiler that a variable will be used frequently Compiler free to ignore the hint "&" operator does not work with these variables Why? If ignored, variable equivalent to an "auto" except the "&" operator will not work Rarely used - modern compilers do better optimization

Application specific

How is the functionality different than PCs? • Implements specific functions • PCs are general purpose Performance? • Must meet real time constraints (e.g. brakes need to activate) • PC - can handle delay or crash Operation? • Processing in response to input stimuli • PC - processing in response to human/batching

How are an array identifier and a pointer to a block of memory different?

Identifier name points to first element Pointer points to any element

Pointer Arithmetic

Incrementing a pointer increments by sizeof(objectiveType)

How do interrupts enable event-driven programming constructs?

Interrupt Event - What triggers the interrupt • Interrupt Request - Flag set in register asking for handling

How does it affect the utilization calculation?

Jitter + Multitasking + Hyperperiod can cause potential missed deadlines

Can you explicitly set an enum variable as an integer that is outside the normal range?

Unfortunately yes... enum MONTHS = {JAN=1,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC}; enum months thisMonth; thisMonth = AUG; //ok, thisMonth=8; thisMonth = 42; //unfortunately, also ok

What is definition?

allocates memory • Amount depends on variable type

What does typedef?

can be used to give new name to existing type EX: typedef unsigned int my_type; my_type this_variable=5;

Give an example of a non-embedded system

computers, mobiles, tablets

Counters

count arbitrary signal changes

Timers

count clock cycles

What is a scheduler?

determine what tasks should run Tasks in TCB ready queue are selected based on scheduling algorithm

What is a signal?

functions conveying information about behavior or attributes of some phenomenon"

Name ways an RTOS is different than a desktop OS.

has time constraints that must be met Hard Real-Time - Unmet condition = System Failure • Soft Real-Time - Unmet condition = System Degradation • Firm Real-Time - Degradation leading to failure

Write a line of code that declares, defines, and initialized a variable:

int example2 = 5; //def. decl. and init.

Sequential Code in a SM

k can be considered as a single state SM with a self-transition Block needs to run to completion in the given time-period

Objective type

type of variable pointed at

Border cases

which are fringe or extreme cases such as all inputs being 0s and all inputs being 1s, and then various normal cases

Applications of PWM:

• Sensor output • Servo Input • LED dimming • Power Delivery

Quantization error?

- Difference between measured value and discrete value

Dispatcher?

- Gives control of CPU to process selected by scheduler Also handles interrupts Must: • Switch Context • Call function for new task

What is measurement error?

- Instantaneous value measurement error e.g. Voltage measurement within ± 0.05V

Parallel Interfaces

- Many binary signals to represent word-length values - D0-D7 represent a single byte to be transferred

Aliasing Error?

- Missing signals by sampling too slowly

What is the internet of things?

- Network of devices, and connectivity to interact & exchange data

What is the value of a const that is not explicitly initialized at declaration?

0 • const float PI; //valid, PI = 0

Successive approximation algorithm

1. Compare against half of range 2. Continue narrowing until limited by LSB 3. Error upper bounded by 1 LSB • Assuming value just less than next LSB, and no nearest bit comparison

What is the maximum value of an unsigned char?

A char is stored in 1 byte 256?

What is an Analog to Digital Converter?

A2D/ADC/(A/D), A to D - Device to convert physical quantity (voltage) to a discrete (digital) value

TDMA

Advantages • Nodes only need to listen during frame - save power • Guaranteed no collision Disadvantages • Lower Throughput - A node may not need to use their frame

Difference between Analog and Digital signals

Analog - Continuous in time and amplitude Digital - Discrete in time and amplitude

There are 6 Variable Quantifiers:

Auto, Register, Extern, Static, Volatile, Const

What is entropy? How does entropy relate to signal processing?

Average amount of information produced by stochastic source of data

What are some advantages of interrupts over software flags?

Avoid writing code that must frequently check status of pins/flags Polling = "busy wait" - CPU executes executions waiting for an event Example: while(!Timer1CompareFlag); //Wait for Timer1 to match

What is the difference between a string and a char array?

C doesn't have a "string" type Implemented using char arrays & "string literals" To be a "string", a char array must be null terminated • char string1[] = "hello world!"; • char string2[] = {'h','e','l','l','o',' ','w','o','r','l','d',' !','\0'}; • char string3[5] = "hello"; //Error: 6 characters in string literal • char string4[10] = "hello"; // "hello\0\0\0\0\0

What are advantages/disadvantages of each of those technologies?

CSMA Advantages • Low latency if channel is not busy • No need for centralized control Disadvantages • Busy channel causes many collisions - low throughput & high energy waste

Polling vs Interrupt Flag

Can poll from register & read value while(COUNTER_REG < VALUE); Can be used to perform timer-polling based delay Reasonable & predicable accuracy compared to software delay Especially useful when other actions are being performed (e.g. tick functions)

What is an interrupt service routine (ISR)?

Code executed to handle the interrupt event

What is an actuator?

Component with in input that converts input to energy e.g. • Servo - Kinetic Energy • LED - Light Energy • Thermal - Heating elements

What is the relationship between interrupts and tasks for concurrent FSMs?

Concurrent tasks - Tasks executed during same time window How did we implement concurrency? State machines with different tick frequencies

Compiler

Converts (nearly) machine independent C code to machine dependent assembly code

What is a mixed-signal transform?

Converts analog signal to digital signal DAC is also a mixed-signal transform - converts digital to analog

What is a Kernel?

Core" OS functions • Perform Scheduling - Handled by scheduler • Dispatch Processes - Handled by the dispatcher • Facilitate inter-process communication Must structure tasks to pass between scheduler/dispatcher/OS

Capture Register

Dedicated hardware for capture time of event When external event occurs, counter register value latched to capture register

What is jitter?

Delay between time task was ready & when it starts executing

Differences from desktop programming?

Differences from desktop programming: • Input/Output • Math • Memory and Hardware • Code Development

Analog/Digital

Digital - Discrete, discontinuous representation of information i.e. [..., -100, -99, ..., 0, 1, 2, 3, ..., 100, 101, ...] Contrasted with Analog - Continuous signal i.e. Soundwave Digital can be used to approximate analog signals Some loss of precision

Difference between continuous and discrete

Discrete data can take on only integer values whereas continuous data can take on any value.

Software Timer Extension

Effective timer/counter range can be extended using software and the overflow bit Example: count 10.5 *max counter • Start counter, value = 0 • Counter overflows (overflow bit set) • Software detects overflow, increments value resetsoverflow flag • Value reaches 10, ISR set on compare register • Counter hits 1 2 max, interrupt occurs

Pulse Width Modulation

Encoding message through pulsing signal

State Declaration

Enums are useful for defining states e.g enum elevatorStateList = {E INIT STATE, BUTTON PRESSED, ...} These labels are descriptive, can be used for switch statements in Tick function

What is thread reentrancy? What is thread safe?

Function can be interrupted in exeuction and run again (re-entered) before previous invocations complete Other threads or processes can run safely at same time. For single core, a different task can preempt and execute fully with no effect on other tasks

Amplifier

Gain > 1

Greatest Common Divisor

Good choice for tick frequency e.g. 1 second for above example

Compare Register

Hardware for control-defined comparison Detect if counter <, >, or == compare register Can: • Trigger interrupt • Set flag for polling • Drive changes on external pins • Reset counter register

Debouncing

Imperfect contact can create "glitches" Use delays to verify signal is steady

Event-Driven

Input events drive programs/threads Typically a main loop that listens for events, and calls "callback" function when event is detected Can be implemented using hardware interrupts

What is interrupt priority?

Interrupt events can co-occur Especially when waking from a sleep mode

Queues & Volatility

Interrupts may disrupt push/pull operations and corrupt data items DisableInterrupts() - Prevent the current operations from being interrupted Should be only the critical portion of code - Called atomicity EnableInterrupts() - Allows interrupts again

What is cross compiling is important?

It's a very useful technique, for instance when the target system is too small to host the compiler and all relevant files. A cross compiler is necessary to compile for multiple platforms from one machine. A platform could be infeasible for a compiler to run on, such as for the microcontroller of an embedded system because those systems contain no operating system.

Signed/Unsigned

Keep up with the signed/unsigned nature of values Representation between systems should be documented to prevent miscalculation This includes type of sign (e.g. Sign bit, one's complement, two's complement)

Variable Quantifiers - extern

Let compiler know of global variable in another file extern keyword is for declaration not definition extern keyword does not create storage Storage must be created with global definition

What are limits to physical sensors?

Limitations: • Range - How wide the physical quantity can be measured • Resolution - How specific can the measurement be • Accuracy/Precision - How close is measured value to actual value • Raw - Typically measuring voltage or other physical quantity that relates to the actual value - Requires processing

What is clipping?

Loss of signal values beyond input range

Name 2-3 wireless technologies for connecting devices

Machine-to-Machine (M2M) Communication - Systems exchange information w/ no user interaction Caller ID (1968) - Phones needed to process analog waveform to exchange identifier Smart Meters & Load balancing (1977) → precursor to smart grid / modern smart meters Cellular M2M (1995) - GSM module "M1" - share data over cellular network Device-to-Device (D2D) - Direct M2M connection without traversing WAN/core network Either cellular or unlicensed spectrum (e.g. WiFi/Bluetooth)

What is dynamic range? How does it differ from signal range?

Measure of the precision of a device w/ respect to range of values it can convert Range = peak-to-peak gap Dynamic range = Ratio of max range to minimum precision of the converter

What is gain?

Multiple that signal is multiplied by

How do you prevent/reduce timer overrun?

Need a construct for detecting timer overruns

Why should ISRs be short & atomic?

No Nested Interrupts, Generally implemented inside a function with no parameters & no return value

Can C functions have overloading?

No, C does not have function overloading Function is fully and uniquely identified by name No method overloading There can only be one main() function in a C application

What is preemptive scheduling vs. non-preemptive scheduling? What are advantages of each? What is a sleep mode? Why would you use a sleep mode?

Non-preemptive - no interrupting Preemptive - interrupts can occur ften have varying wake-up times - jitter overhead Timed events can use timer interrupts to wake from sleep (& account for wake-up)

What is signal underloading?

Not enough gain; ADC not sensitive

What is predictability? Why is it an important metric for RTOS?

OS will complete tasks by deadline Predictability/Reliability more important than speed

Name a way that interrupt priority may be implemented.

Often IVT implemented as list of unconditional jumps at top of program memory

Time ordered behavior

Outputs depend on order of input Many real-world computation challenges involve time-ordered behavior

Why are microcontrollers used for most embedded systems?

Peripheral Loaded • ADCs, DACs, GPIOs, Serial, Timers, etc... Cheap • ∼ $1 for 8-bit processor Low Power • ∼ 300µA operation (AA battery for 275 days) • < 300µA sleep (AA battery for 225 years) Programmable - Usually Assembly, C, C++

Precision

Precision of a number depends on width of the storage(in bits), and the variability of the quantity being measured Going beyond that number causes overflow/underflow

Preprocessor

Prepares file for compiler, handles processing macros, source selection, preprocessor directives, and file includes

What is aliasing noise? What are solutions for removing aliasing noise?

Presence of unexpected signal in the signal path Source of noise if unhandled Example: Car wheel in commercials Two approaches: 1. Sample fast enough to digitally eliminate noise - Overampling 2. Filter higher frequency signal Oversampling is expensive in terms of storage & processing

What is declaration?

Puts the variables name into the namespace • No memory is allocated • Sets identifier and type

What impact does the concept have on Embedded Systems development moving forward?

Real Time Operating Systems (RTOS) and microprocessors and microcontrollers, followed by memory footprints and networking, open source communities and developers.

What does RTOS stand for?

Real-Time Operating System Real Time - has time constraints that must be met

Handshake

Request/Acknowledge pattern with two 1-bit global variables

Voltage Divder

Resistor Sensors - Thermometers, Photoresistors, Force sensors, etc... Measure resistance through two known quantities Derived from Ohm's Law (w/ assumptions)

Measurement Circuits

Sensor manufacturers create elements that have a predictable response to a stimulus These responses modulate a quantity that can be sampled by a digital system Typical quantities: • Resistance • Capacitance • Inductance

Round Robin

Serialization of concurrent tasks is called multi-tasking Execution of each in every period is called "round-robin" task execution

Why is the capture register necessary?

Software driven capture may miss one or more timer counts before reading register

Shared Input/Variables

Some systems require sharing between concurrent tasks Example: Smart Stop Light Concurrent separate state machines: • Camera to detect presence • Stoplight controller Why separate tasks instead of one big state machine? "Separation of concerns" - Let each task take care of its behavior Build system from multiple concerns - Abstract some details when assembling big system

What about multiple intervals?

Some systems will have different interval requirements Choose a tick frequency that is evenly divides into all tasks Example: Stoplight turns Green after 25 seconds, yellow after 20 seconds, red after 4 seconds

SPI (Serial Peripheral Interface)

Synchronous unidirectional master-slave data transfer Master device configures clock, clock polarity, and when communication occurs Data frame - Frame started by a logic 0 on the Source Select line Determines which slave device is to listen Data is transferred bit-by-bit, latched at either rising or falling edges

What is a transform?

Takes input, modifies, & generates output

Queues/Message Passing

Tasks communicate through packets (messages) of data/commands

What is timer overrun?

Tasks have a non-negligible finite execution time If execution time + overhead > tick frequency, can miss deadlines Need a construct for detecting timer overruns

Capture/Convert Process

The process is always the same: 1. Capture - Define the process in terms of an FSM 2. Convert - Represent the FSM through C code 3. Iterate - Any changes that need to made should start at the FSM level, not the C level

Why is header guarding important?

To avoid compiler error - "multiple name definitions" To avoid errors, .h files should be guarded

What is signal overloading?

Too much gain; signal outside range of ADC

What is throughput? Latency? Fairness?

Total network bits-per-second Average time form packet creation to reception Do devices receive equal share of resource (airtime)?

What is an amplifier?

Transform - Multiplies signal by some value

Tasks

Unique continuously executing behavior e.g. • Flashing LED • Sample Sensor Input at given frequency • Refresh LCD Display Concurrent Tasks - Tasks that execute during the same time window

How do you reduce utilization?

Utilization is composed of two factors: • WCET Task Time • Tick Frequency To reduce utilization, one of these factors must change WCET Task Time - Optimize Code or split function into two states Tick Frequency - Decrease tick frequency

Loader

When executed, loads executable into memory

What is the difference between break and continue?

While "break" - Pop out of while loop While "continue" - Jump to end of control block Pressing "Break" temporarily stops program execution and highlights the next statement to execute. Pressing Continue resumes normal program execution.

Know how a successive approximation ADC works

a type of analog-to-digital converter that converts a continuous analog waveform into a discrete digital representation via a binary search through all possible quantization levels before finally converging upon a digital output for each conversion

Mealy Actions

allows actions on transitions as well as on states

What is signal processing?

analysis, synthesis, and modification of signals"

State-Diagram

drawn model of the state machine

Tick Function

executes different set of code depending on current state switch/case statement with enum helps conditional execution Each state will evaluate transition conditions and actions

Variable Quantifiers - static

extends lifetime of variable to program operation May not be accessed outside of declaring file, even if global

What is preempting? What is context? What is context switching?

interrupt a currently executing task To preempt a task: • Save state of process • Save program counter • Save any registers These in total are called the "context" saving of one state and loading another Context switching creates overhead in multitasking/preemption

GPIO (General Purpose Input Output)

is a type of pin found on an integrated circuit that does not have a specific function. While most pins have a dedicated purpose, such as sending a signal to a certain component, the function of a GPIO pin is customizable and can be controlled by software Digital signal pin with behavior definable at runtime Behavior defined by direction (input/output), enabled/disabled, interruptible, state of output (high, low, high-impedance)

Continuous in time/amplitude

known as a continuous-time signal or an analog signal

Actions

modifications to internal variables or outputs on entry to state e.g. S0 turns off LED0, S1 turns on LED0

Prescaling

modifies rate at which timer changes Allow timer/counter to cover larger range

What is utilization?

period of time in use Can be used to predict if timer overrun likely to occur

GPIO Circuitry

provides a clean interface for digtally reading/writing individual pins In Atmel, these pins can be addressed at memory-mapped registers PORTx, PINx, DDxn MSP430 has PxDIR, PxIN, PxOUT, PxSEL Arduino has PinMode, digitalWrite, digitalRead

Quantization

representing a real number in a given number of bits

"Run to completion"/States that wait

sequential block

What is digital signal processing?

signal processing in the discrete domain

What is an interrupt?

signals a request to CPU to handle an event CPU can grant request & jump to separate instruction memory to handle When finished, CPU returns to code running prior to interrupt

const modifier placement

slide 49 in lecture 5

Use pseudocode to demonstrate a basic TCB

typedef struct tcb{ void(*taskPtr)(void * taskDataPtr); //Task function & argument void *taskDataPtr; //Pointer for data passing void *stackPtr; //Individual Task's stack unsigned short priority; //Priority Information struct TCB * nextPtr; //If linked list struct TCB *prevPtr; //If doubly linked list } TCB;

What is one difference between designing for embedded vs non embedded?

• Embedded in a system • Real-time constraints • Resource Constraints • Application Specific

What are potential interrupt sources?

• Input pin change • Hardware timer overflow/compare-match • Serial Peripheral Communication • UART/SPI/I2C - Receive/Transmit Ready/Complete

What is a good strategy for keeping code thread-safe and reentrant?

• Local Variables - only using local variables makes code reentrant

Name three types of processors that may be used for embedded systems

• Microcontrollers (e.g. MSP430, PIC, Atmel) • Digital Signal Processor Controllers • Microcomputers • FPGAs • ASICs

Name 3 common kernel designs for embedded systems

• Polled Loop - Single instruction tests a flag for event • Cyclic Executive - Round robin execution of short processes to give illusion of concurrency • Cooperative Multitasking - Multiple tasks executed in state-driven fashion (code-driven finite state automata) • Interrupt-Driven System - Main program is a single jump-to-self instruction (e.g. while(1);) Short processes executed by ISRs • Foreground-Background - Interrupts do timely processing of external events - Set up process for main program

What are some advantageous traits of RTOSes?

• Scheduling Algorithms supported • Inter-process communication methods • Preempting (time-based) • Separate process address space • Memory protection • Low memory footprint (both RAM and program memory) • Timing precision • Debugging and Tracing

What are some resource constraints for embedded systems?

• Size/Form Factor • Memory Capacity • Disk Capacity • Display • Energy • Environment (vibration, temperature, radiation) • Cost!

What is the difference between hard-real time and soft-real time?

• Soft Real-Time - Failure to meet time constraint = Degraded performance • Hard Real-Time - Failure to meet time constraint = Failure

Freeing only part of data structure

• Deallocates memory pointed to by p • p must point to previously allocated memory free() returns dynamically allocated memory to the heap Freeing NULL pointer has no effect Failure to free() memory is known as "memory leak"

What is one advantage of #define compared to const modifiers?

#define • Pro - no memory is used for the constant • Con - cannot be seen when code is compiled Removed by pre-compiler • Con not real variables, have no type const variables • Pro - real variables with a type • Pro - Can be examined by debugger • Con - take up memory

Testing a pointer

(NULL on return fail) malloc(), calloc(), realloc() return NULL if not satisfied Validate the return value i.e. int* myArrPtr = malloc(10*sizeof(int)); if(myArrPtr==NULL) //DO SOMETHING

Binary

- 0 or 1 - Building block of digital systems Single binary values (bits) linked together to create larger abstractions

How is identifier different from a variable name?

...Identifier particularly names a 'variable, function, structure, enum, class etc'. An identifier distinctly identifies an entity in a program while its execution. Two identifiers cannot have the same name in a program. Variable is a "name given to a distinct memory location". This named memory location contains a value which may be modified while program gets executed. In C, variable must be declared at the beginning of a program whereas, in C++, a variable could be declared anywhere in a program. Variables can be 'local', 'global' or 'reference' . Local variables are declared inside a function; global variables are declared outside a function. Reference variables are those which provide an "alternate name" for the previously defined variable. If a variable is referenced to another variable, both the variables can be used alternately to represent that variable. If a variable accepts the value of an argument in a function, these variables are called 'formal parameter'.

What is header guarding?

A .h file may include other .h files • .h files may be included more than once • Compiler Error - "multiple name definitions" To avoid errors, .h files should be guarded • #ifndef #endif directives around header file Other compiler directives: • #ifdef - if defined • #else • #elif - else if

What is a cross-compiler?

A compiler that runs on one platform but outputs code for another target machine (e.g. Intel compilation of microcontroller code to run on embedded architecture)

What is a microcontroller?

A microcomputer on a single chip. It brings together the microprocessor core and a rich collection of peripherals and I/O capability

itoA

C function to convert from integers to ascii

Macros

C provides macros as an alternative to small functions • More common prior to C99 (inline functions) Handled by preprocessor Inline functions are usually better Macro format • #define NAME(params (if any)) code here • Note: no space b/w name and left paren a process where an identifier in a program is replaced by a predefined string or value. #define is a preprocessor statement and is used to define macros. Syntax: Form 1 : (simple macro) #define identifier predefined_string or value Example : #define pf printf

Transitions

Change in status of the internal system Reflected by transition from one state to another Transition can re-enter the same state Example: vending machine - add coin, but still not enough to buy would stay in the same state with updated "value" variable

Byte Representation

Computer Architectures started to use 8-bit bytes as the basic storage size Popularized by 1970s microprocessors (Intell 8008, predecessor of the 8080 and 8086) Arithmetic units/registers increased number of bits, but terminology of the Byte stuck A byte can represent 256 discrete values Can represent any 256 values determined by programmer To take advantage of logic, usually linearly continuous so adder circuits work Many exceptions, including ASCII 'A' + 'C' == ?

Assembler

Converts assembly language to machine language of an object relocatable file (addresses not all resolved)

Self referential structs

Create powerful data structures when struct data member is a pointer to same type

What is the difference between declaration, definition, and initialization?

Declaration - Puts the variables name into the namespace Definition - Allocates memory Initialization (optional) - Sets initial value to be stored in variable

Time-Interval Behavior

Events must be separated by specific intervals of time

Type Casting

Explicit - unary cast operator - "(type)" e.g. int i = (int)3.4; // i = 3 Implicit - when assignment/operators don't match e.g. int i1=3, i2=4; float f1 = i1/i2; // f1 = 0, should be 0.75 if explicit casts

Global vs. Static How can these variables be maintained?

Global variables Disadvantage - Can be modified outside of the tick function Static variables Disadvantage - Can only be modified in tick function Choose variable scope that makes sense in your application

Default Case

If you are using a switch/case statement for the tick function, the default case shouldn't ever be called Good practice to use it as a way to reinitialize system in case state variable is corrupted

Give an example of an embedded system

Industrial Robots, GPS Receivers, Digital Cameras, DVD Players, Wireless Routers, Set top Boxes, Gaming Consoles, Photocopiers, Microwave Ovens, MP3 Players

Demotion

Integral type → Integral type tries to shorten Bit truncation, or undefined if value cannot be stored Floating type → Integral type attempts to truncate fraction • NOT ROUNDING! • int i = 1.5; //i = 1 Unsigned → signed can be very dangerous! unsigned int j = -1; // j = maximum int value

Sequential Computation

Many programming languages are built to perform sequential computation Good at data processing, not meant for time-ordered behavior C follows a sequential computational model Each statement executed one after another

Maintaining Variables

Often, states will want to share variables & have variables exist between ticks Example: Vending machine Initial state sets value = 0 Count state adds value of coin to value Purchase state reduces value by cost of item Refund state gives coins back until value == 0

What is initialization?

Sets initial value to be stored in variable

Inline Functions

Short functions may be defined as "inline" • Suggestion to compiler that calls to the function should be replaced by body of the function • Suggestion, not a requirement Inline functions provide code the structure and readability advantages of using functions without overhead of actual function calls • i.e. inline bool isEven(int n); inline is more important in embedded environments than in other environments https://www.geeksforgeeks.org/inline-functions-cpp/

Structs vs Union

Similarities: • Syntax nearly identical • Member access nearly identical Differences: • Struct members have own memory • Size of struct at least as big as sum of sizes of members • Members of union share memory • Size of union is size of largest member

What variable modifier will initialize a variable on declaration:

Static variables are initialized to zero upon memory allocation • Good style to explicitly code it to make clear that zero initialization was intended • May initialize to other constants • Exception - pointers variables initialize to NULL

Struct Storage in Memory

Struct elements stored in order they are declared in Total size reserved not necessarily sum of size of elements • Some systems require variables aligned at certain memory addresses • Requires padding between member variables • Reordering of members may reduce padded bytes Rule of thumb: Place larger byte members at the beginning of definition

Text (ASCII/Unicode)

Text is stored in C using ASCII (which we have already covered) In practice, may need to store more than Roman characters Unicode - Character set with ∼120,000 characters Commonly used Unicode Schemes: UTF-8, UTF-16, UTF-32

Bit Fields

To save space, struct elements may be bit-packed Known as bit fields struct weather{ unsigned int temperature : 5; unsigned int windSpeed : 6; unsigned int isRaining : 1; unsinged int isSunny : 1; unsigned int isSnowing : 1; }; Above is 14 bits - uses 2 bytes Almost everything about bit fields is implementation specific Depends on machine & compiler Bit fields may only be defined as (unsigned) ints Bit fields do not have addresses (i.e. & operator does not work) are a structure that defines the exact number of bits each member of a structure will use

Determinism/ Mutually Exclusive

Transitions in a state must be mutually exclusive i.e. An FSM is only in one state at a time

What is the difference between scope and lifetime?

Variable "scope" refers to part of the program that may access the variable • Block scope - variables declared in {} are visible in that block • Nested-Bock - Inner block takes precedence, has access to outer block variables • Function Scope - variable visible from beginning to end of function - only for goto/switch labels • Program Scope - Variable declared outside function (global variables) - visible between files • Requires use of "extern" keyword • File Scope - Only visible within file - static variables in global areas, cannot be accessed by other files "Lifetime" refers to when a variable occupies memory Determined by where & how variable defined e.g. • global - lifetime from initialization to program end • static - lifetime from initialization to program end • block - lifetime from initialization to block exit • dynamic - lifetime managed by malloc/calloc to free

Address of operator (&)

Variable address accessed through ampersand (&) operator Literally the "address of" the variable Example: int val = 5; int* myPtr = &val; //myPtr now is equal to memory location of val

Are identifiers case sensitive?

YES • CASE SENSITIVE! • First character must be alphabetical or underscore • May NOT be a C keyword (e.g. int, return, this) • No length limit imposed by standard (but may have compiler limitation)

States

a description of system status while waiting to execute a transition Each state has a set of actions and transitions

What is an embedded system?

a programmed controlling and operating system with a dedicated function within a larger mechanical or electrical system, often with real-time computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. Textbook:a computer system embedded in another device

Are embedded systems typically application specific or general purpose?

application specific

Function Pointers

are a pointer to instruction memory Can create a pointer to the instruction Type == Return type of function Also declared with parameters of function

Write a line of code that declares a variable:

char example1; //definition and declaration void example3(void){ //def. and decl. of a function int x = 7; }

Variable Quantifiers - auto

default for function/block variables auto int a == int a Storage automatically allocated on function/block entry Freed when function/block exited May not be used with global variables

Variable Quantifiers - volatile

indicates variable value may be affected outside sequential execution Two primary scenarios: • Memory mapped devices & registers • Global variables accessed by multiple tasks or interrupts Prevents the compiler from making optimizations to relationships of code - is often used to create a software delay loop that won't disappear

Example of function pointers:

int myFunction(int param1); int (*myFunctionPtr)(int) = &myFunction; int ret = (*myFunctionPointer)(10);

Inner block scope code question

int y = 0; //Global Scope void print_y(){ printf("%d\n",y) // prints 0 } int main(){ int x = 3; //block scope int y = 5; int i = 0; for(i=0;i<5;i++){ int x = 2; //nested block scope printf("%d\n",x);//prints 2 } printf("%d\n",x);//prints 3 printf("%d\n,y);//prints 5 print_y();//prints 0 } void print_z(){ static int z=0; printf("z: %d\n",z++); } int main(){ int x = 3; int i = 0; for(i=0;i<5;i++){ int x = 2; printf("x: %d\n",x); print_z(); } printf("x: %d\n",x); }

What is an identifier?

name of function or variable

Wireless Communication

or sometimes simply wireless, is the transfer of information or power between two or more points that are not connected by an electrical conductor Radio waves are analog, how are they converted to digital? Amplitude Modification (AM) Frequency Modification (FM) Phase Modification

fgets

read a line of input from file until n-1 characters or '\n' Newline then replaced with null character Safer, as max length can be specified! File can be STDIN Returns NULL when EOF detected!

scanf

scanf() - stdio function for taking input from stdin Format: scanf("%s",string1); • Reads characters from stdin until whitespace encountered • Can write beyond end of array! • Best case - "stack smashing detected" • Worst case - Overwrites other memory

Variable Quantifiers - const

used with datatype declaration to specify unchanging value const objects may not be changed e.g. const int five = 5; five += 1; //illegal

Example of objective type:

• int* p; //objective type = int • int a[10]; //objective type = int • int**p; //root objective type is int, objective type is int*


Conjuntos de estudio relacionados

Microeconomics True and False: CH 5,6,7

View Set

Ch 23-- Electric current, Ohms law

View Set

Functional Anatomy Lecture Test One

View Set

Chapter 24: Male Genitourinary System

View Set