Меню

Does not name a type arduino ошибка

I have written a library, but have problem with error does not name a type. I’ve tryed everything, searched for couple of hours and no luck. Library is placed in the «libraries» folder of the arduino sketch folder. Please help!!! I am using OSX, but the same problem occurs on Windows also.

This is header file of the library:

#ifndef OpticalSensor_h
#define OpticalSensor_h

#include <Arduino.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <String.h>

class OpticalSensor
{
    public:
        OpticalSensor(int analogPort);
        void LCDInit(int columns, int rows);
        void SerialInit(int bitRate);
        void SDInit();
        double& ReadFromAnalogPort();
        void SDCreateFile(String fileName);
        void SDDeleteFile(String fileName);
        void SDWriteToFile(String fileName);
        void SDStreamToFile(String Text);
        void SDOpenFileToStream(String fileName);
    private:
        int _analogPort;
        bool _displayFlag;
        Adafruit_RGBLCDShield _lcd;
        File _MainRecFile;
        double _voltage;
        void _LCDClearAll();
        void _LCDWriteInTwoRows(String row1, String row2);
        void _DelayAndClearLCD(bool returnStatus);
};

#endif

This is .cpp file of the library:

#include <OpticalSensor.h>

Adafruit_RGBLCDShield _lcd;
File _MainRecFile;
double _voltage;

OpticalSensor::OpticalSensor(int analogPort)
{
    _analogPort = analogPort;
}

void OpticalSensor::LCDInit(int columns, int rows)
{

    _lcd = Adafruit_RGBLCDShield();
    _lcd.begin(columns,rows);
}

void OpticalSensor::SerialInit(int bitRate)
{
    Serial.begin(bitRate);
    _bitRate = bitRate;
    while(!Serial) {
        //wait until serial is not open
    }
}

void OpticalSensor::SDInit()
{
    // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
    // Note that even if it's not used as the CS pin, the hardware SS pin
    // (10 on most Arduino boards, 53 on the Mega) must be left as an output
    // or the SD library functions will not work.
    pinMode(10, OUTPUT);

    //check if SD can be found and initialized. Print also message to
    //Serial if initialized and to _lcd if initialized.
   if(!SD.begin(4)) {
     if(Serial){
         Serial.println("Initialization failed!");
     }
     if(_lcd){
         _lcd.print("Init failed!");
     }
     _DelayAndClearLCD(true);
   }
   else {
       if(Serial) {
           Serial.println("Initialization done!");
       }
       if(_lcd) {
           lcd.print("Init done!");
       }
       _DelayAndClearLCD(false);
   }
}

void OpticalSensor::SDCreateFile(String fileName)
{
    //check if file allready exists, if not it creates one
    //and writes apropriate response to
    //lcd and Serial if they are initialized.
    if(SD.exists(fileName)) {
        if(Serial) {
            Serial.println(fileName + " already exists!");
        }
        if(_lcd) {
            _LCDWriteInTwoLines(fileName,"already exists!");
        }
        _DelayAndClearLCD(false);
    }
    else
    {
        if(Serial) {
            Serial.println(fileName + "Creating file " + fileName + "...");
        }
        if(_lcd) {
            _LCDWriteInTwoLines("Creating file", fileName);
        }
        _MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
        _MainRecFile.close();
        _DelayAndClearLCD(false);


        //check if file was created successffully and print apropriate response
        //to lcd and Serial if they are initialized
        if(SD.exists(fileName + ".txt")) {
            if(Serial) {
                Serial.println(fileName + ".txt" + " created successffully!");
            }
            if(_lcd) {
                _LCDWriteInTwoLines(fileName + ".txt", "created!");
            }
            _DelayAndClearLCD(false);
        }
        else {
            if(Serial) {
                Serial.println("error: failed to create file!");
            }
            if(_lcd) {
                _LCDWriteInTwoLines("error: failed to","create file!");
            }
            _DelayAndClearLCD(false);
        }
    }
}

//delete file from SD card
void OpticalSensor::SDDeleteFile(String fileName)
{

}

//open file, write data to it, and close file after.
void OpticalSensor::SDWriteToFile(String fileName, String Text)
{
    _MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
    _MainRecFile.println(Text);
    _MainRecFile.close();
}

//Open file to stream data to it.
void OpticalSensor::SDOpenFileToStream(String fileName)
{
    _MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
}

//Write data to file while file is open.
//Notice that you can stream data only to one file at a time!!!
//For instance, if you have two sensors that you want to
//write data to two different files, you have to use SDWriteToFile
//function!!!
void OpticalSensor::SDStreamToFile(String Text)
{
    if(_MainRecFile) {
        _MainRecFile.println(Text);
    }
}

//close file that you streamed data too.
void OpticalSensor::SDCloseStreaming(String fileName)
{
    _MainRecFile.close();
}

//clear entire LCD
void OpticalSensor::_LCDClearAll()
{
    _lcd.clear();
    _lcd.setCursor(0,0);
}

void OpticalSensor::_LCDWriteInTwoRows(String row1, String row2)
{
    //write first String in row1
    _lcd.print(row1);
    //set cursor to the beginning of row 2
    _lcd.setCursor(0,1);
    //write second String to row 2
    _lcd.print(row2);
}

void OpticalSensor::_DelayAndClearLCD(bool returnStatus)
{
    //if Serial or _lcd are initialized, delay for 2 seconds
    //and clear LCD
    if(Serial || _lcd) {
        delay(2000);
        if(_lcd)
            _LCDClearAll();
    }
    //terminate
    if(bool == true) {
        return;
    }
}

double& ReadFromAnalogPort()
{
    _voltage = analogRead(_analogPort);
    return _voltage;
}

And this is the .ino file where library is included:

#include <OpticalSensor.h>

OpticalSensor sensor(0);

void setup() {
  sensor.LCDInit(16,2);
  sensor.SerialInit(9600);
  sensor.SDInit();
  sensor.SDCreateFile("test1");
  sensor.SDOpenFileToStream("test1");
}

void loop() {

}

this is the error:

In file included from Test_OpticalSensorLib.ino:1:
/Users/gaspersladic/Documents/Arduino/libraries/OpticalSensor/OpticalSensor.h:34:
error: ‘Adafruit_RGBLCDShield’ does not name a type
/Users/gaspersladic/Documents/Arduino/libraries/OpticalSensor/OpticalSensor.h:35:
error: ‘File’ does not name a type

I’m getting a "'Serial' does not name a type" error when this program is compiled. I need for the 8 channels of voltage to be displayed. I’m sure it’s a simple fix, however I’m still learning Arduino programming. I thank you for your help.

int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}
Serial.print("Raw  Value = " );
Serial.print(RawValue); 

uint128_t's user avatar

asked Mar 4, 2016 at 3:45

Tom Evans's user avatar

2

Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.

Because those statements refer to RawValue, I’m guessing you want to put them in loop(), where RawValue is being updated.

Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.

answered Mar 4, 2016 at 4:01

uint128_t's user avatar

uint128_tuint128_t

8185 silver badges14 bronze badges

Please put these lines inside the loop() function block:

Serial.print("Raw  Value = " );
Serial.print(RawValue); 

Should look something like:

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue); 
}

That should at least remove the first issue with your code.

Cheers!

answered Mar 4, 2016 at 21:27

Mikael Patel's user avatar

Mikael PatelMikael Patel

7,9192 gold badges12 silver badges21 bronze badges

In addition to the good answers by Mikael and Uint, everything needs to be inside {curly braces} otherwise the IDE does not know where it belongs. If you didn’t want the last 2 lines in your loop segment you could put them in a separate void xxxx () section to be called when the time is right (by using an ISR with an enableinterrupt function for example).

gre_gor's user avatar

gre_gor

1,6564 gold badges18 silver badges28 bronze badges

answered Aug 24, 2018 at 16:02

Microk's user avatar

MicrokMicrok

1159 bronze badges

Вопрос:

Я строю метеостанцию, используя код моего друга. Тем не менее, он более старая версия Ардуино, и мне трудно понять, почему. Я новичок в программировании, поэтому я не знаю, что означает “dht” не называет тип “означает? Я использую Arduino 1.04, и мой друг закодировал свою метеостанцию на Arudino 0022. Мой вопрос: почему моя проверка не может скомпилироваться? Что я делаю неправильно?

Вот мой код:

#include <dht.h>
dht DHT;
#define DHT22_PIN 2
#include <Wire.h>
#define BMP085_ADDRESS 0x77  // I2C address of BMP085

const unsigned char OSS = 3;  // Oversampling Setting

// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;

// b5 is calculated in bmp085GetTemperature(...), this variable is also used in      bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;
short temperature;
long pressure;

void setup()
{
pinMode(2, INPUT);
Wire.begin();
bmp085Calibration();
Serial.begin(115200);
analogReference(INTERNAL);
}

void loop() {
// READ DATA
float bat_read=analogRead(6);
//bat_read = analogRead(BAT_voltage);
float chk = DHT.read22(DHT22_PIN);

// DISPLAY DATA
Serial.print(bat_read, DEC);
Serial.print(", ");
Serial.print(DHT.humidity, 2);
Serial.print(", ");
temperature = bmp085GetTemperature(bmp085ReadUT());
pressure = bmp085GetPressure(bmp085ReadUP());
Serial.print(temperature, DEC);
Serial.print(", ");
Serial.println(pressure, DEC);
delay(1000);
}

Ошибки:

error: 'dht' does not name a type

sketch_jul05a.ino: In function 'void loop()': error: 'DHT' was not declared in this scope

Лучший ответ:

О вашей конкретной ошибке вы должны

‘dht’ не называет тип

Это означает, что у вас есть слово dht, которого нет в месте, где компилятор мог понять, что вы имеете в виду.

как мне изменить его на тип?

Вы не хотите изменять его в тип, вы хотите решить проблему компиляции, которую вы получаете.

что означает тип?

Вы должны прочитать K & R по этому вопросу. Тип – это правило, которое ограничивает вас в создании когерентного кода.

Вы должны скопировать в свой вопрос полную ошибку, которую вы получаете, чтобы мы лучше вам помогли.

Предположим, что ошибка указана в следующей строке:

#include <dht.h>
dht DHT;  

Компилятор не знает, что такое dht, поскольку он никогда не видел, чтобы это было определено раньше. Я предполагаю, что dht.h должен быть заголовок, который должен быть включен, что потребности должны содержать определение типа dht. Вы должны посмотреть, есть ли у вас dht.h в вашей файловой системе и нажать его в своем каталоге эскизов. И, наконец, измените #include <dht.h> на #include "dht.h", поэтому он ищет dht.h в вашем локальном каталоге.

EDIT: Извините, я не думаю, что я не могу помочь вам здесь больше, чем то, что я только что сказал. Проблема в том, что вы не понимаете, что я говорю вам, чтобы решить вашу проблему, и объясняя это вам, вы дадите вам урок программирования C. Итак, вы должны сначала начать читать K & R, пойти на курсы программирования C/C++/Arduino (возможно, в вашем местном хакерском пространстве?) И/или попросить своего друга помочь вам и объяснить вам, что происходит.

Ответ №1

Вчера у меня была такая же проблема, обновляя эскиз с помощью датчика DHT22, который был написан в Arduino 0022. Я пытался отредактировать его в среде Arduino 1.0.5. Несколько ошибок компиляции, особенно с функцией millis(). Я думаю, что это могло бы сработать, если бы я только открыл IDE 0022, но я подумал, что пришло время принести эскиз в это десятилетие;)

Я загрузил библиотеку Adafruit DHT22 из Github и немного перерисовал набросок, чтобы использовать библиотечные методы. Это было довольно заметно. Примерный эскиз, включенный в библиотеку, вы можете получить, чтобы все было в порядке.

В моем эскизе у меня все получилось:

#include "DHT.h"
#define DHTPIN 7 // what pin we're connected to on the Arduino UNO

#define DHTTYPE DHT22 // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}

Разница между старой версией и обновленной версией была “dht.begin(); в блоке настройки.

Библиотека Adafruit не такая же надежная, как предыдущая библиотека, которую я использовал, особенно с обработкой ошибок, но она просто работала после 45 минут игры.

Может помочь мне, если библиотека XBee перестанет работать в будущей версии Arduino IDE!

Ответ №2

“Тип” описывает вашу переменную. Как целое число (5), строка (“Hello world”), символ (“a”), логическое (true или false) или float (3.1415).

Похоже, что “dht” должен быть типом, но IDE arduino не распознает его, поскольку он не является нормальным типом. Это нужно решить, импортировав библиотеку, которая создает этот тип. Тогда ардуинец может это распознать.

Именно здесь приходит ваш “#include”. Я бы рекомендовал изменить его на “#include” dht.h “.

Кроме того, дважды проверьте, чтобы dht.h действительно был файлом, к которому может обращаться ардуино.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Does he got a new car где ошибка
  • Dodge stratus ошибка p0441