🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

GentleAloe

Uploaded by GentleAloe

الرازي

Tags

microcontroller programming interrupts timers embedded systems

Full Transcript

Interrupts & Timers INTERRUPTS Interrupts | Introduction  An interrupt is a request for the processor to interrupt currently executing code, so that the event can be processed in a timely manner. ‫ أو حدث برمجي يتسبب في جعل المعالج‬input pin ‫ هي عبارة عن طرف دخل‬: interrupt ‫ تقنية الم...

Interrupts & Timers INTERRUPTS Interrupts | Introduction  An interrupt is a request for the processor to interrupt currently executing code, so that the event can be processed in a timely manner. ‫ أو حدث برمجي يتسبب في جعل المعالج‬input pin ‫ هي عبارة عن طرف دخل‬: interrupt ‫ تقنية المقاطعة‬.‫يتوقنف عن ما يفعله االن ويسنتجيب للحدث المسبب للمقاطعة ويعالجه بسرعة ثم يعود مرة أخرى لما كان يفعله‬ Interrupts Type of Interrupts  Hardware Interrupts  External Interrupts: Triggered by external terminals. In ATmega328p, they are triggered by the INT0 and INT1 pins or any of the PCINT23..0 pins.  Internal interrupts are triggered by changes in the AVR’s internal hardware.  Software Interrupts: which occur in response to a command issued in software  In ATmega328p, if external interrupt is enabled and the pin is configured as an output, then you can generate an interrupt from software by changing the voltage level status of the pin. Interrupt Source  Port Pins : INT0, INT1 and INT2  Timers  UART  SPI  ADC  EEPROM  Analog Comparator  TWI or I2C What Triggers an Interrupt  For a signal:  Raising Edge, Falling Edge, Toggling Signal, and (While HIGH, While LOW)  For Timers/Counters  Overflow, etc.  For others (In general)  Status changed Interrupt Vectors  Interrupt vectors are addresses that inform the interrupt handler as to where to find the ISR (interrupt service routine, also called interrupt service procedure). Program Vector No. Source Interrupt Definition Address 1 0x0000 RESET External pin, power-on reset, brown-out reset and watchdog system reset 2 0x002 INT0 External interrupt request 0 3 0x0004 INT1 External interrupt request 1 4 0x0006 PCINT0 Pin change interrupt request 0 5 0x0008 PCINT1 Pin change interrupt request 1 6 0x000A PCINT2 Pin change interrupt request 2 7 0x000C WDT Watchdog time-out interrupt 8 0x000E TIMER2 COMPA Timer/Counter2 compare match A ATmega328p 9 0x0010 TIMER2 COMPB Timer/Counter2 compare match B 10 0x0012 TIMER2 OVF Timer/Counter2 overflow 11 0x0014 TIMER1 CAPT Timer/Counter1 capture event 12 0x0016 TIMER1 COMPA Timer/Counter1 compare match A 13 0x0018 TIMER1 COMPB Timer/Counter1 compare match B 14 0x001A TIMER1 OVF Timer/Counter1 overflow 15 0x001C TIMER0 COMPA Timer/Counter0 compare match A 16 0x001E TIMER0 COMPB Timer/Counter0 compare match B 17 0x0020 TIMER0 OVF Timer/Counter0 overflow 18 0x0022 SPI, STC SPI serial transfer complete 19 0x0024 USART, RX USART Rx complete 20 0x0026 USART, UDRE USART, data register empty 21 0x0028 USART, TX USART, Tx complete 22 0x002A ADC ADC conversion complete 23 0x002C EE READY EEPROM ready ANALOG 24 0x002E Analog comparator COMP 25 0x0030 TWI 2-wire serial interface 26 0x0032 SPM READY Store program memory ready Interrupt Priority  What happen if two or more interrupts happen at the same time?  For AVR architecture, the lower the vector address, the higher the priority. Enable Interrupts  Individual Interrupt Control Bits: Each required Interrupt should be enabled individually by setting its corresponding bit in a specific control registers. For instance, to enable INT0 pin interrupt, you should set 2nd bit in EIMSK.  Whenever an interrupt is raised, the interrupt flag will be set (how to know which one caused the interrupt if they are sharing same IV address  Global Interrupt: Enable or disable all interrupts at once  ATmega328p Assembly commands: (Enable: sei, Disable: cli) Interrupt Flag  Interrupt flag bits get set when an interrupt condition occurs (regardless of the state of its corresponding enable bit or the global enable bit)  The flag will be cleared automatically once the ISR routine is executed, and can be cleared manually (in software - by writing one to it in ATmega328p for instance) as well. Interrupt Service Routine (ISR)  In AVR MCU, an ISR is called if  Global Interrupts Enable bit (I) is set. And  The individual interrupt source's enable is set. And  The condition for the interrupt must be met. For example, for the USART Receive Complete (USART RX) interrupt, a character must have been received. Interrupt Service Routine (ISR) ISRs are special kinds of functions Extra Notes:  It cannot have any parameters  millis() relies on interrupts to count  They shouldn’t return anything  millis() will never increment inside an ISR  It should be as short and fast as possible  You should not use a blocking function inside an ISR.  For multiple ISRs, only one can run at a time.  If you continuously receive many interrupts  Multiple ISRs runs in an order that depends on within a very short time, your main program the priority they have. might halt…How to mitigate this issue?  Global and volatile variables are (must)  Be careful when reading a variable (with size used to pass data between an ISR and the multiple of MCU SRAM word size) that is main program. Why volatile type? updated inside the ISR…..Why? Interrupt Service Routine (ISR) Mode of Interrupt Trigger Vector Source External Interrupt command ISR | Arduino Functions Here are some functions available in arduino:  External Interrupt command  attachInterrupt(digitalPinToInterrupt(pin),ISR,Mode)  detachInterrupt(digitalPinToInterrupt(pin))  Global Interrupt Enable/Disable  interrupts()  nointerrupts() Nested Interrupts  To prevent nesting interrupts, Global Interrupt is disabled automatically when the execution jump into an ISR and will be enabled after exiting the ISR.  To allow for nested interrupts, enable the global interrupt inside the ISR. ‫تمرين‪ :‬تشغيل المقاطعة ‪INT0‬‬ ‫‪ ‬الدائرة التالية مكونة من ‪ 2‬دايودات ضوئية ‪ +‬مفتاح‪.‬قم بتشغيل الدايود األول المتصل بمنفذ ‪ PA0‬بصورة طبيعية ليقوم بعمل ‪Blink.‬‬ ‫كل مئة مللي ثانية أما الدايود المتصل بالطرف ‪ PC0‬قم بتشغيله أو إطفاؤه فقط عند حدوث مقاطعة على الطرف ‪.INT0‬‬ Timers & Counters Timers/counters  Timers/counters are an independent unit inside a micro-controller.  primarily used for the following:  Internal Timer: As an internal timer the unit, ticks on the oscillator frequency. The oscillator frequency can be directly feed to the timer or it can be pre-scaled. In this mode it used to generate precise delays. Or as precise time counting machine.  External Counter: In this mode the unit is used to count events on a specific external pin on a MCU.  Pulse width Modulation(PWM) Generator: PWM is used in speed control of motors and various other applications.  ATmega328p has  Two 8-bit Timer/Counters  One 16-bit Timer/Counter Timer 0 | 8 bit timer  Output Compare Register (OCR) set the last count (value) that will set the output compare flag (OCF). Output Compare Counter Register Timer OverFlow Flag ATmega328P 8-bit Timer/Counter Block Diagram Counter Unit Block Diagram Output Compare Unit, Block Diagram Compare Match Output Unit, Schematic PWM (Pulse Width Modulation) Pulse Width Modulation  Pulse Width Modulation (PWM) is a process that is used to control the average DC voltage by controlling the pulse width of high frequency pulses.  PWM is used in many applications to control speed and light intensity. Terms  Duty cycle  Period/Duration  Average Voltage PWM | Period & Duty Cycle  The larger the duty cycle percentage, the larger the output signal will be 1 1 Frequency= = 𝑃𝑒𝑟𝑖𝑜𝑑 𝑇 𝑡𝑜𝑛 Duty Cycle=𝑡 × 100% 𝑜𝑛 +𝑡𝑜𝑓𝑓 𝑡 Duty Cycle=𝑝𝑒𝑟𝑖𝑜𝑑 𝑜𝑛 × 100% How To Create PWM  Manually; Using delay functions void setup() { pinMode(3, OUTPUT); } void loop() { digitalWrite(3, HIGH); delayMicroseconds(10); 10𝜇𝑠 Duty Cycle=10𝜇𝑠+10𝜇𝑠 × 100% = 50% digitalWrite(3, LOW); delayMicroseconds(10); } How To Create PWM Before your code. volatile bool status=false;  Automatically; Using Timer interrupt #define FCPU 16000000 //CPU Clock Speed #define TD.5 //500ms delay before counter overflow void setup() { #define PRESCALER 1024 pinMode(2, INPUT); digitalWrite(2,status); #define RELOAD (65536-FCPU*TD/PRESCALER) cli(); //Disable Global Interrupt TCNT1 = RELOAD; //load the TCNT1 with RELOAD value for 500ms delay //for normal mode operation and pre-scalar of 1024 TCCR1A = 0x00; TCCR1B = 0b00000101; bitSet(TIMSK1, TOIE1); Use datasheet to know how to sei(); //Enable Global Interrupt calculate and set values to setup } required duty cycle and frequency void loop() {} ISR(TIMER1_OVF_vect){ TCNT1 = RELOAD; status=!status; digitalWrite(2,status); } How To Create PWM  Using the arduino function analogWrite(pin, duty_cycle)  0 ≤ 𝑑𝑢𝑡𝑦_𝑐𝑦𝑐𝑙𝑒 ≤ 255  analogWrite uses internal timer PWM mode that automatically switch pins on/off.  analogWrite frequency is fixed per pin. Board PWM Pins Frequency Uno, Nano, Mini 3, 5, 6, 9, 10, 11 490 Hz (pins 5 and 6: 980 Hz) Mega 2 - 13, 44 - 46 490 Hz (pins 4 and 13: 980 Hz) How To Create PWM You may change the frequency by  Using the arduino function analogWrite(pin, duty_cycle) resetting/overwriting the timer prescaller setting (using TCCR2B/TCCR1B) after  0 ≤ 𝑑𝑢𝑡𝑦_𝑐𝑦𝑐𝑙𝑒 ≤ 255 calling analogWrite function void setup() { pinMode(5, OUTPUT); pinMode(6, OUTPUT); analogWrite(5, 15); analogWrite(6, 250); } void loop() {} Board PWM Pins Frequency Uno, Nano, Mini 3, 5, 6, 9, 10, 11 490 Hz (pins 5 and 6: 980 Hz) Mega 2 - 13, 44 - 46 490 Hz (pins 4 and 13: 980 Hz) Output Compare Unit, Block Diagram Example: PWM (duty cycle=50%) Suppose ATmega328P clock is 16MHz. 1- 𝑓𝑟𝑒𝑞(𝑓𝑎𝑠𝑡 𝑚𝑜𝑑𝑒) = 𝐹𝑐𝑝𝑢 /(𝑁 × 256). Timer clock, based on supported prescaler values are (64khz, 8khz, 1khz, 128hz, or 16hz). Set prescale factors N 2- Set COM0x1:0 bits to 2 (non-inverted PWM mode) 3- set output comparator to OCRnx to 255*50%=128 How To Create PWM Before your code. volatile bool status=false;  Automatically; Using Timer PWM mode #define FCPU 16000000 //CPU Clock Speed #define TD.5 //500ms delay before counter overflow  Variable PWM period and Frequency #define PRESCALER 1024 #define RELOAD (65536-FCPU*TD/PRESCALER) void setup() { pinMode(9, OUTPUT); pinMode(10, OUTPUT); cli(); //Disable Global Interrupt TCNT1 = RELOAD; //load the TCNT1 with RELOAD value for 500ms delay //for normal mode operation and pre-scalar of 1024 TCCR1A = 0x50; TCCR1B = 0b00000101; bitSet(TIMSK1, OCIE1B); bitSet(TIMSK1, OCIE1A); sei(); //Enable Global Interrupt } void loop() {} How To Create PWM  Automatically; Using Timer PWM mode  There are different PWM modes  Fast PWM Mode  Phase Correct PWM Mode Extra Topics Memory (Flash & EEPROM) EEPROM | Arduino  To work on EEPROM include the library.  address start at 0  EEPROM.read(address) : Read byte from the specified address.  EEPROM.write(address, value) : Write byte value into the specified address.  EEPROM.update(address, value) : Write byte value into the specified address if its content doesn’t equal value. This help lengthen memory life.  EEPROM.get(address, data) : Read any data type or object from the specified address.  EEPROM.put(address, data) : Write any data type or object into the specified address.  QUIZ: What is the main difference between update and write function? Flash | Arduino  You can use Flash memory to store/read data instead of using SRAM. Store data Example: into FLASH Memory const char a_string[] PROGMEM = "Hello world!"; char myChar; Length function for (byte k = 0; k < strlen_P(a_string); k++) { works with string myChar = pgm_read_byte_near(a_string + k); data saved in Serial.print(myChar); FLASH Memory } Read data from FLASH Memory QUIZ: What is the benefit of using Flash for storing constants? Flash | Arduino | F Macro  You can use Flash memory to store/read data instead of using SRAM. Example: Serial.print(F("A typical constant string to be printed")); Exercise  Write a code that relies on ISR to turn on/off Led 1, 2, or 3 based on the received value from UART (Serial Interface)?  Write a code that prevents interrupts appropriately when working on a critical process (any operation, for instance changes variable values)?  Write a program that uses timers to generate PWM signals to a Pin without the intervention of any code for flipping PWM signals?

Use Quizgecko on...
Browser
Browser