Kristianstad University
DT232A: Embedded Systems I
SOLUTIONS TO EXAMINATION QUESTIONS
1. (6 points)
a) Which two-input logical block generate the timing-diagram below? (2)
OR gate
b) Place following function in the Karnaugh map (4)
Simplify as much as possible.
Design a sequential circuit that divides input frequency by 8 and shows the output on a 4-bit counter.
Note: the output of the frequency divider is used as an input to the counter.
You can use your preferred flip-flop type for this purpose. You may use different types of flip-flops for the divider and the counter, if you wish.
3. (6 points)
• Explain the difference between Harvard and Von Neumann memory architectures. (1.5)
What are the advantages of Harvard over Von Neumann? (1)
Harvard: Separate bus and storage code and data memory. Safer, faster but hardware is expensive
Von Neumann: shared storage and bus for code and data. Risk of inadvertent modification of code may lead to system crash, but is cheaper because it uses less hardware.
• The CPU contains different types of registers. Taking any processor you are familiar with (e.g. AVR, ARM, X86, etc.), describe the types (groups) of registers it has.
What is the purpose of each group of register? About how many registers does the processor have? (3.5)
ATMega168 Features
• Processor – 8-bit – RISC Architecture – 131 Powerful Instructions –Most Single Clock Cycle Execution – 32 x 8 General Purpose Working Registers – Up to 20 MIPS Throughput at 20 MHz – On-chip 2-cycle Multiplier
Memory -Harvard Architecture -16K Bytes of In-System Self-Programmable Flash program memory -512 Bytes EEPROM -1K Bytes Internal SRAM -Write/Erase Cycles: 10,000 Flash, 100,000 EEPROM -Data retention: 20 years at 85°C, 100 years at 25°C
Peripherals -Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode -One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode -Real Time Counter with Separate Oscillator -Six PWM Channels -23 Programmable I/O Lines -Programmable Serial USART -Master/Slave SPI Serial Interface -Byte-oriented 2-wire Serial Interface (Philips I2C compatible
Read lectures 8-9 (from page 14)
4. (5 points)
• Explain at least 3 disadvantages (problems) of dynamic memory (DRAM) compared with static memory (SRAM). (2)
SRAM is faster made of flip flops, doesn’t require frequent refreshing, but is expensive
DRAM is slower, made of capacitors, requires refreshing, cheaper
• Explain in detail the operation flow and sequence of the fetch-execute cycle.
The fetch execute cycle is the basic operation (instruction) cycle of a computer (also known as the fetch decode execute cycle). During the fetch execute cycle, the computer retrieves a program instruction from its memory. It then establishes and carries out the actions that are required for that instruction.
•
• (3p) Read lecture slides 8-9
Please take note of the functions of the following registers in the fetch-execute cycle
PC (Program Counter) is a register that stores the address of the next instruction to be fetched in the memory.
MAR (Memory Address Register) is a temporary register that holds the address of the memory location from which the next instruction or data is to be fetched.
MBR (Memory Buffer Register) is a temporary register that stores data that is
• just read from the memory (at address indicated by MAR) or
• about to be written into memory (such as results of an arithmetic or logic operation)
IR (Instruction Register) holds the instruction (also called opcode) that is just read from the memory through MBR. The opcode is decoded by the instruction decoder to determine if it has operands (and how many).
According to the Von Neumann architecture, the instruction format is
Opcode operand (The operand can be 0, 1 or more)
If the opcode has no operand (argument), the opcode is directly executed and PC is incremented (or updated to point to the next instruction’s address: PC = PC+1)
If the opcode has m operands, the operands are read one by one by incrementing MAR to point to the next consecutive memory address after the opcode. The data that is read from memory is stored in MBR from where it will be transferred to other CPU registers used by the ALU. Once all operands are read, PC is updated such that PC = PC + m)
If the iinstruction (opcode) is an I/O instruction such as IN or OUT,
I/O AR (IO Address Register) is used to store the address of the IO to be accessed
I/O BR (IO buffer register) is used to store data that is read from (IN) or written to (OUT) the I/O
The ALU (Arithmetic and Logic Unit) is responsible for decoding and executing most arithmetic and logic instructions implemented in its hardware (such as ADD, SUB, MUL, CMP,…). Some instructions do not involve the ALU operations. E.g. CALL, JMP, NOP, etc
The Control Unit (not shown) is responsible for timing, synchronization and coordination of the above activities in their proper sequence.
PC and IR are internal registers that are not visible to units outside the CPU. ALU is also internal and has no communication with other units outside the CPU.
CPU
MEMORY
CPU internal data transfer lines
Address bus
Data bus
CPU
MEMORY
CPU internal data transfer lines
Address bus
Data bus
What is an address register?
In a computer, the Memory Address Register (MAR) is the CPU register that either stores the memory address from which data will be fetched from the CPU, or theaddress to which data will be sent and stored. In other words, MAR holds the memory location of data that needs to be accessed
5. (5 points)
A typical I/O module of a computer can be described using the following diagram:
• As you can see in the diagram, an I/O module has three types of registers: data, status,
control. What are the functions of each register type? (3)
Data Register: used to store the data to be sent or received via the I/O
Control Register: used to configure the settings of the I/O (e.g. baud rate, parity, etc in UART)
Status Register: shows what is going on in the I/O unit: (e.g. data register is empty or full, interrupt generated, etc)
• For addressing I/O units, we use two methods; memory mapped I/O and port mapped I/O.
What is the difference between the two addressing methods?
The main difference between memory mapped IO and IO mapped IO is that the memory mapped IO uses the same address space for both memory and IO device while the IO mapped IO uses two separate address spaces for memory and IOdevice. … Memory-mapped IO uses the same address space to address bothmemory and I/O devices (2)
6. (5 points)
An embedded system designer wishes to build an embedded system to be installed in a manufacturing machine. The hardware of the embedded system contains an 8-bit CPU and the following memory chips (total 4):
Data memory (RAM)
3 modules (chips)
size: 4KB each
Program memory (ROM)
1 module,
size: 2KB
• Design the addressing circuit and bus structure used to connect the CPU to the memory unit. Show a schematic diagram of your design with proper connections between the hardware components. (3)
• Describe the resulting memory address map and additional hardware you need to realize the addressing unit. (2)
We have a total of (2+4+4+4) = 14KB addressable memory.
The number of address lines necessary to access 14KB is
L = log2 14000 > 13. Therefore, we need 14 address lines
Since we have 4 memory chips we need
Log2 4 = 2 lines for chip selection. The rest of the address lines are shared by all memory chips and used for internal addressing within the chip.
CPU
R
O
M
Chip
KB
2
RAM
Chip
KB
4
RAM
Chip
KB
4
RAM
Chip
4
KB
2
to 4
Decoder
CPU
R
O
M
Chip
KB
2
RAM
Chip
KB
4
RAM
Chip
KB
4
RAM
Chip
4
KB
2
to 4
Decoder
Address bus (in chip address, 10 bits))
Chip decoder (chip selector, 2 bits)
Data bus
Memory Address map:
Chip# Starting Ending Chip Select
• 0 2047 00
• 4096 8191 01
• 8191 12287 10
• 12288 16383 11
Additional Hardware needed to implement the addressing system is a 2-to-4 decoder.
7. (7 points)
You are required to write an assembly program code for a weather station which is based on the ATMega168 microcontroller. Your code displays the total amount of rainfall in 2014. The total rainfall is the sum of the monthly rainfall data. Assume that:
• The 12-month rainfall data is already stored in consecutive memory as integer values.
• The starting memory address of the rainfall data is 0x1000 (e.g. January’s rainfall).
• The microcontroller has an 8-bit processor with 16MHZ speed
You should write an assembly program code that calculates the sum of the monthly rainfall data which is already stored in memory.
a) Write an assembler code with proper comments to do the required task. (4)
Here are the important steps:
• A down counter is used to track the number of loop executions (in this case it is 12 times)
• A register is cleared (set to 0) to hold the sum of the addition operation
• The memory address containing the monthly data is initialized via R27:R26
• The data from memory is read to R16
• Addition operation is performed on the data just read from memory
• The pointer to next memory address is incremented (R26)
• The counter is decremented and compared with zero
• If counter is not zero execution returns to line 4 above
• Otherwise, the sum is sent to the output port (PORTD). For this the DDRD should be set for output (0xFF) first. Then the sum in R20 is sent to PORTD.
ldi R19, 0 ;used to compare if down counter is zero ldi R17, 12 ;number of data points to be added ldi R20, 0x00 ;store the sum here ldi R27, 0x10 ;pointer to data memory higher address
ldi R26, 0x00 ;pointer to data memory lower address looper: ;addition loop starts here ld R16, X ;get data from memory add R20, R16 ;add data to sum register inc R26 ;increment to get data from to next address dec R17 ;decrement data count
cp R17, R19 ;check if loop counter is 0
brne looper ;if counter not 0, go back to beginning of loop ldi R18, 0xff ;use R18 to set DDRD for output out PORTD, R18 ;set PortD for output
out PORTD, R20 ;send the sum to PortD ret ;return to the calling routine
• How much time does it take to complete the execution of the above program? Justify your answer by showing the necessary calculations. (1.5)
There are 6 lines in the loop. The loop is executed 12 times. There are 9 lines outside the loop (5 before and 4 after the loop).
This means, a total of 81 lines are executed. (6X12) + 9.
Assuming each line to take 1 or 2 clock cycles, we can estimate that the entire code is executed in 81 to 162 clock cycles. (Actually it is 103 cycles).
On a 1MHZ computer this corresponds to 103 micro seconds.
• How much flash memory is required to store your compiled code? Justify your answer by
showing the necessary calculations. (1.5)
Most instructions take 2 bytes. Given that there are 15 instructions (see in b above), we estimate that the code occupies about 30 bytes of flash (program) memory.
8. (6 points)
A toy factory wants to use a microcontroller based blinker (red and blue LED lamps) on one of its products. When a child presses the POWER ON button, the red and blue lights blink one after the other. Each LED lamp is switched on for a 2 seconds duration and switched off for the next 2 seconds. If the blue lamp is ON, the red lamp is OFF and vice versa.
Write a C program for this application. Use the following assumptions:
– You shall use the ATMega168 processor which has a speed of 16MHZ – You shall use Timer0 to control the lighting interval.
Use a flow chart or relevant diagram in order to make your solution understandable.
Write proper comments to describe your code.
To create a delay of 2seconds, we use timer0. We use the corresponding ISR for timer0 overflow. We then count the number of overflows that correspond to the desired delay (2sec). You need a global counter for this:
The timer counter0 is 8-bits which means it overflows every 256 cycles.
Since the processor has 16MHZ the overflow duration corresponds to
256/16000000 seconds
However, with a pre-scaler value of 1024, the over flow duration can be
256/(16000000/1024) seconds = 0.0164sec 16.4msec.
For a delay of 2 seconds we need 2/0.0164 12 over flows, that is the maximum value our global counter can have.
Int gcount ;
The main method shall have the following structure:
Void main(){
gcount = 0;
Timerinit();
While (1) {
;
}
}
The Timerinit() method shall be initialized according to the notes in Lecture 17 Void Timer0init() {
TCCR0A = 0b00000000;
// normal mode
TCCR0B = 0b00000101;
// prescaler 1024
TIMSK = 0b00000001;
// enable Timer 0 overflow interrupt
sei();
// enable interrupt subsystem globally
2019.part1
Address bus –
It is a group of conducting wires which carries address only. Address bus is unidirectional because data flow in one direction, from microprocessor to memory or from microprocessor to Input/output devices (That is, Out of Microprocessor).
Length of Address Bus of 8085 microprocessor is 16 Bit (That is, Four Hexadecimal Digits), ranging from 0000 H to FFFF H, (H denotes Hexadecimal). The microprocessor 8085 can transfer maximum 16 bit address which means it can address 65, 536 different memory location.
The Length of the address bus determines the amount of memory a system can address. Such as a system with a 32-bit address bus can address 2^32 memory locations. If each memory location holds one byte, the addressable memory space is 4 Bowater, the actual amount of memory that can be accessed is usually much less than this theoretical limit due to chipset and motherboard limitations.
Data bus –
It is a group of conducting wires which carries Data only. Data bus is bidirectional because data flow in both directions, from microprocessor to memory or Input/output devices and from memory or Input/output devices to microprocessor.
Length of Data Bus of 8085 microprocessor is 8 Bit (That is, two Hexadecimal Digits), ranging from 00 H to FF H. (H denotes Hexadecimal).
When it is write operation, the processor will put the data (to be written) on the data bus, when it is read operation, the memory controller will get the data from specific memory block and put it into the data bus.
The width of the data bus is directly related to the largest number that the bus can carry, such as an 8 bit bus can represent 2 to the power of 8 unique values, this equates to the number 0 to 255.A 16 bit bus can carry 0 to 65535.
Control bus –
It is a group of conducting wires, which is used to generate timing and control signals to control all the associated peripherals, microprocessor uses control bus to process data, that is what to do with selected memory location. Some control signals are:
Memory read
Memory write
I/O read
I/O Write
Opcode fetch
If one line of control bus may be the read/write line.If the wire is low (no electricity flowing) then the memory is read, if the wire is high (electricity is flowing) then the memory is written.
Condition Code Registers
• Sets of individual bits –e.g. result of last operation was zero
• Can be read (implicitly) by programs –e.g. Jump if zero
• Can not (usually) be set by programmer directly
2019.part3
Semiconductor Memory
• RAM –Misnamedas all semiconductor memory is random access –Read/Write –Volatile –Temporary storage –Static or dynamic
Read Only Memory (ROM)
• Permanentstorage –Nonvolatile • Used often in microprogramming(see later) • Also stores –Library subroutines –Systems programs (BIOS) –Function tables
Written during manufacture – Very expensive for small runs • Programmable (once) – PROM – Needs special equipment to program • Read “mostly” – Erasable Programmable (EPROM) • Erased by UV – Electrically Erasable (EEPROM) • Takes much longer to write than read – Flash memory • Erase whole memory electrically
What are interrupts?
Interrupts are basically events that require immediate attention by the microcontroller. When an interrupt event occurs the microcontroller pause its current task and attend to the interrupt by executing an Interrupt Service Routine (ISR) at the end of the ISR the microcontroller returns to the task it had pause and continue its normal operations.
In order for the microcontroller to respond to an interrupt event the interrupt feature of the microcontroller must be enabled along with the specific interrupt. This is done by setting the Global Interrupt Enabled bit and the Interrupt Enable bit of the specific interrupt.
External interrupts generally refer to interrupt requests issued by computer peripherals, such as keyboard interrupts, printer interrupts, and timer interrupts. External interrupts are interrupts that can be masked, that is, interrupt requests can be masked by these external devices. Internal interrupts are interrupts caused by hardware errors (such as sudden power loss, parity errors, etc.) or arithmetic errors (divisor zero, arithmetic overflow, single-step interrupt, etc.).
Internal interrupts are non-maskable interrupts. Software interrupts are not really interrupts, they are just general programs that can be called to execute. For example, various external device management interrupt service programs (keyboard management interrupt, display management interrupt, printer management interrupt, etc.) in the ROM BIOS, and DOS system function calls (INT 21H) are software interrupts.
PWM
Select the operation mode of Timer 1: CTC, fast PWM, or phase correct PWM, set TCCR1A and TCCR1B • Select how output compare pin will be updated on compare match event. (i) • Configure timer 1: clock source, prescaler, … set TCCR1A and TCCR1B • Put correct values in the output compare registers. set OCR1A
• set TCCR1A and TCCR1B (ii) set OCR1A
Timer goes from 0 to TOP, where TOP is equal to the value in OCRnx register. (or) 0xFF (for 8-bit mode, WGM = 0101) or 0x1FF (for 9-bit mode, WGM = 0110) or 0x3FF (for 10-bit mode, WGM = 0111) or • Whenever the timer value reaches the value of OCRnx, an output pin is pulled low and when counting begins from 0, it is pulled high again to Vcc. Thisis similarto fast PWM exceptthatthe timer starts countingdown insteadof resettingto 0 whenit reachesthe maximum. • The valueofthe Ocnpin togglesonlywhen the valueofOCRnmatcheswiththe TIMERncontent.
Writea program to initializethe appropriateADC registers and performanalog-to-digital conversionaccordingto the followingrequirements: ADC source: channel0 Referencevoltage: AVCC = 5V Alignment: left, top8-bit in ADCH Auto-trigger: Disable ADC interrupt: Disable Prescaler: 2 (fastestconversion)
The goal of code optimization is to discover, at compile-time, information about the runtime behavior of the program and to use that information to improve the code generated by the compiler. Improvement can take many forms. The most common goal of optimization is to make the compiled code run faster.
In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program.
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources and/or executes faste
Start your program running under the debugger. If it is a kind of program that normally runs very fast, but you want it to go faster, you can add a temporary outer loop of say, 1000 times, to give you enough time to halt it.
While it is being slow, halt it manually. Do this by striking a break or pause key that makes the program stop wherever it happens to be. Do not do this by setting a breakpoint in the code, because then you will not be able to see what it was doing when you struck the key.
Record the call stack. What you need to record is the file and line number of each statement on the call stack. Hopefully there is an easy way to copy-paste this information into a text editor, but if not, do it the hard way, with paper and pencil.、、
Interrupt latency – The elapsed time between the occurrence of an interrupt and the execution of the first instruction of the interrupt service routine (ISR). – Indirectly related to system responsiveness. The smaller the latency, the faster the response. • Interrupts can happen at any time and in any order (but can be “masked” in some processors). • Interrupts can be ignored (masked) when critical task is executed.
Programming Interrupts
Steps: 1. Write the program that should be executed (ISR) when the event triggering the interrupt occurs. 2. Ensure the ISR for a specific interrupt points to the correct interrupt vector (starting) address. 3. Enableglobal interruptin the status register ofthe processor by callingsei()(enableinterrupt). This Enables the Global Interrupt Enable (I-bit) in the Status Register (SREG). 4. To disable interrupts, call cli()(clear interrupt). Note: It may be necessary to disable interrupts in some cases
ATmega168/328 Code:
#include
#include
int main(void)
{
DDRD &= ~(1 << DDD2); // Clear the PD2 pin
// PD2 (PCINT0 pin) is now an input
PORTD |= (1 << PORTD2); // turn On the Pull-up
// PD2 is now an input with pull-up enabled
EICRA |= (1 << ISC00); // set INT0 to trigger on ANY logic change
EIMSK |= (1 << INT0); // Turns on INT0
sei(); // turn on interrupts
while(1)
{
/*main program loop here */
}
}
ISR (INT0_vect)
{
/* interrupt code here */
}
Writea program to initializethe appropriateADC registers and performanalog-to-digital conversionaccordingto the followingrequirements: ADC source: channel0 Referencevoltage: AVCC = 5V Alignment: left, top8-bit in ADCH Auto-trigger: Disable ADC interrupt: Disable Prescaler: 2 (fastestconversion)
Signal conditioning is the manipulation of a signal in a way that prepares it for the next stage of processing. Many applications involve environmental or structural measurement, such as temperature and vibration, from sensors.
C
In C++, variables can be declared, at any point of time, before they are used in the instructions. ... Here the main difference between a local and a global variable is that, a local variable is declared inside a function block, where As the global variable is declared outside the functions in the program.Apr 22, 2016
A local variable is a variable which is either a variable declared within the function or is an argument passed to a function. As you may have encountered in your programming, if we declare variables in a function then we can only use them within that function.
• global variables -------> data (correct)
• static variables ——-> data (correct)
• constant data types —–> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code
• local variables(declared and defined in functions) ——–> stack (correct)
• variables declared and defined in main function —–> heap also stack (the teacher was trying to trick you)
• pointers(ex: char *arr, int *arr) ——-> heap data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment.
• dynamically allocated space(using malloc, calloc, realloc) ——–> stack heap
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors. FILE *fptr;
When you open those files, you’ll see all the contents within the file as plain text. You can easily edit or delete the contents.They take minimum effort to maintain, are easily readable, and provide least security and takes bigger storage space.
• #include
• #include
•
• int main()
• {
• int num;
• FILE *fptr;
• fptr = fopen(“C:\\program.txt”,”w”);
•
• if(fptr == NULL)
• {
• printf(“Error!”);
• exit(1);
• }
•
• printf(“Enter num: “);
• scanf(“%d”,&num);
•
• fprintf(fptr,”%d”,num);
• fclose(fptr);
•
• return 0;
• }
Read from a text file using fscanf()
• #include
• #include
•
• int main()
• {
• int num;
• FILE *fptr;
•
• if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL){
• printf(“Error! opening file”);
•
• // Program exits if the file pointer returns NULL.
• exit(1);
• }
•
• fscanf(fptr,”%d”, &num);
•
• printf(“Value of n=%d”, num);
• fclose(fptr);
•
• return 0;
•
2. Binary filesBinary files are mostly the .bin files in your computer.Instead of storing data in plain text, they store it in the binary form (0’s and 1’s).
They can hold higher amount of data, are not readable easily and provides a better security than text files. fwrite(address_data,size_data,numbers_data,pointer_to_file);
• #include
• #include
•
• struct threeNum
• {
• int n1, n2, n3;
• };
•
• int main()
• {
• int n;
• struct threeNum num;
• FILE *fptr;
•
• if ((fptr = fopen(“C:\\program.bin”,”wb”)) == NULL){
• printf(“Error! opening file”);
•
• // Program exits if the file pointer returns NULL.
• exit(1);
• }
•
• for(n = 1; n < 5; ++n)
• {
• num.n1 = n;
• num.n2 = 5*n;
• num.n3 = 5*n + 1;
• fwrite(&num, sizeof(struct threeNum), 1, fptr);
• }
• fclose(fptr);
•
• return 0;
• }
Read from a binary file using fread()
• #include
• #include
•
• struct threeNum
• {
• int n1, n2, n3;
• };
•
• int main()
• {
• int n;
• struct threeNum num;
• FILE *fptr;
•
• if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL){
• printf(“Error! opening file”);
•
• // Program exits if the file pointer returns NULL.
• exit(1);
• }
•
• for(n = 1; n < 5; ++n)
• {
• fread(&num, sizeof(struct threeNum), 1, fptr);
• printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
• }
• fclose(fptr);
•
• return 0;
• }
A union is a special data type available in C that allows to store different data types in the same memory location. ... Unions provide an efficient way of using the same memory location for multiple-purpose.
A buffer overflow occurs when a program or process attempts to write more data to a fixed-length block of memory, or buffer, than the buffer, is allocated to hold
the executed code can be shellcode which gives the attacker an OS shell with administrative privileges for example or even add a new (administrator) user to the system. Also with buffer overflows the executed code happens in the context of the running application
In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly. Various keywords are used to specify this statement: descendants of ALGOL use "for", while descendants of Fortran use "do"
...
Example 1: for loop
• # Print numbers from 1 to 10.
• #include
• int main() {
• int i;
• for (i = 1; i < 11; ++i)
• {
• printf("%d ", i);
• }
The main difference between do while loop and while loop is in do while loop the condition is tested at the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops. Note: In do while loop the loop body will execute at least once irrespective of test condition.
Bit Field in C. Bit field can be used to reduce memory consumption when it is known that only some bits would be used for a variable. Bit fields allow efficient packaging of data in the memory. As we know, integer takes two bytes(16-bits) in memory. ... For example, if we use a variable temp to store value either 0 or 1.
The biggest advantage of bit fields is that one does not have to keep track of how flags and masks actually map to the memory. ... Bit fields are used to pack more variables into a smaller data space, but cause the compiler to generate additional code to manipulate these variables.
Integer overflow is the result of trying to place into computer memory an integer (whole number) that is too large for the integer data type in a given system.
Stack overflow refers specifically to the case when the execution stackgrows beyond the memory that is reserved for it. ... Buffer overflow refers to any case in which a program writes beyond the end of the memory allocated for anybuffer (including on the heap, not just on the stack