Error expected initializer before numeric constant

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 […]

Содержание

  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.

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

Источник

The full error is

error: expected unqualified-id before numeric constant
 note: in expansion of macro ‘homeid’
string homeid;
       ^

You’re trying to declare a variable with the same name as a macro, but that can’t be done. The preprocessor has already stomped over the program, turning that into string 1234;, which is not a valid declaration. The preprocessor has no knowledge of the program structure, and macros don’t follow the language’s scope rules.

Where possible, use language features like constants and inline functions rather than macros. In this case, you might use

const int homeid = 1234;

This will be scoped in the global namespace, and can safely be hidden by something with the same name in a narrower scope. Even when hidden, it’s always available as ::homeid.

When you really need a macro, it’s wise to follow the convention of using SHOUTY_CAPS for macros. As well as drawing attention to the potential dangers and wierdnesses associated with macro use, it won’t clash with any name using other capitalisation.

Kerpi а в Arduino IDE ты что делаешь? По пунктам поясни пож.

1. Написал код

int PINa = 23;

int PINb = 24;

int PINc = 25;

int PINd = 26;

void setup(){

pinMode(PINa,OUTPUT);

pinMode(PINb,OUTPUT);

pinMode(PINc,INPUT);

pinMode(PINd,INPUT);

}

void loop()

{

delay(5);

if(digitalRead(PINd == HIGH)

) digitalWrite(PINb,HIGH);

delay(5);

digitalWrite(PINb,LOW);

delay(5);

digitalWrite(PINa,HIGH);

delay(5);

digitalWrite(PINa,LOW);

if(digitalRead(PINc == HIGH)

) digitalWrite(PINa,HIGH);

delay(5);

digitalWrite(PINa,LOW);

delay(5);

digitalWrite(PINb,HIGH);

delay(5);

digitalWrite(PINb,LOW);

};

2. Выбрал: плата — Atmega8 (устанавливал библиотеку сверху), программатор — usbasp.

3. Скетч > загрузить через программатор

Ну и ошибки показывает:

«Плата arduino:avr:atmega8 не устанавливает свойство ‘build.board’. Автоматически выбрано: AVR_ATMEGA8

Плата arduino:avr:?atmega8 не устанавливает свойство ‘build.board’. Автоматически выбрано: AVR_?ATMEGA8

Скетч использует 1 126 байт (14%) памяти устройства. Всего доступно 7 680 байт.

Глобальные переменные используют 17 байт динамической памяти.

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: warning: cannot set sck period. please check for usbasp firmware update.»

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.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.

Источник

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.

Источник

So I need to declare Form2 as a type?
And or find where it is declared as a numeric constant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include "_27_7Main.h"
#include <wx/msgdlg.h>
#include "Form2.h"

//(*InternalHeaders(_27_7Frame)
#include <wx/font.h>
#include <wx/intl.h>
#include <wx/string.h>

//*)

//helper functions
enum wxbuildinfoformat {
    short_f, long_f };

wxString wxbuildinfo(wxbuildinfoformat format)
{
    wxString wxbuild(wxVERSION_STRING);

    if (format == long_f )
    {
#if defined(__WXMSW__)
        wxbuild << _T("-Windows");
#elif defined(__UNIX__)
        wxbuild << _T("-Linux");
#endif

#if wxUSE_UNICODE
        wxbuild << _T("-Unicode build");
#else
        wxbuild << _T("-ANSI build");
#endif // wxUSE_UNICODE
    }

    return wxbuild;
}

//(*IdInit(_27_7Frame)
const long _27_7Frame::ID_BUTTON1 = wxNewId();
const long _27_7Frame::ID_CHECKBOX1 = wxNewId();
const long _27_7Frame::ID_STATICTEXT1 = wxNewId();
const long _27_7Frame::ID_BUTTON2 = wxNewId();
const long _27_7Frame::idMenuQuit = wxNewId();
const long _27_7Frame::idMenuAbout = wxNewId();
const long _27_7Frame::ID_STATUSBAR1 = wxNewId();
//*)

BEGIN_EVENT_TABLE(_27_7Frame,wxFrame)
    //(*EventTable(_27_7Frame)
    //*)
END_EVENT_TABLE()

_27_7Frame::_27_7Frame(wxWindow* parent,wxWindowID id)
{
    //(*Initialize(_27_7Frame)
    wxMenuItem* MenuItem2;
    wxMenuItem* MenuItem1;
    wxMenu* Menu1;
    wxMenuBar* MenuBar1;
    wxMenu* Menu2;

    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("id"));
    SetClientSize(wxSize(400,215));
    SetBackgroundColour(wxColour(255,128,0));
    Button1 = new wxButton(this, ID_BUTTON1, _("Close"), wxPoint(312,176), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1"));
    CheckBox1 = new wxCheckBox(this, ID_CHECKBOX1, _("Label"), wxPoint(136,104), wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
    CheckBox1->SetValue(false);
    StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Last Test 27-Jul-2016"), wxPoint(88,48), wxDefaultSize, 0, _T("ID_STATICTEXT1"));
    wxFont StaticText1Font(18,wxFONTFAMILY_SWISS,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Comic Sans MS"),wxFONTENCODING_DEFAULT);
    StaticText1->SetFont(StaticText1Font);
    Button2 = new wxButton(this, ID_BUTTON2, _("Form 2 Open"), wxPoint(88,160), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2"));
    MenuBar1 = new wxMenuBar();
    Menu1 = new wxMenu();
    MenuItem1 = new wxMenuItem(Menu1, idMenuQuit, _("QuittAlt-F4"), _("Quit the application"), wxITEM_NORMAL);
    Menu1->Append(MenuItem1);
    MenuBar1->Append(Menu1, _("&File"));
    Menu2 = new wxMenu();
    MenuItem2 = new wxMenuItem(Menu2, idMenuAbout, _("AbouttF1"), _("Show info about this application"), wxITEM_NORMAL);
    Menu2->Append(MenuItem2);
    MenuBar1->Append(Menu2, _("Help"));
    SetMenuBar(MenuBar1);
    StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[1] = { -1 };
    int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
    StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);

    Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&_27_7Frame::OnButton1Click);
    Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&_27_7Frame::OnButton2Click);
    Connect(idMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&_27_7Frame::OnQuit);
    Connect(idMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&_27_7Frame::OnAbout);
    //*)
}

_27_7Frame::~_27_7Frame()
{
    //(*Destroy(_27_7Frame)
    //*)
}

void _27_7Frame::OnQuit(wxCommandEvent& event)
{
    //Close();
}

void _27_7Frame::OnAbout(wxCommandEvent& event)
{
    wxString msg = wxbuildinfo(long_f);
    wxMessageBox(msg, _("Welcome to..."));
}

void _27_7Frame::OnButton1Click(wxCommandEvent& event)
{
    Close();
}

void _27_7Frame::OnButton2Click(wxCommandEvent& event)
{
    Form2* frm1 = new Form2(0);  // error: expected unqualified-id before numeric constant
                                 // error: expected initializer before numeric constant
    frm1->Show();   //error: base operand of '->' is not a pointer 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#ifndef FORM2_H
#define FORM2_H

//(*Headers(Form2)
#include <wx/stattext.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/frame.h>
//*)

class Form2: public wxFrame
{
	public:

		Form2(wxWindow* parent,wxWindowID id=wxID_ANY);
		virtual ~Form2();

		//(*Declarations(Form2)
		wxButton* Button1;
		wxPanel* Panel1;
		wxStaticText* StaticText1;
		//*)

	protected:

		//(*Identifiers(Form2)
		static const long ID_STATICTEXT1;
		static const long ID_BUTTON1;
		static const long ID_PANEL1;
		//*)

	private:

		//(*Handlers(Form2)
		void OnClose(wxCloseEvent& event);
		void OnButton1Click(wxCommandEvent& event);
		void OnButton1Click1(wxCommandEvent& event);
		//*)

		DECLARE_EVENT_TABLE()
};

#endif 

arduino_compilation_errors

Table of Contents

If you want to send us your comments, please do so. Thanks

More on comments


Arduino compilaton errors

Also Warnings and Notices

Could not create the sketch

It is possible that the file / folder name contains invalid characters like a space, File and folder names may only contain letters and numbers and not start with a number

expected constructor

When you get something like

filename.test:10: error: expected constructor, destructor, or type conversion before '(' token
expected constructor, destructor, or type conversion before '(' token

Check the part before setup(). Probably there are items which should in setup()

expected initializer

programname:7107:27: error: expected initializer before numeric constant
  const byte variablename value

This can happen when you convert from #define to const . The code should be

const byte variablename = value;

( “=” and “;” added )

expected unqualified-id

expected unqualified-id before 'if'

Maybe you typed a bracket wrong like “{” in stead of “}”

expected ‘)’ before

filename:520: error: expected ')' before ';' token

This can be caused by using a ; in

Serial.println(variable A;variable B;variable C;variable D);

The compiler thinks the first ; is the end of the command. The solution is to split the command:

Serial.print(variable A);
Serial.print(";");
Serial.print(variable B);
Serial.print(";");
Serial.print(variable C);
Serial.print(";");
Serial.print(variable D);
Serial.println(";");

The ; is handy when the output has to be imported in a spreadsheet program

expected ‘)’ before ‘;’ token

/somesketch.ino: In function 'void setup()':
somesketch:7432:38: error: expected ')' before ';' token
   Serial.println(F("sometext");
exit status 1
expected ')' before ';' token

Reason: println(F(something); is not allowed. Only println(something); is. This is not valid for the print(F(something); (without ln) statement

function-definition not allowed

a function-definition is not allowed here before '{' token

Check for missing “}” or “;”’s

was not declared in this scope

Error:

/home/user/sketchbook/someprojectNameTheDirectory
/someprojectName.ino: In function 'void setup()':
someprojectName:7401:5: error: 'functionName or variableName' was not declared in this scope
     ^~~~~~~~~~~~~~~~~~~

exit status 1
'functionName or variableName' was not declared in this scope

Solution: check in the code

  • if “functionName or variableName” is declared

  • for missing or obsolete (curly)brackets

Warnings

ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:

Use const char (#define also works but is not advised) instead of const byte for the constant might solve the issue and all the warnings and notices that follow it. Like

note: candidate 1: uint8_t TwoWire::requestFrom(int, int) uint8_t requestFrom(int, int);

The cause seems to be a flaw in the definition of the library


arduino_compilation_errors.txt

· Last modified: 28-05-2020 18:21 by

wim


Centavrianin

0 / 0 / 0

Регистрация: 11.07.2016

Сообщений: 2

1

11.07.2016, 21:02. Показов 15852. Ответов 4

Метки нет (Все метки)


Здравствуйте! Просьба помочь разобраться с ошибкой.

Изучаю Си по книге Б. Кернигана и Д. Ритчи «Язык программирования Си». Переписал очередной пример из книги, но при попытке скомпилировать код выходит сообщение об ошибке:

Bash
1
2
3
4
5
6
user@user-mint ~/progs $ gcc maxline.c
maxline.c:2:17: error: expected ‘;’, ‘,’ or ‘)’ before numeric constant
 #define MAXLINE 1000 /*максимальный размер вводимой строки*/
                 ^
maxline.c:4:34: note: in expansion of macro ‘MAXLINE’
 int getline_max(char line[], int MAXLINE);

Сам код:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#define MAXLINE 1000 /*максимальный размер вводимой строки*/
 
int getline_max(char line[], int MAXLINE);
void copy_max(char to[], char from[]);
 
main()
{
    int len; /* длина текущей строки */
    int max; /* длина максимальной из просмотренных строк */
    char line[MAXLINE]; /* массив текущей строки */
    char longest[MAXLINE]; /* массив самой длинной строки */
    max = 0;
    while ((len = getline_max(line, MAXLINE)) > 0)
        if (len > max){
            max = len;
            copy_max(longest, line);
        }
    if (max > 0) /* была ли хоть одна строка? */
        printf("%s", longest);
    return 0;
}
 
 
/* getline: читает строку в s, возвращает длину */
int getline_max(char s[], int lim)
{
    int c, i;
    for (i = 0; i < lim-1 && ((c = getchar()) != 'n') && c != EOF; ++i)
        s[i] = c;
    if (c == 'n') {
        s[i] = c;
        ++i;
    }
    s[i] = '';
    return i;
}
 
/* copy: копирует из 'from' в 'to'; to достаточно большой */
void copy_max(char to[], char from[])
{
    int i;
    i = 0;
    while ((to[i] = from[i]) != '')
        ++i;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

11.07.2016, 21:02

4

ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

Регистрация: 14.02.2011

Сообщений: 22,972

11.07.2016, 21:09

2

Лучший ответ Сообщение было отмечено Centavrianin как решение

Решение

Цитата
Сообщение от Centavrianin
Посмотреть сообщение

int getline_max(char line[], int MAXLINE);

нельзя так
это объявление функции, а не вызов
после обработки препроцессором макросы развернутся и получишь вот что

C
1
 int getline_max(char line[], int 1000);

напиши как в определении

C
1
int getline_max(char s[], int lim);

или без наименования параметра

C
1
int getline_max(char s[], int );

Добавлено через 16 секунд

Цитата
Сообщение от Centavrianin
Посмотреть сообщение

int getline_max(char line[], int MAXLINE);

нельзя так
это объявление функции, а не вызов
после обработки препроцессором макросы развернутся и получишь вот что

C
1
 int getline_max(char line[], int 1000);

напиши как в определении

C
1
int getline_max(char s[], int lim);

или без наименования параметра

C
1
int getline_max(char s[], int );



3



Даценд

Эксперт .NET

5858 / 4735 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

11.07.2016, 21:15

3

Centavrianin,
А зачем идентификатор параметра функции совпадает с константой MAXLINE. Объявите

C
1
int getline_max(char s[], int lim);

или

C
1
int getline_max(char[], int);



2



0 / 0 / 0

Регистрация: 11.07.2016

Сообщений: 2

11.07.2016, 22:30

 [ТС]

4

Понял. Спасибо за разъяснение!
Про функции надо будет перечитать еще раз.



0



42 / 10 / 9

Регистрация: 13.03.2015

Сообщений: 74

13.07.2016, 21:35

5

Centavrianin, У меня тоже на этом моменте были проблемы. Помниться я пол дня над ним корпел =)



0



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.

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before cout
  • Error expected initializer before class
  • Error expected initializer before cin
  • Error expected initializer before char
  • Error expected indentation of 6 spaces but found 4 indent