![]() ![]() You can also use one of the timer interrupts on the Arduino to ensure that your scheduled measurements take place when you want them to no matter what the code in the main loop is doing. You can do reduce that overhead by at least a factor of 10 by using interrupts to handle the pulse measurement. If you are doing this 5 times a second then that is 190 mS or 19% of the time wasted waiting for signals to change. To do this accurately in the main loop it can do nothing else until the pulse has completed which effectively wastes up to 38 mS every measurement waiting for a pin to change state. They all rely on the timing function pulseIn() to measure the duration of the echo pulse. This is where most examples of using this sensor fall short in my opinion. From that, together with the speed of sound, you can calculate the distance to the object. So all you have to do is measure the time during which the Echo signal is high. If there is no object in view then the Echo signal will stay high for 38 mS. ![]() It will remain high for up to 25 mS depending on the distance from the object. ![]() When the ultrasonic burst of pulses has been trasmitted by the HC-SR04 the signal voltage on the Echo pin goes high. The trigger pulse needs to be at least 10 µS long and will be delivered from pin 2 on the Arduino Uno. First it transmits a short ultrasonic pulse then it listens for the echo. When the HC-SR04 receives a short pulse on the trigger input the module begins a measurement. The module requires 5 volt power to operate so connect the Ground pin to one of the ground pins on the Arduino and the VCC to a 5V pin on the Arduino. If you want to learn more about using interrupts on the Arduino then take a look at this timer interrupt example. I thought that I would be different and show you a better way using interrupts. ![]() Putting all the code in the main loop makes it difficult to schedule your measurements and it introduces significant delays eats into the available processing time you have available. This is ok if all you want to do is prove that the ultrasonic module is working but it isn't very convenient if you are expecting your software to do something smart with the information from the sensor. When I looked around I found that all the examples of using the HC-SR04 with the Arduino used sketches that live exclusively in the main loop() of the sketch. Interrupts are not magic but they can make your programs so much better if you use them properly. Don't worry, no matter what you might have been told, there is nothing scary aboout this. The software sketch that I'm going to give you makes use of interrupts. Use interrupts to make your code better and faster ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |