Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
In this article, we will explore the micros() function in Arduino and understand its importance in time-sensitive applications. The micros() function is a built-in function in Arduino that returns the number of microseconds since the Arduino board started running. This function is particularly useful when precise timing is required, such as in robotics, home automation, or any application that involves time-sensitive operations.
The micros() function is adjusted to align with the Arduino environment, providing a simple and convenient way to access the internal timer of the microcontroller. By using this function, you can accurately measure time intervals, control timing-dependent actions, and synchronize different parts of your Arduino projects.
Project: For our example project, let's consider a simple home automation system that turns on a light for a specific duration when a motion sensor detects movement. We will use the micros() function to accurately measure the time elapsed since the motion sensor was triggered and control the duration of the light being turned on.
Components List:
Examples:
int motionSensorPin = 2;
int relayPin = 3;
int lightDuration = 5000; // 5 seconds
void setup() { pinMode(motionSensorPin, INPUT); pinMode(relayPin, OUTPUT); }
2. Controlling the Light with micros():
```cpp
void loop() {
if (digitalRead(motionSensorPin) == HIGH) {
digitalWrite(relayPin, HIGH); // Turn on the light
unsigned long startTime = micros(); // Record the start time
while (micros() - startTime < lightDuration * 1000) {
// Wait until the desired duration has passed
}
digitalWrite(relayPin, LOW); // Turn off the light
}
}
In this example, we first initialize the motion sensor pin and relay pin as inputs and outputs, respectively. Inside the loop function, we check if the motion sensor detects any movement. If it does, we turn on the light by setting the relay pin to HIGH and record the start time using the micros() function.
We then enter a while loop that continuously checks if the elapsed time since the start is less than the desired light duration. This is achieved by subtracting the start time from the current time obtained through micros(). Once the desired duration has passed, we turn off the light by setting the relay pin to LOW.
This example demonstrates how the micros() function can be used to accurately control the timing of actions in time-sensitive applications.