message:
The code is working fine with Arduino Uno but not with NodeMCU

I uploaded program MPU6050_DMP6_Multiple.ino (https://github.com/eadf/MPU6050_DMP6_Multiple/blob/master/MPU6050_DMP6_Multiple.ino) to Arduino Uno and it works fine.
When I upload the very same code to NodeMCU 1.0 board in Arduino IDE I have this message from the compiler :

Errors :

    Arduino: 1.8.5 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (3M SPIFFS), v2 Prebuilt (MSS=536), Disabled, None, 115200"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
    Using board 'nodemcuv2' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
    Using core 'esp8266' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
    Detecting libraries used...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev\I2Cdev.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire\Wire.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master\MPU6050.cpp" -o "nul"
    Generating function prototypes...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp.o"
    In file included from C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/Arduino.h:244:0,

                 from C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp:1:

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: error: __c causes a section type conflict with __c

    #define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                                   ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

    #define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                            ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

    #define F(string_literal) (FPSTR(PSTR(string_literal)))

                                  ^

    C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino:225:20: note: in expansion of macro 'F'

     Serial.println(F("FIFO overflow!"));

                    ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: note: '__c' was declared here

    #define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                                   ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

    #define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                            ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

    #define F(string_literal) (FPSTR(PSTR(string_literal)))

                                  ^

    C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master/DeathTimer.h:45:22: note: in expansion of macro 'F'

         Serial.print(F("S:")); Serial.println(time % 60);

                      ^

    Using library I2Cdev in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev (legacy)
    Using library Wire at version 1.0 in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire
    Using library MPU6050_DMP6_Multiple-master in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master (legacy)
    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I am not so good in programming to understand what I can do to solve the problem !
I'd like to use NodeMCU with two MPU6050 and I need help !

body:
It is [an issue][1] in esp8266 Arduino core. It is hard to explain, but here is a workaround for you:

In MPU6050_Wrapper.h change word `__FlashStringHelper` to `char` for function `halt` to be `void halt(const char* errMessage = NULL)`.

In DeathTimer.h remove `#include <Arduino.h>`.

In sketch add before includes `#define F(s) s` to hide the F macro.

  [1]: https://github.com/esp8266/Arduino/issues/2078


sender: user

message:
Is it okay to short IN and GND pins of relay module with controller ground?

I have this [relay module][1] that is attached to an ESP8266 ([Wemos D1 Mini][2]). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from [an external power supply][3]

The circuit diagram can be found [here][4].

The module works fine and all but I am wondering: is it okay to operate it like this ?

[![circuit diagram][5]][5]

  [1]: https://arduinomodules.info/ky-019-5v-relay-module/
  [2]: https://wiki.wemos.cc/products:d1:d1_mini
  [3]: https://eu.mouser.com/ProductDetail/MEAN-WELL/IRM-03-5?qs=NKmfXavxMazJdFbXlu0eDA==
  [4]: https://easyeda.com/stefanpruneanu/smart-switch
  [5]: https://i.stack.imgur.com/RdcgS.png

sender: assistant

body:
You mean that you pull your Arduino relay control pin LOW, causing it to ground the pin? Yes, that sounds correct. (And you would set it HIGH to not energize the relay.) You might need a low value resistor between the relay's logic pin and the Arduino output if the relay is sinking too much current through the Arduino logic pin. A 100 ohm resistor would prevent sinking too much current through the Arduino logic pin. Try it and see if the relay still energizes.

## EDIT:

When I posted my answer the image wasn't loading, so I had to guess as to what you were describing. My guess was wrong, and thus my answer was wrong too.

Since you're driving the gate of a transistor you will need a current limiting resistor or you will overload the logic pin on your microcontroller. (As Jot says in their answer.)

There are 3.3v versions of these logic-driven relay modules readily available, and some even include optical isolation, so why not use one of those?

Take this one for example: https://www.adafruit.com/product/3191
(I don’t think that one has optical isolation.)


body:
It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.

The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "*5VDC to 12VDC (some boards may work with 3.3)*" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.

Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.

Could try to connect the collector only the IN pin? As in the schematic below.

[![schematic][1]][1]

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

----------

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.

  [1]: https://i.stack.imgur.com/ZBQr9.png


message:
strcat char concatenation trouble

Still don't understand about char concatenation.

    void setup() {

      testCounter(3);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

    char testCounter(int countx){
      char a[10];
      strcpy(a, "COUNTER: ");
      strcat(a, printDigits(countx));
      return a;
    }

    char printDigits(int digits){
      char a[3];
      if(digits < 10) {
        strcpy(a, "0");
        sprintf(a,"%d",digits);
      } else {
        sprintf(a,"%d",digits);
      }
      return a;
    }

Error:  *invalid conversion from 'char' to 'const char*' [-fpermissive]* in `testCounter` line:

    strcat(a, printDigits(countx));

Don't understand this part of error.

`printDigits` function return char, so... `strcat` should be work. But why still error?

Please help...

body:
<!-- language: lang-c++ -->

    char printDigits(int digits){

You are telling the compiler you will return **one** character.

<!-- language: lang-c++ -->

     char a[3];

`a` is three characters. Thus the declaration doesn't match.

---

You could change the declaration to:

<!-- language: lang-c++ -->

    char * printDigits(int digits){

But even that would be bad because `a` would go out of scope after the function returns.

---

<!-- language: lang-c++ -->

     char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

---

The simplest way of doing what you seem to be wanting is:

<!-- language: lang-c++ -->

    void setup() {
      Serial.begin (115200);
      testCounter(3);
    }

    void loop() {
    }

    char testCounter(int countx){
      char a[15];
      sprintf (a, "COUNTER: d", countx);
      Serial.println (a);
    }

---

Also, here:

<!-- language: lang-c++ -->

      if(digits < 10) {
        strcpy(a, "0");
        sprintf(a,"%d",digits);
      } else {

That won't work because you are putting "0" into `a` and then **overwriting** it with `sprintf`.

---

> `printDigits` function return `char`, so... `strcat` should be work. But why still error?

Look at the prototype for `strcat`:

http://www.cplusplus.com/reference/cstring/strcat/

It expects `char *` not `char`. They are different things. One is a pointer, one isn't.


message:
Analog vs Digital Accelerometers - pro's and con's?

For my project i need to measure accelerations up to 16g. My options are either digital accelerometers such as the MPU6050 or MPU9250 or an analog accelerometer such as the ADXL326.

What are any major pro's and con's of each. number of wires would be almost equal. the digital accelerometer is less pins on the board but i could easily use analog to digital convertors to bypass that. sampling rate is lower at 550Hz for the analog vs 4000Hz for the MPU9250. However i believe 550Hz would be more than adequate. And the biggest difference for me. £2 for an MPU9250 and £12 for the ADXL326!

Does anyone have any general advice on the main differences when choosing between analog and digital? I am measuring suspension motion on a motorcycle and need 5 of these accelerometers.

body:
The biggest difference is where the measurement (the conversion to digital) is done.  On the digital accelerometer, it is done in the accelerometer itself. On the analog one it is done at the MCU.

For simple arrangements where the accelerometer is near the MCU that makes no difference. However the analog one is more susceptible to noise. With longer wires / traces between the accelerometer and the MCU you can get less accurate results with an analog one since it picks up noise which you are then sampling and including in your results.

The digital one is more immune to that kind of interference - instead it is susceptible to digital noise - corruption of the data as it traverses long wires. But that is less of a problem since it takes far more induced voltage to corrupt a digital signal than an analog one.

One other main difference is that you are limited to the ADC that is in the digital accelerometer. If you want a different resolution you have to use a different accelerometer. With analog, since it has no inherent resolution, you sample at the resolution of your MCU's ADC.

Digital is also easier to interface in modern systems.  Many SoCs don't have analog inputs. So adding an analog accelerometer would mean adding an ADC chip as well - and you don't really want to do that in something like a mobile phone.

So in summary:

* Digital is the most convenient, reliable and suitable for current basic uses
* Analog is more of a niche product that is rarely used in consumer electronics


body:
The ADXL326 is only an accelerometer.
When you have one, you can measure the output of the sensor with a oscilloscope. For the final project a digital sensor is preferred as @Majenko has explained in his answer.

The MPU-9250 is an accelerometer, gyro and magnetometer. That makes it possible to use sensor fusion (combining the sensors with software calculations for a much improved result).

Are there vibrations involved? An accelerometer is sensitive for vibrations. I doubt if an accelerometer can be used to measure the suspension motion.

By the way, I'm ignoring the MPU-6050 and so should you. The MPU-9250 is less noisy.


message:
Debugging a Nordic MCU (feather NRF52) using Segger J-Link

I have an Afafruit NRF52 board with SD 132 and 5.1 dual fw bootloader.
I implemented RTT logging and controlling (input) and the code is compiled using arduinoBuilder with RTT and debug level 3.
The device uses to control DALI lights but sometimes it hangs, I can see that it does not responses to input and light level never changes.

I want to debug it, maybe getting a stacktrace to see where it hangs, hoping it's a software issue.

Any leads on how to do that ?
Tutorial maybe ?

body:
I haven't tried this, but [OpenOCD](http://openocd.org/) supports both the nRF52 and the JLink.  Something like (on Linux):

    openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

might start OpenOCD.

You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).

You can find information about using gdb with OpenOCD [here](http://openocd.org/doc/html/GDB-and-OpenOCD.html) and [here](http://openocd.org/doc/html/General-Commands.html).


message:
Leonardo - always on power, status remains between computer reboots?

I'm looking for two answer here.

 1. Is it possible to power a Leonardo to be always on, separate from the power from the USB host - I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that. I've bought a battery shield too which will be arriving soon.

 2. I want it be power-able via a switch with batteries so that I do a few things. For a start avoid it's boot up time and have it pressing a key as soon as the booted computer sees it (I'm running it as a keyboard/mouse via USB-HID) and also at one point I have the computer send serial data to have the Arduino run a different part of it's code...at this point the host computer reboots. Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

Do I need to change code, or libraries to achieve any of this?

With the theory intact answered, here is some of my actual code, i've stripped most of it out as it's just a bunch of keyboard presses

    #include <Keyboard.h>
    #include <Mouse.h>
    char returnKey = KEY_RETURN;
    char tabKey = KEY_TAB;
    void setup() {
    Keyboard.begin();
    Mouse.begin();
    // delay(60000); //Deploy Delay
    delay(3000); //Testing Delay
    // Keyboard commands
    Keyboard.write(returnKey);
    delay(14000);
    // Welcome Screen
    Mouse.click(MOUSE_LEFT);
    delay(100);
    }

    void loop() {
    }

body:
> Is it possible to power a Leonardo to be always on, separate from the power from the USB host

Yes, that is what the barrel jack is for.

> I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that.

Then your code is wrong. Are you using `while (!Serial);` or something similar near the top of your code?

> For a start avoid it's boot up time

The most certain way of doing that is to not use the bootloader. Instead program the board directly with a hardware programmer disabling (or erasing) the bootloader.

> Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

The Leonardo only reboots if you open the serial port at 1200 baud, or toggle the RESET pin / button.

> Do I need to change code, or libraries to achieve any of this?

It sounds like you may need to, yes - since it's not working at the moment when if the code were correct it should work.

----

**IMPORTANT**

**Most computers will not recognize the Leonardo until the operating system is fully booted. This means you cannot use the Leonardo to interact with the BIOS or boot menu. The Leonardo does not implement the "Boot Protocol" keyboard which is required to interact with the BIOS or other pre-boot environment.**


body:
It is possible to tell if the computer has opened or closed the serial port.

The serial port is located on the Arduino board.
By testing `if(Serial)` you can check if the serial port has been made active by the computer.
You could send keyboard and mouse events after it became active.

The fading in and out of the led at pin 13 is done by the bootloader. You could upload the sketch with a programmer to run without bootloader.

As far as I know, even without bootloader the serial port is still created.
The Teensy boards have a little more control over the USB interface.

To know what is going on and when a computer is connected, a mini linux computer is a lot easier. For example a Raspberry Pi.
The ATmega32u4 of the Arduino Leonardo has the possibilities and the information is available, but as far as I know, there are no libraries functions to use it.


message:
(Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light

int RlightPin=0;  //pin for right Photoresistor
    int LlightPin=1;  //pin for left Photoresistor
    int TranslateAnalogR=0;
    int TranslateAnalogL= 1;
    #include <Servo.h> //Servo library.
    int pos=90; //Declare and initialize the variable pos.
    int servoPin=9; //Servo connected to pin 9
    int servoDelay=10; //Time motor waits before working again.
    Servo myArms; //Servo object called myArms

    void setup() {
    Serial.begin(9600); //Start serial communication.
    pinMode(7,OUTPUT);
    pinMode(servoPin,OUTPUT);
    myArms.attach(servoPin);

    }

    void loop() {

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

    Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
    TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

    if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
    myArms.write(pos); // sets the servo position according to the scaled value
    delay(servoDelay);// waits for it to get to the position

    }

    if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
    for (pos=0; pos>=40; pos=pos+1)  {
      myArms.attach(servoPin);
      myArms.write(pos); //send servo to pos
      if(TranslateAnalogR=TranslateAnalogL){
      myArms.detach();}
    }
    }

    if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
    for (pos=0; pos>=40; pos=pos-1){
       myArms.attach(servoPin);
       myArms.write(pos); //send sevo to pos
       if(TranslateAnalogL=TranslateAnalogR){
       myArms.detach(); }

    }
    }

    }

body:
There are many issues with this code:

    pinMode(7,OUTPUT);

What is this pin for? Why do you set it to `OUTPUT` and then never
actually output anything? If the pin is in use, you should declare a
constant for it, like

    const int fooPin = 7;

and then use the constant instead of the bare number 7.

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

`analogRead()` is a slow function, and it is quite inefficient to do the
analog to digital conversion twice. You can instead

    TranslateAnalogR = analogRead(RlightPin);
    Serial.println(TranslateAnalogR);

As a matter of style, I would remove the comments. Commenting code is
generally considered a good practice, as long as the comments tell
something non obvious, like giving the “big picture” or the rationale
for doing something in a particular way. Paraphrasing in English what
the code already says in C++ is useless.

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    //...
    Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

You won't know what value corresponds to the left and what value
corresponds to the right. I would instead do something like:

    Serial.print("L: ");
    Serial.print(TranslateAnalogL);
    Serial.print(", R: ");
    Serial.println(TranslateAnalogR);

Then:

    if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

You mean `==`.

    if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

The first test is redundant. If R>L, then obviously R≠L.

        for (pos=0; pos>=40; pos=pos+1)  {
            myArms.attach(servoPin);
            myArms.write(pos); //send servo to pos
            if(TranslateAnalogR=TranslateAnalogL){
                myArms.detach();
            }
        }

This is a very contrived way of searching the optimum. Normally you
attach the servo once and keep it attached all the time. Then you adjust
the position until you see the same illumination on both LDRs. This way
you keep track of the correct position and you need not redo the whole
angle scan every time. Also, this will not work for three reasons:

1. You mean `TranslateAnalogR==TranslateAnalogL` rather than
   `TranslateAnalogR=TranslateAnalogL`
2. `TranslateAnalogR` and `TranslateAnalogL` are not updated within the
   loop, you need to explicitly perform an analog read.
3. The loop will run too fast for the servos to follow the requested
   positions.

Later:

        for (pos=0; pos>=40; pos=pos-1){

The loop is backwards. You probably mean

        for (pos=40; pos>=0; pos=pos-1){

-------------------------------------------------------------------

Here is my take at this, completely untested:

    #include <Servo.h>

    // Pinout.
    const int PIN_LDR_R = 0;  // right photoresistor
    const int PIN_LDR_L = 1;  // left photoresistor
    const int PIN_SERVO = 9;  // servo

    const int SERVO_DELAY = 20; // time motor waits before working again

    int pos = 90; // servo position in degrees
    Servo servo;  // servo object

    void setup() {
        Serial.begin(9600);
        pinMode(PIN_SERVO, OUTPUT);
        servo.attach(PIN_SERVO);
    }

    void loop() {
        // Read and report light levels.
        int level_L = analogRead(PIN_LDR_L);
        int level_R = analogRead(PIN_LDR_R);
        Serial.print("L: ");
        Serial.print(level_L);
        Serial.print(", R: ");
        Serial.println(level_R);

        // Adjust the servo position.
        if (level_R > level_L && pos < 180)
            ++pos;
        if (level_R < level_L && pos > 0)
            --pos;

        // Update the servo.
        servo.write(pos);
        delay(SERVO_DELAY);
    }

A few things worth noting:

* Constants are qualified as `const` (it helps the compiler optimize and
  catch bugs) and spelled in full caps (a common stylistic convention).
* The servo position is adjusted step by step, one degree per loop
  iteration. No need to perform a full scan every time.
* The program does not do anything special when the light levels are
  equal, because in that case there isn't actually much to do.
* I increased the delay between servo updates to 20 ms, as
  the serial communication alone can take close to 19 ms per
  iteration.
* You may want to add some hysteresis in order to avoid the servo
  jitter when it has found the optimum.


message:
Calculate the Li-Po Battery Level in ESP-Wroom-02

I am very new to micro controller and circuits. I am not at all with this field. But trying to create a home project where I have a device image attached below.

[![enter image description here][1]][1]

This is 18650 Lipo battery powered device. Here **I want to calculate the battery level**. After doing some research on google I found that I need to have Voltage Divider which I think I already included in this with 220k ohms and 100k ohms

[![enter image description here][2]][2]

People are using different ways to calculate it. Which I found in few examples. Which I am not able to understand at all, that what formula or values they are referring to calculate it.

if someone can help to understand that will be helpful. Here is how I am coding it which I saw somewhere on internet itself.

          #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    //#include "DHTesp.h"

    #define DHT_PIN       16

    //SSID and Password of your WiFi router
    const char* ssid = "Asus";
    const char* password = "Xmv02488!!**";

    ESP8266WebServer server(80); //Server on port 80

    /***************************************************************
     * SETUP
     **************************************************************/
    void setup(void){
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);

      WiFi.begin(ssid, password);     //Connect to your WiFi router
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      //If connection successful show IP address in serial monitor
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP

      server.on("/", handleRoot);      //Which routine to handle at root location

      server.begin();                  //Start server
      Serial.println("HTTP server started");

      pinMode(LED_BUILTIN, OUTPUT);
      pinMode(A0, INPUT);

    }
    /***************************************************************
     * LOOP
     **************************************************************/
    void loop(void){
      server.handleClient();          //Handle client requests

    }

    /***************************************************************
     * This function converts IPAddress struct to a String
     **************************************************************/
    String IpAddress2String(const IPAddress& ipAddress)
    {
      return String(ipAddress[0]) + String(".") +\
      String(ipAddress[1]) + String(".") +\
      String(ipAddress[2]) + String(".") +\
      String(ipAddress[3])  ;
    }

    /***************************************************************
     * This rutine is exicuted when you open its IP in browser
     **************************************************************/
     void handleRoot() {
      IPAddress ip_address = WiFi.localIP();
      String ip_str = IpAddress2String(ip_address);

      int nVoltageRaw = analogRead(A0);
      float fVoltage = (float)nVoltageRaw * 0.00486;

      float fVoltageMatrix[22][2] = {
        {4.2,  100},
        {4.15, 95},
        {4.11, 90},
        {4.08, 85},
        {4.02, 80},
        {3.98, 75},
        {3.95, 70},
        {3.91, 65},
        {3.87, 60},
        {3.85, 55},
        {3.84, 50},
        {3.82, 45},
        {3.80, 40},
        {3.79, 35},
        {3.77, 30},
        {3.75, 25},
        {3.73, 20},
        {3.71, 15},
        {3.69, 10},
        {3.61, 5},
        {3.27, 0},
        {0, 0}
      };

      int i, perc;

      perc = 100;

      for(i=20; i>=0; i--) {
        if(fVoltageMatrix[i][0] >= fVoltage) {
          perc = fVoltageMatrix[i + 1][1];
          break;
        }
      }

      server.send(200, "text/plain", "Hello from esp8266!\n\rIP: " + ip_str +
        ".\n\rTemp: " + "NO" +
        ", Hum: " + "NO" +
        "\n\r" + "NO" +
        "\n\r" + "Voltage: " + fVoltage +
        "\n\r" + "Charge: " + perc + '%');
    }

This is a copied code. Where I am not sure about where they got the this formula and how they got the value of 0.00486

I copied this code from different source references. But I hope this will help you to understand the issue.

Any suggestions will be helpful!

Thank you! (In advance)

  [1]: https://i.stack.imgur.com/72QGO.png
  [2]: https://i.stack.imgur.com/aZuTb.png

body:
The problem with LiPo batteries is that the discharge curve is very flat.  Here's an example:

[![enter image description here][1]][1]

As you can see, for about 95% of the life of the battery there is very little change in voltage.  You can't just take the voltage between "full" and "empty" and get a percentage from that. Instead you have to map points along that curve to different percentages.

The simplest way is to just have a set of percentages that you are interested in - every 5% as in the code you have above. Then you say "If the voltage is above this value then it's 100%. If it's above this next value down it's 95%. If it's above the next value down then it's 90%". etc.

The array `fVoltageMatrix` contains that mapping.  For 100% the voltage must be 4.2V or greater.  For 95% it must be 4.15V or greater. And so on.

If we take those voltage values from the array and plot them on a graph they look like this:

[![enter image description here][2]][2]

As you see that looks kind of similar. Quite flat, with a sudden drop off.

The code that gets the percentage charge simply reads the value from the ADC and converts it to a voltage by multiplying it by 0.004861, then it steps through the array one element at a time. The first time it finds one that fails the test "This percentage's threshold is less than the voltage" makes it take the previous one in the list as the percentage.  Personally, I think that's backwards and a bad way of doing it.  Instead, it should be the first one that passes the test "The voltage is greater than or equal to this percentage's threshold" that should be taken.  I'd rewrite the loop like this:

    perc = 0;

    for(i=0; fVoltageMatrix[i][0] > 0; i++) {
      if(fVoltage >= fVoltageMatrix[i][0]) {
        perc = fVoltageMatrix[i][1];
        break;
      }
    }

----

1 The number 0.00486 is the number of volts applied to the input to give a 1 from the ADC. Incidentally, if I am using the right figures, I calculate it should be 0.003125.  1 * (1/1024) gives 0.000976563 (that's 1 volt maximum range on the ADC, multiplied by one bit - a 1024th since it's 10 bit resolution on the ESP8266). Multiply that by the ratio of the resistors ((R1 + R2)/R2) which is 3.2, and that gives 0.003125. To compress it, you get:  `x = (R1 + R2) / R2 * 1/1024` = `320000 / 100000 * 0.000976563` = `0.003125`

However, my numbers could be wrong...

  [1]: https://i.stack.imgur.com/Njfh3.png
  [2]: https://i.stack.imgur.com/bJ0aV.png


body:
One problem I have with the ESP8266 is the crappy results from the A/D converter. There are a number of hoops that you need to go through for the planets to align in order to get consistent readings. See  Fluctuating ADC with stabilized source https://github.com/esp8266/Arduino/issues/2070

The other issue I have is with the assumption that the range of operation of the A/D is 0-1.0 volts and that certainly is not the case.

> I calculate it should be 0.003125. 1 * (1/1024) gives 0.000976563
> (that's 1 volt maximum range on the ADC

The above shows how precise our calculations can be but unfortunately the six digits of precision gets thrown out the window if the assumed 1 volt top end has variations of 5%. Unfortunately there are no specifications given as far as the A/D converter in the miniscule spec sheet.

Yes the ESP8266 A/D can be calibrated, and measurements taken under controlled conditions. But make sure that you do the required work and verify the results under all operating conditions before you trust your results.


body: Another problem you can run into is that a lot of the A/D converters use the VCC as a voltage reference. Which means that as your input voltage drops (what you are trying to measure) the reference voltage also drops which means the values you are recording will not appear to change or at least will not give an accurate reference.


message:
Mega attachInterrupt on pins 18 or 19 require EIFR bit set first (to clear it)?

Experimenting with external interrupts on a Mega. Pins 2 and 3 work with standard

 `attachInterrupt(digitalPinToInterrupt(iPin),ISR,FALLING);`

coding and call my ISR. With pins 18 and 19 I had to add

    EIFR = 4;
for pin 19, and

    EIFR = 8;
for pin 18 before calling attachInterrupt(...) to get them to work. Why?

BTW, I'll add this table that I filled in by trial and error for anyone interested in Atmel (AVR) external interrupt numbers to Arduino external interrupt numbers (I won't list the AVR chip pin numbers)

    AVR INT      5 .  4 .  3 .  2 .  1 .  0
    EIFR (Dec)  32 . 16 .  8 .  4 .  2 .  1
    Arduino Pin  3 .  2 . 18 . 19 . 20 . 21
    Arduino INT  1 .  0 .  5 .  4 .  3 .  2

I know writing a 1 to the EIFR bit for the appropriate interrupt clears the interrupt. When I reset the Arduino without clearing interrupts on pins 2 and 3 it's fine. If I don't clear 18 and 19 after a reset, it throws the interrupt right away. (Yes, I should OR the EIFR with the bit I want to change but I'm just playing) Didn't try 20 and 21 because I'm using them for comm.

body:
It's not that pins 18 or 19 are faulty, you are just lucky the other ones worked.

As I mention on [my page about interrupts](http://www.gammon.com.au/interrupts)* you are recommended to always write 1 to the appropriate EIFR bit before enabling interrupts because it (the interrupt condition) may have been set in the past.

I checked the source for `attachInterrupt` in the file WInterrupts.c and there is no mention of the EIFR register, therefore `attachInterrupt` never affects that register.

---

\* Also see my answer: https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969


message:
Interfacing MPU6050 with Arduino uno

What is the meaning of "volatile bool mpuInterrupt = false; " in Arduino Program interfacing MPU6050?

body:
The i2cdevlib has that declared in this file: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino

That is the "dmp" example.
Inside the MPU-6050 sensor is a "dmp" and a FIFO buffer. The "dmp" is a processing unit that collects the sensor data, does some calculations and puts the data in the FIFO buffer. After that the Arduino is signalled with a interrupt.

In the Arduino, in the interrupt routine, the flag 'mpuInterrupt' is set. In the loop() that flag is checked and the amount of data in the FIFO buffer is read. When there is enough data, that data is read and used in the sketch.

Since the variable 'mpuInterrupt' is used in a interrupt routine and in the loop(), it is made 'volatile'. That tells the compiler that the variable can change at any moment, so the compiler can keep that in mind when creating binary code for the loop().


message:
How do I keep track of the time passed in this code? (PCR machine)

I am desperate need of help with my code. It is meant to be a biology project (a pcr machine) and I struggle with inplementing a time tracker. Everytime the cyclus goes to a function, I need it to save that exact time, and then lt it run for a certain amount of time (this variable is given in a parameter). So help is really really appreciated.

    //variabelen

    #include <Adafruit_MAX31855.h>

    int maxSO =  4;
    int maxCS = 5;
    int maxSCK = 6;

    Adafruit_MAX31855 thermocouple(maxSCK, maxCS, maxSO);

    int fan = 9; //connected to transistor base
    int temp;
    int tempMin = 18;   //variable to check if the thermocouple is connected
    int tempMax = 100;   //never exceed this temperature
    int fanSpeed;
    int RelayP = 3; //still got to check if it is 3 or 4
    int cyclusamount = 3; //still got to add a button

    //cyclussen op één rij
    float DENTEMP = 94;
    float ANTEMP = 62;
    float EXTEMP = 72;

    //tijden op een rij
    unsigned int INITDENTIME = 53000;
    unsigned int DENTIME = 33000;
    unsigned int ANTIME = 33000;
    unsigned int EXTIME = 33000;
    unsigned int ENDEXTIME = 42000;

    unsigned long timer1 = 0;
    unsigned long timer2 = 0;
    double temp;
    double MaxTempIncrease = 2;

    //int cycles = 0;
    int phase = 0;
    int a = 0;
    int g = -1;
    int phaseOfCyclus = 0;
    int timesArray[] = [33000, 33000, 33000];
    int tempsArray[] = [94, 62, 72];
    int cycluscounter = 0;

    const unsigned long startTime;
    unsigned long startMillis;

    void setup() {
      Serial.begin(9600);
      delay(500);
      pinMode(fan, OUTPUT);
      digitalWrite(fan, LOW);
      pinMode(RelayP, OUTPUT);
      digitalWrite(RelayP, LOW);
      delay(5500);
    }

    void loop() {
      //eerst is er een delay, na de delay zal a springen op a=1
    if(a == 0) {
        delay(1000);
        a++;
      }

    //wanneer a=1 geldt dan zal de temperatuur stijgen naar 94 graden, wanneer dit is bereikt wordt  a=2 en phaseOfCyclus=1
    else if(a == 1){
         raiseTemp(DENTEMP);
      }

    //wanneer a=2 geldt dan zal de temperatuur stabiel worden gehouden (dus 94 graden) voor de initiatie-stap duur, dat is ongeveer rond de 4minuten
    //wanneer deze tijd is verstreken dan wordt a=3 (en phaseOfCyclus=1 (nog steeds))
    else if(a == 2) {
        holdTemp(DENTEMP, INITDENTIME);
      }

    else if(a == 3) {

    //De eerste fase van één cyclus in de PCR machine begint met 94 graden voor 30 seconden.
    //de functie raiseTemp heeft 1 parameter en die wordt verkregen door het eerste getal uit de tempsArray
    //Is dit volbracht, dan wordt phaseOfCyclus=2
    if(phaseOfCycles = 1) {
      raiseTemp(tempsArray[1];
    }

    //de temperatuur wordt dan weer stabiel gehouden, de twee parameters geven de tijdsduur en de temperatuur van de fase waarin de cyclus van de pcr machine zich bevind
    //is dit volbracht en was phaseOfCyclus=2, dan wordt phaseofcyclus=3
    else if (phaseOfCyclus = 2) {
      holdTemp(tempsArray[1], timesArray[1]; //hoort 0

    }

    //dan zal de temperatuur afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=3 dan wordt phaseofcyclus=4
    else if (phaseOfCyclus = 3) {
      cooldown(tempsArray[2]; //hoort 1
    }

    //de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 4 dan phaseofcyclus=5
    else if (phaseOfCyclus = 4) {
      holdTemp(tempsArray[2], timesArray[2]; //hoort 1

    }

    //dan zal de temperatuur verder afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=5 dan wordt phaseofcyclus=6
    else if (phaseOfCyclus = 5) {
      cooldown(tempsArray[3]; //hoort 2
    }

    //de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 5 dan phaseofcyclus=6
    //bij één hele cyclus zal holdtemp 3x worden aangeroepen, elke keer als dit dus 3x gebeurt dan zal de cyclusamount +1 in hoeveelheid toenemen
    //als de cyclusamount niet gelijk is aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> phaseofCyclus = 1
    //is dit wel groter of gelijk aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> a =4  (als a = 3 en phaseofcyclus = 6)
    else if (phaseOfCyclus = 6) {
      holdTemp(tempsArray[3], timesArray[3]; //hoort 2
    }}

    //dan zal de extending temperatuur stabiel worden gehouden en als de tijd is verstreken dan zal a = 5 worden en zal de lcd zeggen dat de cyclus is volbracht
    else if (a == 4) {
       holdTemp(EXTEMP, 42000);
      }
    else if(a == 5) {
      digitalWrite(fan, LOW);
      digitalWrite(RelayP, LOW);
      Serial.println("Cyclus completed");
    }
    }

    void raiseTemp(double y) {
      double prevTemp = thermocouple.readCelsius();
      temp = thermocouple.readCelsius();

    if (temp < tempMin) {
       Serial.println("is the thermocouple connected???");
      }

    while (temp < y) {
        int waittime = min(650, ((650*(y-temp))));
        digitalWrite(RelayP, HIGH);
        delay(waittime);
        digitalWrite(RelayP, LOW);
        temp=thermocouple.readCelsius();

    if(temp >= y) {
        if(phaseOfCyclus = 1) {
          phaseOfCyclus = 2;
          a = 3;
        }
        else if (phaseOfCyclus = 0){
          phaseOfCyclus++;
          a = 2;
        }
          // break; //wat doet dit precies?
        }

    if((y-temp) < 1) {
          do  {
            prevTemp = temp;
            delay(250);
            temp = thermocouple.readCelsius();
          }
          while(temp > prevTemp);
        }

    if(temp >= TempMax)
         break;

    else {
          prevTemp = temp;
       }

       while ((temp-prevTemp) >= MaxHeatIncrease) {
         prevTemp = temp;
         Serial.print("HEATING UP TOO FAST! ");
         delay(1000);
         temp = thermocouple.readCelsius();
         Serial.println(temp);
       }

       while(temp >= y) {
         delay(1000);
         Serial.print("DANGER DANGER DANGER");
         Serial.println(temp);
       }
    }}

    void holdTemp(double phaseTemp, double duration) {
      g++;
      z = phaseTemp;

      startMillis = millis();
      unsigned long whatitneedstobe = startTime + duration;
      //startMillis < whatitneedstobe

      if(timegone < duration){
            temp = thermocouple.readCelsius();
          if(temp < z) {
            digitalWrite(RelayP, HIGH);
            delay(90);
            digitalWrite(RelayP, LOW);
          }
          else if (temp > (z+0.5)) {
            digitalWrite(fan, HIGH);
            delay(90);
            digitalWrite(fan, LOW);
            //or
            //fanSpeed = map(temp, tempMin, y, 32, 255);
            //analogWrite(fan, fanSpeed);
          }
         delay(210);
         timegone = millis() - startTime;
         }

      else {
        if(phaseOfClus = 1) {
          a = 3;
        }
        else if(phaseOfCyclus = 2) {
          phaseOfCyclus = 3;
        }
        else if(phaseOfCyclus = 4) {
          phaseOfCyclus = 5;
        }
        else if(g == 3) {
        g = 0;
        cycluscounter++;
        if(cycluscounter < cyclusamount) {
          a = 3;
          phaseOfCyclus = 1;
        }
        else(cycluscounter >= cyclusamount {
          a = 4;
        }
      }
      else if(a = 4) {
        a = 5;
      }
        }
      }

    void cooldown(double c) {
      unsigned long startTime = millis();
    while ((temp = thermocouple.readCelsius()) > (minTemp+0.75)) {
        digitalWrite(fanPin, HIGH);
        delay(300);
       }
       digitalWrite(fanPin, LOW);
    if(thermocouple.readCelsius() == c){
      if(phaseOfCyclus = 3) {
        phaseOfCyclus = 4;
      }
      else if(phaseOfCyclus = 5) {
        phaseOfCyclus = 6;
      }
    }
    }

body:
If you want the `holdTemp()` function to run for a specified duration,
you can write it like this:

    void holdTemp(double phaseTemp, unsigned long duration) {
        unsigned long start_time = millis();
        while (millis() - start_time < duration) {
            // whatever...
        }
    }

Note that if you use `delay()` inside the function, the time spent in it
may get longer than the requested duration, by as much as the duration
of the delay.


message:
Connecting TFT Display MI0283QT-9A to ESP32

I have purchased a MI0283QT-9A TFT display (https://download.mikroe.com/documents/add-on-boards/other/display/tft-proto/tft-proto-manual-v200.pdf) which is
driven by the ILI9341 display controller.

I've managed to find the following board specification: http://pub.ucpros.com/download/tft_320_240_mi0283qt_9a_v1_3_spec.pdf

First of all, the pins are named differently from all the examples I can find for connecting it to my ESP32 microcontroller. For example, the TFT specs describe:

    33 SDO Serial Output Signal
    34 SDI Serial Input Signal
    35 RD Read execution control pin
    36 WRX(D/CX) Write execution control pin ; Serial Register select s Signal
    37 D/CX(SCL) Register select signal; Serial Interface Clock
    38 CSX Chip Select Signal
    39 TE Tearing effect out pin synchronize MPU to frame writng

But this Adafruit ILI9341 example (https://github.com/adafruit/Adafruit_ILI9341/blob/master/examples/graphicstest/graphicstest.ino) talks about CS, DC, MOSI, CLK, RST, and MISO.

I think these map as follows, **can anyone confirm that**?

    ESP32 = TFT
    --------------
    DC    = RS
    CLK   = WR, although maybe it should connect to DC???
    CS    = CSX
    MOSI  = SDI
    RST   = RST
    MISO  = SDO

I'm really unsure about the first two!

Second, in the PDF it refers to note 1 on page 11:

[![enter image description here][1]][1]

So as far as I can tell, I need to set the voltage high/low on the four IM* pins, depending upon the interface I want to use. So the second question is **which interface does the Adafruit ILI9341 library use**?

  [1]: https://i.stack.imgur.com/FcfbK.png

body:
It sounds like you want a 4-wire 8-bit serial SPI compatible interface.  To get that you have to set the IMx pins to the right state to enable that interface.  That means:

* IM0 = LOW
* IM1 = HIGH
* IM2 = HIGH
* IM3 = HIGH

You can hard-wire those to GND for LOW and +3.3V for HIGH.

That will then configure it to work in the right mode for you, where it gives you access to the following pins:

    | Display  | ESP32   | Function                    |
    |----------|---------|-----------------------------|
    | SCL (RS) | SCK     | Serial clock                |
    | SDI      | MOSI    | Serial data Master -> Slave |
    | SDO      | MISO    | Serial data Slave -> Master |
    | D/CX (WR)| DC      | Data / Command register sel |
    | CSX      | CS      | Chip Select (Active Low)    |
    | RST      | RST     | Reset                       |


body:
Same (TFT proto board) tested Arduono DUE.

Pins IM1-3 HI, IM0 LO. (4-wire 8-bit data serial interface)

SDI - MOSI, SDO - MISO,RS - CLK, RD - HI, WR - D9, CS - D10, Reset - Reset (D8)

Driver UTFT myGLCD (ILI9341_S5P, MOSI, SCK, 10,8,9);

or

    // For the Adafruit shield, these are the default.
    #define TFT_DC 9
    #define TFT_CS 10
    Adafruit_ILI9341 tft = Adafruit_ILI9341 (TFT_CS, TFT_DC);

Backlight needs resistor!


message:
Arduino MKR GSM 1400 SSL client example fails to connect

I am using the GsmSSLWebClient example which comes with the MKRGSM library.
The original example works just fine, I get the arduino ascii logo. But when I change the URL the arduino doesn't get any answer:

    //char server[] = "arduino.cc";
    //char path[] = "/asciilogo.txt";
    char server[] = "wepardi.fi";
    char path[] = "/robots.txt";

    Starting Arduino web client.
    connecting...
    connected
    GET /robots.txt HTTP/1.1
    Host: wepardi.fi
    Connection: close

    disconnecting.

From Firefox https://www.wepardi.fi/robots.txt is displayed correctly.
I tried also some other sites, and from some of them I get the ascii file content correctly, and from some others not.

Something wrong with my settings?

Prints from debug mode:

    connecting...

...

    AT+USECMNG=0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5",1239
    >
    +USECMNG: 0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5","cb17e431673ee209fe455793f30afa1c"

    OK
    AT+USOCR=6

    +USOCR: 0

    OK
    AT+USOSEC=0,1,0

    OK
    AT+USECPRF=0,0,1,4,"www.wepardi.fi"

    OK
    AT+USOCO=0,"www.wepardi.fi",443

    ERROR

    +UUSOCL: 0
    AT+USOCL=0

    ERROR
    connected
    GET /robots.txt HTTP/1.1
    Host: www.wepardi.fi
    Connection: close

    disconnecting.

Command
    AT+USOCO=0,"www.wepardi.fi",443
fails

GsmWebClient (no SSL) example works fine with any hosts I have tried.

body:
The problem you have is that of redirection.

You connect to `wepardi.fi` and request the file `/robots.txt` from that host. It immediately tells you "Ok, but that file is actually on `www.wepardi.fi/robots.txt`. Go get it from there.

But it won't.

You have to go direct to the source.

Here's a trace:

    GET /robots.txt HTTP/1.1
    Host: wepardi.fi
    Connection: close

    HTTP/1.1 302 Found
    Date: Tue, 08 Jan 2019 14:26:51 GMT
    Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
    Strict-Transport-Security: max-age=63072000; includeSubdomains;
    X-Powered-By: PHP/7.0.32
    Location: https://www.wepardi.fi/
    Cache-Control: max-age=1296000
    Expires: Wed, 23 Jan 2019 14:26:51 GMT
    Content-Length: 0
    Connection: close
    Content-Type: text/html; charset=UTF-8

And when you change to `www.wepardi.fi`:

    GET /robots.txt HTTP/1.1
    Host: www.wepardi.fi
    Connection: close

    HTTP/1.1 200 OK
    Date: Tue, 08 Jan 2019 14:27:49 GMT
    Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
    Strict-Transport-Security: max-age=63072000; includeSubdomains;
    X-Powered-By: PHP/7.0.32
    X-Robots-Tag: noindex, follow
    Link: <https://www.wepardi.fi/wp-json/>; rel="https://api.w.org/"
    Cache-Control: max-age=300
    Expires: Tue, 08 Jan 2019 14:32:49 GMT
    Content-Length: 67
    Connection: close
    Content-Type: text/plain; charset=utf-8

    User-agent: *
    Disallow: /wp-admin/
    Allow: /wp-admin/admin-ajax.php
    read:errno=0


body:
I finally found a solution to this problem. Disabling certificate validation in MKRGSM library makes the SSL connection succeed also to this site. In MKRGSM/src/GSMClient.cpp I changed

    //     MODEM.sendf("AT+USECPRF=0,0,1,4,\"%s\"", _host);
           MODEM.sendf("AT+USECPRF=0");

to use modem factory settings. I still don't know what was the problem with the certificates.
Thanks to everyone who tried to help with this.


message:
Voltage meter ADC + serial: Bytes lost during communication

I want to make a simple digital voltage monitor. So I have a sketch:

    void setup() {
      Serial.begin(115200);
    }

    void loop() {
      int val = analogRead(A4);     // read the input pin
      val = 1;
      byte buf[4];
      buf[0] = 0;
      buf[1] = 0;
      buf[2] = val & 255;
      buf[3] = (val >> 8) & 255;
      Serial.write(buf, 4);             // report voltage value
    }

When I tried to read serial buffer on PC host, I noticed that sometimes 1 byte can be lost, which lead to shifts and headache. How should the streaming be done?

---
PS.

- host os: win7 x64;
- language: c/c++
- com port library: [CSerial](https://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c2503/CSerial--A-C-Class-for-Serial-Communications.htm)

---
Loop is as follows:

    typedef int32_t sample_t;
    while (true) {
     int nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(sample_t));
     size_t numRead = nBytesRead / sizeof(sample_t);
     if (numRead > 0)
      std::cout << "read: " << numRead << " samples\n"; // Calculate average here!
    }

body:
With help in a comments I've managed to deal with the task myself.

First of all, as @Majenko pointed out, I was dealing with some multi-byte data. So I need some control character, that separates packets. I choose hex output with '\n' delimeter as control character - that served good. I was able to read 3.5 to 5k packets per second (with voltage reading) from serial on the host.

Second improvement, credited to @Jot, is to stack some sequential values right in arduino, before sending.

Alongside with [increasing sampler frequency](http://yaab-arduino.blogspot.com/2015/02/fast-sampling-from-analog-input.html) that could be very good.

    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

    void setup() {
      sbi(ADCSRA, ADPS2);
      cbi(ADCSRA, ADPS1);
      cbi(ADCSRA, ADPS0);
      Serial.begin(115200);
    }

    void loop() {
      int val = 0;
      for( int i = 0; i < 32; ++i )
        val += analogRead(A0);
      Serial.print(val, HEX);
      Serial.print("\n");
    }

at the host recieve side, some simple conversion could be done:

    #include "Serial.h"
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <ctime>

    // sample to voltage
    double s2v(int sample) {
     return 5.0 * (static_cast<double>(sample) / 1024);
    }

    int main() {
        std::ofstream ofs("test.csv", std::ios::out | std::ios::ate);

     size_t comPort = 3;
     size_t baudRate = 115200; // 57600;

     CSerial serial;
     if (serial.Open(comPort, baudRate))
     {
      std::cout << "COM" << comPort << " opened @" << baudRate << "bit/s\n";

      // serial recv buffer
      size_t bufSize = 1048576;
      auto lpBuffer = new char[bufSize];

      // accumulator
      size_t nVals = 0;
      int nAcc = 0;

      // timer
      __time64_t destTime;
      __time64_t destTime2;
      _time64(&destTime);

      while (true) {
                SleepEx(10, false); // care of 100% cpu core usage, poll serial port lazily
       size_t nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(lpBuffer[0]));

       //parse buffer:
       size_t cvtPtr = 0;
       for (size_t i = 0; i < nBytesRead; ++i) {
        if (lpBuffer[i] == '\n') {
         try {
          lpBuffer[i] = '\0';
          auto val = std::stoi(lpBuffer + cvtPtr, nullptr, 16);
          nAcc += val;
          nVals++;
         }
         catch (...) {
          // ignore, or warn that serial recieved junk/empty packet
         }
         cvtPtr = i + 1;
        }
       }

       //check if doom had come!
       _time64(&destTime2);
       if ((destTime2 - destTime) > 0) {
        auto fVoltage = ( s2v(nAcc) / 32 ) / nVals;
        std::cout << fVoltage << "\t(" << nVals << " ksps)\n";
                    ofs << destTime << "," << fVoltage << "," << nVals << "\n";
        if((destTime % 30 ) == 0) // care of disk, write only once in 30 seconds
         ofs.flush();
        destTime = destTime2;
        nVals = 0;
        nAcc = 0;
       }
      } // while
     } // if opened
     return 0;
    }

That gives voltmeter with high precision, about ±0.5mV, that is updated every second.

Also! It was stated about 10bit adc, 5.0V/1024 = 4.88mV, but i got some subthreshold oscillations in vivo, adding samples up. So you are wrong, noise can be attenuated and resolution can be artificially pumbed up, in a trade for increased sampling time. Here is 14bit ADC built on top of 10bit ADC: [![enter image description here][1]][1]. Its photovoltaic cell in a dark street, oscillations are caused by cars' front lights. Timescale is 1000 seconds per grid div

  [1]: https://i.stack.imgur.com/WNaYa.png


message:
Calculate burden resistor value of current transformer and measure ac current with arduino

I Want to measure AC current with current transformer but i dont know exact value of burden resistor or calculation formula...i want to measure current of borewell pump. company specified pump as 1.5Hp power.

[![current transformer ][1]][1]

  [1]: https://i.stack.imgur.com/BOhB5.jpg

body:
There is no "You need X resistor for Y transformer". The resistor you choose depends on what current range you are working with and what voltage range you want that to be expressed as.

That transformer is a 100:5 (or more properly a 20:1) ratio.  That means for every 20A going through it you get 1A out.

That output current is then passed through a burden resistor and you measure the voltage across that resistor.

If you are, for example, working with sensing up to 1A current then the maximum current you'd get out of it would be 1/20A, or 50mA.  If you want that to be expressed reliably within the range of a 5V ADC then you would:

1. Work from the mid-range of the ADC as 0V to give ±2.5V (assuming AC)
2. Calculate the resistor that gives 2.5V across it when 50mA is passed through it
3. Pick the next-lowest common resistor value.
4. Reverse the calculation to get the voltage range you now have.

In this example, R=V/I, so 2.5/0.05 = 50Ω.  50Ω resistors aren't common, but 47Ω ones are, so you'd pick that.

Then reversing it gives V=IR = 0.05 * 47 = ±2.35V

Give it a 2.5V offset to the ADC and you can now read points on a sinewave between 0.15V and 4.85V at 1A sensed current.


message:
Command through Serial monitor does not properly work in Arduino

I am executing a function in Arduino by giving String input to the serial monitor.

The issue here is when I enter `SHOW$`, the function `showData()` works but when I enter the same `SHOW$`, it doesn't gets called.
I want to call the function `showData()` every time i enter the `SHOW$` text into the serial console.

My question here is to what mistake I am doing here, and what is the solution for this.

    String strReq = "";
    char inChar = 0;

    void setup() {

      Serial.begin(9600);

    }

    void loop() {

      while (Serial.available())
      {
        inChar = Serial.read();

        if (inChar == '$') {

         Serial.println(" Received String :");
         Serial.print(strReq);

         if (strReq.equalsIgnoreCase("SHOW"))
           showData();

         Serial.flush();
         strReq = "";

        } else {

          strReq = strReq + inChar;
        }
      }
    }

    void showData() {
      Serial.print("Showing Information");
    }

body:
The solution was to use String.trim() function.
Thanks guys for giving a quick reply on the question.


body:
The root of your problem seems to be not knowing what `Serial.flush()` does.

It pre-Arduino 1.0.0 times `Serial.flush()` used to clear any data in the serial's RX buffer. It would throw it away.  In your code that would throw away the line ending `\r\n` that is sent along with the command.

However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer.  This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.

This change was not widely documented, but it is mentioned in the manual:

> Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with `Serial.flush()` acting like it does in current versions, you would get a different string the second time around.  You would see:

    SHOW$
    \r\nSHOW$
    \r\nSHOW$

and so on.

You have come up with a "fix", which uses `String::trim()` to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings.  However it would be far better to ignore them in the first place and not need to do the trimming.

The simplest way would be to only add characters to your string if they are printable:

    if (inChar == '$') {
     Serial.println(" Received String :");
     Serial.print(strReq);
     if (strReq.equalsIgnoreCase("SHOW"))
       showData();
     Serial.flush();
     strReq = "";
    } else if (inChar >= ' ') { // << Only add if a space or above
      strReq = strReq + inChar;
    }

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.


message:
2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage

hi does anyone know how to

1) set Max Brightness

2) change the start up splash screen from being white to black

3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

The code from the sketch may answer some of your tecnical question re the environment i am working with

    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_TFTLCD.h> // Hardware-specific library

    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0

body:
> 1) set Max Brightness

You set the brightness of the backlight (usually) using PWM.

> 2) change the start up splash screen from being white to black

That's not a splash screen. That's just the back light being on before the screen is initialised. Just don't turn on the back light until you need it.

> 3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

Either do it in software (tricky) or look at the MADCTL (many have it called that) register in the datasheet.  The library probably won't support it, but it's part of how it deals with display rotation, so you could examine that function and compare it with what's in the datasheet (hint: 180° rotation is actually flipping both the X and Y axis).


message:
SIM900/Arduino UNO R3 serial communication not working

For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial.
I tried several ways to wire it up:
shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial.
shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial.
shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial.
Tried even different pins other than 7 & 8. None worked.
I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop.
Any suggestions ?
Here's the code:

    #include <SoftwareSerial.h>

    //Create software serial object to communicate with SIM900
    SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

    void setup()
    {
      //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);

      //Begin serial communication with Arduino and SIM900
      mySerial.begin(9600);

      Serial.println("Initializing...");
      delay(1000);

      mySerial.println("AT"); //Handshaking with SIM900
      updateSerial();

      mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
      updateSerial();
      mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
      updateSerial();
      mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
      updateSerial();
      mySerial.write(26);
    }

    void loop()
    {
    }

    void updateSerial()
    {
      delay(500);
      while (Serial.available())
      {
        mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(mySerial.available())
      {
        Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
      }
    }

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

body:
> And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

There aren't.  There is only one of each. They just have them in multiple convenient places.

J11 selects the pins to use on the shield. Make sure that is set to D7 and D8. You then use pins D7 and D8 on the shield. Normally that would be mounted directly onto an Arduino and you would just use those pins in your code.

However, if you want to attach it to something that doesn't have an Arduino UNO footprint you can solder wires to the TX/RX pins in the J10/J17 "UART" header. That ignores the J11 jumpers, which only pertain to using the Arduino UNO shield headers.

As to why you can't communicate, my guess is:

* You have 9600 baud in your code:

----
    mySerial.begin(9600);

However, on the Amazon product you linked to:

> The factory default setting for the GPRS Shield UART is 19200 bps 8-N-1. (Can be changed using AT commands).

Using 19200 instead of 9600 should improve matters somewhat.


body:
To make everything work fine with this exact code and wiring from the *[lastminuteengineers][1]*, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins **D8(RX)** and **D7(TX)**, which are the pins at the top of the **yellow plate**, to the two pins in the middle of the **yellow plate**.

  [1]: https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/


message:
RN4678 Bluetooth doesn't respond

I am facing very basic level issue with RN4678. I purchased a module from https://www.mikroe.com/rn4678-click

I want to simply communicate with it through serial port.  To do that I connected it to PC by usb to TTL. Whatever I send, I don't get any response from module.  Then parallely I paired it with mobile phone and on successful connection, from  Android app terminal I tried the same and nothing happened.  If I send something from PC, I get it on mobile but reverse doesn't work.    And the main issue is Module doesn't respond at all.   I tried 3modules as well.
Help would be appreciated.

body: Have you made sure that your USB to TTL is implementing flow control on the UART. An option is to delete the CTS/RST in RN configuration and try two wire UART to eliminate CTS/RTS option


message:
noisy output lines when waking up from a sleep

Using code similar to these examples from AVR

https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__sleep.html

my program causes my Adafruit Feather 32u4 to often sleep. When the firmware has nothing to do it will sleep about 75% of the time. Typically after several hours of operation there will be corruption on the LCD display. The elapsed time to the corruption is not deterministic.

When it sleeps or wakes up from sleep I believe the processor sends garbage to the LCD module via the SPI (serial) lines. I have no oscilloscope to observe this but the problem seems to be removed if I comment out the sleep code.

A description of the Adafruit ST7565 LCD module is at this link

https://www.adafruit.com/product/250.

My Arduino setup code relevant to sleeping is this:

    cli(); // atomic operation begins here
    WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
    WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
    WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset
    sei(); // global interrupt enable
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);

My sleep code in the Arduino loop is adapted from the AVR webpage and is invoked if the firmware is not busy, is as follows:

    cli(); // atomic operation begins here
    sleep_enable();
    sei();
    sleep_cpu();
    sleep_disable();

The watchdog ISR for when it wakes up is an empty function, as follows:

    ISR(WDT_vect) // need this to avoid a reset
    { // no code here
    }

I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up. The evidence comes from my rotary encoders. I see false encoder activity sometimes when the processor wakes up and I eliminated this problem by putting some "debounce code" in the watchdog ISR. I also make sure the encoder lines use the processor's internal pull-up resistors. Note that I already have debounce code for the encoders for the purpose of doing actual debouncing of the activity of actually touching the encoders. The additional "debounce code" in the watchdog ISR is for the situation in which I am not even touching the encoders but the processor is waking up and the lines are noisy. The encoder "debounce code" is not shown in the watchdog ISR code snippet because it's not relevant to my LCD problem.

The pull-up and debounce remedy for encoder input lines is not applicable to my LCD problem because the LCD involves output lines.

Edit: I tried to solve it by setting high the active low chip select of the LCD before sleep and then reverting the line upon waking up (in the watchdog ISR). This had the effect of making the display very sluggish. I update the display once per second and it seemed to be updating only once every 2 or 3 seconds. I have not analyzed whether my "direct intervention" is incompatible with the Adafruit library for this LCD.

The LCD library: https://github.com/adafruit/ST7565-LCD

The boards are as pictured. The encoder board has 2 encoders wired up and 2 encoders unused. The encoder board sits on a 3mm thick piece of foam and is clamped to the desk. The breadboard is attached to the desk via the double sided foam tape that seems to be standard on this item.

[![picture][1]][1]
Addendum: Given Nick Gammon's answer, I will run with the following to see if the problem is eliminated. Since the corruption is not deterministic, it may take many hours or days before I form an opinion.

      cli(); // atomic operation begins here
      WDTCSR = bit(WDCE); // enter a brief change mode
      WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
      sei(); // global interrupt enable
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

After less than 10 hours there was corruption on the LCD. I will test with the following.

      cli(); // atomic operation begins here
      WDTCSR = bit(WDCE) | bit(WDE); // enter a brief change mode
      WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
      sei(); // global interrupt enable
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

The above still failed after several hours.

  [1]: https://i.stack.imgur.com/roVEQ.jpg

body:
    WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
    WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
    WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset

Your code above is not doing a WDT interrupt every 0.25 seconds as you appear to be wanting, because you assign (not OR) in the third line. That means WDP0/WDP1/WDP2?WDP3 will all be zero which means the watchdog will fire every 16 ms.

> This had the effect of making the display very sluggish.

I'm not totally surprised, if you interrupt every 16 ms.

---

> I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up.

The lines should remain what they were set to when the processor sleeps. It wouldn't be very useful to sleep if the processor started outputting random junk while asleep. I can't comment further as I can only see part of your code.


message:
Upload data to MAX 7219

I have the following code to write data on MAX7219 for light up a 8x8 LED Matrix:

    for (i = 0; i < 8; i++)
    {
        CLK = LOW;
        DIN = temp & MSBIT >> i;
        CLK = HIGH;
    }

The thing is, sadly, I just know that the code line `(DIN = temp & MSBIT >> i;)`, must be exactly like that, otherwise the LED´s won't show the expected, but I don't understand how it works...

Please, I really need explanation because I'm stuck....

Note: variable "temp" is always a hexadecimal number like `0x20`, and `"MSBIT" = 0x80`.

body:
You have to send 16 bits to load data.  The first 8 are the register the data goes into, 0 to 15, the next 8 are the data to be displayed. Registers 1-8 are the data that gets displayed, the others are used to set up: intensity, display test, normal/shutdow, decode/no decode mode, and number of digits/columns connected (such as 4 digits, or 8 for an 8x8 matrix).

In Arduino, I use hardware SPI to send data to MAX7219 - SCK, MOSI, and SS.

    digitalWrite (ssPin, LOW);
    SPI.transfer(addressRegister); // 0 to 15
    SPI.transfer(dataToLoad);
    digitalWrite (ssPin, HIGH);

Do that for each register. The control registers only need to be written once. In Arduino, that is usually in setup().  Intensity might be changed later for brightness (0 to 15 as valid data).

In loop(), use the above to update your display for the 8 display data registers (1-8).


message:
5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply

I am trying to setup my first relay module with live environment. I have attached the relay module image below.

[![enter image description here][1]][1]

Which I am using to control 4 devices in my switch board as follows:

 1. Fan (working fine),
 2. 6w celling LED panel (2 connected in series) (Working fine)
 3. 15w celling LED panel (2 connected in series) (Sometimes work sometimes don't)
 4. Spotlights 3 lights in series and some LED strips connected to it (Sometimes works sometimes don't.).

I have cut one wire which is connected to main normal mechanical switch WHICH IS NOT A HOT WIRE its just the another wire connected to the button.

But I am not sure why its not working? Do I need to connect neutral to the another end of the relay. As I have only 2 wires connected to the relay for each of the switches. Here is a screenshot of specifications 15watt LED panel which is connected to my house, if this can help to understand better.

[![enter image description here][2]][2]

If I connect Neutral on the first pin of relay and when I close the relay switch, do the current will go into the neutral wire as well?

If I keep my 3w spotlights ON or more then 3-4 hours and try to close the relay on connected to it. The relay LED light for that connected relay goes OFF but the light don't. Seems like the mechanical relay is not getting enough power to move the mechanical relay off.

I want to know why this is happening? And how can I solve this issue? Attaching a neutral (earth) wire will help to reduce this? But if connect neutral to first (off side of relay) pin, then will get the current?

Any suggestions will be helpful. Also I added 3.3v from NodeMCU to VCC (instead of jumper) pin. But that is also not helpful.

  [1]: https://i.stack.imgur.com/vA0Pq.jpg
  [2]: https://i.stack.imgur.com/tReNp.jpg

body:
You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.

And as stated in the comments, the relay need 5V for operating reliable.

In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.

2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.

1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/14WTN.jpg


message:
Voltage sensor Calibration

We had used a voltage sensor unit to measure the voltage of the odroid board using an Arduino Uno. wWhen I uploaded the sketch and got the output, the value which was being displayed was around 4.7 to 4.9V, but when I measured the top of the voltage sensor module using a multimeter, it had a stable voltage of 5.08V. Is their any particular reason why this is happening?

[Voltage sensor module][1]

  [1]: https://www.google.com/search?q=voltage sensor module&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjX58W-0-DfAhXJPo8KHaH9CV4Q_AUIDigB&biw=1920&bih=928#imgrc=FeDCSiiT_1sBYM:

    int analogInput = A0;
    float vout = 0.0;
    float vin = 0.0;
    float R1 = 30000.0;
    float R2 = 7500.0;
    int value = 0;
    void setup() {
    pinMode(analogInput, INPUT);
      Serial.begin(9600);
      Serial.print("DC VOLTMETER");
    }
    void loop() {
      // read the value at analog input
    value = analogRead(analogInput);
    vout = (value * 5.0) / 1024.0;
    vin = vout / (R2 / (R1 + R2));
    Serial.print("INPUT V= ");
    Serial.println(vin, 2);
    delay(500);
    }

body:
Multimeters are designed to provide a stable response. It would be averaging the readings.

As far as the difference in voltage reading, if you are using the Arduino board as is the default is to assume a reference voltage for the A/D as being 5.0 volts.(for your calculations) That may not be the case. Also there may be a tolerance issue on the measurement board, but I think the reference for the A/D on the Arduino is the bigger issue.


message:
Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial

I am working on this tutorial,

https://www.hackster.io/SURYATEJA/morse-code-communication-using-laser-module-both-ea1b01

and the author created a "Send" and "Receive" code for encoding and decoding Morse code. He created the "Send" code with the entire alphabet A-Z, but his receive code only has 9 letters.

I thought I could easily add in the missing characters, and even add in numbers, but I am stuck.

His code has 2 values to decode the morse - "a" and "f"

In his receive code he has a value "f" that is supposed to be calculated by the number of spaces, but I cannot see how he comes up with his result.

For example, this is his sending code for "a"

        case 'a':
    MorseDot();
    LightsOff(elemPause);
    MorseDash();
    LightsOff(elemPause);
    break;

Then this is the receive code;

    if(a==4 && f==10) {   Serial.print("a");

I understand the value of 4 for "a", but I cannot understand the value of 10 for "f"

"a" is calculated by assigning a value of 1 for a dot and 3 for a dash and adding the values (in this case one dot and one dash, 1+3 = 4)

He explains how to calculate "f" here in his tutorial, but I still don't understand.

2. When the LASER falls on the LDR, the value goes beyond 1000, and then it will enter into a loop.

3. Now quantize the values i.e. if the value goes beyond 1000, then assign it as '1', otherwise assign it as '0'.

4. Inside a loop, calculate the number of '1's and '0's. Set the counters 'a' and 'f'. Count the number of '1's and store it in 'a' and similarly count the number of '0's and store it in 'f' respectively.

5. Now check the specific values of 'a' and 'f' respectively. Each character will have different set of 'a' and 'f'. The matching value will be displayed.

That seems to indicate;
Laser on = Over 1000 = 1
Laser off = Under 1000 = 0

So for the letter a, I only see 2 times the laser goes off, not 10.Minof formatting changes

body:
This is not a good tutorial. The receiver works by assuming 14 `dotLen` time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then `a` is incremented, otherwise `f` is incremented. This means that the sum of `a` and `f` is always 14, and the case where `a==0` means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out `a==5` (which would be `R` or `U`), but does define 1 through 10 otherwise.

The receiver code does not differentiate between dots and dashes, it only counts the number of `dotLen` transitions where light is detected. This is not Morse Code.

The receiver code cannot distinguish between `S` (dot-dot-dot) and `T` (dash) because they both have 3 `dotLen` value. Same for `A` (dot-dash) vs. `N` (dash-dot).

If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.