树莓派使用Qt操作GPIO并设置开机启动

1. 编写程序

在Qt中新建控制台程序,在pro中增加:

QT += network
LIBS += -lwiringPi

main.cpp代码为:

#include 
#include 
#include 
#include 

#include 


int main(int argc, char *argv[])
{
    //初始化wiringPi库

    if (wiringPiSetup())
    {
        qDebug()<<"GPIO init fail";
        return 0;
    }

    qDebug()<<"GPIO inited";

    //设置管脚1为PWM输出(需要root用户或sudo)
    pinMode(1,PWM_OUTPUT);

    qDebug()<<"Set pin 1 to PWM_OUTPUT";

    QCoreApplication a(argc, argv);

    //使用UDP监听数据
    QUdpSocket *pUdpSocket = new QUdpSocket();

    if (!pUdpSocket->bind(12345))
    {
        qDebug()<<"Bind port 12345 fail";
        return 0;
    }

    qDebug()<<"Listening on port 12345...";

    while (1)
    {
        if (pUdpSocket->waitForReadyRead())
        {
            while (pUdpSocket->hasPendingDatagrams())
            {
                QByteArray baRcv = pUdpSocket->receiveDatagram().data();

                if (baRcv.count() == 2)
                {
                    int iValue = (static_cast(baRcv.at(0))<<8) + static_cast(baRcv.at(1));

                    //在管脚1写出PWM值,iValue的范围是0~1024
                    pwmWrite(1,iValue);
                    qDebug()<<"Write to"<

编译后部署在/opt/background/bin/中(完整路径为/opt/background/bin/background)。

2. 设置开机启动

方法一(不推荐,实测GUI程序无法正常启动):编辑/etc/rc.local文件,在exit 0之前加入如下:

/opt/background/bin/background

方法二:新建background文本文件,输入如下内容:

#!/bin/bash
### BEGIN INIT INFO
# Provides: Background
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Background 
# Descrption: This service is used to test auto start service
### END INIT INFO

case "$1" in
    start)
        echo "Stat"
        /opt/background/bin/background &
        ;;
    stop)
        echo "Stop"
        killall /opt/background/bin/background
        exit 1
        ;;
    *)
        echo "Usage:service Background start|stop"
        exit 1
        ;;
esac
exit 0

复制到/etc/init.d目录中,然后放开访问权限:

sudo chmod 777 /etc/init.d/background

添加到开机启动:

sudo update-rc.d background defaults

可以手动测试一下打开关闭:

sudo service background start
sudo service background stop

 

你可能感兴趣的:(树莓派)