在Arduino中使用C ++类

时间:2016-05-09 00:14:11

标签: c++ class arduino

我需要使用Arduino中的类才能执行多任务。我在here找到了一个班级示例,但我想保持我的主要代码干净,所以我决定把这个班级放在 .h .cpp 文件。经过一段谷歌搜索后,这就是我想出来的: Work.h 档案:

/*
 * Work.h
 *
 *  Created on: 2016-05-09
 *      Author: Secret
 */

#ifndef WORK_H_
#define WORK_H_
int ledPin;      // the number of the LED pin
unsigned long OnTime;     // milliseconds of on-time
unsigned long OffTime;    // milliseconds of off-time

int ledState;                   // ledState used to set the LED
unsigned long previousMillis;   // will store last time LED was updated
class Work {

public:
    Work(int pin, long on, long off);
    void Update();
};

#endif /* WORK_H_ */

Work.cpp 文件:

/*
 * Work.cpp
 *
 *  Created on: 2016-05-09
 *      Author: Secret
 */

#include "Work.h"
#include <Arduino.h>

Work::Work(int pin, long on, long off) {

    ledPin = pin;
    pinMode(ledPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    ledState = LOW;
    previousMillis = 0;

}
void Update() {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime)) {
        ledState = LOW;  // Turn it off
        previousMillis = currentMillis;  // Remember the time
        digitalWrite(ledPin, ledState);  // Update the actual LED
    } else if ((ledState == LOW)
            && (currentMillis - previousMillis >= OffTime)) {
        ledState = HIGH;  // turn it on
        previousMillis = currentMillis;   // Remember the time
        digitalWrite(ledPin, ledState);   // Update the actual LED
    }
}

当我尝试编译时,我在Work.cpp中遇到错误,方法Update()我有多个 OnTime OffTime ledState的定义 previousMillis
我在这里做错了什么以及如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

该错误意味着您将这些变量出现在多个翻译单元中。默认情况下,非const个全局变量具有外部链接。

要将其设为内部版,您可以使用static对其进行限定。或者您只需将定义移动到翻译单元(.cpp文件)

在Work.h中使用static获得资格

static int ledPin;      // the number of the LED pin
static unsigned long OnTime;     // milliseconds of on-time
static unsigned long OffTime;    // milliseconds of off-time

static int ledState;                   // ledState used to set the LED
static unsigned long previousMillis;   // will store last time LED was updated
class Work {

public:
    Work(int pin, long on, long off);
    void Update();
};

最好将它们移动到.cpp文件中,因为您没有在Work.h文件中使用它们。

修改

错误源自.cpp文件中的Update()函数。

void Update() { ....

^^定义了一个新函数,并且正在使用那些全局变量......我相信你想要做

void Work::Update() {....

答案 1 :(得分:0)

由于方法Update()是Work类的一部分,它应该在Work类的范围内定义,如下所示:

void Work :: Update () {....