Arduino Tutorial: Interface Arduino Pro Mini and Ultrasonic Sensor
The Arduino Pro Mini is a compact, versatile microcontroller board that is widely used in various projects, especially those where space is a constraint. One of the most commonly used sensors in Arduino projects is the ultrasonic sensor, which can measure distances using sound waves. In this tutorial, we will explore how to interface the Arduino Pro Mini with an ultrasonic sensor and create a simple distance measuring system.
Requirements:
To follow along with this tutorial, you will need the following components:- Arduino Pro Mini board
- Ultrasonic sensor (HC-SR04 or similar)
- Jumper wires
- Breadboard (optional, but recommended)
Connect the Arduino Pro Mini
The Arduino Pro Mini has a minimal number of pins, so we need to make sure to connect the sensor to the correct pins. Here's how to do it:- Connect the VCC pin of the ultrasonic sensor to the VCC pin (5V) of the Arduino Pro Mini.
- Connect the GND pin of the ultrasonic sensor to the GND pin of the Arduino Pro Mini.
- Connect the TRIG pin of the ultrasonic sensor to any digital pin of the Arduino Pro Mini (for example, pin 10).
- Connect the ECHO pin of the ultrasonic sensor to any digital pin of the Arduino Pro Mini (for example, pin 11).
Write the Arduino Code
Next, we need to write the code that will allow the Arduino Pro Mini to interface with the ultrasonic sensor. The code will trigger the sensor, measure the time it takes for the sound wave to bounce back, and calculate the distance based on the speed of sound.// Define the pins
const int trigPin = 10;
const int echoPin = 11;
void setup() {
// Set the trigPin as an output
pinMode(trigPin, OUTPUT);
// Set the echoPin as an input
pinMode(echoPin, INPUT);
// Initialize the serial communication
Serial.begin(9600);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, calculate the duration in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay for 500 milliseconds before the next measurement
delay(500);
}
Comments
Post a Comment