#328 ESP32 Secrets: Interrupts, and Deep-Sleep under the Hood

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you need speed your reactions and simple coding then interrupt are a good thing to use and because interrupts have things in common with deep sleep we will also take into that topic and we will find some secrets of the ESP 32 for sure we will look under its hood maybe you find a hint to improve or simplify your project or you find out why it does not perform as you want gritty youtubers here is the guy with a Swiss accent with the new episode and fresh ideas around sensors and microcontrollers remember if you subscribe you will always sit in the first row in this video we will use interrupts for fast reaction time and simplicity compare it with a standard sketch we learn how to debug real time sketches find unwanted behavior and check how the wakeup works and how we can optimize current consumption first we will concentrate on fast reactions and simplicity most applications need to monitor and react to signals from the real world in standard programming we have to pull an input pin in each loop and respond if an event is detected if this signal is too short our sketch will not recognize it this is easily possible primarily if we work with delays if an outside event occurs during this delay statement our MCU will not detect it this is why people say good practice is to avoid delays statements wherever possible in the other scenario we want to save power and the outside signals are rare then we want to sleep our ESP 32 like dishka for the whole day only on an external event she wakes up and moves maybe from time to time she also gets hungry and has to move without an external event just because it's time for both cases the ESP 32 offers same methods the hardware of the chip monitors pings or a timer independently of the processor only if this monitor discovers a specific event it signals to the processor hello I discovered an agreed event this function is fast simple and does not need a lot of energy we only have to enable it and tell it upfront which pattern it has to monitor for example if we want to be triggered by rising or falling signals or by a particular timer then we have to write a part in our sketch where we define what it has to do after the signal was discovered for example count the events connect to Wi-Fi and send a message read the sensor or create a reaction on another pin like to switch a motor let's create a small example for fast speed a simple frequency counter it should count all pulses during one second and display the result as the measured frequency on an LCD we can do it the conventional way read an input pin and count up if we detect an edge I use here a simple state machine to detect the edge not the fastest way but I am a fan of state machines each second the count is displayed as frequency because the frequency is the number of counts per second in this sketch we also see the basic principle to avoid delay statements we compare Milly's with the last time we entered the display routine and if it's longer than 1000 milliseconds for example we display the value simple the code always loops and can supervise our pin let's check our frequency counter in reality we start by counting 10 Hertz and we get 10 Hertz cool our frequency counter works but how about 1 kilohertz I chose 999 Hertz not too bad at 10 kilohertz I chose a stable 9990 six Hertz still okay at 100 kilohertz the result starts to move around a little and the frequency shown is too low the error is already considerable at 200 kilohertz and 300 kilohertz the error is bigger but it still counts at 400 kilohertz it shows a completely wrong result it is no more capable of detecting all signal changes not too bad for such a simple sketch a proof that the ESP 32 is a speedy processor but of course the CPU is always used and as soon as we would start to do something else in the loop we would lose counts already at low frequencies what if we could count the events independently from the loop this is why interrupts were invented they interrupt the loop wherever it is save all the relevant data in a particular place called stack or heap and execute a different function as soon as this function is finished the processor reloads all data and gives control back to the loop if this function is short your sketch does not recognize it it runs like in parallel this is why these functions must not contain time-consuming commands like serial print or delay statements for example n abling such an interrupt is simple first we have to attach an interrupt service routine short ISR to the same signal pin as before the command contains three elements the pin number the name of the ISR to call and the event we can trigger on rising or falling edges after that command the ISR is called every time the pin goes high automatically let's look at the ISR itself it consists of only one command count plus plus each time it is called the counter is counted one up simple because the rest is done in hardware there are a few tricks with interrupts you do not need to understand the details first we have to write volatile before all variables used in is ours and second we have to insert this line before setup and these two lines as the first and the last statements in the is are done they make sure that nothing bad happens our loop is much simpler now just display every 1000 milliseconds the count and reset it and it works more precisely than before it still fluctuates at higher frequencies and stops working at around 200 kilohertz lower than before very strange there is an easy way to discover what happens we add these two commands in the ISR to toggle a pin and a touch channel 2 of the oscilloscope - this pin on channel 1 we connect the input signal this is by the way the method of choice to debug fast real-time systems toggle pins at various points in your code and watch them with your oscilloscope or your logic analyzer at 1 kilohertz our account 2 shows the exact value if we look at the oscilloscope we see the input signal in yellow and the short Peaks in green if we store the signal we see that the time from the input signal to the reaction of the ISR called latency of the interrupt is a little above 3 microseconds quite slow for a CPU with a 240 megahertz clock rate according to even from expressive this is due to the architecture of the chip if we look at the signals in real time we see something strange the latency is not stable not good for real-time systems where we have to count on a stable and short latency if we go up with a frequency the period of the input signal gets shorter and shorter and the spike gets closer and closer to the next edge and because the latency is variable it sometimes is even longer than the signal period which means that we lose one count this behavior starts already before 200 kilohertz if we increase the frequency even more the ESP crashes this is probably because a next interrupt is generated while the ISR is running many processors allow disabling interrupts during an ISR unfortunately I did not find this feature for the ESP 32 maybe you know how it can be done with disabling interrupts during the ISR it would only show us the wrong results so the verdict is clear the ESP 32 cannot be used for fast real-time applications but we were able to create a simple frequency counter you can imagine that such functionality can be used for many other scenarios like measuring speeds of a motor measuring wind speeds etc another advantage of interrupts is that we can add more to the loop without disturbing our frequency counting for example I can add a second counter on line 3 it counts up without disturbing our frequency counter it looks like both counters work independently and in parallel but the ESP 32 can do more we could add a timer interrupt to our frequency counter to make things even simpler and more accurate for that we add a second is our just as before it has only two lines because we will run this is our every second we just store the frequency value and set the counter to zero just as we did before in the loop to make it work we have to add three similar lines as before just copy them and you are okay in addition we have to enable the timer interrupt with these four lines here you define a pre scale factor and here the divider it is simple the initial frequency is 80 megahertz we divided by eight and afterward by 1 million and we get one second just change these numbers if you need a different time that's it the ESP 32 will now monitor the input pin count up when an H is detected and every second stores and the frequency value our loop is now straightforward display and delay you see right we can use delay without any problem now the timing is done under the hood the top frequency unfortunately is not higher because our counting is still the same one word of caution if you use Wi-Fi your interrupt timing can be influenced by the Wi-Fi functionality this is why I switched it off for these experiments you see with interrupts we can react quite fast to events and also in the background but the ESP 32 has to be always on and therefore consumes power all the time we have a second similar possibility deep sleep and wake up also here Hardware outside the processor monitor spins or timers and reacts when a predefined event takes place but the processor does not execute other stuff in loop it sleeps the whole time and only wakes up after an event occurred as before we can use external and timed wake up's and you cannot only use standard pins you can also use touch sensors etc let us now build a counter for people to save energy we only want to send a message every 10 persons for that we need a count which does not lose its value during sleep and after the counter reaches 10 we trigger a function that sends a message after deep sleep the sketch always starts in setup and never reaches loop because we send it to sleep at the end of setup so the setup part is comparable with the ISR from before let's try it out I use the phone generator to simulate a steady flow of people by sending short impulses to pin five and we use the code from the ESP 32 examples the loop is empty and the last line in setup is ESP deep sleep start after that statement the ESP will sleep well as long as you want until the next person comes and has to be counted right after the event the ESP 32 starts to run the same way as after a powerup first it initializes serial and prints the wake-up reason then it increases the count and goes to sleep again by the way I had to declare the variable count with a preceding RTC data attribute to make sure it is stored in RTC memory this memory survives deep sleep but not powered on I also added a statement to set pin 17 to high for debugging I do not set it to low because this is automatically done when the CPU goes for an app like that we can monitor how long the CPU works I also added a check for the wake-up reason to make sure the counter only counts the events produced by our people counter after 10 people it calls sent message for this video I just update the display but we could start Wi-Fi and send an MQTT message to a broker the backlight of the display goes often on for a moment when a new count is written to the display as a proof if we want to optimize the power consumption we have to reduce the time the CPU is on so we take out all not needed statements our sketch is now very short how long does it take from the wake-up signal till the ESP starts to work this latency is a little more than 140 microseconds much longer than before of course the code itself runs very fast to check the power consumption I use my ot we see two main phases with different power consumptions and the total length is also 150 microseconds this diagram shows that the ESP 32 processor starts to consume energy as soon as it gets the wake-up call first a little less and afterwards the full 80 milliampere everything without Wi-Fi of course to count one person consumes nine microwatt hours every tenth person it takes of course longer because the message has to be displayed so we built a low power consuming person counter of course it is much slower than the one using interrupts but it needs less current you can also use a timer to create a wakeup it works very similarly you just start the timer before you set the ESP 32 to sleep here again you see that the ESP 32 is not optimized for a fast wakeup other processor architectures are faster in this respect this was all for today summarized we saw that interrupts are handy to monitor events they interrupt a running sketch to do something different you should use them instead of digital read whenever possible they reduce the complexity of your sketches and are simple to implement if you know how interrupt service routines have to be as short as possible never never use serial print statements or delays in such functions we can use to simple statements plus an oscilloscope to debug real-time sketches the interrupt latency of the ESP 32 is significant and even worse unstable so pay attention if you want to use it in fast applications it can crush your MCU deep sleep and wake up work very similar to interrupts the main difference the sleep is interrupted not a running program the wake-up time of the ESP 32 is not short and consumes some energy so it's not ideal for extremely low-power applications we can use variables start in the RTC to shorten the sketch if we do not need to transfer every result we can use timed wake-ups for regular events also here we could read a sensor and only send a message when its value is dangerous like that we can reduce the time and energy the sketch needs if you need even more power reduction you can use the ultra-low power processor of the ESP 32 shown in video number 2 v 2 and there is a third possibility between the two using so-called stops unfortunately I did not find information on how to use it in the arduino ide these long latencies may be related to the fact that the ESP 32 uses an artist's operating system but i'm not sure as always you find all relevant links in the description i hope this video was useful or at least interesting for you if true please consider supporting the channel to secure its future existence thank you bye
Info
Channel: Andreas Spiess
Views: 169,567
Rating: undefined out of 5
Keywords:
Id: CJhWlfkf-5M
Channel Id: undefined
Length: 18min 57sec (1137 seconds)
Published: Sun May 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.