Expected unqualified id before numeric constant ардуино ошибка

After debugging and having some conflicting declarations about analog pins, I finally thought it was done, after compiling I got this error: 32:0, 1: 31:12: error: expected unqualified-id before n...

After debugging and having some conflicting declarations about analog pins, I finally thought it was done, after compiling I got this error:

32:0,
1:
31:12: error: expected unqualified-id before numeric constant


2:5: note: in expansion of macro 'B1'

I can’t understand what this means. What’s wrong with my code down here?

// don't judge me if it's too long and overcomplicated :P I'm still new xD
int AA1 = 0;
int B1 = 1;
int C1 = 2;
int D1 = 3;
int AA2 = 4;
int B2 = 5;
int C2 = 6;
int AA3 = 8;
int B3 = 9;
int C3 = 10;
int D3 = 11;
int B4 = 12;
int C4 = 13;
int sec = 0;
int min1 = 0;
int min2 = 0;
int hour1 = 8;
bool hour2 = 0;

void setup() {
  pinMode(AA1, OUTPUT);
  pinMode(B1, OUTPUT);
  pinMode(C1, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(AA2, OUTPUT);
  pinMode(B2, OUTPUT);
  pinMode(C2, OUTPUT);
  pinMode(AA3, OUTPUT);
  pinMode(B3, OUTPUT);
  pinMode(C3, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(B4, OUTPUT);
  pinMode(C4, OUTPUT);
}

void loop() {
  OutputOn();
  delay(1000);
  sec++;
  if(sec == 60) {
    sec = 0;
    min1++;
      if(min1 == 10) {
      min1 = 0;
      min2++;
        if(min2 == 6) {
        min2 = 0;
        hour1++;
          if(hour1 == 10) {
          hour1 = 0;
          hour2 = 1;
        }
        if(hour2 == 1, hour1 == 3) {
          hour1 = 1;
          hour2 = 0;
        }
      }
    }
  }
}

void OutputOn() {
  digitalWrite(B1, LOW);
  digitalWrite(C1, LOW);
  digitalWrite(D1, LOW);
  digitalWrite(A2, LOW);
  digitalWrite(B2, LOW);
  digitalWrite(C2, LOW);
  digitalWrite(A3, LOW);
  digitalWrite(B3, LOW);
  digitalWrite(C3, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(B4, LOW);
  digitalWrite(C4, LOW);
  if(min1 == 1) { digitalWrite(AA1, HIGH); }
  if(min1 == 2) { digitalWrite(B1, HIGH); }
  if(min1 == 3) { digitalWrite(B1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 4) { digitalWrite(C1, HIGH); }
  if(min1 == 5) { digitalWrite(C1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 6) { digitalWrite(D1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 7) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 8) { digitalWrite(D1, HIGH); }
  if(min1 == 9) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 1) { digitalWrite(AA2, HIGH); }
  if(min2 == 2) { digitalWrite(B2, HIGH); }
  if(min2 == 3) { digitalWrite(B2, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 4) { digitalWrite(C2, HIGH); }
  if(min2 == 5) { digitalWrite(C2, HIGH); digitalWrite(A2, HIGH); }
  if(min2 == 6) { digitalWrite(C2, HIGH); digitalWrite(B2, HIGH); }
  if(hour1 == 1) { digitalWrite(AA3, HIGH); }
  if(hour1 == 2) { digitalWrite(B3, HIGH); }
  if(hour1 == 3) { digitalWrite(B3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 4) { digitalWrite(C3, HIGH); }
  if(hour1 == 5) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 6) { digitalWrite(C3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 7) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 8) { digitalWrite(D3, HIGH); }
  if(hour1 == 9) { digitalWrite(D3, HIGH); digitalWrite(C3, HIGH); }
  if(hour2 == 1) { digitalWrite(B4, HIGH); digitalWrite(C4, HIGH); }
}

It’s supposed to be code for a clock (if it wasn’t obvious enough) hooked up to 4 7-segment decoders, also connected to 4 7-segment LED displays.

Первая прошивка


Итак, разобрались со средой разработки, теперь можно загрузить прошивку. Рекомендую загрузить пустую прошивку, чтобы убедиться, что все драйвера установились и плата вообще прошивается. Также лучше делать это с новой или заведомо рабочей платой.

1. Плата подключается к компьютеру по USB, на ней должны замигать светодиоды. Если этого не произошло:

  • Неисправен USB кабель.
  • Неисправен USB порт компьютера.
  • Неисправен USB порт Arduino.
  • Попробуйте другой компьютер, чтобы исключить часть проблем из списка.
  • Попробуйте другую плату, чтобы исключить часть проблем из списка.
  • На плате Arduino сгорел диод по питанию USB.
  • Плата Arduino сгорела полностью из-за неправильного подключения питания или короткого замыкания

2. Компьютер издаст характерный сигнал подключения нового оборудования, а при первом подключении появится окошко “Установка нового оборудования”. Если этого не произошло:

  • См. предыдущий список неисправностей.
  • Кабель должен быть data-кабелем, а не “зарядным”.
  • Кабель желательно втыкать напрямую в компьютер, а не через USB-хаб.
  • Не установлены драйверы для Arduino.

3. В списке портов (Arduino IDE/Инструменты/Порт) появится новый порт, отличный от COM1. Если этого не произошло:

  • См. предыдущий список неисправностей.
  • Некорректно установлен драйвер CH341.
  • Если список портов вообще неактивен – драйвер Arduino установлен некорректно, вернитесь к установке
  • Возникла системная ошибка, обратитесь к знакомому компьютерщику

4. Выбираем свою плату. Если это Arduino Nano, выбираем в ИнструментыПлатаArduino Nano. Если другая – выбираем другую. Нажимаем стрелочку в левом верхнем углу (загрузить прошивку). Да, загружаем пустую прошивку.

  • [Для Arduino Nano] В микроконтроллер китайских нанок зашит “старый” загрузчик, поэтому выбираем ИнструментыПроцессорATmega328p (Old Bootloader). Некоторые китайцы зашивают в свои платы новый загрузчик, поэтому если прошивка не загрузилась (загрузка идёт минуту и вылетает ошибка avrdude: stk500_getsync()) – попробуйте сменить пункт Процессор на ATmega328p.

Если появилась надпись “Загрузка завершена” – значит всё в порядке и можно прошивать другие скетчи. В любом случае на вашем пути встретятся другие два варианта событий, происходящих после нажатия на кнопку “Загрузка” – это ошибка компиляции и ошибка загрузки. Вот их давайте рассмотрим более подробно.

Ошибки компиляции


Возникает на этапе компиляции прошивки. Ошибки компиляции вызваны проблемами в коде прошивки.

  • В некоторых случаях ошибка возникает при наличии кириллицы (русских букв) в пути к папке со скетчем. Решение: завести для скетчей отдельную папочку в корне диска с английским названием.
  • В чёрном окошке в самом низу Arduino IDE можно прочитать полный текст ошибки и понять, куда копать.
  • В скачанных с интернета готовых скетчах часто возникает ошибка с описанием название_файла.h no such file or directory. Это означает, что в скетче используется библиотека <название файла>, и нужно положить её в Program Files/Arduino/libraries/. Ко всем моим проектам всегда идёт папочка с использованными библиотеками, которые нужно установить. Также библиотеки всегда можно поискать в гугле по название файла.
  • При использовании каких-то особых библиотек, методов или функций, ошибкой может стать неправильно выбранная плата в “Инструменты/плата“. Пример: прошивки с библиотекой Mouse.h или Keyboard.h компилируются только для Leonardo и Micro.
  • Если прошивку пишете вы, то любые синтаксические ошибки в коде будут подсвечены, а снизу в чёрном окошке можно прочитать более детальное описание, в чём собственно косяк. Обычно указывается строка, в которой сделана ошибка, также эта строка подсвечивается красным.
  • Иногда причиной ошибки бывает слишком старая, или слишком новая версия Arduino IDE. Читайте комментарии разработчика скетча
  • Ошибка недостаточно свободного места возникает по вполне понятным причинам. Возможно поможет урок по оптимизации кода.

Частые ошибки в коде, приводящие к ошибке компиляции


  • expected ‘,’ or ‘;’ – пропущена запятая или точка запятой на предыдущей строке
  • stray ‘320’ in program – русские символы в коде
  • expected unqualified-id before numeric constant – имя переменной не может начинаться с цифры
  • … was not declared in this scope – переменная или функция используется, но не объявлена. Компилятор не может её найти
  • redefinition of … – повторное объявление функции или переменной
  • storage size of … isn’t known – массив задан без указания размера

Ошибки загрузки


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

  • USB кабель, которым подключается Arduino, должен быть Data-кабелем, а не кабелем только для зарядки. Нужным нам кабелем подключаются к компьютеру плееры и смартфоны.
  • Причиной ошибки загрузки являются не установленные/криво установленные драйвера CH340, если у вас китайская NANO.
  • Также будет ошибка avrdude: ser_open(): can’t open device, если не выбран COM порт, к которому подключена Arduino. Если кроме COM1 других портов нет – читай два пункта выше, либо попробуй другой USB порт, или вообще другой компьютер.
  • Большинство проблем при загрузке, вызванных “зависанием” ардуины или загрузчика, лечатся полным отключением ардуины от питания. Потом вставляем USB и по новой прошиваем.
  • Причиной ошибки загрузки может быть неправильно выбранная плата в “Инструменты/Плата”, а также неправильно выбранный процессор в “Инструменты/Процессор”. Также в свежих версиях IDE нужно выбирать ATmega328P (Old Bootloader) для китайских плат NANO.
  • Если у вас открыт монитор COM порта в другом окне Arduino IDE или плата общается через СОМ порт с другой программой (Ambibox, HWmonitor, SerialPortPlotter и т.д.), то вы получите ошибку загрузки, потому что порт занят. Отключитесь от порта или закройте другие окна и программы.
  • Если у вас задействованы пины RX или TX – отключите от них всё! По этим пинам Arduino общается с компьютером, в том числе для загрузки прошивки.
  • Если в описании ошибки встречается bootloader is not responding и not in sync, а все предыдущие пункты этого списка проверены – с вероятностью 95% сдох загрузчик. Второй неприятный исход – загрузчик “слетел”, и его можно прошить заново.

Предупреждения


Помимо ошибок, по причине которых проект вообще не загрузится в плату и не будет работать, есть ещё предупреждения, которые выводятся оранжевым текстом в чёрной области лога ошибок. Предупреждения могут появиться даже тогда, когда выше лога ошибок появилась надпись “Загрузка завершена“. Это означает, что в прошивке нет критических ошибок, она скомпилировалась и загрузилась в плату. Что же тогда означают предупреждения? Чаще всего можно увидеть такие:

  • # Pragma message… – это просто сообщения, оставленные разработчиком проекта или библиотеки. Чаще всего номер версии и прочая информация.
  • Недостаточно памяти, программа может работать нестабильно – Чуть выше этого предупреждения обычно идёт информация о задействованной памяти. Память устройства можно добивать до 99%, ничего страшного не случится. Это флэш память и во время работы она не изменяется. А вот динамическую память желательно забивать не более 85-90%, иначе реально могут быть непонятные глюки в работе, так как память постоянно “бурлит” во время работы. НО. Это зависит от скетча и в первую очередь от количества локальных переменных. Можно написать такой код, который будет стабильно работать при 99% занятой SRAM памяти. Так что ещё раз: это всего лишь предупреждение, а не ошибка.

FAQ


Завершая раздел Введение в Arduino поговорим о вопросах, которые очень часто возникают у новичков:

  • Ардуину можно прошить только один раз? Нет, несколько десятков тысяч раз, всё упирается в ресурс Flash памяти. А он довольно большой.
  • Как стереть/нужно ли стирать старую прошивку при загрузке новой? Память автоматически очищается при прошивке, старая прошивка автоматически удаляется.
  • Можно ли записать две прошивки, чтобы они работали вместе? Нет, при прошивке удаляются абсолютно все старые данные. Из двух прошивок нужно сделать одну, причём так, чтобы не было конфликтов. Подробнее в этом уроке.
  • Можно ли “вытащить” прошивку с уже прошитой Ардуины? Теоретически можно, но только в виде нечитаемого машинного кода, в который преобразуется прошивка на С++ при компиляции, т.е. вам это НИКАК не поможет, если вы не имеете диплом по низкоуровневому программированию. Подробнее в этом уроке.
    • Зачем это нужно? Например есть у нас прошитый девайс, и мы хотим его “клонировать”. В этом случае да, есть вариант сделать дамп прошивки и загрузить его в другую плату на таком же микроконтроллере.
    • Если есть желание почитать код – увы, прошивка считывается в виде бинарного машинного кода, превратить который обратно в читаемый Си-подобный код обычному человеку не под силу.
    • Вытащить прошивку, выражаясь более научно – сделать дамп прошивки, можно при помощи ISP программатора, об этом можно почитать здесь.
    • Снять дамп прошивки можно только в том случае, если разработчик не ограничил такую возможность, например записав лок-биты, запрещающие считывание Flash памяти, или вообще отключив SPI шину. Если же разработчик – вы, и есть желание максимально защитить своё устройство от копирования – гуглите про лок-биты и отключение SPI

Видео


Полезные страницы


  • Набор GyverKIT – большой стартовый набор Arduino моей разработки, продаётся в России
  • Каталог ссылок на дешёвые Ардуины, датчики, модули и прочие железки с AliExpress у проверенных продавцов
  • Подборка библиотек для Arduino, самых интересных и полезных, официальных и не очень
  • Полная документация по языку Ардуино, все встроенные функции и макросы, все доступные типы данных
  • Сборник полезных алгоритмов для написания скетчей: структура кода, таймеры, фильтры, парсинг данных
  • Видео уроки по программированию Arduino с канала “Заметки Ардуинщика” – одни из самых подробных в рунете
  • Поддержать автора за работу над уроками
  • Обратная связь – сообщить об ошибке в уроке или предложить дополнение по тексту ([email protected])

Offline

Зарегистрирован: 15.08.2020

Код ошибки «Arduino: 1.8.13 (Windows 10), Плата:»Arduino Nano, ATmega328P (Old Bootloader)»

In file included from C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:4:0:

C:Users����DocumentsArduinolibrariesTime-master/Time.h:1:2: warning: #warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h» [-Wcpp]

#warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h»

^~~~~~~

sketch_aug15a:9:11: error: expected unqualified-id before numeric constant

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void setup()’:

sketch_aug15a:120:7: error: unable to find numeric literal operator ‘operator»»dig_display.init’

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void loop()’:

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:166:27: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

sketch_aug15a:195:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:197:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:199:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:201:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:203:10: error: unable to find numeric literal operator ‘operator»»dig_display.point’

exit status 1

expected unqualified-id before numeric constant

Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»»
Сам код:
#include
#include
#include
#include
#include «TM1637.h»
#define CLK 6
#define DIO 5

TM1637 4dig_display(CLK, DIO);

// для данных времени

int8_t ListTime[4]={0,0,0,0};

// для данных dd/mm

int8_t ListDay[4]={0,0,0,0};

// разделитель

boolean point=true;

// для смены время / день-месяц

unsigned long millist=0;

tmElements_t datetime;

OLED myOLED(4, 3, 4); //OLED myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

///// часы ..
byte decToBcd(byte val){
return ( (val/10*16) + (val%10) );
}

byte bcdToDec(byte val){
return ( (val/16*10) + (val%16) );
}

void setDateDs1307(byte second, // 0-59
byte minute, // 0-59
byte hour, // 1-23
byte dayOfWeek, // 1-7
byte dayOfMonth, // 1-28/29/30/31
byte month, // 1-12
byte year) // 0-99
{
Wire.beginTransmission(0x68);
Wire.write(0);
Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(dayOfWeek));
Wire.write(decToBcd(dayOfMonth));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
}

void getDateDs1307(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{

Wire.beginTransmission(0x68);
Wire.write(0);
Wire.endTransmission();

Wire.requestFrom(0x68, 7);

*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}

///// температура ..
float get3231Temp(){
byte tMSB, tLSB;
float temp3231;

Wire.beginTransmission(0x68);
Wire.write(0x11);
Wire.endTransmission();
Wire.requestFrom(0x68, 2);

if(Wire.available()) {
tMSB = Wire.read(); //2’s complement int portion
tLSB = Wire.read(); //fraction portion

temp3231 = (tMSB & B01111111); //do 2’s math on Tmsb
temp3231 += ( (tLSB >> 6) * 0.25 ); //only care about bits 7 & 8
}
else {
//oh noes, no data!
}

return temp3231;
}

void setup()
{
Serial.begin(9600); // запустить последовательный порт

// запуск дисплея

4dig_display.init();

// яркость дисплея

//tm1637.set(7);

Serial.begin(9600);
myOLED.begin();
Wire.begin();

// установка часов
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
second = 30;
minute = 0;
hour = 14;
dayOfWeek = 3; // день недели
dayOfMonth = 1; // день
month = 4;
year = 14;

//setDateDs1307(00, 40, 15, 6, 15, 8, 2020);

}

void loop(){
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
char week[8][10] = {«Monday», «Tuesday», «Wednesday», «Thursday», «Friday», «Saturday», «Sunday»};

getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);

char time[10];
char data[11];

snprintf(time, sizeof(time),»%02d:%02d:%02d»,
hour, minute, second);

snprintf(data, sizeof(data), «%02d/%02d/%02d»,
dayOfMonth, month, year);

myOLED.setFont(SmallFont);

myOLED.print(time, CENTER, 15);
myOLED.print(data, CENTER, 0);
myOLED.printNumF(get3231Temp(), 2, 55, 30);
myOLED.print(«C», 43, 30);
myOLED.update();

// получение времени

if (RTC.read(datetime)) {

ListTime[0]= datetime.Hour/10;

ListTime[1]= datetime.Hour%10;

ListTime[2]= datetime.Minute/10;

ListTime[3]= datetime.Minute%10;

ListDay[0]= datetime.Day/10;

ListDay[1]= datetime.Day%10;

ListDay[2]= datetime.Month/10;

ListDay[3]= datetime.Month%10;

}

else {

// ошибка

4dig_display.display(0,ListDay[0]);

4dig_display.display(1,ListDay[1]);

4dig_display.display(2,ListDay[2]);

4dig_display.display(3,ListDay[3]);

4dig_display.point(false);

}

delay(500);

// поменять индикацию точек

point=!point;

delay(1000);
}

Arduino.ru

Что значит ошибка expected unqualified-id before numeric constant? Как её исправить?

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

Код ошибки «Arduino: 1.8.13 (Windows 10), Плата:»Arduino Nano, ATmega328P (Old Bootloader)»

In file included from C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:4:0:

C:Users����DocumentsArduinolibrariesTime-master/Time.h:1:2: warning: #warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h» [-Wcpp]

#warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h»

sketch_aug15a:9:11: error: expected unqualified-id before numeric constant

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void setup()’:

sketch_aug15a:120:7: error: unable to find numeric literal operator ‘operator»»dig_display.init’

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void loop()’:

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:166:27: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

sketch_aug15a:195:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:197:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:199:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:201:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:203:10: error: unable to find numeric literal operator ‘operator»»dig_display.point’

expected unqualified-id before numeric constant

Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»»
Сам код:
#include
#include
#include
#include
#include «TM1637.h»
#define CLK 6
#define DIO 5

TM1637 4dig_display(CLK, DIO);

// для данных времени

// для данных dd/mm

// для смены время / день-месяц

unsigned long millist=0;

OLED myOLED(4, 3, 4); //OLED myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

///// часы ..
byte decToBcd(byte val) <
return ( (val/10*16) + (val%10) );
>

byte bcdToDec(byte val) <
return ( (val/16*10) + (val%16) );
>

void setDateDs1307(byte second, // 0-59
byte minute, // 0-59
byte hour, // 1-23
byte dayOfWeek, // 1-7
byte dayOfMonth, // 1-28/29/30/31
byte month, // 1-12
byte year) // 0-99
<
Wire.beginTransmission(0x68);
Wire.write(0);
Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(dayOfWeek));
Wire.write(decToBcd(dayOfMonth));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
>

void getDateDs1307(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
<

Wire.beginTransmission(0x68);
Wire.write(0);
Wire.endTransmission();

*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
>

///// температура ..
float get3231Temp() <
byte tMSB, tLSB;
float temp3231;

Wire.beginTransmission(0x68);
Wire.write(0x11);
Wire.endTransmission();
Wire.requestFrom(0x68, 2);

if(Wire.available()) <
tMSB = Wire.read(); //2’s complement int portion
tLSB = Wire.read(); //fraction portion

temp3231 = (tMSB & B01111111); //do 2’s math on Tmsb
temp3231 += ( (tLSB >> 6) * 0.25 ); //only care about bits 7 & 8
>
else <
//oh noes, no data!
>

void setup()
<
Serial.begin(9600); // запустить последовательный порт

Serial.begin(9600);
myOLED.begin();
Wire.begin();

// установка часов
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
second = 30;
minute = 0;
hour = 14;
dayOfWeek = 3; // день недели
dayOfMonth = 1; // день
month = 4;
year = 14;

//setDateDs1307(00, 40, 15, 6, 15, 8, 2020);

char time[10];
char data[11];

snprintf(time, sizeof(time),»%02d:%02d:%02d»,
hour, minute, second);

snprintf(data, sizeof(data), «%02d/%02d/%02d»,
dayOfMonth, month, year);

Источник

DIY Robotics Lab

Correcting Arduino Compiler Errors

(Intended) Errors and Omissions

What happens after you select the Arduino menu item Sketch -> Verify/Compile and you get error messages that your program failed to compile properly. Sometimes the compiler warnings help you spot the problem code. Other times the error messages don’t make much sense at all. One way to understand the error messages is to create some intentional errors and see what happens.

Create a new program named: LEDBlink_errors

This is one time when it is better to copy the following code so we don’t introduce more errors into the program than are already there.

If you run Verify/Compile command you should see a number of compiler error messages at the bottom of the dialog display.

Arduino Compiler Error Messages

Line 1 Error

Uncaught exception type:class java.lang.RuntimeException

java.lang.RuntimeException: Missing the */ from the end of a /* comment */

/*— Blink an LED —//

The error messages go on for several more lines without adding much information to help solve the problem. You will find a clue to the problem above the compiler message box stating:

Missing the */ from the end of a /* comment */“.

The article “Introduction to Programming the Arduino” describes the comment styles used by C programs. The error on line 1 is caused by mixing the comment styles. The comment begins with the “/*” characters but ends with “//” instead of the “*/” characters. Correct the line as follows:

/*— Blink an LED —*/

Now, rerun the Verify/Compile command.

Line 4 Error

error: stray ‘’ in program

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

This is another problem with incorrect commenting technique. In this line the “\” characters are used to begin a comment instead of the “//” characters. The correct line follows:

int ledPin = 3; //We’re using Digital Pin 3 on the Arduino.

Now, rerun the Verify/Compile command.

Line 6 Error

error: expected unqualified-id before ‘<’ token

void setup();

This is an easy mistake to make. The problem is the semicolon “;” at the end of a function declaration. The article “Learning the C Language with Arduino” contains a section about correct usage of semicolons. To correct this problem remove the semicolon as shown below:

void setup()

Now, rerun the Verify/Compile command.

Line 8 Error

In function ‘void setup()’:

error: expected `)’ before numeric constant/home/myDirectory/Desktop/myPrograms/arduino-0015/hardware/cores/arduino/wiring.h:102:

error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’ At global scope:

pinMode(ledPin OUTPUT); //Set up Arduino pin for output only.

The clue to this problem is found in the message error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’“. The message includes a list of the function’s arguments and data types (uint8_t). The error is complaining that we have too few arguments. The problem with this line of code is the missing comma between ledPin, and OUTPUT. The corrected code is on the following line:

pinMode(ledPin, OUTPUT); //Set up Arduino pin for output only.

Now, rerun the Verify/Compile command.

Line 11 Error

error: expected constructor, destructor, or type conversion before ‘(’ token

loop()

In this line the type specifier for the function is missing.

To fix this problem place the data type for the function’s return type. In this case we’re not returning any value so we need to add the keyword void in front of the loop function name. Make the following change:

void loop()

Now, rerun the Verify/Compile command.

Line 12 Error

error: function ‘void loop()’ is initialized like a variable

The block of code that makes up the loop function should be contained within curly braces “<“ and “>”. In this line a left parenthesis character “(“ is used instead of the beginning curly brace “<“. Replace the left parenthesis with the left curly brace.

Now, rerun the Verify/Compile command.

Line 13 Error

error: expected primary-expression before ‘/’ token At global scope:

/The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

This line is supposed to be a comment describing what the program is doing. The error is caused by having only one slash character “/” instead of two “//”. Add the extra slash character then recompile.

//The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

Line 14 Error

error: ‘high’ was not declared in this scope At global scope:

digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.

This error message is complaining that the variable “high” was not declared. Programming in C is case sensitive, meaning that it makes a difference if you are using upper or lower case letters. To solve this program replace “high” with the constant value “HIGH” then recompile.

digitalWrite(ledPin, HIGH); //Setting a digital pin HIGH turns on the LED.

Line 15 Error

error: expected `;’ before ‘:’ token At global scope:

delay(1000): //Get the microcontroller to wait for one second.

This error message is helpful in identifying the problem. This program statement was ended with a colon character “:” instead of a semicolon “;”. Replace with the proper semicolon and recompile.

delay(1000); //Get the microcontroller to wait for one second.

Line 16 Error

error: expected unqualified-id before numeric constant At global scope:

digitalWrite(ledPin. LOW); //Setting the pin to LOW turns the LED off.

This error can be particularly troublesome because the comma “,” after the variable ledPin is actually a period “.” making it harder to spot the problem.

The C programming language allows you to build user defined types. The dot operator (period “.”) is part of the syntax used to reference the user type’s value. Since the variable ledPin is defined as an integer variable, the error message is complaining about the unqualified-id.

digitalWrite(ledPin, LOW); //Setting the pin to LOW turns the LED off.

Line 17 Error

In function ‘void loop()’:

error: ‘Delay’ was not declared in this scope At global scope:

Delay(1000); //Wait another second with the LED turned off.

This error was caused by the delay function name being spelled with an incorrect upper case character for the letter “d”. Correct the spelling using the lower case “d” and try the Sketch Verify/Compile again.

delay(1000); //Wait another second with the LED turned off.

Line 18 Error

error: expected declaration before ‘>’ token

There is an extra curly brace at the end of this program. Delete the extra brace to correct this error.

Now, rerun the Verify/Compile command.

Success (or so it seems)

The compiler completed without any more error messages so why doesn’t the LED flash after loading the program on my Arduino?

Line 4 Error

No error message was given by the compiler for this problem.

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

The Digital pins are limited to pin numbers 0 through 13. On line 4 the code is assigning a non-existant pin 23 to the ledPin variable. Change the pin assignment to pin 3 and the program should compile, upload to your Arduino and flash the LED if everything is wired properly on your breadboard.

int ledPin = 3; \We’re using Digital Pin 3 on the Arduino.

(c) 2009 – Vince Thompson

Like this:

This entry was posted on June 5, 2009 at 3:54 pm and is filed under Arduino. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Correcting Arduino Compiler Errors”

[…] Robotics Lab Bringing Robotics Home « Microcontrollers as Time Keepers Correcting Arduino Compiler Errors […]

Nice, thank you.
The “stray ‘’ in program” error can also occurs if there’s an accent (like è) in the name of a function.

Источник

Arduino.ru

exit status 1 Error compiling for board Arduino/Genuino Uno.

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

можно задать ворос что произашло при загрузки програми которая работала день назад видает теперь

exit status 1
Error compiling for board Arduino/Genuino Uno.

вот все что мне написал компилятор
D:arduino-nightlylibrariesDS1307/DS1307.h:54:17: error: expected identifier before numeric constant

#define SUNDAY 7

D:arduino-nightlylibrariesDS1307/DS1307.h:54:17: error: expected ‘>’ before numeric constant

D:arduino-nightlylibrariesDS1307/DS1307.h:54:17: error: expected unqualified-id before numeric constant

In file included from C:UsersdimaDesktopfinalsketch_nov05asketch_nov05a.ino:4:0:

c:usersdimaappdatalocalarduino15packagesarduinotoolsavr-gcc4.9.2-atmel3.5.3-arduino2avrincludetime.h:506:1: error: expected declaration before ‘>’ token

Using library DHT-sensor-library-master at version 1.2.3 in folder: D:arduino-nightlylibrariesDHT-sensor-library-master
Використання бібліотеки LedControlMS з теки: D:arduino-nightlylibrariesLedControlMS (legacy)
Використання бібліотеки DS1307 з теки: D:arduino-nightlylibrariesDS1307 (legacy)
Using library Wire at version 1.0 in folder: C:UsersdimaAppDataLocalArduino15packagesarduinohardwareavr1.6.14librariesWire
Using library Adafruit-BMP085-Library-master at version 1.0.0 in folder: D:arduino-nightlylibrariesAdafruit-BMP085-Library-master
exit status 1
Error compiling for board Arduino/Genuino Uno.

Источник

Содержание

  1. Arduino.ru
  2. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  3. forum.arduino.ru
  4. Что значит ошибка expected unqualified-id before numeric constant? Как её исправить?
  5. TROUBLESHOOTING SOLUTIONS: CODE PROBLEMS, COMPILE ERRORS
  6. MISSING SEMICOLONS ;
  7. ошибка arduino: ожидается ‘,’ или ‘…’ перед числовой константой
  8. Решение
  9. Другие решения
  10. Arduino.ru
  11. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  12. forum.arduino.ru
  13. ПОМОГИТЕ. не знаю где ошибки

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

Что значит ошибка expected unqualified-id before numeric constant? Как её исправить?

Код ошибки «Arduino: 1.8.13 (Windows 10), Плата:»Arduino Nano, ATmega328P (Old Bootloader)»

In file included from C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:4:0:

C:Users����DocumentsArduinolibrariesTime-master/Time.h:1:2: warning: #warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h» [-Wcpp]

#warning «Please include TimeLib.h, not Time.h. Future versions will remove Time.h»

sketch_aug15a:9:11: error: expected unqualified-id before numeric constant

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void setup()’:

sketch_aug15a:120:7: error: unable to find numeric literal operator ‘operator»»dig_display.init’

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino: In function ‘void loop()’:

C:UsersПенёкDocumentsArduinosketch_aug15asketch_aug15a.ino:166:27: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

sketch_aug15a:195:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:197:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:199:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:201:10: error: unable to find numeric literal operator ‘operator»»dig_display.display’

sketch_aug15a:203:10: error: unable to find numeric literal operator ‘operator»»dig_display.point’

expected unqualified-id before numeric constant

Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»»
Сам код:
#include
#include
#include
#include
#include «TM1637.h»
#define CLK 6
#define DIO 5

TM1637 4dig_display(CLK, DIO);

// для данных времени

// для данных dd/mm

// для смены время / день-месяц

unsigned long millist=0;

OLED myOLED(4, 3, 4); //OLED myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

///// часы ..
byte decToBcd(byte val) <
return ( (val/10*16) + (val%10) );
>

byte bcdToDec(byte val) <
return ( (val/16*10) + (val%16) );
>

void setDateDs1307(byte second, // 0-59
byte minute, // 0-59
byte hour, // 1-23
byte dayOfWeek, // 1-7
byte dayOfMonth, // 1-28/29/30/31
byte month, // 1-12
byte year) // 0-99
<
Wire.beginTransmission(0x68);
Wire.write(0);
Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(dayOfWeek));
Wire.write(decToBcd(dayOfMonth));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
>

void getDateDs1307(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
<

Wire.beginTransmission(0x68);
Wire.write(0);
Wire.endTransmission();

*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
>

///// температура ..
float get3231Temp() <
byte tMSB, tLSB;
float temp3231;

Wire.beginTransmission(0x68);
Wire.write(0x11);
Wire.endTransmission();
Wire.requestFrom(0x68, 2);

if(Wire.available()) <
tMSB = Wire.read(); //2’s complement int portion
tLSB = Wire.read(); //fraction portion

temp3231 = (tMSB & B01111111); //do 2’s math on Tmsb
temp3231 += ( (tLSB >> 6) * 0.25 ); //only care about bits 7 & 8
>
else <
//oh noes, no data!
>

void setup()
<
Serial.begin(9600); // запустить последовательный порт

Serial.begin(9600);
myOLED.begin();
Wire.begin();

// установка часов
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
second = 30;
minute = 0;
hour = 14;
dayOfWeek = 3; // день недели
dayOfMonth = 1; // день
month = 4;
year = 14;

//setDateDs1307(00, 40, 15, 6, 15, 8, 2020);

char time[10];
char data[11];

snprintf(time, sizeof(time),»%02d:%02d:%02d»,
hour, minute, second);

snprintf(data, sizeof(data), «%02d/%02d/%02d»,
dayOfMonth, month, year);

Источник

TROUBLESHOOTING SOLUTIONS: CODE PROBLEMS, COMPILE ERRORS

Compile errors are errors that happen when you attempt to compile your code and the Arduino software (the compiler) finds an error in it. If you receive an error when you attempt to compile and upload your code, you know you have either a compile error or an upload error.

symptoms
If you’re not sure if you have a compile error or an upload error, scroll to the top of the black area at the bottom of the Arduino window. If you see the name of your program followed by .ino in orange text at the top of the box, you know you have a compile error (below, top). If you see a message in white text at the top of the box that looks something like “Binary sketch size: 4,962 bytes (of a 30,720 byte maximum)” you know that you have an upload error (below, bottom).

finding compile errors in your code
Compile errors often occur because of missing or incorrect punctuation, misspellings, and mis-capitalizations. They will also occur if you attempt to use a variable you have not initialized at the top of your program or if there is extra text anywhere in your program. If you get a compile error, begin by carefully reading the error messages in the feedback area of the Arduino window for clues. Investigate your code around the location that the Arduino software highlights or jumps to. If you cannot see any problems in that area, carefully read through your entire program line by line, looking for the problems described in this section.

the rest of this section
The next few pages explore common code mistakes (the ones listed below) and the compile errors they generate, along with tips on how to find and fix these problems.

Each section begins with examples of problematic pieces of code. The location of the problem is highlighted in yellow. Below each code example is an example of the kind of error you might receive if you made a similar mistake in your code. This is followed by advice on finding and fixing similar errors.

MISSING SEMICOLONS ;

symptoms
Error messages for missing semicolons are relatively straightforward. In each error message, either in the orange or the black feedback area, there is a line that says: error: expected ‘;’ before… This is an indication that you’re missing a semicolon. The Arduino software will usually highlight the line immediately after the missing semicolon to indicate the location of your error.

Источник

ошибка arduino: ожидается ‘,’ или ‘…’ перед числовой константой

Я новичок в Arduino и C ++ и сталкиваюсь с вышеуказанной ошибкой. Это кажется довольно очевидным, однако я не могу найти пропущенную запятую в коде. Код работал нормально, прежде чем я добавил binaryOut функция, поэтому я верю, что это там.

Было бы хорошо, если бы Arduino дал указание о том, где происходит ошибка.

Любая помощь будет принята с благодарностью.

РЕДАКТИРОВАТЬ: в Arduino HIGH и LOW определены константы (http://arduino.cc/en/Reference/Constants ) и логический тип данных является примитивным (http://en.wikipedia.org/wiki/Primitive_data_type )

EDIT2: я смоделировал binaryOut из примера ( shiftOut ) на изображении ниже.

EDIT3: точная ошибка:

Сначала я думал, что «111» и «112» соответствуют номеру строки, но мой код содержит менее 90 строк.

Решение

Библиотеки Arduino используют идентификаторы dataPin и clockPin для своих собственных целей. Определив их с фактическими значениями в вашем коде, вы сделали код Arduino некомпилируемым. Переименуй их.

Другие решения

Этот ответ только для целей записи.

Ниже строки в примере кода также выдает мне ту же ошибку ожидается ‘,’ или ‘…’ перед числовой константой

Но когда я изменил строки выше, что-то вроде этого (ниже) работает нормально.

при определении вы не можете использовать строчные буквы.

Источник

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

ПОМОГИТЕ. не знаю где ошибки

Не , еще больший список ошибок выдает:

а библиотеку pitches.h подключили?

все, сам разобралса(буква эта досих пор не работает), вот, што полуилось, можите посмотреть (послушать) как а создавал гимн Америки:

А на хрена нам гимн америки?

Так он же этот — Трамп, типо.

Добрый день. Помогите разобраться с ошибками компиляции. Скетч переделывал уже из готового, внес пару параметров и не могу скомпилировать, ошибки вылазят там где их не было в исходном коде.

Вот сами ошибки:

Добрый день. Помогите разобраться с ошибками компиляции.

Не просто прочитать, а сделать как написано.

Проблема с компиляцией никуда не ушла, все так же появляются ошибки.

Странно, что Вы до сих пор не разобрались.

Ну, читайте сообщения. В строке 3 говорится, что в строке 242 программы используется необъявленная функция ‘stringToNumber’ . У Вас есть возражения? Надеюсь, нет.

Эта функция у Вас объявлена в строках 279-287, т.е. после использования, а по правилам языка всё должно объявляться до использования. Ну так возьмите строки 279-287 и перенесите выше функции ParseSMS , Например вставьте после строки 223.

Остальные ошибки связаны с путаницей с фигурными скобками, но они исчезнут сами собой после переноса, о котором я уже сказал.

Источник

(Intended) Errors and Omissions

What happens after you select the Arduino menu item Sketch -> Verify/Compile and you get error messages that your program failed to compile properly. Sometimes the compiler warnings help you spot the problem code. Other times the error messages don’t make much sense at all. One way to understand the error messages is to create some intentional errors and see what happens.

Create a new program named: LEDBlink_errors

This is one time when it is better to copy the following code so we don’t introduce more errors into the program than are already there.

/*--- Blink an LED  ---//
//Associate LEDs with an Arduino Digital pin.
//The Arduino already has a built-in LED that we can use on Digital Pin 13.
int ledPin = 23;  \We're using Digital Pin 23 on the Arduino.

void setup();
{
   pinMode(ledPin OUTPUT);   //Set up Arduino pin for output only.
}

loop()
(
   /The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.
   digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.
   delay(1000):  //Get the microcontroller to wait for one second.
   digitalWrite(ledPin. LOW);  //Setting the pin to LOW turns the LED off.
   Delay(1000);  //Wait another second with the LED turned off.
   }
}

If you run Verify/Compile command you should see a number of compiler error messages at the bottom of the dialog display.

Arduino Compiler Error Messages

Arduino Compiler Error Messages

Line 1 Error

Uncaught exception type:class java.lang.RuntimeException

java.lang.RuntimeException: Missing the */ from the end of a /* comment */

at processing.app.Sketch.scrubComments(Sketch.java:2008) …

/*— Blink an LED  —//

The error messages go on for several more lines without adding much information to help solve the problem. You will find a clue to the problem above the compiler message box stating:

Missing the */ from the end of a /* comment */“.

The article “Introduction to Programming the Arduino” describes the comment styles used by C programs. The error on line 1 is caused by mixing the comment styles. The comment begins with the “/*” characters but ends with “//” instead of the “*/” characters. Correct the line as follows:

/*— Blink an LED  —*/

Now, rerun the Verify/Compile command.

Line 4 Error

error: stray ‘’ in program

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

This is another problem with incorrect commenting technique. In this line the “\” characters are used to begin a comment instead of the “//” characters. The correct line follows:

int ledPin = 3;  //We’re using Digital Pin 3 on the Arduino.

Now, rerun the Verify/Compile command.

Line 6 Error

error: expected unqualified-id before ‘{’ token

void setup();

This is an easy mistake to make. The problem is the semicolon “;” at the end of a function declaration. The article “Learning the C Language with Arduino” contains a section about correct usage of semicolons. To correct this problem remove the semicolon as shown below:

void setup()

Now, rerun the Verify/Compile command.

Line 8 Error

In function ‘void setup()’:

error: expected `)’ before numeric constant/home/myDirectory/Desktop/myPrograms/arduino-0015/hardware/cores/arduino/wiring.h:102:

error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’ At global scope:

pinMode(ledPin OUTPUT); //Set up Arduino pin for output only.

The clue to this problem is found in the message error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’“. The message includes a list of the function’s arguments and data types (uint8_t). The error is complaining that we have too few arguments. The problem with this line of code is the missing comma between ledPin, and OUTPUT. The corrected code is on the following line:

pinMode(ledPin, OUTPUT); //Set up Arduino pin for output only.

Now, rerun the Verify/Compile command.

Line 11 Error

error: expected constructor, destructor, or type conversion before ‘(’ token

loop()

In this line the type specifier for the function is missing.

To fix this problem place the data type for the function’s return type. In this case we’re not returning any value so we need to add the keyword void in front of the loop function name. Make the following change:

void loop()

Now, rerun the Verify/Compile command.

Line 12 Error

error: function ‘void loop()’ is initialized like a variable

(

The block of code that makes up the loop function should be contained within curly braces “{“ and “}”. In this line a left parenthesis character “(“ is used instead of the beginning curly brace “{“. Replace the left parenthesis with the left curly brace.

Now, rerun the Verify/Compile command.

Line 13 Error

error: expected primary-expression before ‘/’ token At global scope:

/The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

This line is supposed to be a comment describing what the program is doing. The error is caused by having only one slash character “/” instead of two “//”. Add the extra slash character then recompile.

//The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

Line 14 Error

error: ‘high’ was not declared in this scope At global scope:

digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.

This error message is complaining that the variable “high” was not declared. Programming in C is case sensitive, meaning that it makes a difference if you are using upper or lower case letters. To solve this program replace “high” with the constant value “HIGH” then recompile.

digitalWrite(ledPin, HIGH); //Setting a digital pin HIGH turns on the LED.

Line 15 Error

error: expected `;’ before ‘:’ token At global scope:

delay(1000): //Get the microcontroller to wait for one second.

This error message is helpful in identifying the problem. This program statement was ended with a colon character “:” instead of a semicolon “;”. Replace with the proper semicolon and recompile.

delay(1000); //Get the microcontroller to wait for one second.

Line 16 Error

error: expected unqualified-id before numeric constant At global scope:

digitalWrite(ledPin. LOW); //Setting the pin to LOW turns the LED off.

This error can be particularly troublesome because the comma “,” after the variable ledPin is actually a period “.” making it harder to spot the problem.

The C programming language allows you to build user defined types. The dot operator (period “.”) is part of the syntax used to reference the user type’s value. Since the variable ledPin is defined as an integer variable, the error message is complaining about the unqualified-id.

digitalWrite(ledPin, LOW); //Setting the pin to LOW turns the LED off.

Line 17 Error

In function ‘void loop()’:

error: ‘Delay’ was not declared in this scope At global scope:

Delay(1000); //Wait another second with the LED turned off.

This error was caused by the delay function name being spelled with an incorrect upper case character for the letter “d”. Correct the spelling using the lower case “d” and try the Sketch Verify/Compile again.

delay(1000); //Wait another second with the LED turned off.

Line 18 Error

error: expected declaration before ‘}’ token

}

}

There is an extra curly brace at the end of this program. Delete the extra brace to correct this error.

Now, rerun the Verify/Compile command.

Success (or so it seems)

The compiler completed without any more error messages so why doesn’t the LED flash after loading the program on my Arduino?

Line 4 Error

No error message was given by the compiler for this problem.

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

The Digital pins are limited to pin numbers 0 through 13. On line 4 the code is assigning a non-existant pin 23 to the ledPin variable. Change the pin assignment to pin 3 and the program should compile, upload to your Arduino and flash the LED if everything is wired properly on your breadboard.

int ledPin = 3; \We’re using Digital Pin 3 on the Arduino.

(c) 2009 – Vince Thompson

Tags: Arduino, C Language, error correction, error message, how-to program, programming


This entry was posted on June 5, 2009 at 3:54 pm and is filed under Arduino. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Понравилась статья? Поделить с друзьями:
  • Expected string or bytes like object python ошибка
  • Expected package found eof как исправить go
  • Expected linebreaks to be lf but found crlf как исправить
  • Expected function or variable vba ошибка
  • Expected error junit