找不到在 .ino 中声明的函数

Function declared in .ino not found

我正在尝试创建一个简单的应用程序,它在 EEPROM 内存中存储一​​个结构,并在启动时从 EEPROM 读取存储的结构,然后根据存储的数据执行其余部分。

这是我的主 ino 文件:

extern "C" {
    #include "Structs.h"
}

Settings settings;

void setup()
{
    settings = settings_read();
}

void loop()
{

  /* add main program code here */

}

这是 Structs.h 文件:

#ifndef _STRUCTS_h
#define _STRUCTS_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

typedef struct {
    byte lastCountry;
    byte lastMode;
} Settings;

#endif

这是 Settings.ino 文件:

#include <EEPROM.h>

Settings settings_read() {
    byte country, mode;
    Settings settings;

    country = EEPROM.read(0);
    mode = EEPROM.read(1);

    settings = {
        country,
        mode
    };

    return settings;
}

这是编译器错误:

Compiling 'Stoplicht' for 'Arduino Uno'
Stoplicht.ino:5:1: error: 'Settings' does not name a type
Stoplicht.ino:In function 'void setup()'
Stoplicht.ino:9:27: error: 'settings_read' was not declared in this scope
Error compiling

我尝试了很多不同的方法来让它工作。我尝试将 Settings.ino 中的代码放入 .C 文件中。这给出了更多错误,它说 EEPROM.h 函数没有声明。我还尝试将 structsettings_read 放入 Settings.ino 中,这会产生更多错误。我是 C 语言的新手,我在这里找不到我做错了什么。

它是 "Arduino.h",而不是 "arduino.h",因此您应该将这些行更改为:

#ifndef _STRUCTS_h
#define _STRUCTS_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

typedef struct {
    byte lastCountry;
    byte lastMode;
} Settings;

#endif

下一个问题是你笨拙的 include 语法?!我不知道这个 extern "C" 东西,但它应该通过简单地使用来工作:

#include "Structs.h"

没有任何锅炉板。

作为提示,当使用多个文件 Arduino IDE 时,它缺少自动完成功能,它的 *.ino 垃圾会使您的项目变得混乱,并确保您不时遇到编译问题。对于多文件项目,我建议使用默认 c/++ 的 biicode(http://docs.biicode.com/arduino/gettingstarted.html)。

正如我在评论中所说,Arduino 的首选语言 是 C++,而不是 C。

因此,遵循 C++ 构建应用程序的方式似乎是个好主意。忘记 C 方式,它通常包含解决方法,因为 C 中缺乏足够的干净编程机制。(并不是说 C++ 是完美的...)。

所以我重组了您的示例代码,它现在展示了如何为 Settings 类型定义和使用库。

首先从主ino文件开始

// StopLicht.ino

#include "Settings.h"

Settings settings;

void setup()
{
   settings.read(); // doing it the OO way
}

void loop()
{
   // code here. does some stuff with 
   // settings.mode and settings.country
}

Settings 类型定义为具有 2 个字段的 struct,以及(C++ 中的)作用于 Settings 的成员函数 read() :

// Settings.h

#ifndef SETTINGS_H_INCLUDED
#define SETTINGS_H_INCLUDED

struct Settings 
{
  byte country; 
  byte mode;

  void read();   // to get values from EEPROM
};

#endif

并且在ino文件中实现

// Settings.ino

#include <EEPROM.h>

#include "Settings.h"

void Settings::read() 
{
     country = EEPROM.read(0);
     mode    = EEPROM.read(1);
};

备注:Settings当然可以写成class而不是结构。在这种情况下没什么大不了的。