Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.4 kB
0
Indexable
Never
#include <pigpio.h>
#include <iostream>
#include <unistd.h> // For sleep()

int main() {
    // Initialize the pigpio library
    if (gpioInitialise() < 0) {
        std::cerr << "Failed to initialize pigpio" << std::endl;
        return 1;
    }

    // Set GPIO pin number
    int pin = 14;

    // Set servo parameters
    double min_pulse_width = 0.000544;
    double max_pulse_width = 0.0024;

    // Initialize servo
    gpioSetMode(pin, PI_OUTPUT);
    gpioServoRange(pin, 1000); // 1ms - 2ms
    gpioServo(pin, (int)((min_pulse_width + max_pulse_width) / 2 * 1000));

    // Print servo mid
    std::cout << "servo mid" << std::endl;
    sleep(3);

    // Loop for servo movement
    while (true) {
        // Move servo from -90° to 90°
        for (int i = 0; i <= 10; ++i) {
            gpioServo(pin, (int)((min_pulse_width + max_pulse_width) / 2 * 1000 + (-1 + 0.2 * i) * (max_pulse_width - min_pulse_width) / 2 * 1000));
            sleep(2);
        }
        // Move servo from 90° to -90°
        for (int i = 0; i <= 10; ++i) {
            gpioServo(pin, (int)((min_pulse_width + max_pulse_width) / 2 * 1000 + (1 - 0.2 * i) * (max_pulse_width - min_pulse_width) / 2 * 1000));
            sleep(2);
        }
    }

    // Terminate pigpio library
    gpioTerminate();

    return 0;
}
Leave a Comment