SlideShare a Scribd company logo
Embedded System Design:
From Electronics
to Microkernel Development
Rodrigo Maximiano Antunes de Almeida
E-mail: rmaalmeida@gmail.com
Twitter: @rmaalmeida
Universidade Federal de Itajubá
Creative Commons License
The work ”Embedded System Design: From Electronics to Microkernel
Development” of Rodrigo Maximiano Antunes de Almeida was licensed
with Creative Commons 3.0 – Attribution – Non Commercial – Share Alike
license.
Additional permission can be given by the author through direct contact
using the e-mail: rmaalmeida@gmail.com
Workshop schedule
● Electronic building
● Board programming
● Kernel development
Electronic building
● Electronics review
● Schematics
● Protoboard/breadboard
● System design
● Basic steps
● Microcontroller
● LCD
● Potentiometer
Electronics review
● http://xkcd.com/730/
Schematics
● Way to represent
the components
and its connections
● Each component
has its own symbol
● Crossing wires only
are connected if
joined with a dot
Protoboard/Breadboard
System design
● Steps on a generic electronic system design
● Define the objective(s)
● Choose the main components needed to
achieve the objective
● Get the use example and recommendations
from component datasheet
● Build the schematics
● Simulation of HW elements
● Board layout
Datasheets
● The main source of information concerning
electronics
● Presents
● Electrical characteristics
● Simplified schematics
● Use example
● Opcodes/API
System design
● Objective
● Build digital voltage reader
● Main components
● Microcontroller
● LCD text display
● Potentiometer
Microcontroller
● System-on-a-chip
● Processor
● Memory
● Input/Output
peripherals
● Communication
● Safety components
Microcontroller
● Xtal configuration
● Reset pin
● DC needs
● Many peripherals
on the same pin
LCD Display
LCD Display
● Data connection
● Backlite
● Current
consumption
● Power on
time/routine
Potentiometer
● Linear/Log
● Used as voltage
divisor
● Need an analog
input
● Filter
System design
● Cad tool: Fritzing (fritzing.org)
1
● Hands On!
Board programming
● Programmer
● IDE
● Basic concepts
● CPU Architecture
● HW configuration
● Memory access
● First program (He110 DEFC0N)
● Peripheral setup
● Second program (ADC read)
Board programming
● Programmer
● PICkit3
● Can use ICSP
● Can program a lot
of Microchip
products
● Also a debugger
Board programming
● IDE
● MPLABX
– Based on Netbeans
● Compiler
● SDCC
– Based on GCC
● GPUtils
Basic concepts
● PIC architecture
Basic concepts
● Memory segmentation
Basic concepts
● HW configuration
● Some options must be set before the program
start
● This can only be accomplished by special
instructions
● Compiler datasheet
Basic concepts
● HW configuration
//CONFIG.H
// No prescaler used
__code char __at 0x300000 CONFIG1L = 0x01;
// Internal Oscillator
__code char __at 0x300001 CONFIG1H = 0x08;
// Disabled-Controlled by SWDTEN bit
__code char __at 0x300003 CONFIG2H = 0x00;
// Disabled low voltage programming
__code char __at 0x300006 CONFIG4L = 0x00;
Basic concepts
Basic concepts
Basic concepts
● Build a pointer to a specific memory
address:
void main (void){
char *ptr;
//pointing to the port D
ptr = 0xF83;
//changing all outputs to high
*ptr = 0xFF;
}
//this is not an infinite loop!
while(PORTD==PORTD);
Basic concepts
● Building a header with all definitions
● __near = sfr region
● Volatile = can change without program
acknowledge
//BASIC.H
#define PORTD (*(volatile __near unsigned char*)0xF83)
#define TRISC (*(volatile __near unsigned char*)0xF94)
Basic concepts
● Bitwise operations
//bit set
char bit = 2;
char mask;
mask = 1 << bit;
arg = arg | mask;
//one line
arg = arg | (1<<bit)
//using define
#define BitSet(arg,bit) ((arg) |= (1<<bit))
#define BitClr(arg,bit) ((arg) &= ~(1<<bit))
#define BitFlp(arg,bit) ((arg) ^= (1<<bit))
#define BitTst(arg,bit) ((arg) & (1<<bit))
First program
● Open MPLABX IDE
● configure SDCC and PICkit
● Create a project to:
● Initialize LCD
● Print "He110 DEFC0N"
LCD communication
● The data is always an 8 bit information
● It may be split in two 4 bit "passes"
● The data may represent a character or a
command
● They are distinguished by RS pin
● The data must be stable for "some time"
● In this period the EN pin must be set
#define RS 0
#define EN 1
#define RW 2
void Delay40us(void)
{
//for 8MHz each instruction takes 0,5 us:
//40/0,5 = 80 instruction
unsigned char i;
for(i = 0; i < 25; i++); //3 + 3 * 25 = 78
}
LCD communication
void LCD_comm(unsigned char data, char cmd){
if (cmd)
BitClr(PORTC,RS); //cmd
else
BitSet(PORTC,RS); //data
BitClr(PORTC,RW); // writing
PORTD = cmd;
BitSet(PORTC,EN); //enable read
Delay40ms();
BitClr(PORTC,EN); //finish read
}
LCD communication
void LCD_init(void){
unsigned char i;
for (i=0; i<200; i++)
Delay40us(); // initialize delay
//pin configuration
BitClr(TRISC,0); //RS
BitClr(TRISC,1); //EN
BitClr(TRISC,2); //RW
TRISD = 0x00; //data
//display initialization
LCD_comm(0x38,1); //8bits, 2 lines, 5x8
LCD_comm(0x06,1); //increment mode
LCD_comm(0x0F,1); //cursor ON
LCD_comm(0x03,1); //clear internal counters
LCD_comm(0x01,1); //clean display
LCD_comm(0x80,1); //initial position
}
LCD communication
LCD character creation
● The LCD can hold
up to 8 custom
characters
● Each character is a
5*8 matrix
● Translating: 40*64
b/w drawing area
LCD character creation
Source: http://www.8051projects.net/lcd-interfacing/lcd-custom-character.php
LCD character creation
//each line represents one "character"
char defcon[48] = {
0x00,0x01,0x03,0x03,0x03,0x03,0x01,0x04,
0x0e,0x1f,0x04,0x04,0x1f,0x0e,0x11,0x1f,
0x00,0x10,0x18,0x18,0x18,0x18,0x10,0x04,
0x0c,0x03,0x00,0x00,0x00,0x03,0x0c,0x04,
0x00,0x00,0x1b,0x04,0x1b,0x00,0x00,0x00,
0x06,0x18,0x00,0x00,0x00,0x18,0x06,0x02
};
//first memmory position
LCD_comm(0x40, 1);
for(i=0; i<48; i++)
{
LCD_comm(defcon[i],0);
}
Peripherals setup
● Get on the
datasheet the
information about
the peripheral
registers and
configuration info
Peripherals setup
● ADC
void ADC_init(void)
{
BitSet(TRISA,0); //pin setup
ADCON0 = 0b00000001; //channel select
ADCON1 = 0b00001110; //ref = source
ADCON2 = 0b10101010; //t_conv = 12 TAD
}
ADC setup
unsigned int ADC_read(void)
{
unsigned int ADvalue;
BitSet(ADCON0,1); //start conversion
while(BitTst(ADCON0,1)); //wait
ADvalue = ADRESH; //read result
ADvalue <<= 8;
ADvalue += ADRESL;
return ADvalor;
}
ADC setup
Second program
● Read ADC value
and present in LCD
A little break to follow 3-2-1 DEFC0N rule!
Could not found any picture of Garfield taking shower =/
//today topics
void main (void){
//variable declaration
kernel_project(1);
//initialization
concepts(2);
//hard-work
microkernel(3);
device_driver_controller(4);
}
void kernel_project (float i){
what_is_a_kernel(1.1);
alternatives(1.2);
monolithic_vs_microkernel(1.3);
kernel_design_decisions(1.4);
this_course_decisions(1.5);
}
kernel_project(1);
what_is_a_kernel(1.1);
kernel_project(1);
kernel_project(1);
● Kernel tasks:
1)Manage and coordinate the processes
execution using “some criteria”
2)Manage the free memory and coordinate the
processes access to it
3)Intermediate the communication between the
hardware drivers and the processes
kernel_project(1);
Develop my own kernel?
Why?
kernel_project(1);
● Improve home design
● Reuse code more efficiently
● Full control over the source
● Specific tweeks to the kernel
● Faster context switch routine
● More control over driver issues (interrupts)
kernel_project(1);
Develop my own kernel?
Why not?
kernel_project(1);
● Kernel overhead (both in time and memory)
● Free and paid alternatives
● Time intensive project
● Continuous development
kernel_project(1);
kernel_project(1);
● Alternatives
● Windows Embedded Compact®
● VxWorks®
● X RTOS®
● uClinux
● FreeRTOS
● BRTOS
kernel_project(1);
● Monolithic kernel versus microkernel
● Linus Torvalds and Andrew Tanenbaum
kernel_project(1);
● Kernel design decisions
● I/O devices management
● Process management
● System safety
kernel_project(1);
● Our decisions:
● Microkernel
● Non-preemptive
● Cooperative
● No memory management
● Process scheduled based on timer
● Isolate drivers using a controller
void concepts (float i){
function_pointers(2.1);
structs(2.2);
circular_buffers(2.3);
temporal_conditions(2.4);
void_pointers(2.5);
}
concepts(2);
function_pointers(2.1);
concepts(2);
● Necessity:
● Make an image
editor that can
choose the right
function to call
●
1st
Implementation
● Use a option
parameter as a
switch operator
concepts(2);
image Blur(image nImg){}
image Sharpen(image nImg){}
image imageEditorEngine(image nImg, int opt){
image temp;
switch(opt){
case 1:
temp = Sharpen(nImg);
break;
case 2:
temp = Blur(nImg);
break;
}
return temp;
}
concepts(2);
● Function pointers
● Work almost as a normal pointer
● Hold the address of a function start point
instead the address of a variable
● The compiler need no known the function
signature to pass the correct parameters and
the return value.
● Awkard declaration (it is best to use a typedef)
concepts(2);
//defining the type pointerTest
//it is a pointer to function that:
// receives no parameter
// returns no parameter
typedef void (*pointerTest)(void);
//Function to be called
void nop (void){ __asm NOP __endasm }
//creating an pointerTest variable;
pointerTest foo;
foo = nop;
(*foo)(); //calling the function via pointer
concepts(2);
Re-code the image editor engine using
function pointers
concepts(2);
image Blur(image nImg){}
image Sharpen(image nImg){}
typedef image (*ptrFunc)(image nImg);
//image editor engine
image imageEditorEngine(ptrFunc function,
image nImg){
image temp;
temp = (*function)(nImg);
return temp;
}
concepts(2);
● Good
● New function
additions do not
alter the engine
● The engine only
needs to be tested
once
● Can change the
function
implementations
dynamically
● Bad
● More complex code
(function pointers
are not so easy to
work with)
● Not all compilers
support function
pointers
concepts(2);
structs(2.2);
concepts(2);
// struct declaration
typedef struct{
unsigned short int age;
char name[51];
float weight;
}people;
● Structs are composed variables.
● Group lots of information as if they were one
single variable.
● A vector that each position stores a different
type
void main(void){
struct people myself = {26, "Rodrigo", 70.5};
myself.age = 27;
//using each variable from the struct
printf("Age: %dn", myself.age);
printf("Name: %sn", myself.name);
printf("Weight: %fn", myself.weight);
return 0;
}
concepts(2);
// struct declaration
typedef struct{
unsigned short int *age;
char *name[51];
float *weight;
}people;
void main(void){
struct people myself = {26, "Rodrigo", 70.5};
//using each variable from the struct
printf("Age: %dn", myself->age);
printf("Name: %sn", myself->name);
printf("Weight: %fn", myself->weight);
return 0;
}
concepts(2);
concepts(2);
circular_buffers(2.3);
concepts(2);
● Circular Buffers
● “Endless” memory spaces
● Use FIFO aproach
● Store temporary data
● Can implemented using vectors or linked-lists
concepts(2);
● Vector implementation
● Uses less space
● Need special caution when cycling
● Problem to differentiate full from empty
#define CB_SIZE 10
int circular_buffer[CB_SIZE];
int index=0;
for(;;){
//do anything with the buffer
circular_buffer[index] = index;
//increment the index
index = (index+1)%CB_SIZE;
}
concepts(2);
concepts(2);
#define CB_SIZE 10
int circular_buffer[CB_SIZE];
int start=0, end=0;
char AddBuff(int newData)
{
//check if there is space to add a number
if ( ((end+1)%CB_SIZE) != start)
{
circular_buffer[end] = newData;
end = (end+1)%CB_SIZE;
return SUCCESS;
}
return FAIL;
}
concepts(2);
temporal_conditions(2.4);
concepts(2);
In the majority part of embedded systems, we
need to guarantee that a function will be
executed in a certain frequency. Some
systems may even fail if these deadlines are
not met.
concepts(2);
● To implement temporal conditions:
1)There must be a tick event that occurs with a
precise frequency
2)The kernel must be informed of the execution
frequency needed for each process.
3)The sum of process duration must “fit” within
the processor available time.
concepts(2);
●
1st
condition:
● Needs an internal timer that can generate an
interrupt.
●
2nd
condition:
● Add the information for each process when
creating it
●
3rd
condition:
● Test, test and test.
● If fail, change chip first, optimize only on last
case
concepts(2);
● Scheduling processes:
● Using a finite timer to schedule will result in
overflow
● Example: scheduling 2 processes for 10 and 50
seconds ahead.
concepts(2);
● And if two process are to be called in the
same time?
concepts(2);
● Question:
● From the timeline above (only the timeline) is
P2 late or it was scheduled to happen 55(s)
from now?
concepts(2);
● Solution:
● Use a downtime counter for each process
instead of setting a trigger time.
● Problem:
● Each counter must be decremented in the
interrupt subroutine.
● Is it a problem for your system?
concepts(2);
void_pointers(2.5);
concepts(2);
● Void pointers
● Abstraction that permits to the programmer to
pass parameters with different types to the
same function.
● The function which is receiving the parameter
must know how to deal with it
● It can not be used without proper casting!
concepts(2);
char *name = "Paulo";
double weight = 87.5;
unsigned int children = 3;
void main (void){
//its not printf, yet.
print(0, &name);
print(1, &weight);
print(2, &children);
}
concepts(2);
void print(int option; void *parameter){
switch(option){
case 0:
printf("%s",(char*)parameter);
break;
case 1:
printf("%f",*((double*)parameter));
break;
case 2:
printf("%d",*((unsigned int*)parameter));
break;
}
}
void microkernel (float i){
init_kernel(3.0);
for(int i=1; i<4; i++;)
{
kernel_example(3+i/10);
}
running_the_kernel(3.4);
}
microkernel(3);
init_kernel(3.0);
microkernel(3);
● The examples will use a minimum of
hardware or platform specific commands.
● Some actions (specifically the timer) needs
hardware access.
microkernel(3);
//first implementation
kernel_example(3+1/10);
microkernel(3);
● In this first example we will build the main
part of our kernel.
● It should have a way to store which
functions are needed to be executed and in
which order.
● This will be done by a static vector of
pointers to function
//pointer function declaration
typedef void(*ptrFunc)(void);
//process pool
static ptrFunc pool[4];
microkernel(3);
● Each process is a function with the same
signature of ptrFunc
void tst1(void){
printf("Process 1n");
}
void tst2(void){
printf("Process 2n");
}
void tst3(void){
printf("Process 3n");
}
microkernel(3);
● The kernel itself consists of three functions:
● One to initialize all the internal variables
● One to add a new process
● One to execute the main kernel loop
//kernel internal variables
ptrFunc pool[4];
int end;
//kernel function's prototypes
void kernelInit(void);
void kernelAddProc(ptrFunc newFunc);
void kernelLoop(void);
microkernel(3);
//kernel function's implementation
void kernelInit(void){
end = 0;
}
void kernelAddProc(ptrFunc newFunc){
if (end <4){
pool[end] = newFunc;
end++;
}
}
microkernel(3);
//kernel function's implementation
void kernelLoop(void){
int i;
for(;;){
//cycle through the processes
for(i=0; i<end; i++){
(*pool[i])();
}
}
}
microkernel(3);
//main loop
void main(void){
kernelInit();
kernelAddProc(tst1);
kernelAddProc(tst2);
kernelAddProc(tst3);
kernelLoop();
}
microkernel(3);
Simple?
microkernel(3);
//second implementation
//circular buffer and struct added
kernel_example(3+2/10);
microkernel(3);
● The only struct field is the function pointer.
Other fields will be added latter.
● The circular buffer open a new possibility:
● A process now can state if it wants to be
rescheduled or if it is a one-time run process
● In order to implement this every process must
return a code.
● This code also says if there was any error in the
process execution
microkernel(3);
//return code
#define SUCCESS 0
#define FAIL 1
#define REPEAT 2
//function pointer declaration
typedef char(*ptrFunc)(void);
//process struct
typedef struct {
ptrFunc function;
} process;
process pool[POOL_SIZE];
microkernel(3);
char kernelInit(void){
start = 0;
end = 0;
return SUCCESS;
}
char kernelAddProc(process newProc){
//checking for free space
if ( ((end+1)%POOL_SIZE) != start){
pool[end] = newProc;
end = (end+1)%POOL_SIZE;
return SUCCESS;
}
return FAIL;
}
microkernel(3);
void kernelLoop(void){
int i=0;
for(;;){
//Do we have any process to execute?
if (start != end){
printf("Ite. %d, Slot. %d: ", i, start);
//check if there is need to reschedule
if ((*(pool[start].Func))() == REPEAT){
kernelAddProc(pool[start]);
}
//prepare to get the next process;
start = (start+1)%POOL_SIZE;
i++; // only for debug;
}
}
}
microkernel(3);
//vetor de struct
process pool[POOL_SIZE];
// pool[i]
// pool[i].func
// *(pool[i].func)
// (*(pool[i].func))()
//vetor de ponteiro de struct
process* pool[POOL_SIZE];
// pool[i]
// pool[i].func
// pool[i]->func
// pool[i]->func()
microkernel(3);
void kernelLoop(void){
int i=0;
for(;;){
//Do we have any process to execute?
if (start != end){
printf("Ite. %d, Slot. %d: ", i, start);
//check if there is need to reschedule
if (pool[start]->Func() == REPEAT){
kernelAddProc(pool[start]);
}
//prepare to get the next process;
start = (start+1)%POOL_SIZE;
i++; // only for debug;
}
}
}
microkernel(3);
void tst1(void){
printf("Process 1n");
return REPEAT;
}
void tst2(void){
printf("Process 2n");
return SUCCESS;
}
void tst3(void){
printf("Process 3n");
return REPEAT;
}
● Presenting the new processes
microkernel(3);
void main(void){
//declaring the processes
process p1 = {tst1};
process p2 = {tst2};
process p3 = {tst3};
kernelInit();
//Test if the process was added successfully
if (kernelAddProc(p1) == SUCCESS){
printf("1st process addedn");}
if (kernelAddProc(p2) == SUCCESS){
printf("2nd process addedn");}
if (kernelAddProc(p3) == SUCCESS){
printf("3rd process addedn");}
kernelLoop();
}
microkernel(3);
Console Output:
---------------------------
1st process added
2nd process added
3rd process added
Ite. 0, Slot. 0: Process 1
Ite. 1, Slot. 1: Process 2
Ite. 2, Slot. 2: Process 3
Ite. 3, Slot. 3: Process 1
Ite. 4, Slot. 0: Process 3
Ite. 5, Slot. 1: Process 1
Ite. 6, Slot. 2: Process 3
Ite. 7, Slot. 3: Process 1
Ite. 8, Slot. 0: Process 3
...
---------------------------
● Notes:
● Only process 1
and 3 are
repeating
● The user don't
notice that the
pool is finite*
microkernel(3);
//third implementation
//time conditions added
kernel_example(3+3/10);
microkernel(3);
● The first modification is to add one counter
to each process
//process struct
typedef struct {
ptrFunc function;
int period;
int start;
} process;
microkernel(3);
● We must create an function that will run on
each timer interrupt updating the counters
void isr(void) interrupt 1{
unsigned char i;
i = ini;
while(i!=fim){
if((pool[i].start)>(MIN_INT)){
pool[i].start--;
}
i = (i+1)%SLOT_SIZE;
}
}
microkernel(3);
● The add process function will be the
responsible to initialize correctly the fields
char AddProc(process newProc){
//checking for free space
if ( ((end+1)%SLOT_SIZE) != start){
pool[end] = newProc;
//increment start timer with period
pool[end].start += newProc.period;
end = (end+1)%SLOT_SIZE;
return SUCCESS;
}
return FAIL;
}
microkernel(3);
if (start != end){
//Finding the process with the smallest start
j = (start+1)%SLOT_SIZE;
next = start;
while(j!=end){
if (pool[j].start < pool[next].start){
next = j;
}
j = (j+1)%SLOT_SIZE;
}
//exchanging positions in the pool
tempProc = pool[next];
pool[next] = pool[start];
pool[start] = tempProc;
while(pool[start].start>0){
}//great place to use low power mode
if ( (*(pool[ini].function))() == REPEAT ){
AddProc(&(vetProc[ini]));
}
ini = (ini+1)%SLOT_SIZE;
}
microkernel(3);
running_the_kernel(3.4);
“My board's programming” also works =)
void dd_controler (float i){
device_driver_pattern(5.1);
controller_engine(5.2);
isr_abstract_layer(5.3);
driver_callback(5.4);
}
device_driver_controller(4);
device_driver_pattern(5.1);
device_driver_controller(4);
● What is a driver?
● An interface layer that translate hardware to
software
● Device driver standardization
● Fundamental for dynamic drivers load
device_driver_controller(4);
● Parameters problem
● The kernel must be able to communicate in the
same way with all drivers
● Each function in each driver have different
types and quantities of parameters
● Solution
● Pointer to void
device_driver_controller(4);
● Driver example
Generic Device Driver
drvGeneric
-thisDriver: driver
-this_functions: ptrFuncDrv[ ]
-callbackProcess: process*
+availableFunctions: enum = {GEN_FUNC_1, GEN_FUNC_2 }
-init(parameters:void*): char
-genericDrvFunction(parameters:void*): char
-genericIsrSetup(parameters:void*): char
+getDriver(): driver*
driver
+drv_id: char
+functions: ptrFuncDrv[ ]
+drv_init: ptrFuncDrv
device_driver_controller(4);
controller_engine(5.2);
device_driver_controller(4);
● Device Driver Controller
● Used as an interface layer between the kernel
and the drivers
● Can “discover” all available drivers (statically or
dynamically)
● Store information about all loaded drivers
● Responsible to interpret the messages received
from the kernel
device_driver_controller(4);
char initDriver(char newDriver) {
char resp = FAIL;
if(dLoaded < QNTD_DRV) {
//get driver struct
drivers[dLoaded] = drvInitVect[newDriver]();
//should test if driver was loaded correcly
resp = drivers[dLoaded]->drv_init(&newDriver);
dLoaded++;
}
return resp;
}
device_driver_controller(4);
char callDriver(char drv_id,
char func_id,
void *param) {
char i;
for (i = 0; i < dLoaded; i++) {
//find the right driver
if (drv_id == drivers[i]->drv_id) {
return
drivers[i]->func[func_id].func_ptr(param);
}
}
return DRV_FUNC_NOT_FOUND;
}
device_driver_controller(4);
void main(void) {
//system initialization
//kernel also initializate the controller
kernelInitialization();
initDriver(DRV_LCD);
callDriver(DRV_LCD, LCD_CHAR, 'D');
callDriver(DRV_LCD, LCD_CHAR, 'E');
callDriver(DRV_LCD, LCD_CHAR, 'F');
callDriver(DRV_LCD, LCD_CHAR, 'C');
callDriver(DRV_LCD, LCD_CHAR, '0');
callDriver(DRV_LCD, LCD_CHAR, 'N');
callDriver(DRV_LCD, LCD_CHAR, '@');
callDriver(DRV_LCD, LCD_CHAR, 'L');
callDriver(DRV_LCD, LCD_CHAR, 'A');
callDriver(DRV_LCD, LCD_CHAR, 'S');
}
device_driver_controller(4);
Where are the defines?
device_driver_controller(4);
● In order to simplify the design, each driver
build its function define enum.
● The controller builds a driver define enum
enum {
LCD_COMMAND, LCD_CHAR, LCD_INTEGER, LCD_END
};
enum {
DRV_INTERRUPT, DRV_TIMER, DRV_LCD, DRV_END
};
device_driver_controller(4);
isr_abstract_layer(5.3);
device_driver_controller(4);
● Interrupts are closely related to hardware
● Each architecture AND compiler pose a
different programming approach
● How to hide this from programmer?
//SDCC compiler way
void isr(void) interrupt 1{
thisInterrupt();
}
//C18 compiler way
void isr (void){
thisInterrupt();
}
#pragma code highvector=0x08
void highvector(void){
_asm goto isr _endasm
}
#pragma code
device_driver_controller(4);
//Inside drvInterrupt.c
//defining the pointer to use in ISR callback
typedef void (*intFunc)(void);
//store the pointer to ISR here
static intFunc thisInterrupt;
//Set interrupt function to be called
char setInterruptFunc(void *parameters) {
thisInterrupt = (intFunc) parameters;
return SUCESS;
}
device_driver_controller(4);
//Interrupt function set without knowing hard/compiler issues
void timerISR(void) {
callDriver(DRV_TIMER, TMR_RESET, 1000);
kernelClock();
}
void main (void){
kernelInit();
initDriver(DRV_TIMER);
initDriver(DRV_INTERRUPT);
callDriver(DRV_TIMER, TMR_START, 0);
callDriver(DRV_TIMER, TMR_INT_EN, 0);
callDriver(DRV_INTERRUPT, INT_TIMER_SET, (void*)timerISR);
callDriver(DRV_INTERRUPT, INT_ENABLE, 0);
kernelLoop();
}
device_driver_controller(4);
driver_callback(5.4);
device_driver_controller(4);
How to make efficient use of CPU peripherals
without using pooling or hard-coding the
interrupts?
device_driver_controller(4);
Callback functions
device_driver_controller(4);
● Callback functions resemble events in high
level programming
● e.g.: When the mouse clicks in the button X,
please call function Y.
● The desired hardware must be able to rise
an interrupt
● Part of the work is done under interrupt
context, preferable the faster part
Generic Driver
Interrupt Driver
Setup ISR
callback
Interrupt Driver
Generic Driver
Call ISR
callback
Kernel
Add callback
Process
Kernel
Main Process
Execute process
Generic Driver
Request data
(callback passed)
Kernel
Callback
Process
Execute process
Main
Programflow
Interrupt
context
device_driver_controller(4);
device_driver_controller(4);
//********** Excerpt from drvAdc.c **********
// called from setup time to enable ADC interrupt
// and setup ADC ISR callback
char enableAdcInterrup(void* parameters){
callDriver(DRV_INTERRUPT,INT_ADC_SET,(void*)adcISR);
BitClr(PIR1,6);
return FIM_OK;
}
//********** Excerpt from drvInterrupt.c **********
// store the pointer to the interrupt function
typedef void (*intFunc)(void);
static intFunc adcInterrupt;
// function to set ADC ISR callback for latter use
char setAdcInt(void *parameters) {
adcInterrupt = (intFunc)parameters;
return FIM_OK;
}
device_driver_controller(4);
//********** Excerpt from main.c **********
// Process called by the kernel
char adc_func(void) {
//creating callback process
static process proc_adc_callback = {adc_callback, 0, 0};
callDriver(DRV_ADC,ADC_START,&proc_adc_callback);
return REPEAT;
}
//********** Excerpt from drvAdc.c **********
//function called by the process adc_func (via drv controller)
char startConversion(void* parameters){
callBack = parameters;
ADCON0 |= 0b00000010; //start conversion
return SUCCESS;
}
device_driver_controller(4);
//********** Excerpt from drvInterrupt.c **********
//interrupt function
void isr(void) interrupt 1 {
if (BitTst(INTCON, 2)) { //Timer overflow
}
if (BitTst(PIR1, 6)) { //ADC conversion finished
//calling ISR callback stored
adcInterrupt();
}
}
//********** Excerpt from drvAdc.c **********
//ADC ISR callback function
void adcISR(void){
value = ADRESH;
value <<= 8;
value += ADRESL;
BitClr(PIR1,6);
kernelAddProc(callBack);
}
device_driver_controller(4);
//********** Excerpt from main.c **********
//callback function started from the kernel
char adc_callback(void) {
unsigned int resp;
//getting the converted value
callDriver(DRV_ADC,ADC_LAST_VALUE,&resp);
//changing line and printing on LCD
callDriver(DRV_LCD,LCD_LINE,1);
callDriver(DRV_LCD,LCD_INTEGER,resp);
return SUCCESS;
}
My board's programming!
“Don't Reinvent The Wheel, Unless You Plan
on Learning More About Wheels”
Jeff Atwood

More Related Content

What's hot

Lecture 3a analog to digital converter
Lecture 3a   analog to digital converterLecture 3a   analog to digital converter
Lecture 3a analog to digital converter
أشرف أمجد الشريف
 
STM32 MCU Family
STM32 MCU FamilySTM32 MCU Family
STM32 MCU Family
Premier Farnell
 
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLERGSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
Md. Moktarul Islam
 
Micrcontroller iv sem lab manual
Micrcontroller iv sem lab manualMicrcontroller iv sem lab manual
Micrcontroller iv sem lab manual
RohiniHM2
 
Introduction to i.MX27 Multimedia Applications Processors
Introduction to i.MX27 Multimedia Applications ProcessorsIntroduction to i.MX27 Multimedia Applications Processors
Introduction to i.MX27 Multimedia Applications Processors
Premier Farnell
 
Lecture 4 i2 c bus & interrupts
Lecture 4   i2 c bus & interruptsLecture 4   i2 c bus & interrupts
Lecture 4 i2 c bus & interrupts
أشرف أمجد الشريف
 
Synthesis & FPGA Implementation of UART IP Soft Core
Synthesis & FPGA Implementation of UART IP Soft CoreSynthesis & FPGA Implementation of UART IP Soft Core
Synthesis & FPGA Implementation of UART IP Soft Core
ijsrd.com
 
Meta88full
Meta88fullMeta88full
Meta88full
Tony Tagle
 
What is POR,LVD,WDT ?
What is POR,LVD,WDT ?What is POR,LVD,WDT ?
What is POR,LVD,WDT ?
Pantech ProLabs India Pvt Ltd
 
I2c drivers
I2c driversI2c drivers
I2c drivers
Pradeep Tewani
 
report cs
report csreport cs
8-Bit CMOS Microcontrollers with nanoWatt Technology
8-Bit CMOS Microcontrollers with nanoWatt Technology8-Bit CMOS Microcontrollers with nanoWatt Technology
8-Bit CMOS Microcontrollers with nanoWatt Technology
Premier Farnell
 
Em s7 plc
Em s7 plcEm s7 plc
Em s7 plc
chethanraj
 
174085193 pic-prgm-manual
174085193 pic-prgm-manual174085193 pic-prgm-manual
174085193 pic-prgm-manual
Arun Shan
 
Introduction to pic microcontroller
Introduction to pic microcontrollerIntroduction to pic microcontroller
Introduction to pic microcontroller
RAMPRAKASHT1
 
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
Victor Asanza
 
AAME ARM Techcon2013 003v02 Software Development
AAME ARM Techcon2013 003v02  Software DevelopmentAAME ARM Techcon2013 003v02  Software Development
AAME ARM Techcon2013 003v02 Software Development
Anh Dung NGUYEN
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processor
Dhaval Kaneria
 
03 Mcu Day 2009 (C2000) 8 13 Editado
03   Mcu Day 2009 (C2000) 8 13   Editado03   Mcu Day 2009 (C2000) 8 13   Editado
03 Mcu Day 2009 (C2000) 8 13 Editado
Texas Instruments
 
eCOG1X 16-bit Microcontrollers
eCOG1X 16-bit MicrocontrollerseCOG1X 16-bit Microcontrollers
eCOG1X 16-bit Microcontrollers
Premier Farnell
 

What's hot (20)

Lecture 3a analog to digital converter
Lecture 3a   analog to digital converterLecture 3a   analog to digital converter
Lecture 3a analog to digital converter
 
STM32 MCU Family
STM32 MCU FamilySTM32 MCU Family
STM32 MCU Family
 
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLERGSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
GSM 1308 MODEM CONTROL USING PIC-16F877A MICROCONTROLLER
 
Micrcontroller iv sem lab manual
Micrcontroller iv sem lab manualMicrcontroller iv sem lab manual
Micrcontroller iv sem lab manual
 
Introduction to i.MX27 Multimedia Applications Processors
Introduction to i.MX27 Multimedia Applications ProcessorsIntroduction to i.MX27 Multimedia Applications Processors
Introduction to i.MX27 Multimedia Applications Processors
 
Lecture 4 i2 c bus & interrupts
Lecture 4   i2 c bus & interruptsLecture 4   i2 c bus & interrupts
Lecture 4 i2 c bus & interrupts
 
Synthesis & FPGA Implementation of UART IP Soft Core
Synthesis & FPGA Implementation of UART IP Soft CoreSynthesis & FPGA Implementation of UART IP Soft Core
Synthesis & FPGA Implementation of UART IP Soft Core
 
Meta88full
Meta88fullMeta88full
Meta88full
 
What is POR,LVD,WDT ?
What is POR,LVD,WDT ?What is POR,LVD,WDT ?
What is POR,LVD,WDT ?
 
I2c drivers
I2c driversI2c drivers
I2c drivers
 
report cs
report csreport cs
report cs
 
8-Bit CMOS Microcontrollers with nanoWatt Technology
8-Bit CMOS Microcontrollers with nanoWatt Technology8-Bit CMOS Microcontrollers with nanoWatt Technology
8-Bit CMOS Microcontrollers with nanoWatt Technology
 
Em s7 plc
Em s7 plcEm s7 plc
Em s7 plc
 
174085193 pic-prgm-manual
174085193 pic-prgm-manual174085193 pic-prgm-manual
174085193 pic-prgm-manual
 
Introduction to pic microcontroller
Introduction to pic microcontrollerIntroduction to pic microcontroller
Introduction to pic microcontroller
 
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
⭐⭐⭐⭐⭐ Monitoring of system memory usage embedded in #FPGA
 
AAME ARM Techcon2013 003v02 Software Development
AAME ARM Techcon2013 003v02  Software DevelopmentAAME ARM Techcon2013 003v02  Software Development
AAME ARM Techcon2013 003v02 Software Development
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processor
 
03 Mcu Day 2009 (C2000) 8 13 Editado
03   Mcu Day 2009 (C2000) 8 13   Editado03   Mcu Day 2009 (C2000) 8 13   Editado
03 Mcu Day 2009 (C2000) 8 13 Editado
 
eCOG1X 16-bit Microcontrollers
eCOG1X 16-bit MicrocontrollerseCOG1X 16-bit Microcontrollers
eCOG1X 16-bit Microcontrollers
 

Viewers also liked

As diferentes engenharias
As diferentes engenhariasAs diferentes engenharias
As diferentes engenharias
Rodrigo Almeida
 
Testing de software en instrumentos de pesar de funcionamiento no automatico ...
Testing de software en instrumentos de pesar de funcionamiento no automatico ...Testing de software en instrumentos de pesar de funcionamiento no automatico ...
Testing de software en instrumentos de pesar de funcionamiento no automatico ...
Rodrigo Almeida
 
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
Rodrigo Almeida
 
Instalacion de sistemas operativos
Instalacion de sistemas operativosInstalacion de sistemas operativos
Instalacion de sistemas operativos
Javier Santos
 
Working With Files
Working With FilesWorking With Files
Working With Files
User1test
 
大ざっぱにオブジェクト指向
大ざっぱにオブジェクト指向大ざっぱにオブジェクト指向
大ざっぱにオブジェクト指向
azuma satoshi
 
Lectionline xxviii domenica del t o 12 ottobre
Lectionline xxviii domenica del t o 12 ottobreLectionline xxviii domenica del t o 12 ottobre
Lectionline xxviii domenica del t o 12 ottobreMaike Loes
 
2010 Key Tax Numbers
2010 Key Tax Numbers2010 Key Tax Numbers
2010 Key Tax Numbers
Bennett Gordon Cfa Cfp
 
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
UGC Farmacia Granada
 
Paneton evelyn cavero
Paneton evelyn caveroPaneton evelyn cavero
Paneton evelyn caveroEviestefani
 
Group 1: Expository Mode
Group 1: Expository ModeGroup 1: Expository Mode
Group 1: Expository Mode
freshmancomp
 
La normalisation dans le domaine de l'information et de la documentation
La normalisation dans le domaine de l'information et de la documentationLa normalisation dans le domaine de l'information et de la documentation
La normalisation dans le domaine de l'information et de la documentation
Bibliothèque publique d'information - Centre Pompidou
 
Lectionline vi domenica del t o
Lectionline vi domenica del t oLectionline vi domenica del t o
Lectionline vi domenica del t oMaike Loes
 
Dasar pakatan rakyat
Dasar pakatan rakyatDasar pakatan rakyat
Dasar pakatan rakyat
pakatanrakyat
 
Io vangelo iv_avvento
Io vangelo iv_avventoIo vangelo iv_avvento
Io vangelo iv_avventoMaike Loes
 
Monthly highlights
Monthly highlightsMonthly highlights
Monthly highlights
Bennett Gordon Cfa Cfp
 
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrébenKozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
Violetta Joó
 
Perlbeginnes 9 lt_ytnobody
Perlbeginnes 9 lt_ytnobodyPerlbeginnes 9 lt_ytnobody
Perlbeginnes 9 lt_ytnobodyazuma satoshi
 
Iimk news vol.5
Iimk news vol.5Iimk news vol.5
Iimk news vol.5
Akshay Jadhao
 

Viewers also liked (20)

As diferentes engenharias
As diferentes engenhariasAs diferentes engenharias
As diferentes engenharias
 
Testing de software en instrumentos de pesar de funcionamiento no automatico ...
Testing de software en instrumentos de pesar de funcionamiento no automatico ...Testing de software en instrumentos de pesar de funcionamiento no automatico ...
Testing de software en instrumentos de pesar de funcionamiento no automatico ...
 
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
Seguridad de sistemas embebidos para el ámbito regulado - Alejandro Bertello ...
 
Instalacion de sistemas operativos
Instalacion de sistemas operativosInstalacion de sistemas operativos
Instalacion de sistemas operativos
 
Working With Files
Working With FilesWorking With Files
Working With Files
 
大ざっぱにオブジェクト指向
大ざっぱにオブジェクト指向大ざっぱにオブジェクト指向
大ざっぱにオブジェクト指向
 
Lectionline xxviii domenica del t o 12 ottobre
Lectionline xxviii domenica del t o 12 ottobreLectionline xxviii domenica del t o 12 ottobre
Lectionline xxviii domenica del t o 12 ottobre
 
2010 Key Tax Numbers
2010 Key Tax Numbers2010 Key Tax Numbers
2010 Key Tax Numbers
 
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
Modelo de farmacia en el Área de Gestión Sanitaria de Antequera. Ponencia de ...
 
Marzo
MarzoMarzo
Marzo
 
Paneton evelyn cavero
Paneton evelyn caveroPaneton evelyn cavero
Paneton evelyn cavero
 
Group 1: Expository Mode
Group 1: Expository ModeGroup 1: Expository Mode
Group 1: Expository Mode
 
La normalisation dans le domaine de l'information et de la documentation
La normalisation dans le domaine de l'information et de la documentationLa normalisation dans le domaine de l'information et de la documentation
La normalisation dans le domaine de l'information et de la documentation
 
Lectionline vi domenica del t o
Lectionline vi domenica del t oLectionline vi domenica del t o
Lectionline vi domenica del t o
 
Dasar pakatan rakyat
Dasar pakatan rakyatDasar pakatan rakyat
Dasar pakatan rakyat
 
Io vangelo iv_avvento
Io vangelo iv_avventoIo vangelo iv_avvento
Io vangelo iv_avvento
 
Monthly highlights
Monthly highlightsMonthly highlights
Monthly highlights
 
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrébenKozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
Kozma Szilárd: Nagy Attila Puli, avagy az árnyék én a sorsképlet tükrében
 
Perlbeginnes 9 lt_ytnobody
Perlbeginnes 9 lt_ytnobodyPerlbeginnes 9 lt_ytnobody
Perlbeginnes 9 lt_ytnobody
 
Iimk news vol.5
Iimk news vol.5Iimk news vol.5
Iimk news vol.5
 

Similar to Embedded systems development Defcon 19

Lcu14 101- coresight overview
Lcu14 101- coresight overviewLcu14 101- coresight overview
Lcu14 101- coresight overview
Linaro
 
Microcontroller from basic_to_advanced
Microcontroller from basic_to_advancedMicrocontroller from basic_to_advanced
Microcontroller from basic_to_advanced
Imran Sheikh
 
SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016
Koan-Sin Tan
 
TMS320C5x
TMS320C5xTMS320C5x
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOS
ICS
 
Micro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application DevelopmentMicro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application Development
Emertxe Information Technologies Pvt Ltd
 
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheapUWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
edlangley
 
Raspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application DevelopmentRaspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application Development
Corley S.r.l.
 
Atmel and pic microcontroller
Atmel and pic microcontrollerAtmel and pic microcontroller
Atmel and pic microcontroller
Tearsome Llantada
 
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
DefCamp
 
Picmico
PicmicoPicmico
Picmico
loges91
 
Rodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementationRodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementation
Felipe Prado
 
chapter2-part1-140329134839-phpapp02.pptx
chapter2-part1-140329134839-phpapp02.pptxchapter2-part1-140329134839-phpapp02.pptx
chapter2-part1-140329134839-phpapp02.pptx
SangeetaTripathi8
 
Chapter three embedded system corse ppt AASTU.pdf
Chapter three embedded system corse ppt AASTU.pdfChapter three embedded system corse ppt AASTU.pdf
Chapter three embedded system corse ppt AASTU.pdf
MitikuAbebe2
 
Introduction to Blackfin BF532 DSP
Introduction to Blackfin BF532 DSPIntroduction to Blackfin BF532 DSP
Introduction to Blackfin BF532 DSP
Pantech ProLabs India Pvt Ltd
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
chiportal
 
Design of control unit.pptx
Design of control unit.pptxDesign of control unit.pptx
Design of control unit.pptx
Shubham014
 
Arduino by yogesh t s'
Arduino by yogesh t s'Arduino by yogesh t s'
Arduino by yogesh t s'
tsyogesh46
 
Intro to GPGPU Programming with Cuda
Intro to GPGPU Programming with CudaIntro to GPGPU Programming with Cuda
Intro to GPGPU Programming with Cuda
Rob Gillen
 
Challenges in GPU compilers
Challenges in GPU compilersChallenges in GPU compilers
Challenges in GPU compilers
AnastasiaStulova
 

Similar to Embedded systems development Defcon 19 (20)

Lcu14 101- coresight overview
Lcu14 101- coresight overviewLcu14 101- coresight overview
Lcu14 101- coresight overview
 
Microcontroller from basic_to_advanced
Microcontroller from basic_to_advancedMicrocontroller from basic_to_advanced
Microcontroller from basic_to_advanced
 
SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016SoC Idling for unconf COSCUP 2016
SoC Idling for unconf COSCUP 2016
 
TMS320C5x
TMS320C5xTMS320C5x
TMS320C5x
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOS
 
Micro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application DevelopmentMicro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application Development
 
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheapUWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
UWE Linux Boot Camp 2007: Hacking embedded Linux on the cheap
 
Raspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application DevelopmentRaspberry Pi - HW/SW Application Development
Raspberry Pi - HW/SW Application Development
 
Atmel and pic microcontroller
Atmel and pic microcontrollerAtmel and pic microcontroller
Atmel and pic microcontroller
 
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
 
Picmico
PicmicoPicmico
Picmico
 
Rodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementationRodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementation
 
chapter2-part1-140329134839-phpapp02.pptx
chapter2-part1-140329134839-phpapp02.pptxchapter2-part1-140329134839-phpapp02.pptx
chapter2-part1-140329134839-phpapp02.pptx
 
Chapter three embedded system corse ppt AASTU.pdf
Chapter three embedded system corse ppt AASTU.pdfChapter three embedded system corse ppt AASTU.pdf
Chapter three embedded system corse ppt AASTU.pdf
 
Introduction to Blackfin BF532 DSP
Introduction to Blackfin BF532 DSPIntroduction to Blackfin BF532 DSP
Introduction to Blackfin BF532 DSP
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Design of control unit.pptx
Design of control unit.pptxDesign of control unit.pptx
Design of control unit.pptx
 
Arduino by yogesh t s'
Arduino by yogesh t s'Arduino by yogesh t s'
Arduino by yogesh t s'
 
Intro to GPGPU Programming with Cuda
Intro to GPGPU Programming with CudaIntro to GPGPU Programming with Cuda
Intro to GPGPU Programming with Cuda
 
Challenges in GPU compilers
Challenges in GPU compilersChallenges in GPU compilers
Challenges in GPU compilers
 

More from Rodrigo Almeida

Cryptology - Antônio Lacerda
Cryptology - Antônio LacerdaCryptology - Antônio Lacerda
Cryptology - Antônio Lacerda
Rodrigo Almeida
 
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
Rodrigo Almeida
 
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Rodrigo Almeida
 
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Rodrigo Almeida
 
Projeto de uma controladora de drivers
Projeto de uma controladora de driversProjeto de uma controladora de drivers
Projeto de uma controladora de drivers
Rodrigo Almeida
 
Desenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcadosDesenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcados
Rodrigo Almeida
 
Kernel com requisitos temporais
Kernel com requisitos temporaisKernel com requisitos temporais
Kernel com requisitos temporais
Rodrigo Almeida
 
Kernel cooperativo
Kernel cooperativoKernel cooperativo
Kernel cooperativo
Rodrigo Almeida
 
Definição de processos
Definição de processosDefinição de processos
Definição de processos
Rodrigo Almeida
 
Ponteiros de Função
Ponteiros de FunçãoPonteiros de Função
Ponteiros de Função
Rodrigo Almeida
 
Conceitos de ponteiros struct e buffers
Conceitos de ponteiros struct e buffersConceitos de ponteiros struct e buffers
Conceitos de ponteiros struct e buffers
Rodrigo Almeida
 
Introdução aos sistemas operacionais embarcados
Introdução aos sistemas operacionais embarcadosIntrodução aos sistemas operacionais embarcados
Introdução aos sistemas operacionais embarcados
Rodrigo Almeida
 
Segurança de sistemas: invasões, engenharia reversa e análise de virus
Segurança de sistemas: invasões, engenharia reversa e análise de virusSegurança de sistemas: invasões, engenharia reversa e análise de virus
Segurança de sistemas: invasões, engenharia reversa e análise de virus
Rodrigo Almeida
 
Comunicação serial
Comunicação serialComunicação serial
Comunicação serial
Rodrigo Almeida
 
Utilizando um Display de LCD
Utilizando um Display de LCDUtilizando um Display de LCD
Utilizando um Display de LCD
Rodrigo Almeida
 
Leitura de teclas com arranjo matricial
Leitura de teclas com arranjo matricialLeitura de teclas com arranjo matricial
Leitura de teclas com arranjo matricial
Rodrigo Almeida
 
Display de 7 segmentos multiplexados
Display de 7 segmentos multiplexadosDisplay de 7 segmentos multiplexados
Display de 7 segmentos multiplexados
Rodrigo Almeida
 
Acessando os periféricos de um microcontrolador
Acessando os periféricos de um microcontroladorAcessando os periféricos de um microcontrolador
Acessando os periféricos de um microcontrolador
Rodrigo Almeida
 
Acesso à memória e registros
Acesso à memória e registrosAcesso à memória e registros
Acesso à memória e registros
Rodrigo Almeida
 
Operações com Bits
Operações com BitsOperações com Bits
Operações com Bits
Rodrigo Almeida
 

More from Rodrigo Almeida (20)

Cryptology - Antônio Lacerda
Cryptology - Antônio LacerdaCryptology - Antônio Lacerda
Cryptology - Antônio Lacerda
 
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
Troca de contexto segura em sistemas operacionais embarcados utilizando de té...
 
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
 
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
Troca de contexto segura em sistemas operacionais embarcados utilizando técni...
 
Projeto de uma controladora de drivers
Projeto de uma controladora de driversProjeto de uma controladora de drivers
Projeto de uma controladora de drivers
 
Desenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcadosDesenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcados
 
Kernel com requisitos temporais
Kernel com requisitos temporaisKernel com requisitos temporais
Kernel com requisitos temporais
 
Kernel cooperativo
Kernel cooperativoKernel cooperativo
Kernel cooperativo
 
Definição de processos
Definição de processosDefinição de processos
Definição de processos
 
Ponteiros de Função
Ponteiros de FunçãoPonteiros de Função
Ponteiros de Função
 
Conceitos de ponteiros struct e buffers
Conceitos de ponteiros struct e buffersConceitos de ponteiros struct e buffers
Conceitos de ponteiros struct e buffers
 
Introdução aos sistemas operacionais embarcados
Introdução aos sistemas operacionais embarcadosIntrodução aos sistemas operacionais embarcados
Introdução aos sistemas operacionais embarcados
 
Segurança de sistemas: invasões, engenharia reversa e análise de virus
Segurança de sistemas: invasões, engenharia reversa e análise de virusSegurança de sistemas: invasões, engenharia reversa e análise de virus
Segurança de sistemas: invasões, engenharia reversa e análise de virus
 
Comunicação serial
Comunicação serialComunicação serial
Comunicação serial
 
Utilizando um Display de LCD
Utilizando um Display de LCDUtilizando um Display de LCD
Utilizando um Display de LCD
 
Leitura de teclas com arranjo matricial
Leitura de teclas com arranjo matricialLeitura de teclas com arranjo matricial
Leitura de teclas com arranjo matricial
 
Display de 7 segmentos multiplexados
Display de 7 segmentos multiplexadosDisplay de 7 segmentos multiplexados
Display de 7 segmentos multiplexados
 
Acessando os periféricos de um microcontrolador
Acessando os periféricos de um microcontroladorAcessando os periféricos de um microcontrolador
Acessando os periféricos de um microcontrolador
 
Acesso à memória e registros
Acesso à memória e registrosAcesso à memória e registros
Acesso à memória e registros
 
Operações com Bits
Operações com BitsOperações com Bits
Operações com Bits
 

Recently uploaded

Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 

Recently uploaded (20)

Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 

Embedded systems development Defcon 19

  • 1. Embedded System Design: From Electronics to Microkernel Development Rodrigo Maximiano Antunes de Almeida E-mail: rmaalmeida@gmail.com Twitter: @rmaalmeida Universidade Federal de Itajubá
  • 2. Creative Commons License The work ”Embedded System Design: From Electronics to Microkernel Development” of Rodrigo Maximiano Antunes de Almeida was licensed with Creative Commons 3.0 – Attribution – Non Commercial – Share Alike license. Additional permission can be given by the author through direct contact using the e-mail: rmaalmeida@gmail.com
  • 3. Workshop schedule ● Electronic building ● Board programming ● Kernel development
  • 4. Electronic building ● Electronics review ● Schematics ● Protoboard/breadboard ● System design ● Basic steps ● Microcontroller ● LCD ● Potentiometer
  • 6. Schematics ● Way to represent the components and its connections ● Each component has its own symbol ● Crossing wires only are connected if joined with a dot
  • 8. System design ● Steps on a generic electronic system design ● Define the objective(s) ● Choose the main components needed to achieve the objective ● Get the use example and recommendations from component datasheet ● Build the schematics ● Simulation of HW elements ● Board layout
  • 9. Datasheets ● The main source of information concerning electronics ● Presents ● Electrical characteristics ● Simplified schematics ● Use example ● Opcodes/API
  • 10. System design ● Objective ● Build digital voltage reader ● Main components ● Microcontroller ● LCD text display ● Potentiometer
  • 11. Microcontroller ● System-on-a-chip ● Processor ● Memory ● Input/Output peripherals ● Communication ● Safety components
  • 12. Microcontroller ● Xtal configuration ● Reset pin ● DC needs ● Many peripherals on the same pin
  • 14. LCD Display ● Data connection ● Backlite ● Current consumption ● Power on time/routine
  • 15. Potentiometer ● Linear/Log ● Used as voltage divisor ● Need an analog input ● Filter
  • 16. System design ● Cad tool: Fritzing (fritzing.org) 1
  • 18. Board programming ● Programmer ● IDE ● Basic concepts ● CPU Architecture ● HW configuration ● Memory access ● First program (He110 DEFC0N) ● Peripheral setup ● Second program (ADC read)
  • 19. Board programming ● Programmer ● PICkit3 ● Can use ICSP ● Can program a lot of Microchip products ● Also a debugger
  • 20. Board programming ● IDE ● MPLABX – Based on Netbeans ● Compiler ● SDCC – Based on GCC ● GPUtils
  • 21. Basic concepts ● PIC architecture
  • 23. Basic concepts ● HW configuration ● Some options must be set before the program start ● This can only be accomplished by special instructions ● Compiler datasheet
  • 24. Basic concepts ● HW configuration
  • 25. //CONFIG.H // No prescaler used __code char __at 0x300000 CONFIG1L = 0x01; // Internal Oscillator __code char __at 0x300001 CONFIG1H = 0x08; // Disabled-Controlled by SWDTEN bit __code char __at 0x300003 CONFIG2H = 0x00; // Disabled low voltage programming __code char __at 0x300006 CONFIG4L = 0x00; Basic concepts
  • 27. Basic concepts ● Build a pointer to a specific memory address: void main (void){ char *ptr; //pointing to the port D ptr = 0xF83; //changing all outputs to high *ptr = 0xFF; }
  • 28. //this is not an infinite loop! while(PORTD==PORTD); Basic concepts ● Building a header with all definitions ● __near = sfr region ● Volatile = can change without program acknowledge //BASIC.H #define PORTD (*(volatile __near unsigned char*)0xF83) #define TRISC (*(volatile __near unsigned char*)0xF94)
  • 29. Basic concepts ● Bitwise operations //bit set char bit = 2; char mask; mask = 1 << bit; arg = arg | mask; //one line arg = arg | (1<<bit) //using define #define BitSet(arg,bit) ((arg) |= (1<<bit)) #define BitClr(arg,bit) ((arg) &= ~(1<<bit)) #define BitFlp(arg,bit) ((arg) ^= (1<<bit)) #define BitTst(arg,bit) ((arg) & (1<<bit))
  • 30. First program ● Open MPLABX IDE ● configure SDCC and PICkit ● Create a project to: ● Initialize LCD ● Print "He110 DEFC0N"
  • 31. LCD communication ● The data is always an 8 bit information ● It may be split in two 4 bit "passes" ● The data may represent a character or a command ● They are distinguished by RS pin ● The data must be stable for "some time" ● In this period the EN pin must be set
  • 32. #define RS 0 #define EN 1 #define RW 2 void Delay40us(void) { //for 8MHz each instruction takes 0,5 us: //40/0,5 = 80 instruction unsigned char i; for(i = 0; i < 25; i++); //3 + 3 * 25 = 78 } LCD communication
  • 33. void LCD_comm(unsigned char data, char cmd){ if (cmd) BitClr(PORTC,RS); //cmd else BitSet(PORTC,RS); //data BitClr(PORTC,RW); // writing PORTD = cmd; BitSet(PORTC,EN); //enable read Delay40ms(); BitClr(PORTC,EN); //finish read } LCD communication
  • 34. void LCD_init(void){ unsigned char i; for (i=0; i<200; i++) Delay40us(); // initialize delay //pin configuration BitClr(TRISC,0); //RS BitClr(TRISC,1); //EN BitClr(TRISC,2); //RW TRISD = 0x00; //data //display initialization LCD_comm(0x38,1); //8bits, 2 lines, 5x8 LCD_comm(0x06,1); //increment mode LCD_comm(0x0F,1); //cursor ON LCD_comm(0x03,1); //clear internal counters LCD_comm(0x01,1); //clean display LCD_comm(0x80,1); //initial position } LCD communication
  • 35. LCD character creation ● The LCD can hold up to 8 custom characters ● Each character is a 5*8 matrix ● Translating: 40*64 b/w drawing area
  • 36. LCD character creation Source: http://www.8051projects.net/lcd-interfacing/lcd-custom-character.php
  • 37. LCD character creation //each line represents one "character" char defcon[48] = { 0x00,0x01,0x03,0x03,0x03,0x03,0x01,0x04, 0x0e,0x1f,0x04,0x04,0x1f,0x0e,0x11,0x1f, 0x00,0x10,0x18,0x18,0x18,0x18,0x10,0x04, 0x0c,0x03,0x00,0x00,0x00,0x03,0x0c,0x04, 0x00,0x00,0x1b,0x04,0x1b,0x00,0x00,0x00, 0x06,0x18,0x00,0x00,0x00,0x18,0x06,0x02 }; //first memmory position LCD_comm(0x40, 1); for(i=0; i<48; i++) { LCD_comm(defcon[i],0); }
  • 38. Peripherals setup ● Get on the datasheet the information about the peripheral registers and configuration info
  • 40. void ADC_init(void) { BitSet(TRISA,0); //pin setup ADCON0 = 0b00000001; //channel select ADCON1 = 0b00001110; //ref = source ADCON2 = 0b10101010; //t_conv = 12 TAD } ADC setup
  • 41. unsigned int ADC_read(void) { unsigned int ADvalue; BitSet(ADCON0,1); //start conversion while(BitTst(ADCON0,1)); //wait ADvalue = ADRESH; //read result ADvalue <<= 8; ADvalue += ADRESL; return ADvalor; } ADC setup
  • 42. Second program ● Read ADC value and present in LCD
  • 43. A little break to follow 3-2-1 DEFC0N rule! Could not found any picture of Garfield taking shower =/
  • 44. //today topics void main (void){ //variable declaration kernel_project(1); //initialization concepts(2); //hard-work microkernel(3); device_driver_controller(4); }
  • 45. void kernel_project (float i){ what_is_a_kernel(1.1); alternatives(1.2); monolithic_vs_microkernel(1.3); kernel_design_decisions(1.4); this_course_decisions(1.5); }
  • 48. kernel_project(1); ● Kernel tasks: 1)Manage and coordinate the processes execution using “some criteria” 2)Manage the free memory and coordinate the processes access to it 3)Intermediate the communication between the hardware drivers and the processes
  • 50. kernel_project(1); ● Improve home design ● Reuse code more efficiently ● Full control over the source ● Specific tweeks to the kernel ● Faster context switch routine ● More control over driver issues (interrupts)
  • 52. kernel_project(1); ● Kernel overhead (both in time and memory) ● Free and paid alternatives ● Time intensive project ● Continuous development
  • 54. kernel_project(1); ● Alternatives ● Windows Embedded Compact® ● VxWorks® ● X RTOS® ● uClinux ● FreeRTOS ● BRTOS
  • 55. kernel_project(1); ● Monolithic kernel versus microkernel ● Linus Torvalds and Andrew Tanenbaum
  • 56. kernel_project(1); ● Kernel design decisions ● I/O devices management ● Process management ● System safety
  • 57. kernel_project(1); ● Our decisions: ● Microkernel ● Non-preemptive ● Cooperative ● No memory management ● Process scheduled based on timer ● Isolate drivers using a controller
  • 58. void concepts (float i){ function_pointers(2.1); structs(2.2); circular_buffers(2.3); temporal_conditions(2.4); void_pointers(2.5); }
  • 60. concepts(2); ● Necessity: ● Make an image editor that can choose the right function to call ● 1st Implementation ● Use a option parameter as a switch operator
  • 61. concepts(2); image Blur(image nImg){} image Sharpen(image nImg){} image imageEditorEngine(image nImg, int opt){ image temp; switch(opt){ case 1: temp = Sharpen(nImg); break; case 2: temp = Blur(nImg); break; } return temp; }
  • 62. concepts(2); ● Function pointers ● Work almost as a normal pointer ● Hold the address of a function start point instead the address of a variable ● The compiler need no known the function signature to pass the correct parameters and the return value. ● Awkard declaration (it is best to use a typedef)
  • 63. concepts(2); //defining the type pointerTest //it is a pointer to function that: // receives no parameter // returns no parameter typedef void (*pointerTest)(void); //Function to be called void nop (void){ __asm NOP __endasm } //creating an pointerTest variable; pointerTest foo; foo = nop; (*foo)(); //calling the function via pointer
  • 64. concepts(2); Re-code the image editor engine using function pointers
  • 65. concepts(2); image Blur(image nImg){} image Sharpen(image nImg){} typedef image (*ptrFunc)(image nImg); //image editor engine image imageEditorEngine(ptrFunc function, image nImg){ image temp; temp = (*function)(nImg); return temp; }
  • 66. concepts(2); ● Good ● New function additions do not alter the engine ● The engine only needs to be tested once ● Can change the function implementations dynamically ● Bad ● More complex code (function pointers are not so easy to work with) ● Not all compilers support function pointers
  • 68. concepts(2); // struct declaration typedef struct{ unsigned short int age; char name[51]; float weight; }people; ● Structs are composed variables. ● Group lots of information as if they were one single variable. ● A vector that each position stores a different type
  • 69. void main(void){ struct people myself = {26, "Rodrigo", 70.5}; myself.age = 27; //using each variable from the struct printf("Age: %dn", myself.age); printf("Name: %sn", myself.name); printf("Weight: %fn", myself.weight); return 0; } concepts(2);
  • 70. // struct declaration typedef struct{ unsigned short int *age; char *name[51]; float *weight; }people; void main(void){ struct people myself = {26, "Rodrigo", 70.5}; //using each variable from the struct printf("Age: %dn", myself->age); printf("Name: %sn", myself->name); printf("Weight: %fn", myself->weight); return 0; } concepts(2);
  • 72. concepts(2); ● Circular Buffers ● “Endless” memory spaces ● Use FIFO aproach ● Store temporary data ● Can implemented using vectors or linked-lists
  • 73. concepts(2); ● Vector implementation ● Uses less space ● Need special caution when cycling ● Problem to differentiate full from empty
  • 74. #define CB_SIZE 10 int circular_buffer[CB_SIZE]; int index=0; for(;;){ //do anything with the buffer circular_buffer[index] = index; //increment the index index = (index+1)%CB_SIZE; } concepts(2);
  • 75. concepts(2); #define CB_SIZE 10 int circular_buffer[CB_SIZE]; int start=0, end=0; char AddBuff(int newData) { //check if there is space to add a number if ( ((end+1)%CB_SIZE) != start) { circular_buffer[end] = newData; end = (end+1)%CB_SIZE; return SUCCESS; } return FAIL; }
  • 77. concepts(2); In the majority part of embedded systems, we need to guarantee that a function will be executed in a certain frequency. Some systems may even fail if these deadlines are not met.
  • 78. concepts(2); ● To implement temporal conditions: 1)There must be a tick event that occurs with a precise frequency 2)The kernel must be informed of the execution frequency needed for each process. 3)The sum of process duration must “fit” within the processor available time.
  • 79. concepts(2); ● 1st condition: ● Needs an internal timer that can generate an interrupt. ● 2nd condition: ● Add the information for each process when creating it ● 3rd condition: ● Test, test and test. ● If fail, change chip first, optimize only on last case
  • 80. concepts(2); ● Scheduling processes: ● Using a finite timer to schedule will result in overflow ● Example: scheduling 2 processes for 10 and 50 seconds ahead.
  • 81. concepts(2); ● And if two process are to be called in the same time?
  • 82. concepts(2); ● Question: ● From the timeline above (only the timeline) is P2 late or it was scheduled to happen 55(s) from now?
  • 83. concepts(2); ● Solution: ● Use a downtime counter for each process instead of setting a trigger time. ● Problem: ● Each counter must be decremented in the interrupt subroutine. ● Is it a problem for your system?
  • 85. concepts(2); ● Void pointers ● Abstraction that permits to the programmer to pass parameters with different types to the same function. ● The function which is receiving the parameter must know how to deal with it ● It can not be used without proper casting!
  • 86. concepts(2); char *name = "Paulo"; double weight = 87.5; unsigned int children = 3; void main (void){ //its not printf, yet. print(0, &name); print(1, &weight); print(2, &children); }
  • 87. concepts(2); void print(int option; void *parameter){ switch(option){ case 0: printf("%s",(char*)parameter); break; case 1: printf("%f",*((double*)parameter)); break; case 2: printf("%d",*((unsigned int*)parameter)); break; } }
  • 88. void microkernel (float i){ init_kernel(3.0); for(int i=1; i<4; i++;) { kernel_example(3+i/10); } running_the_kernel(3.4); }
  • 90. microkernel(3); ● The examples will use a minimum of hardware or platform specific commands. ● Some actions (specifically the timer) needs hardware access.
  • 92. microkernel(3); ● In this first example we will build the main part of our kernel. ● It should have a way to store which functions are needed to be executed and in which order. ● This will be done by a static vector of pointers to function //pointer function declaration typedef void(*ptrFunc)(void); //process pool static ptrFunc pool[4];
  • 93. microkernel(3); ● Each process is a function with the same signature of ptrFunc void tst1(void){ printf("Process 1n"); } void tst2(void){ printf("Process 2n"); } void tst3(void){ printf("Process 3n"); }
  • 94. microkernel(3); ● The kernel itself consists of three functions: ● One to initialize all the internal variables ● One to add a new process ● One to execute the main kernel loop //kernel internal variables ptrFunc pool[4]; int end; //kernel function's prototypes void kernelInit(void); void kernelAddProc(ptrFunc newFunc); void kernelLoop(void);
  • 95. microkernel(3); //kernel function's implementation void kernelInit(void){ end = 0; } void kernelAddProc(ptrFunc newFunc){ if (end <4){ pool[end] = newFunc; end++; } }
  • 96. microkernel(3); //kernel function's implementation void kernelLoop(void){ int i; for(;;){ //cycle through the processes for(i=0; i<end; i++){ (*pool[i])(); } } }
  • 99. microkernel(3); //second implementation //circular buffer and struct added kernel_example(3+2/10);
  • 100. microkernel(3); ● The only struct field is the function pointer. Other fields will be added latter. ● The circular buffer open a new possibility: ● A process now can state if it wants to be rescheduled or if it is a one-time run process ● In order to implement this every process must return a code. ● This code also says if there was any error in the process execution
  • 101. microkernel(3); //return code #define SUCCESS 0 #define FAIL 1 #define REPEAT 2 //function pointer declaration typedef char(*ptrFunc)(void); //process struct typedef struct { ptrFunc function; } process; process pool[POOL_SIZE];
  • 102. microkernel(3); char kernelInit(void){ start = 0; end = 0; return SUCCESS; } char kernelAddProc(process newProc){ //checking for free space if ( ((end+1)%POOL_SIZE) != start){ pool[end] = newProc; end = (end+1)%POOL_SIZE; return SUCCESS; } return FAIL; }
  • 103. microkernel(3); void kernelLoop(void){ int i=0; for(;;){ //Do we have any process to execute? if (start != end){ printf("Ite. %d, Slot. %d: ", i, start); //check if there is need to reschedule if ((*(pool[start].Func))() == REPEAT){ kernelAddProc(pool[start]); } //prepare to get the next process; start = (start+1)%POOL_SIZE; i++; // only for debug; } } }
  • 104. microkernel(3); //vetor de struct process pool[POOL_SIZE]; // pool[i] // pool[i].func // *(pool[i].func) // (*(pool[i].func))() //vetor de ponteiro de struct process* pool[POOL_SIZE]; // pool[i] // pool[i].func // pool[i]->func // pool[i]->func()
  • 105. microkernel(3); void kernelLoop(void){ int i=0; for(;;){ //Do we have any process to execute? if (start != end){ printf("Ite. %d, Slot. %d: ", i, start); //check if there is need to reschedule if (pool[start]->Func() == REPEAT){ kernelAddProc(pool[start]); } //prepare to get the next process; start = (start+1)%POOL_SIZE; i++; // only for debug; } } }
  • 106. microkernel(3); void tst1(void){ printf("Process 1n"); return REPEAT; } void tst2(void){ printf("Process 2n"); return SUCCESS; } void tst3(void){ printf("Process 3n"); return REPEAT; } ● Presenting the new processes
  • 107. microkernel(3); void main(void){ //declaring the processes process p1 = {tst1}; process p2 = {tst2}; process p3 = {tst3}; kernelInit(); //Test if the process was added successfully if (kernelAddProc(p1) == SUCCESS){ printf("1st process addedn");} if (kernelAddProc(p2) == SUCCESS){ printf("2nd process addedn");} if (kernelAddProc(p3) == SUCCESS){ printf("3rd process addedn");} kernelLoop(); }
  • 108. microkernel(3); Console Output: --------------------------- 1st process added 2nd process added 3rd process added Ite. 0, Slot. 0: Process 1 Ite. 1, Slot. 1: Process 2 Ite. 2, Slot. 2: Process 3 Ite. 3, Slot. 3: Process 1 Ite. 4, Slot. 0: Process 3 Ite. 5, Slot. 1: Process 1 Ite. 6, Slot. 2: Process 3 Ite. 7, Slot. 3: Process 1 Ite. 8, Slot. 0: Process 3 ... --------------------------- ● Notes: ● Only process 1 and 3 are repeating ● The user don't notice that the pool is finite*
  • 110. microkernel(3); ● The first modification is to add one counter to each process //process struct typedef struct { ptrFunc function; int period; int start; } process;
  • 111. microkernel(3); ● We must create an function that will run on each timer interrupt updating the counters void isr(void) interrupt 1{ unsigned char i; i = ini; while(i!=fim){ if((pool[i].start)>(MIN_INT)){ pool[i].start--; } i = (i+1)%SLOT_SIZE; } }
  • 112. microkernel(3); ● The add process function will be the responsible to initialize correctly the fields char AddProc(process newProc){ //checking for free space if ( ((end+1)%SLOT_SIZE) != start){ pool[end] = newProc; //increment start timer with period pool[end].start += newProc.period; end = (end+1)%SLOT_SIZE; return SUCCESS; } return FAIL; }
  • 113. microkernel(3); if (start != end){ //Finding the process with the smallest start j = (start+1)%SLOT_SIZE; next = start; while(j!=end){ if (pool[j].start < pool[next].start){ next = j; } j = (j+1)%SLOT_SIZE; } //exchanging positions in the pool tempProc = pool[next]; pool[next] = pool[start]; pool[start] = tempProc; while(pool[start].start>0){ }//great place to use low power mode if ( (*(pool[ini].function))() == REPEAT ){ AddProc(&(vetProc[ini])); } ini = (ini+1)%SLOT_SIZE; }
  • 116. void dd_controler (float i){ device_driver_pattern(5.1); controller_engine(5.2); isr_abstract_layer(5.3); driver_callback(5.4); }
  • 118. device_driver_controller(4); ● What is a driver? ● An interface layer that translate hardware to software ● Device driver standardization ● Fundamental for dynamic drivers load
  • 119. device_driver_controller(4); ● Parameters problem ● The kernel must be able to communicate in the same way with all drivers ● Each function in each driver have different types and quantities of parameters ● Solution ● Pointer to void
  • 120. device_driver_controller(4); ● Driver example Generic Device Driver drvGeneric -thisDriver: driver -this_functions: ptrFuncDrv[ ] -callbackProcess: process* +availableFunctions: enum = {GEN_FUNC_1, GEN_FUNC_2 } -init(parameters:void*): char -genericDrvFunction(parameters:void*): char -genericIsrSetup(parameters:void*): char +getDriver(): driver* driver +drv_id: char +functions: ptrFuncDrv[ ] +drv_init: ptrFuncDrv
  • 122. device_driver_controller(4); ● Device Driver Controller ● Used as an interface layer between the kernel and the drivers ● Can “discover” all available drivers (statically or dynamically) ● Store information about all loaded drivers ● Responsible to interpret the messages received from the kernel
  • 123. device_driver_controller(4); char initDriver(char newDriver) { char resp = FAIL; if(dLoaded < QNTD_DRV) { //get driver struct drivers[dLoaded] = drvInitVect[newDriver](); //should test if driver was loaded correcly resp = drivers[dLoaded]->drv_init(&newDriver); dLoaded++; } return resp; }
  • 124. device_driver_controller(4); char callDriver(char drv_id, char func_id, void *param) { char i; for (i = 0; i < dLoaded; i++) { //find the right driver if (drv_id == drivers[i]->drv_id) { return drivers[i]->func[func_id].func_ptr(param); } } return DRV_FUNC_NOT_FOUND; }
  • 125. device_driver_controller(4); void main(void) { //system initialization //kernel also initializate the controller kernelInitialization(); initDriver(DRV_LCD); callDriver(DRV_LCD, LCD_CHAR, 'D'); callDriver(DRV_LCD, LCD_CHAR, 'E'); callDriver(DRV_LCD, LCD_CHAR, 'F'); callDriver(DRV_LCD, LCD_CHAR, 'C'); callDriver(DRV_LCD, LCD_CHAR, '0'); callDriver(DRV_LCD, LCD_CHAR, 'N'); callDriver(DRV_LCD, LCD_CHAR, '@'); callDriver(DRV_LCD, LCD_CHAR, 'L'); callDriver(DRV_LCD, LCD_CHAR, 'A'); callDriver(DRV_LCD, LCD_CHAR, 'S'); }
  • 127. device_driver_controller(4); ● In order to simplify the design, each driver build its function define enum. ● The controller builds a driver define enum enum { LCD_COMMAND, LCD_CHAR, LCD_INTEGER, LCD_END }; enum { DRV_INTERRUPT, DRV_TIMER, DRV_LCD, DRV_END };
  • 129. device_driver_controller(4); ● Interrupts are closely related to hardware ● Each architecture AND compiler pose a different programming approach ● How to hide this from programmer? //SDCC compiler way void isr(void) interrupt 1{ thisInterrupt(); } //C18 compiler way void isr (void){ thisInterrupt(); } #pragma code highvector=0x08 void highvector(void){ _asm goto isr _endasm } #pragma code
  • 130. device_driver_controller(4); //Inside drvInterrupt.c //defining the pointer to use in ISR callback typedef void (*intFunc)(void); //store the pointer to ISR here static intFunc thisInterrupt; //Set interrupt function to be called char setInterruptFunc(void *parameters) { thisInterrupt = (intFunc) parameters; return SUCESS; }
  • 131. device_driver_controller(4); //Interrupt function set without knowing hard/compiler issues void timerISR(void) { callDriver(DRV_TIMER, TMR_RESET, 1000); kernelClock(); } void main (void){ kernelInit(); initDriver(DRV_TIMER); initDriver(DRV_INTERRUPT); callDriver(DRV_TIMER, TMR_START, 0); callDriver(DRV_TIMER, TMR_INT_EN, 0); callDriver(DRV_INTERRUPT, INT_TIMER_SET, (void*)timerISR); callDriver(DRV_INTERRUPT, INT_ENABLE, 0); kernelLoop(); }
  • 133. device_driver_controller(4); How to make efficient use of CPU peripherals without using pooling or hard-coding the interrupts?
  • 135. device_driver_controller(4); ● Callback functions resemble events in high level programming ● e.g.: When the mouse clicks in the button X, please call function Y. ● The desired hardware must be able to rise an interrupt ● Part of the work is done under interrupt context, preferable the faster part
  • 136. Generic Driver Interrupt Driver Setup ISR callback Interrupt Driver Generic Driver Call ISR callback Kernel Add callback Process Kernel Main Process Execute process Generic Driver Request data (callback passed) Kernel Callback Process Execute process Main Programflow Interrupt context device_driver_controller(4);
  • 137. device_driver_controller(4); //********** Excerpt from drvAdc.c ********** // called from setup time to enable ADC interrupt // and setup ADC ISR callback char enableAdcInterrup(void* parameters){ callDriver(DRV_INTERRUPT,INT_ADC_SET,(void*)adcISR); BitClr(PIR1,6); return FIM_OK; } //********** Excerpt from drvInterrupt.c ********** // store the pointer to the interrupt function typedef void (*intFunc)(void); static intFunc adcInterrupt; // function to set ADC ISR callback for latter use char setAdcInt(void *parameters) { adcInterrupt = (intFunc)parameters; return FIM_OK; }
  • 138. device_driver_controller(4); //********** Excerpt from main.c ********** // Process called by the kernel char adc_func(void) { //creating callback process static process proc_adc_callback = {adc_callback, 0, 0}; callDriver(DRV_ADC,ADC_START,&proc_adc_callback); return REPEAT; } //********** Excerpt from drvAdc.c ********** //function called by the process adc_func (via drv controller) char startConversion(void* parameters){ callBack = parameters; ADCON0 |= 0b00000010; //start conversion return SUCCESS; }
  • 139. device_driver_controller(4); //********** Excerpt from drvInterrupt.c ********** //interrupt function void isr(void) interrupt 1 { if (BitTst(INTCON, 2)) { //Timer overflow } if (BitTst(PIR1, 6)) { //ADC conversion finished //calling ISR callback stored adcInterrupt(); } } //********** Excerpt from drvAdc.c ********** //ADC ISR callback function void adcISR(void){ value = ADRESH; value <<= 8; value += ADRESL; BitClr(PIR1,6); kernelAddProc(callBack); }
  • 140. device_driver_controller(4); //********** Excerpt from main.c ********** //callback function started from the kernel char adc_callback(void) { unsigned int resp; //getting the converted value callDriver(DRV_ADC,ADC_LAST_VALUE,&resp); //changing line and printing on LCD callDriver(DRV_LCD,LCD_LINE,1); callDriver(DRV_LCD,LCD_INTEGER,resp); return SUCCESS; }
  • 142. “Don't Reinvent The Wheel, Unless You Plan on Learning More About Wheels” Jeff Atwood