香橙派/树莓派 利用Wiring库 使用GPIO模拟PWM

香橙派或者树莓派 等开发板,本身带有硬件PWM,比如香橙派3 lts版,但是这个引脚不符合我的项目需求,我需要外接一个电机,在检测到人脸的时候 转动,但是这个硬件引脚,只要上电就开始输出pwm 信号,导致电机一直再转,因此采用软件 利用GPIO模拟的方式,更符合需求。

#pragma once
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace toolkit;
const int gpioPin = 10;         //GPIO引脚
const int pwmRange = 100;       // PWM范围(0-100对应占空比0-100%)
const int targetDutyCycle = 80; // 目标占空比(0-100)

class Vibration : public std::enable_shared_from_this
{
public:
    using Ptr = std::shared_ptr;
    ~Vibration()
    {
    }

    bool init()
    {
        // 初始化 WiringPi 库
        if (wiringPiSetup() == -1)
        {
            ErrorL << "WiringPi初始化失败!";
            return false;
        }

        // 初始化软件PWM(参数:引脚、初始值、范围)
        if (softPwmCreate(gpioPin, 0, pwmRange) != 0)
        {
            ErrorL << "软件PWM初始化失败!";
            return false;
        }
        return true;
    }

    void vibrate()
    {
        // 设置占空比
        softPwmWrite(gpioPin, targetDutyCycle);

       InfoL<< "PWM运行中 (引脚 " << gpioPin
                  << "), 占空比: " << targetDutyCycle << "%" ;

        // 保持运行(例如5秒)
        delay(3000);

        // 停止PWM
        softPwmWrite(gpioPin, 0);
    }
};

你可能感兴趣的:(C++,单片机,嵌入式硬件,PWM,GPIO,香橙派3,lts)