SlideShare a Scribd company logo
INTRODUCTION TO
MICRO-
CONTROLLERS
PART 2
PREPARED BY
BASEM IBRAHEEM
MODIFIED BY
KHALED M. IBRAHEEM
ADVANCED
MICROCONTROLLER
PROGRAMMING
ARDUINO PLATFORM PROGRAMMING
AGENDA
• DELAY !!!
• IDLE STATE
• INTERRUPTS ARE NOT AVAILABLE
• BLINKING WITHOUT DELAY
• INTERRUPT
• MILLIS
THE PROBLEM
• Assume that:
• We have a fire fighting robot. It keep moving searching for
fire. Digital fire detector sensor is used. It is connected to
pin 4. If the sensor detected fire, it sends HIGH for half a
second then return LOW.
• This robot has a fire fighting tool to vanquish fire (bump/
fan …etc.)
• This tool is connected to pin 12 and is activated by
sending HIGH.
• The robot has a blinking led that blinks every second.
BASIC DELAY
void setup() {
pinMode(13, OUTPUT);
pinMode(4, INPUT);
pinMode(12, OUTPUT);}
void loop() {
Alarm = digitalRead (4);
if (Alarm == HIGH) // If there is fire
digitalWrite(12, HIGH); // set the Fire Fighter on
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH); // set the LED on
for (int x=0; x < 1000; x++) { // Wait for 1 second
delay(1);
}
digitalWrite(13, LOW); // set the LED on
for (int x=0; x < 1000; x++) { // Wait for 1 second
delay(1);
}
}
void setup() {
pinMode(13, OUTPUT);
pinMode(4, INPUT);
pinMode(12, OUTPUT);}
}
void loop() {
digitalWrite(13, HIGH); // set the LED on
for (int x=0; x < 1000; x++) { // wait for a secoond
delay(1);
Alarm = digitalRead (4);
if (Alarm == HIGH) // If there is fire
digitalWrite(12, HIGH); // set the Fire Fighter on
}
digitalWrite(13, LOW); // set the LED off
for (int x=0; x < 1000; x++) { // wait for a secoond
delay(1);
Alarm = digitalRead (4);
if (Alarm == HIGH) // If there is fire
digitalWrite(12, HIGH); // set the Fire Fighter on
}
}
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
int Alarm;
bool ledState = false; // state variable for the LED
void setup() {
pinMode(13, OUTPUT);
pinMode(4, INPUT);
pinMode(12, OUTPUT);}
digitalWrite(13, ledState); }
void loop() {
unsigned long currentMillis = millis(); // grab current time
// check if "interval" time has passed (1000 milliseconds)
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
ledState = !ledState; // "toggles" the state
digitalWrite(13, ledState); // sets the LED based on ledState
// save the "current" time
previousMillis = millis();
}
Alarm = digitalRead (4);
if (Alarm == HIGH) // If there is fire
digitalWrite(12, HIGH); // set the Fire Fighter on
}
const byte ledPin = 13; // LED
const byte FanPin = 12; // Fan
const byte interruptPin = 2;// Sensor input
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
bool ledState = false; // state variable for the LED
void setup() {
pinMode(FanPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), ActivateFan, RISING); //LOW - CHANGE - RISING -
FALLING - HIGH for Due, Zero //and
MKR1000 boards
}
void loop() {
unsigned long currentMillis = millis(); // grab current time
// check if "interval" time has passed (1000 milliseconds)
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
ledState = !ledState; // "toggles" the state
digitalWrite(ledPin, ledState); // sets the LED based on ledState
// save the "current" time
previousMillis = millis(); }}
void ActivateFan() {
digitalWrite(FanPin, HIGH); // set the Fire Fighter on
MEMORIES
REMEMBERING CHANGES
• THE SUPPORTED MICRO-CONTROLLERS ON THE UNO ARDUINO
BOARDS HAVE DIFFERENT AMOUNTS OF EEPROM: 1024 BYTES ON
THE ATMEGA328
• EPROM IS MEMORY WHOSE VALUES ARE KEPT WHEN THE BOARD IS
TURNED OFF (LIKE A TINY HARD DRIVE).
• YOU CAN READ , WRITE , CLEAR , UPDATE
• EEPROM UPDATE: STORES VALUES READ FROM A0 INTO EEPROM, WRITING THE
VALUE ONLY IF DIFFERENT, TO INCREASE EEPROM LIFE.
#include <EEPROM.h>
int addr = 0;
void setup() {}
void loop() {
int val = analogRead(0) / 4;
EPROM.write(addr, val);
addr = addr + 1;
if (addr == EEPROM.length()) {
addr = 0;
}
delay(100);
}
REMEMBERING CHANGES
REMEMBERING CHANGES
#include <EEPROM.h>
int a = 0;
int value;
void setup(){}
void loop()
{
value = EEPROM.read(a);
a = a + 1;
if (a == 512)
a = 0;
delay(500);
}
read()
Description
Reads a byte from the EEPROM.
Locations that have never been written to
have the value of 255.
Syntax
EEPROM.read(address)
Parameters
address: the location to read from, starting
from 0 (int)
Returns
the value stored in that location (byte)
MEMORIES OF AVR / ARDUINO
• MEMORY : THE FIRST THING TO GO
• THERE ARE THREE POOLS OF MEMORY IN THE MICROCONTROLLER USED ON AVR-
BASED ARDUINO BOARDS :
• FLASH MEMORY (PROGRAM SPACE), IS WHERE THE ARDUINO SKETCH IS STORED.
• SRAM (STATIC RANDOM ACCESS MEMORY) IS WHERE THE SKETCH CREATES AND
MANIPULATES VARIABLES WHEN IT RUNS.
• EEPROM IS MEMORY SPACE THAT PROGRAMMERS CAN USE TO STORE LONG-TERM
INFORMATION.
• ATMEGA328 CHIP
• FLASH 32K BYTES (OF WHICH 0.5 K IS USED FOR THE BOOTLOADER)
• SRAM 2K BYTES
• EEPROM 1K BYTE
SKETCH TOO BIG
MY PROGRAM WAS FINE UNTIL :
• "INCLUDED ONE MORE LIBRARY"
• "ADDED SOME MORE LED PIXELS"
• "OPENED A FILE ON THE SD CARD"
• "INITIALIZED A GRAPHICAL DISPLAY"
• "MERGED IN ANOTHER SKETCH"
• "ADDED A NEW FUNCTION
MEMORY ARCHITECTURES
• VON NEUMANN VS HARVARD’S
• SINGLE DATA/PROGRAM PATH
• SEPARATE PATHS (HARVARD)
• FLEXIBILITY VS PERFORMANCE
PC CPU (INTEL / CYRIX / AMD)
• HYBRID ARCHITECTURE
• CACHE MODELS INCLUDE SEPARATE BUSSES FOR DATA CACHE AND
INSTRUCTION CACHE.
• MEMORY (RAM) MODEL INCLUDE VON-NEUMANN FLEXIBLE ARCHITECTURE.
• COST !
AVR ARCHITECTURE FOR ATMEGA328P
• HARVARD
• FLASH FOR SKETCH (PROGRAM)
• SRAM FOR DATA
• COMPILER AND RUNTIME SYSTEM (ARDUINO BOOT LOADER) WORKS TO HANDLE
ALLOCATION AND DEALLOCATION , AS WELL AS TASK SPACE /SEGMENT
PROTECTION. (AND SWAPPING IN OTHER OSS)
GETTING INTO MEMORY MANAGEMENT
• FLASH 32 KB
• SRAM 2 KB
• EPROM 1KB
• 10,000 TO 100,000 TIMES LESS THAN PC MEMORY
DIFFERENCES
Flash SRAM EEPROM
Program Data
Static Data Reserved Block
Constants - Globals – Initial values
Byte by Byte operation
Static , 10 , 000 write
cycles , fused down when
written .
Volatile and Dynamic
Heap : Dynamically allocated data
items growing up
Stack : function calls and interrupr
handler calls growing down
Slower than SRAM , with 100,000
write cycles
FREE MEMORY
• DISTANCE BETWEEN HEAP AND STACK
• DEFRAGMENTATION OF HEAP
• FF (FIRST FIT) ALGORITHM, WHERE THE LIST IS SCANNED FROM THE BEGINNING FOR THE FIRST
“HOLE” THAT IS LARGE ENOUGH.
• NF (NEXT FIT) WHERE THE LIST IS SCANNED FROM WHERE THE LAST SEARCH ENDED FOR THE
NEXT “HOLE” THAT IS LARGE ENOUGH.
• BF (BEST FIT) WHERE THE ENTIRE LIST IS SEARCHED FOR THE HOLE THAT BEST FITS THE NEW
DATA.
• WF (WORST FIT), WHICH PLACES DATA IN THE LARGEST AVAILABLE “HOLE.”
• QF (QUICK FIT) WHERE A LIST IS KEPT OF MEMORY SIZES AND ALLOCATION IS DONE FROM THIS
INFORMATION.
MEASURING FREE MEMORY
• MIKROC STATISTICS LIBRARY
• FREEMEMORY()
ROUTINE FOR ARDUINO
HTTPS://GITHUB.COM/MPFLAGA/ARDUINO-MEMORYFREE
OPTIMIZING MEMORY USAGE
1- OPTIMIZING FLASH USAGE – APPLICATION
CODE
• REMOVE DEAD CODE
• UNUSED LIBRARIES (JUST COMMENT AND COMPILE)
• UNUSED FUNCTIONS
• UNUSED VARIABLES
• UNREACHABLE CODE
• REFACTOR (REPEATED CODE)
• ELIMINATE THE BOOTLOADER
2- OPTIMIZING SRAM USAGE
• PIXELS 3 BYTES PER PIXEL IN RGB
• WOULD YOU RUN A 32X32 PIXEL RGB DISPLAY ON UNO 328P ?
• 32*32=1024
• 1024*3 BYTES = 3072 BYTES = 3K
• UNO 328P SRAM = 2K
• 1 BYTE PER 8 PIXELS IN MONOCHROM
• COMMUNICATION BUFFERS
2- OPTIMIZING SRAM USAGE – DATA AND
DYNAMIC ALLOCATIONS
• REMOVE UNUSED VARIABLES
• F() FIXED STRINGS TO POINTERS TO BASE ADDRESS IN FLASH
• RESERVE() FOR GROWING STRINGS
CONT. 2- OPTIMIZING SRAM USAGE – DATA
AND DYNAMIC ALLOCATIONS
• MOVING CONSTANTS TO PROGMEM
• REDUCING UNUSED BUFFER SIZES OR DATA TYPES
• SERIAL BUFFER SIZE FOR FAST COMMUNICATION 64 BYTES , MAKE IT 32 BYTES
• ALLOCATE LOCAL VARIABLES IN A FUNCTION SCOPE TO ENSURE CLEANUP WITH
STACK POP.
• AVOID DYNAMIC HEAP ALLOCATIONS - THESE CAN QUICKLY FRAGMENT THE
LIMITED HEAP-SPACE.
• PREFER LOCAL TO GLOBAL ALLOCATION - STACK VARIABLES ONLY EXIST WHILE THEY
ARE BEING USED. IF YOU HAVE VARIABLES THAT ONLY ARE USED IN A SMALL SECTION
OF YOUR CODE, CONSIDER MAKING THAT CODE INTO A FUNCTION AND DECLARING
THE VARIABLES LOCAL TO THE FUNCTION.
MEMORY MANAGEMENT UNIT
• MANAGING THE MAPPING BETWEEN LOGICAL (PHYSICAL) MEMORY AND TASK MEMORY
REFERENCES.
• DETERMINING WHICH PROCESSES TO LOAD INTO THE AVAILABLE MEMORY SPACE.
• ALLOCATING AND DEALLOCATING OF MEMORY FOR PROCESSES THAT MAKE UP THE
SYSTEM.
• SUPPORTING MEMORY ALLOCATION AND DEALLOCATION OF CODE REQUESTS (WITHIN
A PROCESS),
• SUCH AS THE C LANGUAGE “ALLOC” AND “DEALLOC” FUNCTIONS, OR SPECIFIC BUFFER
ALLOCATION AND
• DEALLOCATION ROUTINES.
• TRACKING THE MEMORY USAGE OF SYSTEM COMPONENTS.
WHY DOES ADC TAKE TIME?
FLASH A/D CONVERTER
Vref
Vref /2
“00“
“01“
“10“
“11“
Vref /4 3Vref /4
Encoding of voltage intervals
h(t)
No decoding of h(t) > Vref
RESOLUTION AND SPEED OF FLASH A/D-
CONVERTER
• PARALLEL COMPARISON WITH REFERENCE
VOLTAGE
• SPEED: O(1)
• HARDWARE COMPLEXITY: O(N)
• APPLICATIONS: E.G. IN VIDEO PROCESSING
HIGHER RESOLUTION: SUCCESSIVE
APPROXIMATION
• KEY IDEA: BINARY SEARCH:
• SET MSB='1'
• IF TOO LARGE: RESET MSB
• SET MSB-1='1'
• IF TOO LARGE: RESET MSB-1
Speed: O(log2(n))
Hardware complexity: O(log2(n))
with n= # of distinguished
voltage levels;
slow, but high precision possible.
h(t)
w(t)
V-
SUCCESSIVE APPROXIMATION (2)
1100
1000
1010
1011
t
V
Vx
V-
h(t)

More Related Content

PPTX
Embedded system design using arduino
PPTX
Introduction to the Arduino
PPT
01 Intro to the Arduino and it's basics.ppt
PPTX
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
PDF
Documento de acrobat2
PDF
introductiontoarduino-111120102058-phpapp02.pdf
PPTX
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT IV Designing Embedded System with 8051...
PPTX
Arduino intro.pptx
Embedded system design using arduino
Introduction to the Arduino
01 Intro to the Arduino and it's basics.ppt
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
Documento de acrobat2
introductiontoarduino-111120102058-phpapp02.pdf
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT IV Designing Embedded System with 8051...
Arduino intro.pptx

Similar to An Introduction to Microcontrollers part 2 (20)

PDF
PPTX
Introduction To Arduino-converted for s.pptx
PPTX
Sensors and Actuators in Arduino, Introduction
PPTX
Atmel and pic microcontroller
PPT
AVR Fundamentals
PDF
NSTA 2013 Denver - ArduBlock and Arduino
PDF
Arduino Boot Camp Pitch Slides
PPTX
Arduino and its hw architecture
PPTX
Arduino board program for Mobile robotss
PDF
AVR arduino dasar
PPTX
arduino-1.pptxbxavvgAzccgzs fla sh ga aana
PDF
intro_mcu.pdf
PPTX
Arduino.pptx
PPTX
arduinoedit.pptx
PDF
Introduction to Arduino and Circuits
PDF
lecture2-mcu_and_io.pdf
PPTX
Internet of Things (IoT)-Sensors & Actuators - IoT.pptx
PPTX
INDUSTRIAL TRAINING REPORT EMBEDDED SYSTEM.pptx
PPT
E.s unit 4 and 5
Introduction To Arduino-converted for s.pptx
Sensors and Actuators in Arduino, Introduction
Atmel and pic microcontroller
AVR Fundamentals
NSTA 2013 Denver - ArduBlock and Arduino
Arduino Boot Camp Pitch Slides
Arduino and its hw architecture
Arduino board program for Mobile robotss
AVR arduino dasar
arduino-1.pptxbxavvgAzccgzs fla sh ga aana
intro_mcu.pdf
Arduino.pptx
arduinoedit.pptx
Introduction to Arduino and Circuits
lecture2-mcu_and_io.pdf
Internet of Things (IoT)-Sensors & Actuators - IoT.pptx
INDUSTRIAL TRAINING REPORT EMBEDDED SYSTEM.pptx
E.s unit 4 and 5
Ad

Recently uploaded (20)

DOCX
573137875-Attendance-Management-System-original
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Sustainable Sites - Green Building Construction
PDF
Well-logging-methods_new................
PPTX
Geodesy 1.pptx...............................................
PPTX
Artificial Intelligence
PPTX
Lecture Notes Electrical Wiring System Components
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
573137875-Attendance-Management-System-original
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
R24 SURVEYING LAB MANUAL for civil enggi
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Operating System & Kernel Study Guide-1 - converted.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
bas. eng. economics group 4 presentation 1.pptx
UNIT 4 Total Quality Management .pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Mechanical Engineering MATERIALS Selection
Sustainable Sites - Green Building Construction
Well-logging-methods_new................
Geodesy 1.pptx...............................................
Artificial Intelligence
Lecture Notes Electrical Wiring System Components
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Ad

An Introduction to Microcontrollers part 2

  • 1. INTRODUCTION TO MICRO- CONTROLLERS PART 2 PREPARED BY BASEM IBRAHEEM MODIFIED BY KHALED M. IBRAHEEM
  • 3. AGENDA • DELAY !!! • IDLE STATE • INTERRUPTS ARE NOT AVAILABLE • BLINKING WITHOUT DELAY • INTERRUPT • MILLIS
  • 4. THE PROBLEM • Assume that: • We have a fire fighting robot. It keep moving searching for fire. Digital fire detector sensor is used. It is connected to pin 4. If the sensor detected fire, it sends HIGH for half a second then return LOW. • This robot has a fire fighting tool to vanquish fire (bump/ fan …etc.) • This tool is connected to pin 12 and is activated by sending HIGH. • The robot has a blinking led that blinks every second.
  • 5. BASIC DELAY void setup() { pinMode(13, OUTPUT); pinMode(4, INPUT); pinMode(12, OUTPUT);} void loop() { Alarm = digitalRead (4); if (Alarm == HIGH) // If there is fire digitalWrite(12, HIGH); // set the Fire Fighter on digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(13, LOW); // set the LED off delay(1000); // wait for a second }
  • 6. void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); // set the LED on for (int x=0; x < 1000; x++) { // Wait for 1 second delay(1); } digitalWrite(13, LOW); // set the LED on for (int x=0; x < 1000; x++) { // Wait for 1 second delay(1); } }
  • 7. void setup() { pinMode(13, OUTPUT); pinMode(4, INPUT); pinMode(12, OUTPUT);} } void loop() { digitalWrite(13, HIGH); // set the LED on for (int x=0; x < 1000; x++) { // wait for a secoond delay(1); Alarm = digitalRead (4); if (Alarm == HIGH) // If there is fire digitalWrite(12, HIGH); // set the Fire Fighter on } digitalWrite(13, LOW); // set the LED off for (int x=0; x < 1000; x++) { // wait for a secoond delay(1); Alarm = digitalRead (4); if (Alarm == HIGH) // If there is fire digitalWrite(12, HIGH); // set the Fire Fighter on } }
  • 8. unsigned long interval=1000; // the time we need to wait unsigned long previousMillis=0; // millis() returns an unsigned long. int Alarm; bool ledState = false; // state variable for the LED void setup() { pinMode(13, OUTPUT); pinMode(4, INPUT); pinMode(12, OUTPUT);} digitalWrite(13, ledState); } void loop() { unsigned long currentMillis = millis(); // grab current time // check if "interval" time has passed (1000 milliseconds) if ((unsigned long)(currentMillis - previousMillis) >= interval) { ledState = !ledState; // "toggles" the state digitalWrite(13, ledState); // sets the LED based on ledState // save the "current" time previousMillis = millis(); } Alarm = digitalRead (4); if (Alarm == HIGH) // If there is fire digitalWrite(12, HIGH); // set the Fire Fighter on }
  • 9. const byte ledPin = 13; // LED const byte FanPin = 12; // Fan const byte interruptPin = 2;// Sensor input unsigned long interval=1000; // the time we need to wait unsigned long previousMillis=0; // millis() returns an unsigned long. bool ledState = false; // state variable for the LED void setup() { pinMode(FanPin, OUTPUT); pinMode(ledPin, OUTPUT); pinMode(interruptPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interruptPin), ActivateFan, RISING); //LOW - CHANGE - RISING - FALLING - HIGH for Due, Zero //and MKR1000 boards } void loop() { unsigned long currentMillis = millis(); // grab current time // check if "interval" time has passed (1000 milliseconds) if ((unsigned long)(currentMillis - previousMillis) >= interval) { ledState = !ledState; // "toggles" the state digitalWrite(ledPin, ledState); // sets the LED based on ledState // save the "current" time previousMillis = millis(); }} void ActivateFan() { digitalWrite(FanPin, HIGH); // set the Fire Fighter on
  • 11. REMEMBERING CHANGES • THE SUPPORTED MICRO-CONTROLLERS ON THE UNO ARDUINO BOARDS HAVE DIFFERENT AMOUNTS OF EEPROM: 1024 BYTES ON THE ATMEGA328 • EPROM IS MEMORY WHOSE VALUES ARE KEPT WHEN THE BOARD IS TURNED OFF (LIKE A TINY HARD DRIVE). • YOU CAN READ , WRITE , CLEAR , UPDATE • EEPROM UPDATE: STORES VALUES READ FROM A0 INTO EEPROM, WRITING THE VALUE ONLY IF DIFFERENT, TO INCREASE EEPROM LIFE.
  • 12. #include <EEPROM.h> int addr = 0; void setup() {} void loop() { int val = analogRead(0) / 4; EPROM.write(addr, val); addr = addr + 1; if (addr == EEPROM.length()) { addr = 0; } delay(100); } REMEMBERING CHANGES
  • 13. REMEMBERING CHANGES #include <EEPROM.h> int a = 0; int value; void setup(){} void loop() { value = EEPROM.read(a); a = a + 1; if (a == 512) a = 0; delay(500); } read() Description Reads a byte from the EEPROM. Locations that have never been written to have the value of 255. Syntax EEPROM.read(address) Parameters address: the location to read from, starting from 0 (int) Returns the value stored in that location (byte)
  • 14. MEMORIES OF AVR / ARDUINO • MEMORY : THE FIRST THING TO GO • THERE ARE THREE POOLS OF MEMORY IN THE MICROCONTROLLER USED ON AVR- BASED ARDUINO BOARDS : • FLASH MEMORY (PROGRAM SPACE), IS WHERE THE ARDUINO SKETCH IS STORED. • SRAM (STATIC RANDOM ACCESS MEMORY) IS WHERE THE SKETCH CREATES AND MANIPULATES VARIABLES WHEN IT RUNS. • EEPROM IS MEMORY SPACE THAT PROGRAMMERS CAN USE TO STORE LONG-TERM INFORMATION. • ATMEGA328 CHIP • FLASH 32K BYTES (OF WHICH 0.5 K IS USED FOR THE BOOTLOADER) • SRAM 2K BYTES • EEPROM 1K BYTE
  • 16. MY PROGRAM WAS FINE UNTIL : • "INCLUDED ONE MORE LIBRARY" • "ADDED SOME MORE LED PIXELS" • "OPENED A FILE ON THE SD CARD" • "INITIALIZED A GRAPHICAL DISPLAY" • "MERGED IN ANOTHER SKETCH" • "ADDED A NEW FUNCTION
  • 17. MEMORY ARCHITECTURES • VON NEUMANN VS HARVARD’S • SINGLE DATA/PROGRAM PATH • SEPARATE PATHS (HARVARD) • FLEXIBILITY VS PERFORMANCE
  • 18. PC CPU (INTEL / CYRIX / AMD) • HYBRID ARCHITECTURE • CACHE MODELS INCLUDE SEPARATE BUSSES FOR DATA CACHE AND INSTRUCTION CACHE. • MEMORY (RAM) MODEL INCLUDE VON-NEUMANN FLEXIBLE ARCHITECTURE. • COST !
  • 19. AVR ARCHITECTURE FOR ATMEGA328P • HARVARD • FLASH FOR SKETCH (PROGRAM) • SRAM FOR DATA • COMPILER AND RUNTIME SYSTEM (ARDUINO BOOT LOADER) WORKS TO HANDLE ALLOCATION AND DEALLOCATION , AS WELL AS TASK SPACE /SEGMENT PROTECTION. (AND SWAPPING IN OTHER OSS)
  • 20. GETTING INTO MEMORY MANAGEMENT • FLASH 32 KB • SRAM 2 KB • EPROM 1KB • 10,000 TO 100,000 TIMES LESS THAN PC MEMORY
  • 21. DIFFERENCES Flash SRAM EEPROM Program Data Static Data Reserved Block Constants - Globals – Initial values Byte by Byte operation Static , 10 , 000 write cycles , fused down when written . Volatile and Dynamic Heap : Dynamically allocated data items growing up Stack : function calls and interrupr handler calls growing down Slower than SRAM , with 100,000 write cycles
  • 22. FREE MEMORY • DISTANCE BETWEEN HEAP AND STACK • DEFRAGMENTATION OF HEAP • FF (FIRST FIT) ALGORITHM, WHERE THE LIST IS SCANNED FROM THE BEGINNING FOR THE FIRST “HOLE” THAT IS LARGE ENOUGH. • NF (NEXT FIT) WHERE THE LIST IS SCANNED FROM WHERE THE LAST SEARCH ENDED FOR THE NEXT “HOLE” THAT IS LARGE ENOUGH. • BF (BEST FIT) WHERE THE ENTIRE LIST IS SEARCHED FOR THE HOLE THAT BEST FITS THE NEW DATA. • WF (WORST FIT), WHICH PLACES DATA IN THE LARGEST AVAILABLE “HOLE.” • QF (QUICK FIT) WHERE A LIST IS KEPT OF MEMORY SIZES AND ALLOCATION IS DONE FROM THIS INFORMATION.
  • 23. MEASURING FREE MEMORY • MIKROC STATISTICS LIBRARY • FREEMEMORY() ROUTINE FOR ARDUINO HTTPS://GITHUB.COM/MPFLAGA/ARDUINO-MEMORYFREE
  • 25. 1- OPTIMIZING FLASH USAGE – APPLICATION CODE • REMOVE DEAD CODE • UNUSED LIBRARIES (JUST COMMENT AND COMPILE) • UNUSED FUNCTIONS • UNUSED VARIABLES • UNREACHABLE CODE • REFACTOR (REPEATED CODE) • ELIMINATE THE BOOTLOADER
  • 26. 2- OPTIMIZING SRAM USAGE • PIXELS 3 BYTES PER PIXEL IN RGB • WOULD YOU RUN A 32X32 PIXEL RGB DISPLAY ON UNO 328P ? • 32*32=1024 • 1024*3 BYTES = 3072 BYTES = 3K • UNO 328P SRAM = 2K • 1 BYTE PER 8 PIXELS IN MONOCHROM • COMMUNICATION BUFFERS
  • 27. 2- OPTIMIZING SRAM USAGE – DATA AND DYNAMIC ALLOCATIONS • REMOVE UNUSED VARIABLES • F() FIXED STRINGS TO POINTERS TO BASE ADDRESS IN FLASH • RESERVE() FOR GROWING STRINGS
  • 28. CONT. 2- OPTIMIZING SRAM USAGE – DATA AND DYNAMIC ALLOCATIONS • MOVING CONSTANTS TO PROGMEM • REDUCING UNUSED BUFFER SIZES OR DATA TYPES • SERIAL BUFFER SIZE FOR FAST COMMUNICATION 64 BYTES , MAKE IT 32 BYTES • ALLOCATE LOCAL VARIABLES IN A FUNCTION SCOPE TO ENSURE CLEANUP WITH STACK POP. • AVOID DYNAMIC HEAP ALLOCATIONS - THESE CAN QUICKLY FRAGMENT THE LIMITED HEAP-SPACE. • PREFER LOCAL TO GLOBAL ALLOCATION - STACK VARIABLES ONLY EXIST WHILE THEY ARE BEING USED. IF YOU HAVE VARIABLES THAT ONLY ARE USED IN A SMALL SECTION OF YOUR CODE, CONSIDER MAKING THAT CODE INTO A FUNCTION AND DECLARING THE VARIABLES LOCAL TO THE FUNCTION.
  • 29. MEMORY MANAGEMENT UNIT • MANAGING THE MAPPING BETWEEN LOGICAL (PHYSICAL) MEMORY AND TASK MEMORY REFERENCES. • DETERMINING WHICH PROCESSES TO LOAD INTO THE AVAILABLE MEMORY SPACE. • ALLOCATING AND DEALLOCATING OF MEMORY FOR PROCESSES THAT MAKE UP THE SYSTEM. • SUPPORTING MEMORY ALLOCATION AND DEALLOCATION OF CODE REQUESTS (WITHIN A PROCESS), • SUCH AS THE C LANGUAGE “ALLOC” AND “DEALLOC” FUNCTIONS, OR SPECIFIC BUFFER ALLOCATION AND • DEALLOCATION ROUTINES. • TRACKING THE MEMORY USAGE OF SYSTEM COMPONENTS.
  • 30. WHY DOES ADC TAKE TIME?
  • 31. FLASH A/D CONVERTER Vref Vref /2 “00“ “01“ “10“ “11“ Vref /4 3Vref /4 Encoding of voltage intervals h(t) No decoding of h(t) > Vref
  • 32. RESOLUTION AND SPEED OF FLASH A/D- CONVERTER • PARALLEL COMPARISON WITH REFERENCE VOLTAGE • SPEED: O(1) • HARDWARE COMPLEXITY: O(N) • APPLICATIONS: E.G. IN VIDEO PROCESSING
  • 33. HIGHER RESOLUTION: SUCCESSIVE APPROXIMATION • KEY IDEA: BINARY SEARCH: • SET MSB='1' • IF TOO LARGE: RESET MSB • SET MSB-1='1' • IF TOO LARGE: RESET MSB-1 Speed: O(log2(n)) Hardware complexity: O(log2(n)) with n= # of distinguished voltage levels; slow, but high precision possible. h(t) w(t) V-