text:
How to unbrick an Arduino Mega+ESP8266 Wifi
I have a Jaycar XC4421 - Arduino Mega + Wifi which I think have somehow managed to screw up the boot loader.
I have an XC4627 USP-ISP Programmer (and the XC4613 adaptor) which I have previously used to successfully burn boot loaders and update sketches in the past using the Arduino IDE.
However, on this occasion, after trying to reset the bootloader from the IDE, i can no longer upload sketches from the IDE using the inbuilt "upload" function of the IDE (I get timeouts) nor can I upload the sketch using the USB-ISP Programmer.
The symptoms as they currently stand with the USB connected to the 2560 (switches 3 & 4 on, all others off):

If I burn the bootloader (selected board in IDE is "Arduino Mega or Mega 2560"), this appears to work, but uploading sketches still does not work. After burning the bootloader, the builtin LED blinks at an odd cycle of roughly 400ms off, 400ms on, 200ms off, 200ms on.
The board is recognised in the IDE and appears as COM12
If try to upload the "blink" sketch (ctrl-U), I get timeout messages (see transcript below)
If I connect the USB-ISP and upload the blink sketch (ctrl-shift-U), the upload appears to work, but the sketch is never run (i.e. the builtin LED doesn't blink).
After uploading the blink sketch (via the USB-ISP programmer) the aforementioned odd blinking of the builtin LED completely stops (i.e. no blinking at all).
There is no hardware other than the USB-ISP programmer connected to the ICSP pins on the Arduino.
If I reset the DIP switches so that just 5 & 6 are on (USB->ESP) I am able to interact just fine with the "AT program" that was originally supplied on ESP side of the board.

My suspicion is that the Arduino Mega 2560 bootloader code is not completely compatible with the Arduino Mega + WiFi board. I don't think that suspicion makes much sense, but I'm out of ideas!
Where can I get the correct bootloader for this device? Alternatively, how can I correctly unbrick this?
Transcript from "upload blink sketch" showing timeout:
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"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\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -PCOM12 -b115200 -D -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM12
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

An error occurred while uploading the sketch

Transcript from "Upload blink sketch using programmer":
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"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\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: reading input file "C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex"
avrdude: writing flash (2684 bytes):

Writing | ################################################## | 100% 1.69s

avrdude: 2684 bytes of flash written
avrdude: verifying flash memory against C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex contains 2684 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 1.43s

avrdude: verifying ...
avrdude: 2684 bytes of flash verified

avrdude done.  Thank you.

Well after "working" on this all day, it turns out that the solution was to use the "Arduino as an ISP" solution as described on the arduino.cc website.
Why the USB-ISP solution did not work is not immediately obvious as I have used it successfully before - just not with this board!
FWIW, the blinking sequence I observed when burning the bootloader via the USB-ISP programmer also occurred after loading the bootloader via the "Arduino as ISP" solution. I don't know if the sequence was identical, but it certainly was similar. I then tried uploading the blink sketch using the "inbuilt" upload (ctrl-U) and the inbuilt LED blinked "correctly" at a 1s on 1s off cycle as per the standard blink sketch is programmed to do.
Oh well, hopefully this "answer" will help others.


text:
How compact, small and smart a fluid detector need to be communicate with external systems?
I like to build a fluid(liquid) level detector using Arduino that can send 2 types of information:

Status of the Fluid Container (Empty,Full or Below Required Level)
Location of Fluid Container

Now I like to know how small and compact such a fluid detector can be so that it can be placed in vessels, containers, tanks, etc. without causing any contamination to the fluid.
In addition, how can I interface this fluid detector with external systems like a smartphone app or cloud based app, etc.
What Arduino would i be using for the said purpose and why?

Size is inversely proportional to budget.

@Majenko Right... can you further elaborate with examples. Nowadays, there are so many ICs and compact nano-sized gadgets that are used even in human bodies as well. I agree what you said. But what feasibility is there for common commercial use? Thanks

The question you should be asking is not "how small can it be?" but "how small does it need to be?"

If you want small, you wouldn't use an Arduino, especially not an Uno.  You might use a QFN ATmega, but you'd be better off using an MCU integrated with your chosen radio transceiver.  Also, size has little to do with contamination, beyond the degree to which an admitted issue is a problem; you really should be looking for something made or encased in suitable materials.

Your question should be broken into a minimum of two parts.
The first, regarding the sensor, can be addressed with at least one specific product, although there may be others of this nature. It is a teflon coated pressure sensitive strip placed into the holding container or tank. Teflon is a non-reactive plastic and will not contaminate the substance in the tank, unless you are measuring extraordinarily reactive chemical liquids. One example is
Chemical eTape which is available in lengths from 130mm to 800mm.

This particular product is offered in three different interface types, all of which are acceptable to a properly configured Arduino.
The second portion of your question regarding the smartphone and type of Arduino is going to depend on how you plan to use the data you'll collect with the sensor. This aspect of the question is also extremely broad, as there are many solutions, including Blynk, SMS, WiFi and others.
You will want to "start small," and create a local Arduino-only interface, to ensure that you can properly code the sensor to present the results you require.
Once you have the data, you would then explore the many options available for distribution and dissemination.

Wonderful... I appreciate for the valuable detail you have added in your reply here. Now can you tell me what options would I use if I like to transfer the data (liquid level) to remote locations? As you mentioned about Bylink, SMS, WiFi, etc. What option would I go for if the liquid container is in New York and I am in Chicago? Moreover, the Chemical eTape does not detect the location (long. lat.) of the liquid container. How would I be able to detect the location of a certain liquid container, vessel or tank? Thanks

It would be more practical to consider to break off this question into other independent posts regarding both the communications and location aspects of your project. Prior to making a new set of posts, I would suggest to search here and the internet for "GPS Arduino" and "Arduino data over internet." Too many results to list in one comment, or even one answer. Please also check my answer if you feel it qualifies.

source: Stack Exchange

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

sort: votes


text:
How Do I Send An Email WITHOUT An Ethernet or WiFi Shield
I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.
You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.
Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.

Thanks I found an example of your answer: http://www.instructables.com/id/Tweet-a-Pot-Twitter-Enabled-Coffee-Pot/?ALLSTEPS. This project uses Python as the intermediary.

SLIP or "Serial Line Internet Protocol" is an older idea not heard of as much these days, but should accomplish this goal. http://en.wikipedia.org/wiki/Serial_Line_Internet_Protocol

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


text:
How do I listen for a sound that matches a pre-recorded sound?
I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.
I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).
The bell sounds kind of like this: bell sound

I would suggest a sound detector module and a timer to measure the length of the sound. If the duration is predictable this might be enough to discriminate from random sounds. Or if the bell is electronic, can you get access to the output wires and just detect a voltage?

I can't get access to the output wires, but I can place the detector within about 10 feet of the bell. Then I can listen for a certain volume level and once it reaches that level, i'll see if the duration remains for three seconds. This wouldn't be fool proof because there's background noise but it may work.

About the simplest starting point is to use an FFT (fast Fourier transform) library (like ArduinoFFT at openmusiclabs.com) to characterize the spectrum of an audio stream.
[Edit: An alternative method (digital bandpass filter) is mentioned below.]
Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.
The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.
The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.
If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• Comparing an audio signal with a previous 'taught/profiled' signal
• How do I compare chords played on a guitar with a known sample?
• How do I compare 2 audio files, returning a percentage of difference
• What does the phase of a FFT bin of an audio signal represent?
• Sound pattern matching using Fast Fourier Transform in Windows Phone
• How do I go about detecting whistles, pops and other sounds in live audio input?
• The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT
An alternative: digital bandpass filter
Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.
For theoretical background see wikipedia's Digital filter article.  Also see Vaseghi, Chapter 5, Digital Filters, (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
ECE438 digital filter design lecture notes
pdf file.
You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like
v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
freqz(v);
v

will compute coefficients for a Constrained L2 bandpass FIR filter, plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) Serial.write(buf, len) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use mkfilter to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.
Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second (1,2,3,4), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.

This is likely too involved an approach for the limited memory and computational resources of an Uno.  Unless the algorithm can be substantially simplified, it is likely the wrong platform for the job.

@ChrisStratton, I don't see Uno mentioned in question.  Also don't know that Uno is too limited for FFT.  But if so, consider an ATmega2560 Arduino board.  However, I plan to mention an alternate method.

@jwpat7 I will be using an Arduino Uno as it's the only one I have. The bell sounds kind of like this sound. Does that mean your second method will work better? Furthermore, would I need to figure out the frequency of the bell and then use the digital bandpass filter on the incomming sound to check for a match?

Ben, I added some paragraphs about development methods at the end, that may help you figure out answers to those questions.

@Chris Stratton's comment is on the mark. This would be a job for a DSP, not an Arduino.

@DaveP, (1) although Arduino floating point performance is pathetic, it probably is good enough to handle 3000-4000 ADC samples per second and then use a digital bandpass filter to detect occurrence of a 332 Hz tone (if the Uno does nothing else).  (2) If the problem is tougher (eg noisy environment, buzzy tone, additional processing needed) or if short development time and elegant methods are important, yes, a DSP board would make sense.  Ref 4 mentioned in last paragraph of answer says so several times.

Onban Arduino you would definitely want to do this with fixed point math.   More importantly though, if contemplating a software approach at all, the algorithm should first be proven satisfactory by running it on a PC using data from the sound card.  Otherwise inordinate amounts of time are likely to be wasted implementing something that may not be a useful solution on any hardware.


text:
Controlling Protoneer CNC shield without PC
I'm building an small CNC using Protoneer CNC shield, GRBL and Arduino UNO.
With this I need to connect the board to PC and send G-Code from there.
My question is, is it possible to use the arduino itself to control the CNC shield?
If yes how?
If not is there any other way to send commands other than USB (as Arduino's USB port is not a host)
Thanks

Have it read the GCode from an SD card.

@Gerben: no; currently I'm sending using Universal GCode Sender through USB port

That wasn't a question, but a suggestion. Using and SD would negate the need for USB.

An Arduino can talk directly to a shield, independent of a PC.
This will, however, need a way to tell your Arduino to do it's thing. Depending on what you want it to do, this may require nothing ("send this pre-defined g-code as soon as you are turned on"), a memory card of some sort, one or more pushbuttons, or even a small screen. I have seen several 3d printers with memory cards, buttons (usually up/down/select/back), and a small screen that, once set up, can print anything you can load onto a memory card.
There are other forms of communication, too - ethernet, wifi, etc., which you can use, with appropriate shields.
In the end, of course, you still have to design your object - 3d graphics are well beyond the ability of an Arduino, so there will still be some form of computer involved.

Thanks but the shield got all of arduino pins, how can i connect the buttons or sd card ? and when I installed GRBL firmware on arduino can I still program it and send commands to gcode from inside?


text:
Why are MOSFETs only giving 8.1V for LEDs, not 12V?
I'm using three PWM outputs from an Arduino Mini Pro to drive the R/G/B parts of some strips of LEDs. The circuit is basically this:

I've got a single 12V power supply, rated at 200W, to light the LEDs and to power the Arduino via the RAW pin, and there are 5 metres of 60LEDs/m RGB LEDs, i.e. a total of 300 LEDs, which should be drawing ~72W according to the spec sheet (14.4W/m).
The problem is that even when the sketch says digitalWrite(9, 255); digitalWrite(10, 255); digitalWrite(11,255), the LEDs are considerably dimmer than when connected directly to the 12V supply. My cheap, digital volt meter measures ~8.1V between GND and the PWM pins across the LEDs, not the 12V that the transformer is supplying.
Am I doing something wrong? Does the MOSFET really cause such a large drop in voltage? Is there anything I can do to mitigate it? (It's important to get as much brightness as possible from the LEDs for this project).

Which MOSFET are you using? And what voltage is the MCU running on?

Sorry, should have said — I've got three STP36NF06L MOSFETs.
As for the MCU (I take it that means "the Arduino", yes?) — as I said, I'm supplying it with the same 12V as the LEDs, via the RAW pin (the right-most pin on the bottom row of this picture, which I think the Arduino steps down to 5V to use on board.

The pwm pins should only be 5 volt at the most. Or are you referring to the drain of the mosfet? Can you post a picture of your wiring?

Gah, sorry, the 8.1V is measured across the LEDs, not at the Arduino's PWM pin (which is obviously, as you say, at ~4.8V). I've just edited my post to show the correction. I added a circuit diagram at the same time. [I've actually used pins 9, 10, 11 rather than 3, 5, 6, but otherwise my circuit is as shown.]

By my calculations you are sinking 6 amps:
72 W / 12 V = 6 A

I have some doubt that the Arduino board is designed to handle that amount of current through its ground plane. Try running a separate ground wire to the MOSFET sources.
I would also be concerned about the gauge of wire you are using, and whether the prototyping board can handle that amount of current.

+1 Absolutely - the Arduino board is not built for supplying that much current, even as a 'pass through'. Connect the 12V supply (both +Ve and GND) directly to the MOSFET/LED portion.

Your MOSFETs may not be appropriate for driving from a 5V device. I had a similar problem and someone suggested I need to use a MOSFET with a low turn-on voltage, specifically IRLB8743 (http://www.irf.com/product-info/datasheets/data/irlb8743pbf.pdf) which is fully enabled at 4.5V. You might also find that your MOSFETS are getting warm because they are acting as resistors if not fully engaged.
In the above datasheet it says "Very low RDS(on) at 4.5V" meaning low resistance when VGS (arduino output voltage) is at 4.5V or more.
Your datasheet is here http://pdf.datasheetcatalog.com/datasheet2/8/0iyt26iogeofcyaowtrx4z7iwiky.pdf and I'd love to be able to tell you how to compare but I'm not sure which values to look at :/
The breadboard itself may also be introducing resistance. If you wiggle the mosfets around and the lights change brightness this is likely.
LEDs have a set forward (turn on) voltage. You can expect to see that voltage drop over LEDs and not more, which does not indicate the problem (current).


text:
What's Happened with my Arduino?
I am in a First Year Design class, and we are supposed to be making an autonomous robot. After hooking up some wind speed and temperature sensors to calibrate, I plugged in to my laptop (we have 2 arduino nanos) and ran a temperature code. I got the reading, but smelled something burning. Nothing was smoking, but I've found that when I plug my arduinos into my laptop, the light and the code indicate that they are not connected. This is odd because when I plug in the batteries, they show that the proper voltage is coming through, but they will still not connect to the laptop. Is it a problem with the micro-usb port?
I've included the code I'm using just in case that is cause for suspicion. It is notable that our instructors have written an API that allows us to code in Java for the arduinos.
public static void main (String[] args)
{
    robot = new ArduinoNano();
    robot2 = new ArduinoNano();
    robot.setPort("COM5");
    robot2.setPort("COM6");
    robot.connect();

    int reading = getThermistorReading();

    System.out.println("The probe read the value " + reading);
    System.out.println("In volts: " + (reading * (5.0/1023.0)));
    System.out.println();

    double temperature = (reading - 855.02) / -7.563;

    System.out.println("Temperature: " + temperature);

}

public static int getThermistorReading()
{
    int sum = 0;
    int readingCount = 10;

    for (int i = 0; i < readingCount; i++)
    {
        robot.refreshAnalogPins();
        int reading = robot.getAnalogPin(3).getValue();
        sum += reading;
    }

    return sum / readingCount;
}

}

If you smelled burning, doesn't it maybe stand to reason that there might be a hardware issue? And yet you show us code in some unknown API that no one else here has a hope of knowing what it is. I suggest you re-think your question...

Well yes, but I included the code just in case. The fact is that I can't find any hardware issues. There are no shorts in the wires, everything is grounded. I'm stumped with the hardware so I included the code in case someone could see a glaring mistake.

How can we tell? No one else but you and your tutor knows that API. Maybe you should SHOW us your hardware so we can be the judges of if there is something wrong or not.

Did the magic smoke come out? If not, there's still hope.

Have you tried loading the 'Blink' sketch to just the Nano, without anything else attached?

First, did the Arduino continue to respond and operate after you smelled the burning?
Just because there isn't smoke doesn't mean you didn't kill something on the board.
If your Arduino is not responding, there are two possibilites I can think of:

Your port is not working so simply switch to a different USB port
Somehow your laptop must have sent a large amount of amps/volts to the circuit and burned it out. If you have a multimeter you can use the sound setting to test whether or not wires are burned out, and if your nifty with an iron/heat gun, you can replace the part. Or you could buy a new one.

If the connection is good, you will hear a small beep. Oh, and these things don't work if there's a resistor in the way.


text:
Using fluctuating voltage as an input
I had an idea to hack a wireless doorbell so it could send notifications to my phone when someone rings the doorbell.
I pulled out the PCB from the doorbell and powered it using the +5v from the Arduino - so far so good
I used the (once was a wire to the speaker) as an analog input
The issue I have is that the voltage for the chime continues for a long time. eg its at 0 before push then it fluctuates for a second, then returns to 519 for a while, before eventually returning to 0.
Is there a smarter way to do this - I have included my code below.
void loop()
{
  //detect a changing voltage
  val = analogRead(sensorPin); //pin A0
  delay(500);
  oldVal = analogRead(sensorPin);//pin A0

//if the voltage changed then +1 to the ring counter
  if (val != oldVal) {
      ringCounter = ringCounter+1;
  }

  if (ringCounter > 3 && pinDevid1State == false) // someone pressed the doorbell
  {
    if(DEBUG){Serial.println("pinDevid1 is HIGH");}
    pinDevid1State = true;
    Serial.println("DingDong");
    digitalWrite(ledPin, HIGH);
    delay(5000);
    Serial.println("Notification Sent.");

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;
  }

  if (ringCounter < 3 && pinDevid1State == true) // the doorbell stopped ringing
  {
    if(DEBUG){Serial.println("pinDevid1 is LOW");}
    pinDevid1State = false;
    digitalWrite(ledPin, LOW);
    Serial.println("DingDongEnd");
    //Sending request to PushingBox when the pin is LOW
    //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;

  }

What are you trying to solve/improve/create? Does this work the way you want it to?

Expecting two analogRead()s half a second apart not to differ at all isn't realistic, I think.  Low order bits fluctuate a lot if there's any electrical noise at all in your system.

@jwpat7your right but the way the logic works is most of the time they are the same... Its only when the door bell is pressed that it then is consistently different for 30 seconds - hence the ring counter

@JRobert It does do what I want it to do - I just wondered if there was a more intelligent way to trigger a notification from a change in voltage. I guess my issue is there will be positive voltage while the speaker wire tries to power the speaker. I wonder if there is another pin on the board I could read - I want the bell to responsive to people impatiently pressing = multiple notifications and fast so there is as little delay as possible

I will try with an hysteresis,

I wonder if there is another pin on the board I could read

I guess that would depend on the particular doorbell. The transmitter must send some representation of a button press to the receiver - a pulse train for the duration of the press, or perhaps just CW: carrier on, carrier off - which the receiver somehow passes on to trigger the audio. Look at the receiver's output side to identify that trigger signal and pass it, or a processed version of it, to the Arduino.

I wonder if there is another pin on the board I could read

You could try to hook up a multimeter to the pins/leads from the doorbell button. Positive to doorbell button pin, negative to power supply ground/doorbell battery.
Once you figure out which pin has voltage when the doorbell button is pressed, you can have that go into a digital or analog input in the Arduino. Make sure that the ground from the doorbell PCB and the Arduino are connected so that they'll have common ground and it should be detectable.


text:
Issue with length of string value
I have been getting some weird issues with a sketch I put together(apart from memory low warnings, it was working fine)
When im about to post data to my php server - it seems not all the information is available
eg the output will be
42399.92
&HAAlt=-18.24

Is there a limit to string length?
Im crudely constructing a string to send to a post request
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#include <math.h>
#include <Wire.h>
#include "MutichannelGasSensor.h"
#include "HP20x_dev.h"
#include "KalmanFilter.h"

unsigned char ret = 0;

/* Instance */
KalmanFilter t_filter;    //temperature filter
KalmanFilter p_filter;    //pressure filter
KalmanFilter a_filter;    //altitude filter

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192, 168, 0, 30); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 40);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

#define Vc 4.95
//the number of R0 you detected just now
#define R0 35.54
#define DHTPIN A1     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 2000;//sampe 30s ;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;
String data;
String data2;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  delay(150);
  HP20x.begin();
  delay(100);

  /* Determine HP20x_dev is available or not */
  ret = HP20x.isAvailable();
  if (OK_HP20X_DEV == ret)
  {
    Serial.println("HP20x_dev is available.\n");
  }
  else
  {
    Serial.println("HP20x_dev isn't available.\n");
  }

  pinMode(8, INPUT);
  starttime = millis();//get the current time;
  Serial.println("power on!");

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

  //if (Ethernet.begin(mac) == 0) {
  //  Serial.println("Failed to configure Ethernet using DHCP");
  // try to congifure using IP address instead of DHCP:
  Ethernet.begin(mac, ip);

  // give the Ethernet shield a second to initialize:
  delay(10000);
  Serial.println("connecting...");
  //}
  // give the Ethernet shield a second to initialize:
  //delay(1000);
  //Serial.println("connecting...");

  // Serial.println(Ethernet.localIP());

  gas.begin(0x04);//the default I2C address of the slave is 0x04
  gas.powerOn();
  //Serial.print("Firmware Version = ");
  //Serial.println(gas.getVersion());
  //Serial.println("Particles\tRS\tHCHO (PPM)\tNH3 (PPM)\tCO (PPM)\tNO2 (PPM)\tC3H8 (PPM)\tC4H10 (PPM)\tCH4 (PPM)\tH2 (PPM)\tC2H5OH (PPM)");
  dht.begin();
  delay(10000);

  data = "";
  data2 = "";
}

void loop() {

  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  float HATemp2;
  float HAPres2;
  float HAAlt2;

  if (OK_HP20X_DEV == ret)
  {
    long HATemp = HP20x.ReadTemperature();
    float p = HATemp / 100.0;
    HATemp2 = t_filter.Filter(p);

    long HAPres = HP20x.ReadPressure();
    p = HAPres / 100.0;
    HAPres2 = p_filter.Filter(p);

    long HAAlt = HP20x.ReadAltitude();
    p = HAAlt / 100.0;
    HAAlt2 = a_filter.Filter(p);

  }

  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy + duration;

  float d;

  if ((millis() - starttime) >= sampletime_ms) //if the sampel time = = 30s
  {
    ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100

    d = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    //Serial.print("concentration = ");

    lowpulseoccupancy = 0;
    starttime = millis();
  }
  //Serial.print("\t");
  //HCHO

  int sensorValue = analogRead(A0);
  double Rs = (1023.0 / sensorValue) - 1;

  double ppm = pow(10.0, ((log10(Rs / R0) - 0.0827) / (-0.4807)));
  //Serial.print("HCHO ppm = ");

  //MultiChannel Gas
  float NH3 = gas.measure_NH3();
  float CO = gas.measure_CO();
  float NO2 = gas.measure_NO2();
  float C3H8 = gas.measure_C3H8();
  float C4H10 = gas.measure_C4H10();
  float CH4 = gas.measure_CH4();
  float H2 = gas.measure_H2();
  float C2H5OH = gas.measure_C2H5OH();

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  data = String("dust=") + d + "&rs=" + Rs + "&hcho=" + ppm + "&nh3=" + NH3 + "&co=" + CO + "&no2=" + NO2 + "&c3h8=" + C3H8 + "&c4h10=" + C4H10 + "&ch4=" + CH4;
  data2 = String("&h2=") + H2 + "&c2h5oh=" + C2H5OH + "&temp=" + t + "&hum=" + h + "&HATemp=" + HATemp2 + "&HAPres=" + HAPres2 + "&HAAlt=" + HAAlt2;

  Serial.println(data);
  Serial.println(data2);

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("POST /air_add.php HTTP/1.1");
    client.println("Host:  192.168.0.30");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.println(data);
  }
  else
  {
    Serial.println("could not connect");
  }

  if (client.connected()) {
    client.stop();
  }

  Serial.println("done.");

  delay(30000);
}

There isn't a real limit on the length of a String that you are running into.  But when you are running low on RAM (the low memory warnings you mentioned) then there is a limit on how much memory you have to put that String before you cause memory corruption and either crash the program or at best get some weird output.
The String class is particularly wasteful of memory and it has some issues when using the + operator to concatenate Strings that will leave the heap memory full of holes and reduce the amount of memory you have even further.  On memory constrained systems like microcontrollers, the String class crutch is a thing to be avoided.  Learn to use char arrays and real c-style strings and you'll be better off.
One place you could immediately save some memory would be by putting all the constant strings in your code into PROGMEM instead of leaving them out in RAM.  So this:
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");

becomes
client.println(F("Connection: close"));
client.println(F("Content-Type: application/x-www-form-urlencoded;"));

It was memory!! thank you - I did as suggested and it had a huge impact on usage

output is now dust=0.62&rs=12.29&hcho=13.54&nh3=2.71&co=13.67&no2=0.78&c3h8=4579.24&c4h10=2334.79&ch4=42399.92&h2=4.14&c2h5oh=7.25&temp=23.20&hum=65.90&HATemp=11.52&HAPres=507.68&HAAlt=-8.82
:)

Is that good or bad?

It’s good. That’s the full list of sensor data


text:
How to make an SMS notification to my phone with Arduino Uno?
I am planning to make an SMS notification to my phone with Arduino Uno via a push of a button.
I have an Arduino Uno C520A Embedded System. Is it possible to do so with this model ? If yes, which WIFI module should I get ?
I just want to make an API request to the web through the push of a button.

You're going to need a GSM module and working simcard.

Check the specific devices datasheet for the (usually serial AT) commands.

there are 100's of tutorials, just check them out on YouTube/blogs. Search for: Arduino send SMS.

How is the SMS notification related to the WiFi API requests?

It is possible if your provider has a sms gateway e-mail-address. Just google which it is for your provider (e.g. number@tmomail.net for T-Mobile (US)). And there should be a lot of tutorial about how to send an email with an arduino.
Every wifi-module with arduino support will work if your WiFi is a standart 3.6Ghz. And yes it should work with any arduino compatible microcontroller.

Arduino uno is only the processor, you will need a Ethernet shield or Wifi shield to connect to the internet.
I would suggest Ethernet as it is less pain to configure and no drop of connection.
Then you will need to buy a sms gateway, this one looks pretty cool as they have good http api.
By using the Arduino Ethernet sample, you will need to send a http request to the server when the button has been pressed.


text:
Creating a library for attiny85 out of working program
Apologies if this is the wrong sub-forum, the involvement of ATTiny and arduino places this into a strange category. Please correct me if I should post elsewhere.
It is important for this to be a library as small kids will be using this program and hardware for their own projects. Its kind of a rip on the LOLshield but it involves a lot more steps to integrate more lessons all at once.
My whole program takes 8 bytes of information and converts it to data for a shift register driving two multiplexers all driving an 8x8 LED matrix. It can also use multiple of these packets to make a slide show. I have it in a working state right now and would like to turn it into a library for easy use. I am a bit lost in this step as I had to create an interrupt timer and this makes it more complicated than the tutorial on the arduino website covers.
Also if someone could point me to a library for ATTiny85 that makes calling a timer interrupt easy then the rest of this project will likewise become easier.
Any help would be great! I will be continuing to look on online resources and will update should I figure it out.

I would just implement a callback and tell the consumer "call this callback every so often, preferably with a timer interrupt".

Ok could you direct me to a timer interrupt library compatible with the ATTiny85 then? Programming an interrupt for the attiny85 is stupidly messy to a new programmer.

Nope. But it should be easy enough to port something like Timer1 to arduino-tiny.

Already looked into it, it's not. I'm not exactly a great coder in the first place, this is a learning experience for me.

I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc.

Code
In the interests of answering the question though, this works:
// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }

void setup()
 {
  pinMode (4, OUTPUT);  // chip pin 3

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare

  }  // end of setup

void loop()
  {
  // other code here
  }

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.

Prescaler values
From the datasheet:

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.
The delay is then:
125 ns * 256 * 124 = 3.968 ms

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

Flashing more slowly
If you put an LED on pin 3 and want to see the flashing, you need it much slower. For example:
TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13);  // prescaler: 16384

That toggles the pin every 254 ms, which is visible.

Warning
On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.

More information

Timers
Interrupts

Wow that answer was above and beyond what I expected! All this info is super useful! I'll be putting it to good use, hell this post should be put somewhere where more people will see it too!


text:
Trying to figure out how to use an extension board with Pi
I am trying to make the following board work with Raspberry Pi.
Board Name: L293D Motor Drive Shield Expansion Board for Arduino Mega Raspberry Pi

All I need to know is which pins do the following:

Enable the motor
Disable the motor
Rotate forward
Rotate backward

More information about the board:

https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors
https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=16118

Can someone please help me find this information?

Does the schematic not show this?

This is not an Arduino question and should be closed - it never belonged here in the first place, and it's sat abandoned by the asker for half a year now.  If it remains open, the anti-community daemon will continue to useless churn it back up.

The following pins are in use only if the DC/Stepper noted is in use:

Digital pin 11: DC Motor #1 / Stepper #1 (activation/speed control)
Digital pin 3: DC Motor #2 / Stepper #1 (activation/speed control)
Digital pin 5: DC Motor #3 / Stepper #2 (activation/speed control)
Digital pin 6: DC Motor #4 / Stepper #2 (activation/speed control)

The following pins are in use if any DC/steppers are used

Digital pin 4, 7, 8 and 12 are used to drive the DC/Stepper motors via the 74HC595 serial-to-parallel latch

The following pins are used only if that particular servo is in use:

Digitals pin 9: Servo #1 control
Digital pin 10: Servo #2 control

(source)


text:
Reading Multiple RFID tags / Reading and ignoring/holding the tag
I'm currently doing a project where ideally I will have multiple objects with RFID tags on them that are placed on top of a Adafruit PN532 RFID Shield connected to a Arduino Uno Wifi Rev 2. The idea is that once a button is pressed the RFID reader will read a Mifare tag then "ignore" it then reads the next tag until all are read. How can I acheive this?
I have read some about Anti-collision protocols and the limitations of RFID but was also wondering if it might be possible to read a tag then hold or ignore that tag until it leaves the range of the RFID shield?
I've also read a user on the Adafruit forums had some luck by altering the library that is used, I'll link it for reference, but I've tried the same method but had no luck myself. Adafruit-PN532 Library
I'm new to Arduino so I apologise if I've messed anything out.
Thanks for any help!

what is the actual question? I don't see one

Sorry MichaelT, the question is how can I achieve what I intend to do for my project? e.g. hold a tag so it is not read again until it leaves the range of the RFID shield. I have edited the original to make the question more obvious I hope.

You probably want to use UHF RFID for this.  The Adafruit PN532 is only capable of reading max 2 tags at a time in an alternating fashion.  This is confirmed by the board's designer in the Adafruit forums.

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


text:
Arduino delay inside of an Interrupt
Using the delay function inside of an ISR is frowned upon when programming in an Arduino. The general response to solve this desire is to design the program to delay in a more cleanly way outside of the interrupt.
My question is simply why. Why does putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

Why is putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

The first problem is that delay() is a busy loop monitoring millis(). The value that millis() returns will not change inside an ISR as interrupts are turned off inside an ISR; this is why ISRs must be as short and fast as possible, or they will interfere with other interupts
So if you call delay() within an ISR your poor AVR is now deadlocked! It is waiting for something to happen that can now never happen.
A second problem is that if your ISR takes too long, you can miss other interrupts; millis() and micros() can miss ticks and become inaccurate!

This is an addition to esoterik's answer.
Most of the times, that people try to use delay() inside an ISR it is a poor design choice to even use it in a general way, that will lead to the described problems (waiting forever or missing other interrupts). delay() is a simple function mainly for beginners with very simple programs. It is a simple starting point. Mostly the use of it in any program is not a good choice, since you are busy waiting without being able to do something else (like responding to user input). There are better ways, involving millis() itself, that keep your program extendable (so that, if you want to add a functionality, this will not be blocked by the first part of the code). And when your program reaches the complexity of using own ISRs, you should avoid delay(), unless you really know, what you are doing.
IMO at some (rather early) point, every Arduino programmer has to learn how to use millis() to do timed code execution. You can look at the BlinkWithoutDelay example, that comes with the Arduino IDE.

Because a delay inside an interrupt causes that interrupt and other (lower priority) interrupts not to execute anymore until the delay is over.
Assume in an ISR you handle the incoming bytes from a UART. If you add a delay in the ISR, and the buffer of the UART gets full, it will overflow and you miss bytes.

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


text:
Why is Serial Print causing different behaviour based on where its located
Im trying to test out these two motors I have where I need to call a function from the loop. I only want to call this function once so I made a quick little if statement to have the program only run once. However, it seems that when I run this file, the Variable I have set doesn't continue getting incremented. The code will tell more.
int i = 0;

void loop()
{
    // Serial.print("=====");Serial.print(i);Serial.println("=====");
    if(i == 1)
    {
        Serial.print("+++");Serial.print(i);Serial.print("+++");
        DeclinationMotor(DEC_freq, NULL, HIGH);
    }
    i++;
}

The behavior is really odd in that if i just run that code above, the variable i will not get incremented and become stuck at 1. However if I were to un-comment the other serial print line above the if statement, i would be incremented properly and that function will be executed only once.
For reference, the function DeclinationMotor is
float DeclinationMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("DEfS "); Serial.print(angularDistance); Serial.print("DEaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = DEC_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = DEC_degrees_from_home + angularDistance;
        else
            finalLocation = DEC_degrees_from_home - angularDistance;
    }

    SetPinFrequency(DEC_STEP, freqspeed);
    pwmWrite(DEC_STEP, 128);
    digitalWrite(DEC_DIR, direction);
    digitalWrite(DEC_running, HIGH);

    return finalLocation;
}

Full Code Here
//-----------------------------------------------------------------------------
#include <PWM.h>
void analogJoyStick();
void serialEvent();
void meridianFlipT();
float RightAscensionMotor(float freqspeed, float angularDistance, byte direction);
float DeclinationMotor(float freqspeed, float angularDistance, byte direction);
void StopRAMotor();
void StopDECMotor();

// --------------Todo--------------
// Turn the Variables into motor actions for serial event
// Write program that helps figure out the encoders degrees for its
// angle crap. You might just need to count exactly how many
// times the revolution goes around manually
// set up isrs for optical sensors and joystick
// create stop motors function
//

#define RA_sensor 2
#define DEC_sensor 3

// Sensor limit LEDs
#define RA_limit 27
#define DEC_limit 29

// Telescope Position Status LEDs
#define home_pos 35
#define tracking 37

// Joystick
#define xPin A0      // X axis
#define yPin A1      // Y axis
#define JS_button 26 // Button

// Motor 1
#define RA_STEP 10                // Step for Right Ascension
#define RA_DIR 12                 // Direction for Right Ascension
#define RA_EN 32                  // Enable motor disconnection
#define RA_OUT 36                 // Motor fault output
int RA_freq = 800;                // Frequency for normal movement
int RA_freq_tracking = 400;       // Frequency for tracking objects
int RA_freq_slow = 600;           // Frequency for when close to desired position
volatile byte RA_track_DIR = LOW; // Used to store last direction of RA motor

// Encoder 1
#define RA_A 18
#define RA_B 19
#define RA_I 22
long int RA_Encoder_Count = 0;      // Positive value means net position is in B direction
int RA_Complete_Rotations = 0; // Positive value means net complete rotation is in B direction
int RA_degrees_from_home = 0;  // Used to keep track of how far from home position

// Motor 2
#define DEC_STEP 11                 // Step for Declination
#define DEC_DIR 13                  // Direction for Declination
#define DEC_EN 34                   // Enable motor disconnection
#define DEC_OUT 38                  // Motor fault output
int DEC_freq = 800;                 // Frequency for normal movement
int DEC_freq_slow = 600;            // Frequency when close to desired position
volatile byte DEC_track_DIR = LOW;  // Used to store last direction of DEC motor

// Encoder 2
#define DEC_A 20
#define DEC_B 21
#define DEC_I 24
long int DEC_Encoder_Count = 0;      // Positive value means net position is in B direction
int DEC_Complete_Rotations = 0; // Positive value means net complete rotation is in B direction
int DEC_degrees_from_home = 0;  // Used to keep track of how far from home position

// Communication with ATmega328
#define COMM 39
#define RA_running 23
#define DEC_running 25

int i = 0;

void setup()
{
    // Sensor Inputs
    pinMode(RA_sensor, INPUT);
    pinMode(DEC_sensor, INPUT);

    // Sensor Fault LEDs
    pinMode(RA_limit, OUTPUT);
    pinMode(DEC_limit, OUTPUT);

    // Telescope Position Status LEDs
    pinMode(home_pos, OUTPUT);
    pinMode(tracking, OUTPUT);

    // Interrupts for Sensors
    // attachInterrupt(digitalPinToInterrupt(RA_sensor), RA_sensor_trip, CHANGE);
    // attachInterrupt(digitalPinToInterrupt(DEC_sensor), DEC_sensor_trip, CHANGE);

    // Right Ascension Motor Inputs and Outputs
    pinMode(RA_STEP, OUTPUT);
    pinMode(RA_DIR, OUTPUT);
    pinMode(RA_OUT, INPUT);
    // attachInterrupt(digitalPinToInterrupt(RA_OUT), RA_motor_fault, CHANGE);

    // Right Ascension Encoder Inputs
    pinMode(RA_A, INPUT);
    // attachInterrupt(digitalPinToInterrupt(RA_A), RA_Enc, RISING);
    pinMode(RA_B, INPUT);
    pinMode(RA_I, INPUT);

    // Declination Motor Inputs and Outputs
    pinMode(DEC_STEP, OUTPUT);
    pinMode(DEC_DIR, OUTPUT);
    pinMode(DEC_OUT, INPUT);
    // attachInterrupt(digitalPinToInterrupt(DEC_OUT), DEC_motor_fault, CHANGE);

    // Declination Encoder Inputs
    pinMode(DEC_A, INPUT);
    // attachInterrupt(digitalPinToInterrupt(DEC_A), DEC_Enc, RISING);
    pinMode(DEC_B, INPUT);
    pinMode(DEC_I, INPUT);

    // Joystick inputs
    pinMode(xPin, INPUT);
    pinMode(yPin, INPUT);
    pinMode(JS_button, INPUT);

    // Communication with ATmega328
    pinMode(COMM, OUTPUT);
    pinMode(RA_running, OUTPUT);
    pinMode(DEC_running, OUTPUT);

    // Constant signal to ATmega328 to confirm ATmega2560 is operational
    digitalWrite(COMM, HIGH);

    Serial.begin(9600);
    InitTimersSafe();

}

void loop()
{
    // Serial.print("=====");Serial.print(i);Serial.println("=====");
    if(i == 1)
    {
        Serial.print("+++");Serial.print(i);Serial.print("+++");
        DeclinationMotor(RA_freq, NULL, HIGH);
    }
    i++;
}

void analogJoyStick()
{
    int NumbX, NumbY;

    while(digitalRead(JS_button) == LOW)
    {
        NumbX = analogRead(xPin);
        NumbY = analogRead(yPin);

        // Here we go to to move the motor and the numbers have been created with
        // small numerical buffers to allow deadzones. It was made to be linear response
        // to the users input.

        if(NumbX > 530)
            RightAscensionMotor((RA_freq * (NumbX - 512)/512), NULL, HIGH);
        else if(NumbX < 500)
            RightAscensionMotor((RA_freq * (NumbX - 512)/512), NULL, LOW);
        else
            StopRAMotor();

        if(NumbY > 530)
            DeclinationMotor(800, NULL, HIGH);
        else if(NumbY < 500)
            DeclinationMotor(800, NULL, LOW);
        else
            StopDECMotor();
        delay(50);
    }
    // Track();
}

// this thing seems to be appended onto the end of the loop() so the immediate intersection must be
void serialEvent()
{
    char ident = Serial.read();     // first character will be the identifying character

    if(ident == 'R')
    {
        int number1 = Serial.parseInt();        // these variables should become global afterwards
        Serial.read();
        int number2 = Serial.parseInt();

        // you don't know what origin is yet so..
    }
    else if(ident == 'M')
    {
        int raAngle = Serial.parseInt();
        Serial.read();                              // These serial reads are for the separaters in the transmitted string
        int raDirection = Serial.parseInt();
        Serial.read();
        int dAngle = Serial.parseInt();
        Serial.read();
        int dDirection = Serial.parseInt();

        RightAscensionMotor(RA_freq, raAngle, raDirection);
        DeclinationMotor(DEC_freq, dAngle, dDirection);
    }

    // Serial.readbytes()
    Serial.read();      // this is to read the newline character out of the buffer.
}

// This needs to be called if
// if(Osensor1 || Osensor2)
    // meridianFlip();
void meridianFlipT()
{
    float finalLocationRA, finalLocationD;
    byte RACheck = LOW; byte DCheck = LOW;
    Serial.println("F1");    // newline is already incorporated

    // Right so, RA is normal yea whatever, but Declination is made this way to allow the counter weight
    // to always be pointed away from the tripod. For the latitude is 0 at the pole.
    finalLocationRA = RightAscensionMotor(RA_freq, 180, !RA_track_DIR);
    finalLocationD = DeclinationMotor(DEC_freq, ((180 - DEC_degrees_from_home) * 2), !DEC_track_DIR);

    // This is going to check to see if both the motors have turned to their respective locations theres
    // a little buffer period that is inputted to just to see if the motor gets there. We can replaced this later on
    while(RACheck == LOW || DCheck == LOW)
    {
        if(RACheck == LOW && (finalLocationRA + 2 > RA_degrees_from_home && finalLocationRA - 2 < RA_degrees_from_home))
        {
            digitalWrite(RA_running, LOW);
            RACheck = HIGH;
        }
        if(DCheck == LOW && (finalLocationD + 2 > DEC_degrees_from_home && finalLocationD - 2 < DEC_degrees_from_home))
        {
            digitalWrite(DEC_running, LOW);
            DCheck = HIGH;
        }
        delay(10);
    }

    //Track();            // Resume Tracking
    Serial.println("F0");
}

// These two are just functions to move the motors with. Might have a
// return to tell that its finished or something
float RightAscensionMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("RAfS "); Serial.print(angularDistance); Serial.print("RAaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = RA_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = RA_degrees_from_home + angularDistance;
        else
            finalLocation = RA_degrees_from_home - angularDistance;
    }

    SetPinFrequency(RA_STEP, freqspeed);                 // Look at SetPinFrequencySafe()
    pwmWrite(RA_STEP, 128);
    digitalWrite(RA_DIR, direction);
    digitalWrite(RA_running, HIGH);                 // I think this just turns it on?

    return finalLocation;
}

float DeclinationMotor(float freqspeed, float angularDistance, byte direction)
{
    Serial.print(freqspeed); Serial.print("DEfS "); Serial.print(angularDistance); Serial.print("DEaD "); Serial.println(direction);

    int finalLocation = 0;
    if(freqspeed == NULL && angularDistance != NULL)
        freqspeed = DEC_freq;
    if(angularDistance != NULL)
    {
        if(direction == HIGH)
            finalLocation = DEC_degrees_from_home + angularDistance;
        else
            finalLocation = DEC_degrees_from_home - angularDistance;
    }

    SetPinFrequency(DEC_STEP, freqspeed);
    pwmWrite(DEC_STEP, 128);
    digitalWrite(DEC_DIR, direction);
    digitalWrite(DEC_running, HIGH);

    return finalLocation;
}

void StopRAMotor()
{
    Serial.println("-RAMotor Stopped-");
    digitalWrite(RA_STEP, LOW);
    digitalWrite(RA_running, LOW);
}
void StopDECMotor()
{
    Serial.println("-DECMotor Stopped-");
    digitalWrite(DEC_STEP, LOW);
    digitalWrite(DEC_running, LOW);
}

have you tried putting the code into setup() instead. It is made for things, that only should run once

I totally could but that doesn't help me understand why this wouldn't work. (Btw i just did and it worked completely fine) @chrisl

Ahh sorry the F(freqspeed) was me just messing around with storing the data in the flash memory instead of the SRAM as i saw on some other threads.. I didn't have that during actual testing so i should've deleted it from this post. Thanks for the catch @juraj
Edit:
Its deleted now.

Yes that, AND the serial line inside of the if() inside of the loop function has a print out of the variable i, which constantly repeats it being 1. @Juraj

Here is my guess what happens:
Once the code in the if statement have run, the loop() only contains the incrementation of i. This will run very fast. After a rather short time (maybe someone here can make the calculation to get the time, that is needed) i will overflow, going from it's most positive value to it's most negative value, then incrementing further and finally reaching again 1. As this happens rather fast, you think, that i does not increment, but it is just flowing over again and again. i is of type int, which means, that it needs 65535 loop() iterations, to get to 1 again.
About the version with the extra Serial.print() calls: You didn't show us your setup(), but you probably have chosen a rather slow baudrate (maybe 9600, as it is used by many examples). At the first iterations the calls are just placing the data in the buffer and returning fast. But after a few iterations the Serial buffer is full. In this case the Serial.print()/Serial.write() functions (and their siblings) are blocking the code execution, until enough space in the buffer is free. So this would considerably slow down the executing of the loop(), thus considerably increasing the time between i overflows - to a point, where you don't wait long enough to actually see it overflow (but it will happen at some point).

To execute a code part only once you can either use the setup() function (if the call should happen at the start of the program), or you can use a simple flag. Imagine, that you don't increment i in the loop(), but that you are setting it's value to zero inside of the if statement. That would prevent the code in the if statement to execute again, until you yourself set i to 1 again.
byte flag = 0;

void setup(){
    flag = 1; // Set flag to 1 somewhere in your sketch as you like, to execute the if statement
}

void loop(){
    if(flag){
        //execute the wanted code here
        flag = 0; // deactivate this code by setting the flag to 0
    }
}

Notice, that I changed some things here:

I changed the name of the variable to flag, because that's what it is: A simple flag with only 2 states - zero and non-zero
I changed the type of the variable to byte, as you don't need a whole int (16 bits) for a simple flag. So I used the smallest variable type, a byte. (you could also use boolean here, but basically that's the same)
The if statement now only checks for the value of flag directly. It will evaluate as true, if flag is not zero, as false, if it is zero. (So you could set flag to any other value than zero to activate the code, but true is also defined as 1, so I stayed in line with this).
I set the flag back to zero inside the if statement, so that it will not be executed another time. It will only execute again, if you yourself set flag again to a non-zero value somewhere in your code.

Hmm thats interesing, but i don't get why then it wouldn't just skip some numbers at some point and be iterating slowly. However you gave me an idea for something that might be happening. So in other words, the buffer fills up with 8 prints and continues the loop. Once the loop reaches 1 again then it prints out the same 8 prints again which happen to be at i equals 1. This explains it printing out again every half a second. If this is the case, then making the variable i a double or something large should slow down the repeated print outs.

Im going to be putting a screenshot of the print out in the post

Also i just realized, then why is it that when I un-comment the Serial print line above the if() statement then the variable i gets properly incremented and outputed.

Can confirm, I did the opposite of that and made the variable i a byte, and now it prints out everything again a lot faster then before. Increasing it to a float makes it print out only one, but i did not wait nearly long enough to make up the for the numerical difference between an int and a float

The print in the if statement can only output i as 1, since it only executes, if i is one. So here you don't see if i increments. The increments happens outside of the if statement, so you can only see the incrementation, if you output i outside of the if statement. But just because you don't see it increment doesn't mean that it does not increment.

You should use long instead of float. Avr based Arduinos don't have native float calculation, so it is a waste of computation time to use float instead of long

Second one first, yea i ended up using long instead of float.
Yea thats what im saying aswell. The loop function keeps iterating through an int until i hits 1, adding the 8 print lines to the buffer. Since it does that super fast, it just prints those statements again and again at a decent speed, each time i overflows and hits 1. Changing the range that i can loop at, I.E. making it a byte or a long will change the speed at which the prints are printed. Having an outside serial.print just fills up the buffer with all those other numbers of i being made, making it look real time

I can test this later, but i assume if i leave it this way the buffer of the arduino will eventually really fill up and it will start skipping numbers. (when i have the out of if() statement un-commented. Or at least this is what i gleaned from playing around with it and reading everyones comments.

Yes, exactly. It also slows down the loop function

No, it will not skip numbers. The print calls will wait, until enough data from the buffer was send. It slows the sketch down, but it will not loose the serial data

Ah true lol yea i just realized that as you were typing it lol


text:
Connecting multiple RS485 together
I am trying to build communication across multiple Arduino using RS485. When i am trying to connect 3 Arudino nano together using breadboard my code doesn't reach slave where as if i just if i do direct connection between 2 RS485 without breadboard it works but i use breadboard for 2 it doesn't work. Am i missing any setup here?
Breadboard connection - A & B are connected to + & - of both RS485.
Working connection - A & B of first RS485 connected to A & B of 2nd RS485.

show a picture of the breadboard version

It is possible you have too many resistors on the RS485 bus. From the RS485 wikipedia page there is this quote:

Ideally, the two ends of the cable will have a termination resistor
  connected across the two wires.

This may explain why you can use 2 of your RS485 interfaces but not 3.  Consider removing the resistors from the RS485 board in the middle if possible.

problem is even if i use only 2 with breadboard it doesn't work. It only work when i connect them directly ? Do i have to use any resistor on breadboard ?

Breadboards are not good with high frequencies.  Try slowing down the baud rate.  Also check if you are using the breadboard correctly.  So, 2 connected using wires works?  And 3 connected using wires works?  But 2 connected using the breadboard does not work?  And exactly which TTL to RS485 adapter are you using?  Have you added termination resistors to the ends of your RS485 bus?

The thing with termination resistors is, that it's value should be the wave resistance of the specific cable at that specific frequency. I don't think, that this is critical here, as long as the OP does not use too high baudrates. But the breadboard might be the real problem here.


text:
Serial Monitor stops working when using PinMode
I'm having a lot of trouble with my recent Arduino sketch. I need to reset an IC by setting a pin high then low. I also am using the serial monitor for some testing but as soon as I try and do a Serial.print, nothing appears. My Arduino is also on a custom PCB, where D7 is connected to the IC's (MAX3421) reset pin, and also to the Arduino's reset pin.
To try and make my issue clearer, ill post some code and the serial monitor output below:
void setup()
{
  Serial.begin(9600);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[nothing in serial monitor]

void setup()
{
  Serial.begin(9600);

  //pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[lots of TESTs]
Any help is appreciated,
Thomas

You are probably shorting or browning out something.  What exactly do you have attached to pin 7?

I'm using one of my custom PCBs with an Arduino and a MAX3421 for interfacing with USB peripherals.
Pin 7 is connected to MAX3421's reset pin which now I look, is also connected to the Arduino reset pin. I remember doing this because it was necessary to reset the MAX before starting. Is shorting the MAXs reset with the Arduino's reset doing this?

put another serial.print() in setup() ... that way you can tell if the arduino is resetting

I put a Serial.println("x"); before the pinMode and it didn't print anything which is puzzling

"Is shorting the MAXs reset with the Arduino's reset doing this?" In a word, yes.

@VosemMedia You would also need to insert a short delay after the print. The data is send out via interrupts after the print call. So you are resetting the Arduino before the UART interface has enough time to send the data out

Ah yes, I added a short delay and now only the x is being printed over and over. I am now wondering why my code doesn't work as shorting MAX Reset and Arduino Reset should work though i'm still getting the same OSC did not start. error.

Okay that's extremely weird, for some reason it just started working, then I unplugged everything and plugged in again and it no longer works.

This may seem kind of obtuse, but do you understand what RESET pin does on the UNO?

My understanding is that it re-executes the current program though that may be incorrect, just from my experience that's what it seems to do

Also, I fixed my main issue which was the MAX not getting enough power from the USB header, so I introduced a 9v battery which sorted it all. I would love to understand the reset pin more but if you don't think it's in the scope of this question don't worry :)

This normally not meant for discussion, so this is going to be a one-shot comment to address that:  When reset is active (low), the 328P is electrically disconnected from circuit and execution is halted.  When it comes out of RESET is essentially rebooted, like a computer. Owing to what the chip itself does and what the start code does, you've functionally (oversimplifying) lost all prior state.  If you really want to know about it, you want to read in the ATMega328P datasheet.

I appreciate the explanation, thankyou

My issue was that pin 7 was connected to the reset pin on the Arduino, meaning every time it was set to output, the Arduino was reset.
You can see this here:
void setup()
{
  Serial.begin(9600);

  Serial.println("a");

  delay(100);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("test");
}

which outputs a stream of a's separated by 100ms (plus a bit)

I added more information to the question, and don't doubt others have had the same problem so I will keep the question/solution up.


text:
Measure position of gear with arduino
So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like this below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins)  and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.
EDIT:
The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.
Edit: For anyone wondering how to use the sensor, the datasheet is here and it shows the positions of the collector, emitter, anode and cathode.

I know, it’s not helpful at all but I couldn’t find a data sheet and I wanted to say it’s going much too fast to see

you could certainly try that sensor .... paint one of the gear teeth white

I am sure Arduino is fast enough to read the frequency of a gear

You can try to use an encoder attached to the shaft of the motor in this way you can measure the amount of steps per turn and thus you can calculate when and how you turn the motor. Or just get a stepper motor. And for the concern that the Arduino is not fast enough you can use interrupts which are very fast.

unfortunately, for the application in airsoft, it needs to be very compact and sit below the gear, hence why I thought using some sort of IR sensor would be appropriate.

If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.
Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.
So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your loop() function.
If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the loop() function.
Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.
Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.
One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like int x = 1000; will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute x = 1000 will all take just one clock tick.
Others will vary the amount of instructions that are generated to execute them. For example

float x = 1.0;
x = x + 2.0;

will likely take more instructions to execute than it's integer counterpart:

int x = 1;
x = x + 2

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.

Thank you very much, this is unbelievably helpful. I’ll have to try and condense my code down. Do you know if that sensor will pick up the gear even if it’s not painted white? Thanks

Sorry, i am not familiar with that particular sensor. I suggest scrutinising the data sheet on the web page; Asking the manufacturer; And/or posting a new question either here or on the Electronics site.

Alright, I’ll take a look at the datasheet first. Thanks