text:
How to properly understand verbose compiler error text? For beginner level
I'm an Arduino newbie, no background in C/C++, needing help to understand Arduino IDE verbose output about compiler errors. My searching failed to find suitable info - have I missed a relevant guide?
Below example of compiler errors produced when I try to compile Example sketch (TestRTC) from a downloaded library. I assume this Example code is valid. Guessing that my errors relate to missing components. The library was one of two recommended in answer to question. I used IDE Manage Libraries to install from downloaded zip files. Windows file manager shows both library folders are present.
In example below: Which components did the compiler find/not find? Where did compiler search for needed components? What other useful info could be gleaned from this error output?
Would be very grateful for general advice on interpreting error text as well as this particular example. Many thanks.
Arduino: 1.6.11 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\Wire.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master\DS3232RTC.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp.o"
In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

     static void read(tmElements_t &tm);

                      ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:83:23: error: 'tmElements_t' has not been declared

     static void write(tmElements_t &tm);

                       ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:84:27: error: 'tmElements_t' has not been declared

     static void writeTime(tmElements_t &tm);

                           ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:85:27: error: 'tmElements_t' has not been declared

     static void writeDate(tmElements_t &tm);

                           ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:61: error: 'tmElements_t' has not been declared

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                                                             ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:88:61: error: 'tmElements_t' has not been declared

     static void writeAlarm(uint8_t alarm, alarmMode_t mode, tmElements_t tm);

                                                             ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:110:24: error: 'tmElements_t' has not been declared

     static void _wTime(tmElements_t &tm);

                        ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:111:24: error: 'tmElements_t' has not been declared

     static void _wDate(tmElements_t &tm);

                        ^

TestRTC:79: error: 'tmElements_t' does not name a type

 inline uint8_t monthLength(const tmElements_t *date)

                           ^

TestRTC:297: error: 'tmElements_t' does not name a type

 void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                              ^

TestRTC:79: error: 'tmElements_t' does not name a type

 inline uint8_t monthLength(const tmElements_t *date)

                                  ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'uint8_t monthLength(const int*)':

TestRTC:81: error: request for member 'Month' in '* date', which is of non-class type 'const int'

     if (date->Month != 2 || !isLeapYear(date->Year))

               ^

TestRTC:81: error: request for member 'Year' in '* date', which is of non-class type 'const int'

     if (date->Month != 2 || !isLeapYear(date->Year))

                                               ^

TestRTC:82: error: request for member 'Month' in '* date', which is of non-class type 'const int'

         return monthLengths[date->Month - 1];

                                   ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdTime(const char*)':

TestRTC:213: error: 'tmElements_t' was not declared in this scope

     tmElements_t tm;

     ^

TestRTC:218: error: expected unqualified-id before '.' token

         tm.Hour = readField(args, posn, 23);

           ^

TestRTC:219: error: expected unqualified-id before '.' token

         tm.Minute = readField(args, posn, 59);

           ^

TestRTC:221: error: expected unqualified-id before '.' token

             tm.Second = readField(args, posn, 59);

               ^

TestRTC:223: error: expected unqualified-id before '.' token

             tm.Second = 0;

               ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

               ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                ^

TestRTC:224: error: expected primary-expression before '.' token

         if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                                   ^

TestRTC:228: error: expected primary-expression before ')' token

         RTC.writeTime(tm);

                         ^

TestRTC:233: error: expected primary-expression before ')' token

     RTC.read(tm);

                ^

TestRTC:234: error: expected primary-expression before '.' token

     printDec2(tm.Hour);

                 ^

TestRTC:236: error: expected primary-expression before '.' token

     printDec2(tm.Minute);

                 ^

TestRTC:238: error: expected primary-expression before '.' token

     printDec2(tm.Second);

                 ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdDate(const char*)':

TestRTC:245: error: 'tmElements_t' was not declared in this scope

     tmElements_t tm;

     ^

TestRTC:256: error: expected unqualified-id before '.' token

         tm.Day = (byte)(value % 100);

           ^

TestRTC:257: error: expected unqualified-id before '.' token

         tm.Month = (byte)((value / 100) % 100);

           ^

TestRTC:258: error: expected unqualified-id before '.' token

         tm.Year = CalendarYrToTm( (unsigned int)(value / 10000) );

           ^

TestRTC:259: error: expected primary-expression before '.' token

         if (tm.Month < 1 || tm.Month > 12) {

               ^

TestRTC:259: error: expected primary-expression before '.' token

         if (tm.Month < 1 || tm.Month > 12) {

                               ^

TestRTC:263: error: expected primary-expression before ')' token

         uint8_t len = monthLength(&tm);

                                      ^

TestRTC:264: error: expected primary-expression before '.' token

         if (tm.Day < 1 || tm.Day > len) {

               ^

TestRTC:264: error: expected primary-expression before '.' token

         if (tm.Day < 1 || tm.Day > len) {

                             ^

TestRTC:269: error: expected primary-expression before ')' token

         RTC.writeDate(tm);

                         ^

TestRTC:274: error: expected primary-expression before ')' token

     RTC.read(tm);

                ^

TestRTC:275: error: expected primary-expression before '.' token

     if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

           ^

TestRTC:275: error: expected primary-expression before '.' token

     if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

                                          ^

TestRTC:276: error: expected primary-expression before '.' token

     Serial.print(tm.Day, DEC);

                    ^

TestRTC:277: error: expected primary-expression before '.' token

     Serial.print(months[tm.Month - 1]);

                           ^

TestRTC:278: error: expected primary-expression before '.' token

     Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                       ^

TestRTC:278: error: 'tmYearToCalendar' was not declared in this scope

     Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                            ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: At global scope:

TestRTC:297: error: 'tmElements_t' does not name a type

 void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                              ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void printAlarm(byte, alarmMode_t, int)':

TestRTC:324: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

TestRTC:328: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

             printDec2(time.Minute);

                            ^

TestRTC:330: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

TestRTC:336: error: request for member 'Day' in 'time', which is of non-class type 'const int'

               Serial.print(time.Day);

                                 ^

TestRTC:340: error: request for member 'Wday' in 'time', which is of non-class type 'const int'

               Serial.print(days[time.Wday - 1]);

                                      ^

TestRTC:343: error: request for member 'Hour' in 'time', which is of non-class type 'const int'

             printDec2(time.Hour);

                            ^

TestRTC:345: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

             printDec2(time.Minute);

                            ^

TestRTC:347: error: request for member 'Second' in 'time', which is of non-class type 'const int'

             printDec2(time.Second);

                            ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarms(const char*)':

TestRTC:359: error: 'tmElements_t' was not declared in this scope

     tmElements_t time;

     ^

TestRTC:362: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

         RTC.readAlarm(alarmNum, mode, time);

                                           ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:362:43: note: candidate is:

In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                 ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarm(const char*)':

TestRTC:373: error: 'tmElements_t' was not declared in this scope

     tmElements_t time;

     ^

TestRTC:391: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             time.Hour = readField(args, posn, 23);

                  ^

TestRTC:392: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             time.Minute = readField(args, posn, 59);

                  ^

TestRTC:393: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             if (time.Hour == 99 || time.Minute == 99) {

                      ^

TestRTC:393: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

             if (time.Hour == 99 || time.Minute == 99) {

                                         ^

TestRTC:417: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

     RTC.readAlarm(alarmNum, mode, time);

                                       ^

C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:417:39: note: candidate is:

In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

     static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                 ^

C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

Multiple libraries were found for "DS3232RTC.h"
 Used: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master
 Not used: C:\Program Files (x86)\Arduino\libraries\RTC
Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Using library DS3232RTC-master in folder: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master (legacy)
exit status 1
'tmElements_t' does not name a type

The problem is that one error leads to 100’s of error messages. But usually you can trace it back to one single problem. After fixing one thing, you should re-compile, and check what errors persist (or are new ;p). You shouldn't always take the errors too literally, just re check the parts around the error and then the parts related to that.

As @st2000 said, it's best to start with the first error shown as that error may be causing other errors that will go away once you fix the first one. You should be aware of the difference between warnings and errors. Warnings may or may not be related to the error preventing your code from compiling so I'd just focus on the error at first. So scroll the console window all the way up and then start reading down until you find the first error. If the output is very long you may find it useful to copy the output and paste into a text editor then do a search for the word error, starting from the beginning of the file.
In your compiler output the first error listed is:
C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

     static void read(tmElements_t &tm);

                      ^

The first thing we can learn from this is the file where the error occurred:
C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h

The next part of the error message is:
:82:22

This means that the error occurred at line 82, column 22 of the file DS3232RTC.h. This makes it easy for you to find that code in the file. Any decent text editor will show the current line number and column at the cursor.
The next part of the error message is a description of the problem:
error: 'tmElements_t' has not been declared

Often you may not understand exactly what it means. This is where your favorite search engine comes in handy. You can try searching for "'tmElements_t' has not been declared". The 'tmElements_t' part is very specific to this code so you will get less results but they may lead you to others who have had the same problem and the solutions they found.
Searching for the general error "has not been declared" will give you a broader description of what the compiler is trying to tell you.
Finally is the actual code line:
 static void read(tmElements_t &tm);

                  ^

The carat shows the column number of the error.
Unfortunately the actual bug may often be in previous code so this isn't as simple as it may seem.
Now lets talk about your specific issue. A search for "'tmElements_t' has not been declared" does yield some results from others having similar problems but you will probably find after going through their solutions that none of them fix the error. This is because the error is caused by a recent update to a new version of avr-libc in Arduino IDE 1.6.10/Arduino AVR Boards 1.6.12 and later. This version of avr-libc contains a file named time.h. On a case insensitive operating system such as Windows this will cause
#include <Time.h>

to include the wrong file, time.h which causes the error since indeed that file doesn't declare tmElements_t. This problem is known to the author of the Time library and he has moved the code to a file named TimeLib.h as a workaround. The file Time.h was left for backwards compatibility. So the solution is to change:
#include <Time.h>

to:
#include <TimeLib.h>

I was able to get the TestRTC sketch to compile by just making this change in TestRTC.ino but you may also need to change line 25 of DS3232RTC.h.
I have submitted a pull request to fix this issue to the DS3232RTC repository: https://github.com/Tecsmith/DS3232RTC/pull/9
EDIT: My pull request has now been merged so the issue can also be solved by installing the updated Tecsmith/DS3232RTC library.
If this solves your problem please also update your other question so that the people trying to help you there will know it's fixed.

Thank you, I added a link at the other question. I will try what you suggested. Will comment again to confirm. Appreciate very helpful answer. Regret I cannot upvote it (insufficient reputation), hope other people will upvote it please.

Confirming that TestRTC compiled without error after I changed Time.h to TimeLib.h for two includes as recommended above. This answer helped me to understand what was wrong (actually a difficult issue with same-name components).

Consider the Arduino paradigm as a collection of well established (very) sophisticated computing tools. Arguably, the C compiler is the most complex of these tools.  So understanding the compilers output can be challenging at times.
That said, the normal way to approach compiler problems is to solve the 1st error the compiler finds then recompile.  More often then not solving the 1st error will resolve many other errors.
A guess, in this particular case, is that an include file has been omitted.  Find where the type "tmElements_t" is defined and check to see if the include file (a.k.a. header file) where it is defined needs to be included into the source code file where the 1st errors shows up.
Added later...
Ug, the 1st error is not even your code!  It is in the DS323RTC library you downloaded.  We can probably assume this library is working and compiles.  So that leaves the burden on us to find the reason why your code does not compile.  Besides, you can't go back to GitHub saying there is a bug in the library with out trying to solve the problem first.
The 1st stop is to read any readme.txt file at GitHub or the copy of it you downloaded with the library.  We find in the 1st few dozen lines this:
To use the DS3232RTC library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below:

#include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
#include <Time.h>         //http://www.arduino.cc/playground/Code/Time
#include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

So right away we see we need to include Time.h.  If you look in the Time library (another library you need to download if you have not already) you will find that it is where tmElements_t is defined.  It does bother me that Time.h is included after DS323RTC.h.  If you are still having problems try including Time.h first.

Understand this forum deals with sketch programming. To use a sketch we must compile and we must understand compiler errors in order to fix them. Can you recommend a forum more suited for asking about Arduino compiler errors please?

You are right. Stackexchange is the place to ask software questions. But as soon as they see you are asking about sketches they will likely move you back here. I'll change my answer later when I get more time. More importantly, did you figure out the problem? Was the answer correct?

@per1234 figured out the problem. Please see accepted answer that explains the issue and provides information to fix the compile errors.

Meant to say Stackoverflow.com for software questions, which is connected to the *.stackexchange.com family of forum.  Sorry about the confusion.  Then my comment above starts to make sense.


text:
Arduino Java SerialEvent not being called (Rasberry PI) XPOST from stack overflow
I am following a simple example found here (example one), to have an Arduino connected to a Raspberry Pi and read some data from the Arduino on the Pi in Java.
The issue is that the SerialEvent method is never called, which implies that no data is coming in. However, when I open the Serial Monitor I can see that data is being read correctly.
The correct serial port is being used as well.
Here is the Java code.
//This class:
// - Starts up the communication with the Arduino.
// - Reads the data coming in from the Arduino and
//   converts that data in to a useful form.
// - Closes communication with the Arduino.

//Code builds upon this great example:
//http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java
//The addition being the conversion from incoming characters to numbers.

//Load Libraries
import java.io.*;
import java.util.TooManyListenersException;

//Load RXTX Library
import gnu.io.*;

class ArduinoComm implements SerialPortEventListener
{

   //Used to in the process of converting the read in characters-
   //-first in to a string and then into a number.
   String rawStr="";

   //Declare serial port variable
   SerialPort mySerialPort;

   //Declare input steam
   InputStream in;

   boolean stop=false;

   public void start(String portName,int baudRate)
   {

      stop=false;
      try
      {
         //Finds and opens the port
         CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
         mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000);
         System.out.println("Serial port found and opened");

         //configure the port
         try
         {
            mySerialPort.setSerialPortParams(baudRate,
            mySerialPort.DATABITS_8,
            mySerialPort.STOPBITS_1,
            mySerialPort.PARITY_NONE);
            System.out.println("Serial port params set: "+baudRate);
         }
         catch (UnsupportedCommOperationException e)
         {
            System.out.println("Probably an unsupported Speed");
         }

         //establish stream for reading from the port
         try
         {
            in = mySerialPort.getInputStream();
         }
         catch (IOException e)
         {
            System.out.println("couldn't get streams");
         }

         // we could read from "in" in a separate thread, but the API gives us events
         try
         {
            mySerialPort.addEventListener(this);
            mySerialPort.notifyOnDataAvailable(true);
            System.out.println("Event listener added");
         }
         catch (TooManyListenersException e)
         {
            System.out.println("couldn't add listener");
         }
      }
      catch (Exception e)
      {
         System.out.println("Port in Use: "+e);
      }
   }

   //Used to close the serial port
   public void closeSerialPort()
   {
      try
      {
         in.close();
         stop=true;
         mySerialPort.close();
         System.out.println("Serial port closed");

      }
      catch (Exception e)
      {
      System.out.println(e);
      }
   }

   //Reads the incoming data packets from Arduino.
   public void serialEvent(SerialPortEvent event)
   {

      //Reads in data while data is available
      while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE && stop==false)
      {
         try
         {
            //-------------------------------------------------------------------

            //Read in the available character
            char ch = (char)in.read();

            //If the read character is a letter this means that we have found an identifier.
            if (Character.isLetter(ch)==true && rawStr!="")
            {
               //Convert the string containing all the characters since the last identifier into an integer
               int value = Integer.parseInt(rawStr);

               if (ch=='A')
               {
                  System.out.println("Value A is: "+value);
               }

               if (ch=='B')
               {
                  System.out.println("Value B is: "+value);
               }

               //Reset rawStr ready for the next reading
               rawStr = ("");
            }
            else
            {
               //Add incoming characters to a string.
               //Only add characters to the string if they are digits.
               //When the arduino starts up the first characters it sends through are S-t-a-r-t-
               //and so to avoid adding these characters we only add characters if they are digits.

               if (Character.isDigit(ch))
               {
                  rawStr = ( rawStr + Character.toString(ch));
               }
               else
               {
                  System.out.print(ch);
               }
            }
         }
         catch (IOException e)
         {
         }
      }
   }

}

And here is the Arduino Sketch
//Arduino code for Part 01

//First we will define the values to be sent
//Note: The java code to go with this example reads-
//-in integers so values will have to be sent as integers
int valueA = 21;
int valueB = 534;

void setup()
{
   Serial.begin(115200);
   Serial.println("Start");
}

void loop()
{

   //We send the value coupled with an identifier character
   //that both marks the end of the value and what the value is.

   Serial.print(valueA);
   Serial.print("A");

   Serial.print(valueB);
   Serial.print("B");

   //A delay to slow the program down to human pace.
   delay(500);

}

I have read that changing Serial.print() to Serial.write() is the new way to do this, but changing this had no result.

So the reason for no events being triggered was due to the program exiting and ending before it had the chance to.
To solve this i added a thread with a loop inside it inside the main thread.
public static void main(String[] args) throws Exception {
 ArduinoComm = new ArduinoComm ();
 main.start("/dev/ttyUSB0",115200);
 Thread t=new Thread() {
 public void run() {
 try {
 //Messy implementation but it works for this demo purpose
    while(true){
      //optional sleep
      thread.Sleep(500);
    }
 } catch (InterruptedException ie) {}
 }
 };
 t.start();
 System.out.println("Started");
 }

Bit of an oversight on my part.

Good to see you fixed your problem already! You might want to accept this as your answer (when you can, I know, it takes some time ;) ).
A thing I like to do is add debug printlines/cout's at the start and end of my program. So you can see whenever your program finishes or starts. I've had troubles with a microcontroller restarting itself (so the start of a program is an interesting event). And sometimes a device can cause undefined behaviour when breaking out of the main loop. So a while(true); (with debug lines) might indeed do the trick.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Supplying near perfect DC signals from Arduino UNO
My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter?
TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.

Do you have any response-time requirement?  (When using an RC filter, the tradeoff for low ripple is slow response)

Would 0-4.095V in 1mV (or 0.5mV 0-2.047V) steps do for you?  Then why not use some MCP4822 SPI SAC chips?  You get 2 channels on each 8-pin chip (DIP chips are available, yes), and if you need a different voltage range you could always amplify it with a simple op-amp buffer.
So 6 ports would be 3 chips, which would entail using SCK, MOSI and three CS pins, so 5 pins in all.

(1) A multipole active lowpass filter works wonders.
Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD & LT and NatSemi all have good free active filter design programs.
(2) A Simple sample & hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.
With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&H and update them occasionally top compensate for drift.  If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R  resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading.
If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
I2C LCD TFT with UART serial communication for MLX90615 IR thermometer freezing IR output
I have one Ir temperature mlx90615 sensor based of this connection only used for mega2560 RX1&TX1) :

Which is connected to one Arduino 2560 mega with one LCD TFT 2.4 like this (Arduino mega2560 RX1 TX2 instead of Uno for mlx90615 connection and UNO 3.5V and Ground used to power supply the MLX90615):

So my problem is when i insert some new object in the seen area of Ir sensor the output halt for some second delay and don't show new value  via serial point or LCD output.
it characteristic table via datasheet of mlx90615 sensor is :

I have use this source code on library for mlx90615 into my codes by this function:

or(i=0;i<8;i++){
  i=1;
 serialEvent();
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
//           Serial.print("TO:");
//           Serial.println(TO);
//           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
//           Serial.print("TA:");
//           Serial.println(TA);

             tft.fillScreen(BLACK);
             tft.setTextColor(WHITE);
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);

            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);
            tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
   }
  }

 }

void serialEvent(){
  char i;
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
  for (i=0;i<30;i++)
  {
    while (Serial1.available()) {

    Re_buf[counter]=(unsigned char)Serial1.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;i=600;
       sign=1;
    }
  }
  }
}

The total codes are here:
#include "LiquidCrystal.h"

 #include <Adafruit_GFX.h>    // Adafruit's core graphics library
#include <Adafruit_TFTLCD.h> // Adafruit's hardware-specific library
#include <TouchScreen.h>     //Touchscreen library
///#include <Fonts/Org_01.h>    //Include a different font
#include <EEPROM.h>         //Include the EEPROM library to score the highscore
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;

#include <TimeLib.h>

bool backsensed = false;
bool resetsensed = false;

// most mcufriend shields use these pins and Portrait mode:
uint8_t YP = A1;  // must be an analog pin, use "An" notation!
uint8_t XM = A2;  // must be an analog pin, use "An" notation!
uint8_t YM = 7;   // can be a digital pin
uint8_t XP = 6;   // can be a digital pin

#define TS_MINX 100
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940
//Create the touchscreen object
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);  //(data,data,data,data,sensitivity);

//Some of the tft pins
#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
// Optional, used to reset the display
#define LCD_RESET A4

#define REDBAR_MINX 80
#define GREENBAR_MINX 130
#define BLUEBAR_MINX 180
#define BAR_MINY 30
#define BAR_HEIGHT 250
#define BAR_WIDTH 30

//Create the tft object
//Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

// Define some TFT readable colour codes to human readable names
#define BLACK   0x0000
int BLUE = tft.color565(50, 50, 255);
#define DARKBLUE 0x0010
#define VIOLET 0x8888
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF
int GREY =  tft.color565(64, 64, 64);
#define GOLD 0xFEA0
#define BROWN 0xA145
#define SILVER 0xC618
#define LIME 0x07E0

int currentpcolour;

//Minimum and maximum pressure to sense the touch
#define MINPRESSURE 10
#define MAXPRESSURE 1000

#define DRAW_LOOP_INTERVAL 50  //The interval used instead of delay();

//Define the address used in the eeprom memory to store highscores
#define addr 0
int currentpage;

int currentWing;        //Used to flap the wings
int flX, flY, fallRate; //Used to calculete and store the bird's position
int pillarPos, gapPosition;  //Used tho draw the pillars
int score;              //Store the score
int highScore = 0;      //Store the highscore
bool running = false;   //Store weather flying or not
bool crashed = false;   //Store weather crashed or not
bool scrPress = false;  //Store weather sensed some touch and store
long nextDrawLoopRunTime;
int redval;
int greenval;
int blueval;

int redpos = BAR_MINY + 12;
int greenpos = BAR_MINY + 12;
int bluepos = BAR_MINY + 12;

int oldrpos = redpos;
int oldgpos = greenpos;
int oldbpos = bluepos;
int x, y;

int lastDay = 0;
int lastMonth = 0;
int lastYear = 0;
int lastHour = 0;
int lastMinute = 0;
int lastSecond=0;
int movementTimer = 0;
int menuOptions = 4;
int menuOption = 0;
int alarmHours = 0;
//int Heater_alarmMinutes = 0;
//int Heater_alarmSecond=10;
//int Motor_alarmSecond=10;
//int Motor_alarmMinutes=0;

byte Heater_alarmMinutes_end ;
byte Heater_alarmSecond_end;
byte Motor_alarmSecond_end;
byte Motor_alarmMinutes_end;

bool heater_key = 0;
bool backLightOn = 1;
int fadeValue = 255;

byte address=0;
byte value;

bool state=1;

//#$############# MLX9615 ##################

 unsigned char Re_buf[11],counter=0;
 char sign=0;
float TO=0,TA=0;
void serialEvent();

//########################################
void DrawTriangle() {
 int n, i, cx = tft.width() / 2 - 1, cy = tft.height() / 2 - 1;

 tft.fillScreen(BLACK);
 n = min(cx, cy);

 for (i = 0; i < n; i += 15) {
 tft.drawTriangle(
 cx , cy - i, // peak
 cx - i, cy + i, // bottom left
 cx + i, cy + i, // bottom right
 tft.color565(0, 0, i));
 }
}
void drawHome()
{

  tft.fillScreen(BLACK);
  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game

  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);

  tft.fillRoundRect(60, 80, 200, 40, 8, RED);
  tft.drawRoundRect(60, 80, 200, 40, 8, WHITE); //Oscilloscope

  tft.setCursor(60, 20);
  tft.setTextSize(2);
///  tft.setFont();
  tft.setTextColor(WHITE);
  tft.print("Select on Option");
  tft.setCursor(70, 50);
  tft.setTextSize(2);
  tft.setTextColor(LIME);
  tft.print("GSH.ir");
  tft.setTextColor(BLACK);

  tft.setCursor(80, 95);
  tft.print("Heater Setting");

  tft.setCursor(80, 145);
  tft.print("Motor  Setting");

  tft.setCursor(70, 195);
  tft.print("     Start");

  //tft.drawCircle(30, 30, 20, RED);
  //tft.fillCircle(111, 111, 30, WHITE);
  //  delay(500);
  //tft.drawRoundRect(120, 192, 60, 64, 15, YELLOW);
  // tft.fillRoundRect(0, 192, 60, 64, 15, CYAN);

   // tft.drawRect(0, 0, 60, 64, CYAN);

   //  tft.fillRect(180, 192, 60, 64, GREY);
     //DrawTriangle();

}

void drawstart(bool k)
{

  tft.fillScreen(BLACK);
  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

//  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
//  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game
//
//  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
//  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);
//
  tft.fillRoundRect(90, 60, 160, 60, 18, RED);
  tft.drawRoundRect(90, 60, 160, 60, 18, WHITE); //Oscilloscope

  tft.setCursor(40, 180);
  tft.setTextSize(3);
///  tft.setFont();
  tft.setTextColor(WHITE);

  if (k) {
    tft.print("Motor on time");
  }else{
    tft.print("Heater on time");
  }

}
void drawMenu(bool k)
{
   tft.fillScreen(BLACK);

  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

//  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
//  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game
//
//  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
//  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);
//
//  tft.fillRoundRect(75, 80, 160, 60, 18, BLUE);
 // tft.drawRoundRect(700, 60, 160, 80, 18, WHITE); //Oscilloscope

  //tft.fillTriangle(60,60,20,120,180,180,RED);
  tft.fillRoundRect(70, 75, 180, 70, 18, GREEN);
   //tft.fillTriangle(42, 20, 42, 60, 90, 40, RED);
   tft.fillTriangle(260,90, 260, 130, 300, 110, RED);
   tft.fillTriangle(60,90, 60, 130, 20, 110, RED);

  tft.setCursor(45, 180);
  tft.setTextSize(2.95);
///  tft.setFont();
  tft.setTextColor(WHITE);
  if (k) {
    tft.print("Motor Timer Setting");
  }else{
    tft.print("Heater Timer Setting");
  }
//  tft.fillRoundRect(5, 5, 80, 60, 8, WHITE);
//  delay(70);

  tft.setTextSize(4);
  tft.fillRoundRect(5, 5, 80, 60, 8, RED);
  tft.drawRoundRect(5, 5, 80, 60, 8, WHITE);
  tft.setCursor(20,20);
  tft.print("<-");

   tft.fillRoundRect(230, 5, 85, 60, 8, BLUE);
  tft.drawRoundRect(230, 5, 85, 60, 8, WHITE);
  tft.setCursor(250, 20);
  tft.print("OK");

}

void start(){
  tft.fillScreen(BLACK);
   drawstart(0);
   setTime(0, 0, 1, 20, 1, 2013); // hour, min, sec, day, month, year
  lastHour = hour();

          //check for heater key pressed

   heater_key=1;state =1;
 while (state ){

   if ( lastSecond!=second())
   {
       lastMinute = minute();
       lastSecond=second();
       tft.setTextSize(6);
       tft.fillRoundRect(60, 60, 200, 100, 18, RED);
       //tft.fillScreen(BLACK);
       tft.setTextColor(WHITE);
       tft.setCursor(110, 85);
       tft.print(lastMinute);
       tft.setCursor(140,85);
       tft.print(":");
       tft.setCursor(170, 85);
       tft.print(lastSecond);
       //delay(1000);
   }
   if (heater_key)
    {
      // alarm set
      if ((Heater_alarmSecond_end <= lastSecond) && (Heater_alarmMinutes_end == lastMinute))
      {
         state=0;
         digitalWrite(A5, LOW);

      }
       if ((Heater_alarmSecond_end >= lastSecond) || (Heater_alarmMinutes_end >= lastMinute))
         {
          //sound alarm
          digitalWrite(A5, HIGH);
          //setOffAlarm();
         }
     }
   }

    drawstart(1);
    state =1;
   setTime(0, 0, 0, 20, 1, 2013); // hour, min, sec, day, month, year
   while (state){
   if ( lastSecond!=second())
   {
       lastMinute = minute();
       lastSecond=second();
       tft.setTextSize(6);
       tft.fillRoundRect(60, 60, 200, 100, 18, RED);
       //tft.fillScreen(BLACK);
       tft.setTextColor(WHITE);
       tft.setCursor(110, 85);
       tft.print(lastMinute);
       tft.setCursor(140,85);
       tft.print(":");
       tft.setCursor(170, 85);
       tft.print(lastSecond);
       //delay(1000);
   }
   if (1)
    {
      // alarm set
      if ((Motor_alarmSecond_end <= lastSecond) && (Motor_alarmMinutes_end == lastMinute))
      {
         state=0;
         digitalWrite(A6, LOW);

      }
       if ((Motor_alarmSecond_end >= lastSecond) || (Motor_alarmMinutes_end >= lastMinute))
         {
          //sound alarm
          digitalWrite(A6, HIGH);
          //setOffAlarm();
         }
     }
   }

//########### MLX90615 @#############
   char i=0,sum=0;

//  for (i=0;i<100;i++){
   score=1;
    while(score==1){
    serialEvent();
    if(sign)
    {
       sign=0;
       for(i=0;i<8;i++)
        sum+=Re_buf[i];
       if(sum==Re_buf[i] )
       {
             TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
             if ((int)TO>=30){
              score=0;
             }
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);
            tft.fillScreen(BLACK);
            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
     }
    }
  }
//####################
   delay(100);
   drawHome();
   return;

}

void menu(){

// drawMenu();

 TSPoint p = ts.getPoint();     // Read touchscreen
 state =1;
// while(state){
// if (p.z > MINPRESSURE && p.z < MAXPRESSURE)
if (p.z > 10 && p.z < 1000)
    {
     tft.setTextSize(3);
            tft.setTextColor(RED);
            tft.setCursor(10, 10);
            tft.print(p.x);
            delay(500);
      /* if (p.y > 743 && p.x < 247 && p.x > 150 && p.y < 875)
        {
          tft.fillRoundRect(5, 5, 50, 30, 8, WHITE);
          delay(70);
          tft.fillRoundRect(5, 5, 50, 30, 8, BLUE);
          tft.drawRoundRect(5, 5, 50, 30, 8, WHITE);
          tft.setCursor(15, 15);
          tft.print("<-");
          delay(70);
          tft.fillRoundRect(5, 5, 50, 30, 8, BLACK);
          currentpage = 0;
          drawHome();
          p.x = 160;
          p.y = 760;
          return;
        }
      if (p.x > 736 && p.x < 855 && p.y > 255 && p.y < 725  )
      {
        tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(10, 10);
            tft.print("UP2");
            delay(500);

      }
      x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
      y = map(p.y, TS_MINY, TS_MAXY,  tft.height(), 0) + 30;
//tft.fillTriangle(250,90, 250, 130, 290, 110, RED);
//   tft.fillTriangle(60,90, 60, 130, 20, 110, RED);
    if (y > 70 && y < 130)
      {
        if (x > 20 && x < 120)
        {
            tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(50, 140);
            tft.print("DOWN");
        }
        if (x > 220 && x < 320)
        {
            tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(50, 140);
            tft.print("UP");
        }

      }
      */
  }
// }
}
////########## MLX90615    #############
//void serialEvent(){
//  while (Serial1.available()) {
//    Re_buf[counter]=(unsigned char)Serial1.read();
//    if(counter==0&&Re_buf[0]!=0x5A) return;
//    counter++;
//    if(counter==9)
//    {
//       counter=0;
//       sign=1;
//    }
//  }
//}
////########################

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);

void setup()
{

  time_t t = now(); // store the current time in time variable t
  pinMode(A5, OUTPUT);pinMode(A6, OUTPUT);

  tft.reset();
  tft.begin(tft.readID());
//  Serial.begin(9600);
//  Serial.println();
//  Serial.print("reading id...");
//  delay(500);
//  Serial.println(tft.readID(), HEX);

  tft.fillScreen(BLACK);
  tft.setRotation(1);

  currentpage = 0;

  tft.setTextSize(3);
  tft.setTextColor(WHITE);
  tft.setCursor(50, 140);
  tft.print("Loading...");

  tft.setTextColor(tft.color565(255, 255, 0));
  tft.setCursor(30, 70);
  tft.print("By:");

  tft.setCursor(30, 100);
  tft.print("NotesPoint.com GSH.IR");

  for (int i; i < 250; i++)
  {
    tft.fillRect(BAR_MINY - 10, BLUEBAR_MINX, i, 10, RED);
    delay(0.000000000000000000000000000000000000000000000000001);
  }

  tft.fillScreen(BLACK);
  score=14;
  if (EEPROM.read(1)==score){
  address=2;
  tft.setCursor(300, 100);
  tft.print("eeprom writed beffor");
  Heater_alarmSecond_end = EEPROM.read(address);
  Heater_alarmMinutes_end= EEPROM.read(address+1);
  Motor_alarmSecond_end = EEPROM.read(address+2);
  Motor_alarmMinutes_end = EEPROM.read(address+3);
  }
  else{
    tft.setCursor(300, 100);
  tft.print("new eeprom");
    address=1;
  EEPROM.write(address,14);
  EEPROM.write(address+1,10);
  EEPROM.write(address+2,4);
  EEPROM.write(address+3,10);
  EEPROM.write(address+4,0);
  address=1;

  Heater_alarmSecond_end = EEPROM.read(address);
  Heater_alarmMinutes_end= EEPROM.read(address+1);
  Motor_alarmSecond_end = EEPROM.read(address+2);
  Motor_alarmMinutes_end = EEPROM.read(address+3);
  }
  delay(100);
  drawHome();
  setTime(0, 0, 0, 20, 1, 2013); // hour, min, sec, day, month, year
  //########### MLX90615 ############

Serial1.begin(115200);Serial.begin(115200);
  delay(1);
//  Serial1.write(0XA5);
//  Serial1.write(0X45);
//  Serial1.write(0XEA);
  Serial.write(0XA5);
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
//buadrate 115200
  Serial1.write(0XA5);
  Serial1.write(0XAF);
  Serial1.write(0X54);

//#############################

}
//void setup() {
//
//lcd.begin(16,2);
//
//// set cursor position to start of first line on the LCD
//lcd.setCursor(0,0);
////text to print
//lcd.print("   16x2 LCD");
//// set cusor position to start of next line
//lcd.setCursor(0,1);
//lcd.print("   DISPLAY");
//   Serial1.begin(115200);
//   Serial.begin(115200);
//  delay(1);
//  Serial1.write(0XA5);
//  Serial1.write(0X45);
//  Serial1.write(0XEA);
//}

void loop() {

//
//
//
   char cc,i=0,sum=0;

   //  digitalWrite(13, HIGH);
  TSPoint p = ts.getPoint();     // Read touchscreen
//  digitalWrite(13, LOW);

  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);

//   score=1;
//   while(score==1){
for(i=0;i<8;i++){
  i=1;
 serialEvent();
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
//           Serial.print("TO:");
//           Serial.println(TO);
//           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
//           Serial.print("TA:");
//           Serial.println(TA);

             tft.fillScreen(BLACK);
             tft.setTextColor(WHITE);
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);

            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);
            tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
   }
  }

 }

}
void serialEvent(){
  char i;
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
  for (i=0;i<30;i++)
  {
    while (Serial1.available()) {

    Re_buf[counter]=(unsigned char)Serial1.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;i=600;
       sign=1;
    }
  }
  }
}

So has anybody this problem with this kind of sensors or other sensors?and why this happened?
Update:
Based of this site i have combined the blinky and mlx90615 uart sample code, and it's working without freeze, the code is shown below:

unsigned char Re_buf[11],counter=0;
unsigned char sign=0;
float TO=0,TA=0;
void setup() {
   pinMode(LED_BUILTIN, OUTPUT);
   Serial.begin(115200);
  delay(1);
  Serial.write(0XA5);
  Serial.write(0X45);
  Serial.write(0XEA);
}

void loop() {
  unsigned char i=0,sum=0;
 digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(50);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(50);
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
           Serial.print("TO:");
           Serial.println(TO);
           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
           Serial.print("TA:");
           Serial.println(TA);
   }
  }

}
void serialEvent() {
  while (Serial.available()) {
    Re_buf[counter]=(unsigned char)Serial.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;
       sign=1;
    }
  }
}

I have read this queston: Hardware Serial causes hang-up and i think its related to I2C comunication with TFT LCD by this:

I think I found the solution. As you can see on the photo above, I
used unscreened wires in comparison with the Breadboard. I2C is
definitely very sensitive against EMP, which causes the bus freezes. I
now use screened wires and don´t use the Breadboard anymore. The issue
now occurs very rarely. Unfortunately I still don´t understand the
interdependency to the UART interface. I will now improve the
screening of my wireing. Hopefully, the breakdowns will totaly
diappear.
Re: Hardware Serial causes hang-up
Summary: My final solution, after weeks of detective work is, to use another sensor board.  :smiley-fat:
Obviously the ADXL 345 together with connected UART, provoked by EMP
is the problem. I still don´t know why, but now, using the 10DOF GY-86
board with the MCU5060 IMU, it runs stable in a longtime test, for
over 60 hours! No more freeze!!! I hope this will help someone having
similar problems!

Now it the end of week and i will go to holiday so i wil try newx two days by 16X2 Crystal LCD and printed board to check will it happen again?
Until next two days i will appriciate any sugestion or help.
Thanks a lot.

If you have noise problems with the I2C interface, you should add stronger pullup resistors to the lines (SDA and SCL). For example 4.7kOhm or a bit less.

TBH, I've read your question many times but I still do not understand, what your problem is. What I can see is:

You provided picture with wiring for Arduino Uno, not Arduino Mega. If you are using LCD TFT shield intended for I2C and Arduino Uno, it will not work on Mega – this board has I2C on pin 20 (SDA) and 21 (SCL), not like Uno on pin A4 (SDA) and A5 (SCL). But I guess the LCD TFT shield uses SPI, not I2C. Even if it is SPI, it will not work either (again, different pinout).
You are using HW Serial #1 for debug and also for communication with the sensor. This may be the source of your problems. Use different HW Serial for debug (#1 is recommended) and different for communication with the sensor (e.g. Serial #2). Arduino Mega has 3 HW Serial interfaces. If you are using Uno and not Mega, use SoftwareSerial (but I recommend using smaller baud rate, if possible).

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Why do MEGA2560 digital pins go high on serial disconnect?
I'm trying to set up a system using an that delivers a specific number of digital pulses to a device using one of the digital pins. The number of pulses delivered is specified over a the Mega's USB serial connection using a Python script (or terminal for debugging).
When I close the serial connection to the Arduino, I get a short "blip" that looks like a digital high (see image below). This happens when I disconnect in PySerial using Serial.close() or when I simply close my Arduino IDE terminal window.
It does not occur when I press the reset button on the board
Any ideas on how to get rid of this?  Thanks!

You could try adding a pull-down resistor to the pin, and see if the problem persists. Does the Arduino reset itself, when you disconnect the serial connection?

Maybe it's a wiring thing. Try posting a schematic of your setup. Perhaps we need to see the circuitry inside the "device" you've connected the Mega to.

Its definitely a wiring thing; you may have shorted something or missed shorting all grounds in case you have more than one;

What digital pin? What is your code?

When you connect and disconnect from the Arduino, the usb host chip resets the entire device. If you do not want this you can cut the RESET trace on the board.

some boards have a jumper here instead that can be removed.
more info here
https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


text:
Problem uploading the code into an Arduino Uno
I was trying to upload code for a blinking LED. It is a new Arduino Uno board. Any further help will be appreciated.I got the following error:

Info.: OS- Ubuntu 16.04
Software: Arduino IDE 1.8.5

I could not see any port.
I have tried dialout. But still it is not working.
I also have a confusion, i.e. the Programmer menu shows AVRISP mkll.

If anyone wants any information, please do comment.
Error:

An error occurred while uploading the sketch
avrdude: ser_open(): can't open device "COM1": No such file or directory`

An Arduino Uno on Ubuntu will typically be at /dev/ttyACM0.

Ubuntu and other Linux operating systems don’t name the serial ports “COM1” or similar.
They use special files like
/dev/tty.[something]

The [something] depends on the USB device driver. The IDE should list available serial ports in the Port selection menu.

there is not port available

What ports show up?

NO port is shown.

@ChandramauliChakraborty are you in dialout group? Or better, have you read any tutorial about Arduino in Linux?

Perhaps you don’t have the right permissions to access the serial ports. Your user must have access to the serial ports. On Ubuntu, this can be accomplished by adding your user to the dialout group. Also, make sure you have the Uno plugged into the computer.

How to do it? Please elaborate.

https://playground.arduino.cc/Linux/Ubuntu

I have tried it is not working.

After adding your user to the dialout group, you have to log out completely and log back in.

Stil it is not working

One troubleshooting step - unplug the board, then open a terminal window and run the lsusb command.  Note the devices that appear in the list.  Then plug the board back in and run lsusb again - you should see the new device.  If you don't, that could explain why you're not getting a list of available ports.  On my Ubuntu system (Studio, 16.04), the device name shows up as "1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter" and connects through /dev/ttyUSB0.


text:
Which arduino should i use for a very simple one pin "blinking led" type project?
I want to simply switch a relay like Majenko describes it for my last question. (time based switching of a relay)
That's the code I came up with based on the documentation:
int relayPin = 2; // pin where relay is attached
long mins = 5L;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    digitalWrite(relayPin, HIGH);
    delay(mins * 60L * 1000L);
    digitalWrite(relayPin, LOW);
    delay(mins * 60L * 1000L);
}

Now I want to use a real device and have been looking around, but there are tons of different boards, so some shopping advice would be really great. What I would like if possible:

Closed casing to reduce risk of people touching stuff. (also for a "professional" look)
Built in power supply from 220V AC.
Outputs strong enough to work without external logic, just connect the relay and go.
Small size and low cost, in case I start using these everywhere in the house i don't need to reevaluate. :)

No ordinary Arduino will by itself meet all of the case, AC power input and output strength requirements, but there are various combinations of things that may, including relay boards with built in drivers.  The self-contained products that actually do all that off the shelf are typically industrial devices called PLC's, rather than hobby devices like Arduinos (but they are not cheap).  Unfortunately as it stands your question is not clear enough about a specific goal, too broad in possible approaches, and too ultimately dependent on personal opinion to be a fit here.

Thanks for the comment, basically it contains the answer to "can i have it all?" .. Which parts could I remove to make it better suited for the site? i'd prefer going with an arduino, so will take whatever fits best. I'm more the software guy, so the less wiring the better! :)

The part of the project represented by the Arduino itself is the trivial one; as you'll see from other questions here on that it is also subject to endless bike-shedding of opinions (including "don't use an Arduino at all"), and reducing it to that would only see closure as a duplicate of an existing question of that sort.  The more challenging part of the question has to do with packaging it, running it off mains power, switching loads, etc - but that is also where it starts to veer beyond the mission and expertise of this site.

The closest system I am aware of is the Quick240 from Pontech: http://pontech.com/productdisplay/quick240 - It's a DIN rail system. Add a 12v or 24v DIN rail power supply (I like the MeanWell ones), and a DIN rail relay (same voltage as the PSU), and link the relay to the Quick240 using a "Drive Kard (Source)" and you have an Arduino-like PLC. The whole thing can go in a DIN rail housing. More info on Quick240: http://quick240.com/quicki/

Okay, maybe didn't mean thaaat professional, just a simple plastic casing like you have on portable discs. But the DIN rail idea sounds interesting, will investigate further, thx!

The problem with finding what you want is that most Arduino development systems are made by small(ish) companies and designers. As soon as you add a mains power supply into a product it suddenly comes under lots more rules and regulations and testing requirements, all which massively increase costs beyond what a small company making only a small number of devices can reasonably afford and still keep the retail price at a sellable level. It's only when you start creating thousands and thousands of a product that the testing and certification costs become a negligible percentage.

That is why most devices use an external third party power supply instead of integrating it.

Yeah, sorry for the confusion, think we just have different standards what is normal. :D
Last time I did electronics and microcontrollers was in school over two decades ago. We had huge power supplies and lots of wiring and soldering to do. So in my attempt to reduce that I made it too complicated for today, where everything is already neat. As canadiancyborg suggests, I will try with a usb supply, the uno board, a relay shield and a casing. Thanks to you all for the insights, already like that arduino stuff! :)

For beginners, use an Arduino Uno. It is ready to use and quite expendable with shields. They have the USB to SERIAL chip on the board. Only week point is that it is sometimes large from space sensitive projects.

For more advanced users, I would suggest the Pro Mini (my personnal favorite). It is small, powerful and even has more pins then the UNO. The main disadvantage is that it requires an FTDI connector for the USB to SERIAL. Note that this NOT recommended if you use a lot of I2C.

Finaly, there is the overkill option. Only use this if you are considering to get one Arduino to rule them all!. It's the Arduino Mega 2560. It is the overkill of the overkill. So many GPIOs and ANALOG inputs. It is also unique for its core which is different the then normal ATmega328.

Then finaly there is the most easy to use one, the Red Board by Sparkfun. It combines the best of each Arduino in one. Note that this one is not manifactured and backed by Arduino.

That is pretty much a summary of all of the most popular types of Arduino that there is.
[EDIT]
Note that none of them has an included case and a circuit that can reduce 220V to 5V. If you really want a case, get an UNO. There are many cases for it. For transforming 220V to 5V, use an 5V wallplug. If you have something like a 12V wallplug, you can also connect it to the Arduino but you have to make sure you connect it to the Vin port.

With 5V wallplug you mean a USB thingy? that works?

any wallplug that output 5V should work, even the phone chargers could work. just pick the right USB type for it. hope it helped anwser your question

almost! you don't happen to have an easy solution for attaching the relay directly? :)

connect the relay to one of the digital output of the arduino. thats the only and fastest way

a relay shield could also work, you simply stack in directly on the uno. no wires needed

all parts of the question answered, thanks a lot!

Personally I would recommend a chip from the ATtiny series (ATtiny85 for example - it has 5 programmable pins and costs about $1 - $3).
Even though it is not really an Arduino board - it is really great  as you can easily program it from another board from within the Arduino IDE, and it is really lightweight and cheap.
Watch this
Youtube video
for a guide to set it up - it is really useful.
Otherwise you can simply give "attiny85 arduino setup" a google


text:
Is this method to a String from a function going to cause memory corruption?
I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:
bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

You don't need to use the String constructor there. You could just as easily have said: *s = "foo";

You are better off passing the string by reference, like this:
bool getStringOrTimeout(String & s)
{
  if (timed_out)
    return false;
  s = "foo";
  return true;

}

That means the caller's string will be modified. And you no longer need to pass down a pointer to a string.


text:
Possible to determine at runtime whether a pointer is declared PROGMEM?
Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.
The F() macro works around this by changing the type of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:
Serial.println ("Hello, world");
Serial.println (F("Hello, world"));

In this case the appropriate println function is chosen at compile-time by the compiler, based on the type (one would be a const char *, the other a __FlashStringHelper type).
You are best off designing a way (similar to the F() macro) where you can make the decision at compile time.

Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

The AVR MCUs are Harvard Architectures. Data and program memory spaces are separated. There are also several data memory spaces, e.g. SRAM, EEPROM, PROGMEM. Each of these have there own address space, and special instructions are used to access them.
In software anything is possible :) so it is possible to unify the address spaces and use a run-time mechanism to do the respective read and write. A simple method is to use the most significant bits to determine the address space. For instance,
SRAM 0x0000..0x7fff
EEPROM 0x8000..0x8fff
PROGMEM 0x9000..0xffff

SRAM pointers are as usual, EEPROM pointers have an extra 0x8000, and PROGMEM pointers an extra 0x9000.
The next step is to write a simple mapping function from the unified address space to the separate memory address spaces. This can be wrapped into a C+++ smart pointer and/or a simple C++ class hierarchy.
An example of this technique can be found in 1) Forth Virtual Machine for Arduino, https://github.com/mikaelpatel/Arduino-FVM (see https://github.com/mikaelpatel/Arduino-FVM/blob/master/src/FVM.cpp#L85), 2) RPN Postscript/Forth Command Shell for Arduino, https://github.com/mikaelpatel/Arduino-Shell (see https://github.com/mikaelpatel/Arduino-Shell/blob/master/Shell.h#L1059).
Cheers!
PS: An interesting detail with the AVR architecture is that the registers 0..31, and the io-registers, are mapped to the SRAM address space.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is this function subject to memory fragmentation?
I'm trying to understand if the following bit of code is subject to memory fragmentation.
Let's say I incrementally build a string within a function and I don't know how large the string should be.
String f() {
    String s = String("");
    s += "a"; // ...
    s += "bc"; // ...
    return s;
}

The String object does dynamic memory allocation internally, but s is on the stack, so once the function returns, the s object presumably deallocates and dynamically allocated memory is freed.
Before this happens, the String object to be returned must be copied from s. Since String objects hold internal data in dynamically allocated buffers, this means that the s internal buffer is allocated, then the return object internal buffer is allocated, then the s internal buffer is deallocated.
The return object internal buffer allocation is sandwiched between the s object alloc and dealloc.
To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like Serial.readString are also subject to memory fragmentation?

Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.
I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
You are much better off never using the String class and instead sticking to basic C strings (char arrays).

Thanks. And what about all the other classes in the Arduino library? A search at the Arduino source code finds a lot of ...allocs. Are Arduino projects subject to heap fragmentation in general?

There is very little allocation done in the core. It's only really String that does it. Libraries, though, are a law unto themselves.

Memory fragmentation is hard to predict, as it depends on how your
different allocation patters interact. This single pattern, per se,
looks safe. By safe I mean that if

your heap is not fragmented when you enter this function, and
you do no dynamic allocation inside the function other than growing the
string,

then the string will be allocated to the top of the heap and grow from
there without moving or making holes. You can check this is the case by
looking at the address of the string's internal buffer, which is given
by the c_str() method. It should not change inside the function:
String f() {
    String s = String("");
    const char * p = s.c_str();
    s += "a"; // ...
    s += "bc"; // ...
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    return s;
}

Edit: I wrote this small test program to show the behaviour of the
heap when you use string concatenation this way:
extern uintptr_t __brkval;

String f() {
    String s("");
    const char * p = s.c_str();
    Serial.print(F("  f(): string buffer @ 0x"));
    Serial.println((uintptr_t) p, 16);
    for (int i = 0; i < random(8) + 1; i++)
        s += random(2) ? "a": "bc";
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    Serial.print(F("        top of heap at 0x"));
    Serial.println(__brkval, 16);
    return s;
}

void setup() {
    Serial.begin(9600);
    Serial.print(F("***     heap starts at 0x"));
    Serial.println((uintptr_t) __malloc_heap_start, 16);
}

void loop() {
    Serial.print(F("loop(): top of heap at 0x"));
    Serial.println(__brkval, 16);
    String s = f();
    Serial.print(F("  f() returned "));
    Serial.println(s);
    Serial.print(F("        with buffer at 0x"));
    Serial.println((uintptr_t) s.c_str(), 16);
    delay(1000);
}

The output of the program is:
***     heap starts at 0x1D7
loop(): top of heap at 0x0
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DC
  f() returned aa
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1E2
  f() returned aabcabca
        with buffer at 0x1D9
[...]

The very first “top of heap at” is bogus because at this point the
malloc library has not been initialized. Besides that, you can see here
that:

the heap is always empty (top = bottom) at the beginning of loop()
the string is always allocated at the same place
the heap size inside f() varies depending on the string's length
the string is not copied when returned to the caller, as the internal
buffer is still at the same address.

However, if the statement String s = f(); is replaced by
String s; s = f();, then the string is copied when returned to the
caller, which doubles the amount of RAM required to handle it. This is
presumably because only the first form allows copy elision
optimization. (This
paragraph was added after reading Nick Gammon's answer, which made me
realize the copy elision issue).
Keep in mind that this works so nicely only because there is nothing
else doing dynamic allocation in this small program. This usage pattern
is safe, but once you start doing dynamic allocation in different parts
of the program, it becomes difficult to ensure that the
allocation/deallocation pattern is still safe vs. memory fragmentation.

The worst line in your example is this:
s += "a"; // ...

Any sort of loop that adds one byte to a String is potentially going to fragment memory. First the String class allocates zero bytes for the string, then when you add a byte, it has to allocate one byte, then when you add another byte it has to deallocate (free) that byte and allocate two bytes, and so on.
The allocator tries to be efficient, so eventually when you get up to three bytes you will, with luck, actually get the memory previously allocated to the one-byte string followed by the two-byte string.
But if other allocations have occurred (eg. another use of String elsewhere in the program) this might not be possible. Eventually you have lots of small gaps of maybe one or two bytes, with other stuff inbetween. Unless they are adjacent they cannot be recombined into a bigger block. This is your "fragmentation".

When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place.  This works fine, without fragmentation, as long as your buffer is at the top of the heap.

Good point, however if you have multiple String instances, this may not work.
Edgar Bonet is right, however there is certainly the potential, with multiple String instances, for each of them to prevent the others from growing their buffer size neatly. In the example in the question, you will probably find that when f() returns, it returns a copy of the String allocated on the stack, thus we now have 2 x String instances.

While Edgar was writing some test code, so was I. :)
#include <memdebug.h>

String foo;

String f() {
  String s = String("");
  s += "a"; // ...
  s += "bc"; // ...
  return s;
}  // end of f

void showMemoryUsage ()
{
  Serial.println (F("---------------"));
  Serial.print (F("Largest block in freelist: "));
  Serial.println (getLargestBlockInFreeList ());
  Serial.print (F("Largest available memory: "));
  Serial.println (getLargestAvailableMemoryBlock ());
  Serial.print (F("Free memory: "));
  Serial.println (getFreeMemory ());
  Serial.print (F("address of foo data = "));
  Serial.println ((int) foo.c_str ());
} // end of showMemoryUsage

void setup()
{
  Serial.begin (115200);
  Serial.println ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.print (F("foo = "));
  Serial.println (foo);
}  // end of setup

void loop ()
{
}  // end of loop

Memory debug library from http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/
Output:
---------------
Largest block in freelist: 0
Largest available memory: 1675
Free memory: 1677
address of foo data = 478
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
foo = abc

The address of the data in foo has changed from 478 to 482, so my prediction above was right. The function f() made a String, but a second copy was returned, hence we have now "lost" 4 bytes in the heap. Well, not lost, but there is a gap.
Calling f() a second time did not make the fragmentation worse.

BTW, this is unnecessary:
  String s = String("");

Just write:
  String s;

You are invoking a second String just to provide something to copy into the first String. Strings start off empty so this is just wasted time.

Actually, it first allocates one byte (for the NULL at the end of ""), not zero. When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place. This works fine, without fragmentation, as long as your buffer is at the top of the heap.

See amended answer.

Added example code which tests the fragmentation theory.

Thanks for the test. It made me realize mine worked so well (zero copy) only because I used an idiom that allowed the compiler to do copy elision optimization. I added a note to my own answer. It's nice to learn stuff from comparing and elaborating answers this way. ;-)

I also had to print foo or the compiler thought I had made a useless variable and optimized it away. :)


text:
Why does DHT-library (and others) only allow one object instance?
I came across the problem to handle two DHT22 devices.
I use the Adafruit DHT Sensor library.
Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.
I checked the source and found, that the DHT object only gets constructed before setup() as a constant in the examples, because the library is written that way.
I did a quick hack, which works, but seems ugly to me:
DHT.cpp
DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
-  _pin = pin;
-  _type = type;
-  #ifdef __AVR
-    _bit = digitalPinToBitMask(pin);
-    _port = digitalPinToPort(pin);
-  #endif
+  //_pin = pin;
+  //_type = type;
+  //#ifdef __AVR
+  //  _bit = digitalPinToBitMask(pin);
+  //  _port = digitalPinToPort(pin);
+  //#endif

...

-void DHT::begin(void) {
+void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
+  _pin = pin;
+  _type = type;
+  #ifdef __AVR
+    _bit = digitalPinToBitMask(pin);
+    _port = digitalPinToPort(pin);
+  #endif

DHT.h*
-   void begin(void);
+   void begin(uint8_t pin, uint8_t type, uint8_t count=6);

Basically, I moved a few lines from the constructor to the begin() method. The whole thing works. I can even rewire & change the data-pin dynamically while the Arduino runs.
Here are my questions:

Is the hacked away behavior a bug or feature?
Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.

I would contact the owners of the Github repository and point them to your "hack" and get the thumbs up first. At least, you would be notifying them about the issue. Either they don't know about it, or are working on a fix

Upvote for editing my post. Nice diff feature btw.

There is nothing wrong with the library. It does not allow just one object instance.
What is wrong is your way of using it.
It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.
But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete.
DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);

Cool, I missed that, since I'm not familar with the underlying concepts of C, but your answer is what I was looking for. This is why I wrote, that my solution seems ugly to me. I keep the repo on github, to keep this post understandable.

The onky caveat with it is that excessive use on boards with very low memory could lead to heap fragmentation and stability issues. Shouldn't happen as long as you new immediately after deleteing.

On second thought. Wouldn't it save mem on the arduino, if only one Object exists? I think this was the origin of the hack. Changing an objects attribute value should be much cheaper, than instanciating an object and destroying it again.

No memory difference. Just where in memory it resides. Maybe a minor difference in processing at the time of instantiation, but minimal.

Changing the pins sounds like a reasonable requirement, and you shouldn't have to delete/new to achieve it.
I would leave the library alone (for backwards compatibility) except to add a changePins function which you may choose whether or not to call, to assign new pins to the class structure. (Effectively it would be your rewritten begin function with a different name).


text:
Loop behaves oddly in I2C receiveEvent
I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.
This is the code on the ATmega:
#include <Wire.h>

#define SLAVE_ADRESS 0x1A
#define LED 6

int count = 10;
void setup()
{
    pinMode(LED, OUTPUT);
    /*for(int i=1; i<=3; i++)
    {
      digitalWrite(LED, HIGH);
      delay(100);
      digitalWrite(LED, LOW);
      delay(100);
    }*/
    Wire.begin(SLAVE_ADRESS);
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
}

void loop()
{
  delay(10);
}

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

void requestEvent()
{
  Wire.write(count);
}

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like if(1) are there because the code was much more specific originally.) The strange thing is that this is not the case:
The LED only blinks 1 time.
I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5*2 times:
#include <stdio.h>

int main()
{
  int j = 5;
  while(j>0)
  {
    printf("LED, HIGH\n");
    printf("LED, LOW\n");
    j-=1;
  }
  return 0;
}

Circumstances:

I compile the code in the Arduino IDE on the Pi, then upload it
using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages
over the process.
The ATmega gets 3.3 V supply voltage from the Pi, and operates on
16.000 MHz. Only the LED and the Pi is connected to it.
The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

import pigpio
import time

pi = pigpio.pi()
atmega = pi.i2c_open(1, 0x1A)

for i in range(6):
    a = pi.i2c_read_byte(atmega)
    print a

pi.i2c_write_byte(atmega, 0x05)
time.sleep(1)

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

receiveEvent is an ISR (interrupt service routine). Don't do delay in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do delayMicroseconds for testing. In general an ISR should be short.

Interrupts
I2C

Thank you! So I should move as much as possible to the main loop from an ISR, or only avoid timed functions?

It is valid to receive the data in the ISR (make the global variable (buffer) volatile). After that, set a flag (also volatile) and do the rest in the main loop.

I should move as much as possible to the main loop from an ISR - yes you should.


text:
Interrupt problem...?
I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.
In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:
#include <Encoder.h>   // is this library the cause??...

#define PIN_1 4
#define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
#define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

void setup() {
  pinMode(PIN_B, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(PIN_B, ButtonPressISR, FALLING);
  attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
}

void loop() {
  Serial.println("Don't interrupt me");
  delay(10);
}

void ButtonPressISR() {
  Serial.println("Yay, I'm pressed!");
  delay(1000);
}

void ButtonReleaseISR() {
  Serial.println("Yay, I'm released!");
  delay(1000);
}

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.
When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.
The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

simulate this circuit – Schematic created using CircuitLab

Generally, Serial.println() does not work correctly from within an ISR, as println() uses interrupts itself

I believe adding the 2nd interrupt disables the first. Use a single interrupt with CHANGE. Also, digitalPinToInterrupt() might help.

@JamesWaldby-jwpat7 thanks. But does this explain the lack of the 1 sec delay as well? i.e. does the ISR fails completely as is because of println()?

Neinstein, you missed what @JohnnyMopp is saying. Number '2' or '3' are not valid interrupts for the Pro Mini. The function digitalPinToInterrupt is preferred. https://www.arduino.cc/en/Reference/AttachInterrupt (read the whole page). No one sets two interrupts for a single pin, it does not work, a CHANGE does work. Set a volatile byte in the ISR and use that byte in the loop. If you have an encoder, why not use the Encoder library that you have already downloaded ? https://www.pjrc.com/teensy/td_libs_Encoder.html

@jot the Encoder libary does not support buttons AFAIK.

For the Arduino it is often not needed to use interrupts for buttons. For an embedded system, it is normal to connect buttons to interrupts, but it is not normal for the Arduino. When interrupts are needed, the sketch might be written in a bad way. The Bounce2 library handles button bounching and has useful functions: https://github.com/thomasfredericks/Bounce2 It uses normal digital inputs with digitalRead, no interrupts, and millis for debouncing.

Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.

They, however, refuse to work,

more accurately, you are unable to make them work.

don't delay large amount of time;
be careful with calling routines that are also called outside of the isr;
one isr for one pin.


text:
Why do i get additional characters when reading a file through a buffer if buffer size > 15?
This is a follow up question to How to speed up writing a file to a WifiClient?
I modified the old code to read from one Stream and write to another which looked like this and worked fine albite being a bit slow
while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

to use a buffer, like so
char buffer[300];
size_t bufferSize = sizeof(buffer);

// ...

while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize);

    client.print(buffer);
}
client.flush();

Now, if the buffer size is > 15 (in the above case, it's 300), two additional characters Øb are introduced after the buffer size amount of characters. If the buffer size is <= 15, this does not happen.
If the file to be read contains abcdefg repeated several times, I get the following result for a buffer size of 32:
|-------- 32 characters -------|Øb|-------- 32 characters -------|Øb|-----
abcdefgabcdefgabcdefgabcdefgabcdØbefgabcdefgabcdefgabcdefgabcdefgaØbbcdefg

What's causing those additional characters to appear?
The above output is produced in the browser If I do not specify a charset. if I do, I get � instead of Øb.

Try recording the actual number of bytes read and only write that number of bytes:
size_t nr = file.read(buffer, bufferSize);
client.write(buffer, nr);

That worked, btw. what's the matter with the downvotes? How can I improve my questions?

@cross Who knows? This place can be a bit fickle sometimes...

Since you are doing this for speed drop the memset() it's a waste of CPU cycles in this situation

You are quite right there. I have removed it from my example for clarification too.

If the buffer is full of data then there is no null terminator on your data to output, the client.print will keep going past the end of the buffer until it hits a 0. Because of the way the compiler is placing things in memory you happen to always get 0b and nothing else (does your code happen to have some other variable with a value of 11?)
There are two solutions:
Either only output the number of bytes you read (in which case the memset instruction is no longer needed) or limit the file.read to one less than your buffer size so that there is always a 0 left at the end of the buffer.
const int buffersize = 32;
char buffer[buffersize];

while (file.available() > 0)
{
    int bytes = file.read(buffer, bufferSize);
    client.write(buffer,bytes);
}

or
while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize-1);
    client.print(buffer);
}

Also it's more a personal preference than a requirement but I don't like to use sizeof(<array>), it only works within the same scope as the array definition and doesn't work if the array is passed to a function. This site is full of examples of people getting caught out by that and wondering why their array is always giving them a size of 4. So while it works fine in this instance I avoid using it if at all possible.

I am aware of the pitfalls of sizeof and had tried it with a macro definition to double check, but the result was the same. I will try your suggestions regarding the null termination. The question still stands: Why does this only happen if bufferSize > 15?

If the issue does turn out to be a lack of termination (the second option is the best way to prove that) then the reason is that the behavior without the termination is completely undefined. It could well be that with a smaller buffer the compiler placed things in memory in a different way such that there always happened to be a 0 in the byte after the buffer.