Untitled
unknown
plain_text
10 months ago
2.4 kB
11
Indexable
#include <stdio.h>
#include <pigpio.h>
#include <unistd.h>
// Define the GPIO pins for LED and Ultrasonic sensor
#define LED_PIN 2 // GPIO pin for LED
#define TRIG_PIN 23 // GPIO pin for Trig (ultrasonic sensor)
#define ECHO_PIN 24 // GPIO pin for Echo (ultrasonic sensor)
int main() {
// Initialize the pigpio library
if (gpioInitialise() < 0) {
printf("PIGPIO initialization failed\n");
return 1;
}
// LED Control: Turn the LED on and off
printf("LED Control: Turning LED ON...\n");
gpioSetMode(LED_PIN, PI_OUTPUT); // Set LED pin as output
gpioWrite(LED_PIN, 1); // Turn LED ON
getchar(); // Wait for Enter key to turn LED off
gpioWrite(LED_PIN, 0); // Turn LED OFF
printf("LED Control: LED OFF\n");
// Wait a moment before ultrasonic sensor starts
usleep(1000000); // Wait for 1 second before starting ultrasonic measurement
// Ultrasonic Sensor: Measure distance
printf("Ultrasonic Sensor: Measuring Distance...\n");
// Set up Trig pin as output and Echo pin as input
gpioSetMode(TRIG_PIN, PI_OUTPUT);
gpioSetMode(ECHO_PIN, PI_INPUT);
// Ensure the Trig pin is low before sending pulse
gpioWrite(TRIG_PIN, 0);
usleep(2000); // Wait for 2 milliseconds to ensure pin is low
// Send a pulse on the Trig pin to start the measurement
gpioWrite(TRIG_PIN, 1); // Set Trig pin high
usleep(10); // Wait for 10 microseconds
gpioWrite(TRIG_PIN, 0); // Set Trig pin low
// Measure the time the Echo pin is high
while (gpioRead(ECHO_PIN) == 0); // Wait for the Echo pin to go high
int start = gpioTick(); // Record the start time
while (gpioRead(ECHO_PIN) == 1); // Wait for the Echo pin to go low
int stop = gpioTick(); // Record the stop time
// Calculate the duration of the pulse
double pulseDuration = (stop - start) / 1000000.0; // Convert microseconds to seconds
// Calculate the distance (speed of sound ~ 343m/s at 20C)
double distance = pulseDuration * 34300.0 / 2.0; // Divide by 2 because it's the round-trip distance
// Output the distance measured
printf("Distance: %.2f cm\n", distance);
// Clean up and terminate the pigpio library
gpioTerminate();
return 0;
}
Editor is loading...
Leave a Comment