text:
NodeMCU V3 Serial input results in Fatal exception 9 (LoadStoreAlignmentCause)
I am building a simple telnet style interface for experimental settings on my project. I am getting all the serial output sent to serial (and USB to PC). The code works fine, but if I try to read from Serial or check 'Serial.available()' I will get:

Fatal exception 9(LoadStoreAlignmentCause)

Definition:
bool pridaj_cely(uint8_t source_from=0, uint8_t line_LCD=0);
The code:
bool Vstup::pridaj_cely(uint8_t source_from, uint8_t line_LCD) {
  uint8_t i = 0;
  Serial.println(F("one piece input read"));
  switch (origin) {
    case 0: { //Serial
        int16_t znak = -1;
        while (Serial.available() < 0) {
          Serial.print(F("."));
          delay(100);
        }
        Serial.print(F("Somothing is comming"));
        while (Serial.available() > 0) {
          celok[i] = Serial.read();
          if (i < 12)  i++;
        }
      }
      break;
  }
  return 1;
}

Code of Priojenie:
bool pripojenie(bool force_it = 0) {
  Serial.println(("Beginning connection routine"));
  kolo = millis();
  while (!WiFi.isConnected()) {
    int8_t sieti = WiFi.scanComplete();
    Serial.printf("Search result %X", sieti);
    switch (sieti) {
      case -2:
        Serial.println(("\tSearch begins"));
        WiFi.scanNetworks(1);
        delay(50);
        break;
      case -1:
        Serial.print(("."));
        delay(300);
        break;
      default: //This is the relevant case
        Vstup odpoved;
        Serial.ciara;
        Serial.ciara;
        Serial.printf(("Found %X networks"), sieti);
        Serial.ciara;
        Serial.println();
        for (uint8_t i = 0; i < sieti; i++) {
          Serial.printf("%d: %s, Kanál:%d (%ddBm) %s\n", i, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i), WiFi.encryptionType(i) == ENC_TYPE_NONE ? "Otvorena" : "");
        }
        Serial.ciara;
        Serial.println(("\nChose network number:"));
        odpoved.pridaj_cely(0);
        // -------------------Never gets past this one-------
        if ((odpoved.Nacislo10() >= 0) && (odpoved.Nacislo10() < sieti)) {
          Serial.printf(("Zadaj heslo pre %s\n"), WiFi.SSID(odpoved.Nacislo10()).c_str());
          String heslo = Serial.readString();
          Serial.print(F("Dostal som "));
          for (uint8_t i = 0; i > heslo.length(); i++) Serial.print(heslo[i]);
          Serial.println();
          Serial.printf(("Vybral som možnosť číslo %d a sieť: "), odpoved.Nacislo10(), WiFi.SSID(odpoved.Nacislo10()).c_str());
          //WiFi.begin(WiFi.SSID(odpoved.Nacislo10()).c_str(), heslo);
        } else Serial.printf(("Nesprávny výber %d"), odpoved.Nacislo10());
    }
  }
}

I have commented all the functions that use pins. The source compiles without any problem.
I am adding the result of exception decoder as it did not help me solve it.

Decoding stack results
0x40202a8d: __yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 105
0x40202355: Stream::timedRead() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 37
0x40202392: Stream::readString() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 240
0x402013b6: pripojenie(bool) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 315
0x40203411: malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 95
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020141c: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 327
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204bb1: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2073
0x4020197c: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2300
0x4020e5b8: sys_check_timeouts at core/timeouts.c line 368
0x40202957: loop_task(ETSEvent*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 133
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x40206938: _printf_i at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf_i.c line 194
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x402034b4: malloc_loc(size_t, char const*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 126
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204738: umm_realloc(void*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1745
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40201a89: ESP8266WiFiScanClass::scanNetworks(bool, bool, unsigned char, unsigned char*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 98
0x40203942: uart_write(uart_t*, char const*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x402015fd: loop() at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 460
0x40201410: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 325
0x40204bb8: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 1934
0x40204ba4: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2069
0x40201e50: HardwareSerial::setDebugOutput(bool) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.cpp line 79
0x40202a4c: loop_wrapper() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125

line 325 is a wrapper function because async scan can only call void function of specific type and calls pripojenie_samo(uint8_t pointless)
Serial Output: (after translation to English)
Beginning connection routine
Search result 3
-----------------------------------------------------
-----------------------------------------------------
Found  3 networks

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

0: VM5070527, Kanál:11 (-55dBm)
1: Virgin Media, Kanál:11 (-74dBm)
2: VM5076233, Kanál:11 (-85dBm)
-----------------------------------------------------

Chose network number:
Instance cleared
one piece input read

Panic /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp:103 __yield

>>>stack>>>

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

decode the stack dump of the exception. https://github.com/me-no-dev/EspExceptionDecoder

Added, but I see no relevant  info, just disappointment that chip contains full paths
if I comment-out all the Serial-available() and Serial .read() the rest of the code works

the paths are in a file on your computer. the decoding takes the debug info from the files created at build but not uploaded to MCU

Thanks, but the problem is still here

did the build for decoding match the code that crashed? the stack dump indicates crash in pripojenie(bool)

pripojenie creates instance of an Vstup class (and then calls pridaj_cely on that instance which manages to report one piece input read to serial and then resets as stated above.
The same seem to be hapening if the code reaches Serial.available() or Serial.read() in other functions

I have translated and added function pripojenie, in this case it is called from asynchronous scaning

I have figured it out
There seem to be understandable limitations if what kind of function can be run as a result of asynchronous scanning (which doesn't seem to interrupt running of a loop function)
So if I have used delay(x) or a while loop until there is input on serial, MCU resets after allotted time runs out.
I have re-written code to start function from loop when scan is complete, and it all runs fine now.
I guess Arduino isn't right language for parallel programing


text:
MAX7219 and Arduino
I am getting started in running this 8x8 led on an Arduino. Regardless of which tutorial sketch I attempted, I never got a scrolling text that I expect. What happens seems to be only a single (out of four) led module being addressed at a time, resulting in, for example, the message being scrolled on one module at a time, but all four in succession. Could it be a module problem?

Got it somewhat working by changing:
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
to:
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
But still a little problem with the last character in a message not showing all leds lit until it starts to scroll after the initial program delay. Then all is fine.
Anyone want to address that issue? My sketch follows:

{    // Use the Parola library to scroll text on the display
//
// Demonstrates the use of the scrolling function to display text received
// from the serial interface
//
// User can enter text on the serial monitor and this will display as a
// scrolling message on the display.
// Speed for the display is controlled by a pot on SPEED_IN analog in.
// Scrolling direction is controlled by a switch on DIRECTION_SET digital in.
// Invert ON/OFF is set by a switch on INVERT_SET digital in.
//
// UISwitch library can be found at https://github.com/MajicDesigns/MD_UISwitch
// MD_MAX72XX library can be found at https://github.com/MajicDesigns/MD_MAX72XX
//

#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// set to 1 if we are implementing the user interface pot, switch, etc
#define USE_UI_CONTROL 0

#if USE_UI_CONTROL
#include <MD_UISwitch.h>
#endif

// Turn on debug statements to the serial output
#define DEBUG 0

#if DEBUG
#define PRINT(s, x) { Serial.print(F(s)); Serial.print(x); }
#define PRINTS(x) Serial.print(F(x))
#define PRINTX(x) Serial.println(x, HEX)
#else
#define PRINT(s, x)
#define PRINTS(x)
#define PRINTX(x)
#endif

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
//#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
#define MAX_DEVICES 4
#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// HARDWARE SPI
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// SOFTWARE SPI
//MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

// Scrolling parameters
#if USE_UI_CONTROL
const uint8_t SPEED_IN = A5;
const uint8_t DIRECTION_SET = 8;  // change the effect
const uint8_t INVERT_SET = 9;     // change the invert

const uint8_t SPEED_DEADBAND = 5;
#endif // USE_UI_CONTROL

uint8_t scrollSpeed = 25;    // default frame delay value
textEffect_t scrollEffect = PA_SCROLL_LEFT;
textPosition_t scrollAlign = PA_LEFT;
uint16_t scrollPause = 2000; // in milliseconds

// Global message buffers shared by Serial and Scrolling functions
#define BUF_SIZE    75
char curMessage[BUF_SIZE] = { "" };
char newMessage[BUF_SIZE] = { "Got Signals?" };//{ "Hello! Enter new message?" };
bool newMessageAvailable = true;

#if USE_UI_CONTROL

MD_UISwitch_Digital uiDirection(DIRECTION_SET);
MD_UISwitch_Digital uiInvert(INVERT_SET);

void doUI(void)
{
  // set the speed if it has changed
  {
    int16_t speed = map(analogRead(SPEED_IN), 0, 1023, 10, 150);

    if ((speed >= ((int16_t)P.getSpeed() + SPEED_DEADBAND)) ||
      (speed <= ((int16_t)P.getSpeed() - SPEED_DEADBAND)))
    {
      P.setSpeed(speed);
      scrollSpeed = speed;
      PRINT("\nChanged speed to ", P.getSpeed());
    }
  }

  if (uiDirection.read() == MD_UISwitch::KEY_PRESS) // SCROLL DIRECTION
  {
    PRINTS("\nChanging scroll direction");
    scrollEffect = (scrollEffect == PA_SCROLL_LEFT ? PA_SCROLL_RIGHT : PA_SCROLL_LEFT);
    P.setTextEffect(scrollEffect, scrollEffect);
    P.displayClear();
    P.displayReset();
  }

  if (uiInvert.read() == MD_UISwitch::KEY_PRESS)  // INVERT MODE
  {
    PRINTS("\nChanging invert mode");
    P.setInvert(!P.getInvert());
  }
}
#endif // USE_UI_CONTROL

void readSerial(void)
{
  static char *cp = newMessage;

  while (Serial.available())
  {
    *cp = (char)Serial.read();
    if ((*cp == '\n') || (cp - newMessage >= BUF_SIZE-2)) // end of message character or full buffer
    {
      *cp = '\0'; // end the string
      // restart the index for next filling spree and flag we have a message waiting
      cp = newMessage;
      newMessageAvailable = true;
    }
    else  // move char pointer to next position
      cp++;
  }
}

void setup()
{
  Serial.begin(57600);
  Serial.print("\n[Parola Scrolling Display]\nType a message for the scrolling display\nEnd message line with a newline");

#if USE_UI_CONTROL
  uiDirection.begin();
  uiInvert.begin();
  pinMode(SPEED_IN, INPUT);

  doUI();
#endif // USE_UI_CONTROL

  P.begin();
  P.displayText(curMessage, scrollAlign, scrollSpeed, scrollPause, scrollEffect, scrollEffect);
}

void loop()
{
#if USE_UI_CONTROL
  doUI();
#endif // USE_UI_CONTROL

  if (P.displayAnimate())
  {
    if (newMessageAvailable)
    {
      strcpy(curMessage, newMessage);
      newMessageAvailable = false;
    }
    P.displayReset();
  }
  readSerial();
}

}

I suggested an edit to format the code but is this your final answer to the question? If this code still has problems you might be best adding a description of what's wrong and editing it into your question instead.

"Somewhat working?"

Yes, the change to ICSTATION corrected the problem. Thanks for your interest.

source: Stack Exchange

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

sort: votes


text:
detecting presence inside - PIR or ultrasound?
(I am professionally a software guy working in the GCC compiler with MELT, so I am fluent in software, but much less in hardware - I did use a solder for a 74LS00 nand gate based stuff in the 1990s. This is my first Arduino project)
My first Arduino project would be to automate the lights and the fan in my inhouse WC toilet in Paris (France) suburb. I bought several Arduino Nano v3 boards. I'm thinking of driving with a relay a low voltage 12v LED lightbubble. I want to detect human presence in the toilets. I'm thinking of some PIR sensor, but I am afraid that PIR won't detect anything if the temperature is above 37°C (or about 100F), which is unusual in Paris (France) but may happen a few days per year (I've got no air conditioning). Is my worry correct, or can a PIR still work with very warm outside temperature? Should I use an ultrasound detector instead?

I thought about the same thing. My ideal system would be to detect if the door is open using a hall-effect-sensor or reed-switch, and to detect if the door is locked (not quite sure what would be the ideal sensor for that). That way you can detect when people enter (open; close; lock), and when they leave (unlock; open; close).

PIR sensors work fine and are probably easier to program for than ultrasonic sensors. For example, this tutorial on a PIR sensor sold by Adafruit has a datasheet at the bottom that says:

Operating Conditions Operating Temperature -20 ˚C to +70 ˚C
Storage Temperature -30 ˚C to +80 ˚C
Operating Voltage 3 to 10 V at Rs = 47 kΩ

You can try to find and check the datasheet for the sensor you intend to purchase to determine if it will work.

One thing to be wary of with PIR sensors is that they only detect moving heat.  That means that your light would turn on as you enter the toilet, but would turn off again when the sensor fails to detect movement.  That will be once you're sat on the toilet and reading the newspaper.  To keep the light on you would need to flail your arms around to keep the sensor on, and thus the light on.
So from that perspective alone the ultrasound would possibly be a better option since it can detect the presence of anything within its cone of sound - as long as that something is big enough, like a human body.
A third option that you haven't mentioned is infra-red beams.  Depending on how big the toilet is you may be able to just have one IR beam passing through the room, and when someone is in the room that beam will be broken.  Only works in small cubicles though.  For larger rooms you may need either a mesh of beams to cover the whole room, or a dual-beam in-out counting arrangement on the entrance (two beams, one before the other. If beam A breaks before beam B then someone has entered - if beam B breaks before beam A then someone has left. When there are 0 people in the room then turn the light off).

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


text:
how to differentiate in code between Sangunio and Microduino core+
Sanguino and Microduino core+ both uses ATMEGA644PA. I need to write a piece of code in my library where I need to check what board has been selected.

#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#   define TIMER_PWM_PIN  11             // Arduino Mega
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or microduino
#    define TIMER_PWM_PIN  13        //Sanguino PD5
#elif defined(__AVR_ATtiny84__)
# define TIMER_PWM_PIN  6
#else
#   define TIMER_PWM_PIN  9              // Arduino Duemilanove, Diecimila, LilyPad, etc
#endif

If I used the above code #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or Microduino will be true for both Microduino and Sanguino.
Is there a way I can know which one is it?
Here is the board.txt section for Microduino core +
##Microduino Core+ (644pa)
##############################################################
644p.name= Microduino/mCookie-Core+ (644pa)

644p.upload.tool=avrdude
644p.upload.protocol=arduino

644p.bootloader.tool=avrdude
644p.bootloader.unlock_bits=0x3F
644p.bootloader.lock_bits=0x0F

644p.build.board=AVR_PLUS
644p.build.core=arduino
644p.build.variant=plus

Never heard of either of them. Do they have specific Arduino IDE configurations for them? Do those configurations define a _BOARD_xxxx_ macro you can examine?

I ll check that !

Where should they be?

In a file called boards.txt somewhere wherever the boards were installed to by the IDE.

Ok and how should that appear?

As a file. Called boards.txt. What more do you want? It has text in it. Key/value pairs. In groups for the different boards.

I mean which key:value pair will define that? is it the variant? or board?

I have no idea in the current version. It used to be board.define IIRC in older versions.

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

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


text:
Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger?
As stated in www.Arduino.cc FAQ, "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."
For UNO/Pro Mini(ATMega328) and ATmega2560, does these two chips support JTAG type (some chip manufacturers may use different name) programmer / hardware-based debugger in same manner as the ST-Link/J-Link programmer/debugger where one can load code into the MCU and perform hardware break point and single stepping? Example as in  STM32 development board with ST-LINK programmer / debugger where the chip has built-in debug circuit that communicate with ST-Link.
Many thanks in advance.

The ATmegaXX8 does not support JTAG, but the ATmegaXX0, 'XX1, and 'XX4 do. The 'XX8 (as well as other AVR families) supports debugWIRE, which allows debugging over ISP. You will need one of Atmel's debuggers such as the AVR ONE! or the Atmel-ICE as well as Atmel Studio in order to use it.

I use an AVRDragon board with Atmel Studio to do JTAG on a 2560 board and DebugWire on the smaller chips. This is probably the lowest cost solution.

Is the Mega 2560 included in the "ATmegaXX0" class?

@AnnonomusPenguin: Yes. It includes the ATmega640, ATmega1280 (Arduino Mega), and ATmega2560 (Arduino Mega 2560), which only vary by amount of flash available.


text:
SIM900 module connects then disconnects from carrier soon after
I have an Arduino Mega 2560 with an ESP8266 built into it, and a SIM900 shield, which I am building a project with.
The shield is powered by an external adjustable 3-12V, 2A supply set at 6V so power is not an issue.
I have managed to get serial to work, and can issue commands to the device. My issue is the following;

I fire up the shield.
Shield reports back CREG = 2 which means ME is looking for an operator to connect to.
Shield reports back CREG = 1 which means it has connected to an operator.

Running AT+COPS? returns my provider, as long as CREG = 1.

Seconds in, CREG = 4, which means Unknown.

I don't see why it keeps disconnecting me, I have gone through 4 different SIM cards and the problem persists.
Has anyone else had this problem and if you did, how did you manage to work around it?
17:29:25.000 -> NORMAL POWER DOWN
17:29:25.000 ->
17:29:25.000 -> +CREG: 3
17:29:27.993 -> ?????????? (SHIELD TURNS ON, GARBAGE OUTPUT)
17:29:29.520 -> RDY
17:29:29.520 ->
17:29:29.520 -> +CREG: 2
17:29:29.520 ->
17:29:29.520 -> +CREG: 0
17:29:29.520 ->
17:29:29.553 -> +CFUN: 1
17:29:29.553 ->
17:29:29.553 -> +CPIN: SIM PIN
17:29:33.506 -> AT+CPIN=1234
17:29:33.506 ->
17:29:33.506 -> OK
17:29:34.503 ->
17:29:34.503 -> +CREG: 2
17:29:36.528 -> AT+COPS?
17:29:36.528 ->
17:29:36.528 -> +COPS: 0
17:29:36.528 ->
17:29:36.528 -> OK
17:29:38.022 ->
17:29:38.022 -> Call Ready
17:29:39.550 -> AT+COPS?
17:29:39.550 ->
17:29:39.550 -> +COPS: 0
17:29:39.550 ->
17:29:39.550 -> OK
17:29:41.044 ->
17:29:41.044 -> +CREG: 1
17:29:42.572 -> AT+COPS?
17:29:42.572 ->
17:29:42.572 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:42.572 ->
17:29:42.572 -> OK
17:29:44.565 -> AT+COPS?
17:29:44.565 ->
17:29:44.565 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:44.598 ->
17:29:44.598 -> OK
17:29:47.587 -> AT+COPS?
17:29:47.587 ->
17:29:47.587 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:47.620 ->
17:29:47.620 -> OK
17:29:49.580 ->
17:29:49.580 -> +CREG: 4
17:29:50.111 -> AT+COPS?
17:29:50.111 ->
17:29:50.111 -> +COPS: 0
17:29:50.111 ->
17:29:50.111 -> OK

6 V on barrel jack or Vin of Mega is not enough

The mega is powered by the USB cable connected to my laptop. It's the SIM900 shield that is connected to the power supply.


text:
Arduino IDE says fcould not convert 'pinMode(buttons[((inti)], 0u)' from 'void' to 'bool'. How do I fix
Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?
#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {1, 2, 9, 11, 12, 13}; // the analog 0-5 pins are also known as 14-19
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'currently pressed'
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

void setup() {
byte i;

// set up serial port
Serial.begin(9600);
Serial.print("Button checker with ");
Serial.print(NUMBUTTONS, DEC);
Serial.println(" buttons");

// pin1 LED
pinMode(1, OUTPUT);

 // Make input & enable pull-up resistors on switch pins
 for (i=0; ipinMode(buttons[i], INPUT);
 digitalWrite(buttons[i], HIGH);
  }

 // Run timer2 interrupt every 15 ms
 TCCR2A = 0;
 TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

 //Timer2 Overflow Interrupt Enable
  TIMSK2 |= 1<<TOIE2;

 }

SIGNAL(TIMER2_OVF_vect) {
check_switches();
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
static byte currentstate[NUMBUTTONS];
 static long lasttime;
 byte index;

  if (millis() // we wrapped around, lets just try again
     lasttime = millis();
  }

  if ((lasttime + DEBOUNCE) > millis()) {
    // not enough time has passed to debounce
return;
  }
  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
  lasttime = millis();

  for (index = 0; index digitalRead(buttons[index]);   // read the button

    /*
    Serial.print(index, DEC);
    Serial.print(": cstate=");
    Serial.print(currentstate[index], DEC);
    Serial.print(", pstate=");
    Serial.print(previousstate[index], DEC);
    Serial.print(", press=");
    */

    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))        {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH     means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally  of the buttons
  }
}

void loop() {
  for (byte i = 0; i if (justpressed[i]) {
      justpressed[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just pressed");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (justreleased[i]) {
      justreleased[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just released");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (pressed[i]) {
      Serial.print(i, DEC);
      Serial.println(" pressed");
      // is the button pressed down at this moment
    }
  }
}

int questionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) / //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n - i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if (digitalRead(questionNumberArray) == HIGH) {
  then(digitalRead(1, 2, 9, 11, 12, 13 == High(3))
  break;
}
}

Also, how do I make it so that people have infinite times to try

int QuestionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself - seems related to your other question.

Maybe Mr. Google will help you: Fairly Simple Simon – an Arduino memory game for 4 LEDs and 4 switches

There is very little about the code you are producing at the moment that could be classified as "right".
You are like a child who has been playing with LEGO® being let loose on the workings of a nuclear reactor.  You're sticking things together without a) knowing what they do and b) knowing how they are supposed to work, and it's all going to end in tears.
I suggest that, for the time being, you forget this game project of yours and go back to the basics.  Start by learning how to make an LED light up when you press a button.  That will teach you both how to read the state of a button and how to control an LED.  Then move on to doing it with multiple LEDs and multiple buttons.
As it stands you are just going to end up getting frustrated and annoyed.  You're asking questions without either knowing just what it is you are asking or how to understand the answers when you are given them.  And that is going to end up reflecting badly on the rating of your various users (hint: if you ask reasonable questions you get reasonable answers, and that means upvotes and reputation, which then means you can ask more questions so you don't have to keep creating new users to ask more questions where you don't actually understand what you're asking).

If only this "game project" wasn't an assigment due to be handed in tomorrow.

@CharlieHanson Sometimes you have to be cruel to be kind.  If someone just jumps in at the end of a project at the last minute without doing any of the preliminary research then they're doomed to fail.  After a few repeats they may finally learn. When you do a project on a piece of equipment or in an environment you don't know the first thing to do is learn how to use it. Only then can you even begin to consider doing anything more complex than blink an LED or print "Hello World".

I'm not disputing that, I was simply adding that this project has been mandated rather than willingly chosen.

@CharlieHanson That's still no excuse for not starting at the beginning of the correct sequence of steps - or maybe paying attention in class instead of playing Candy Crush Saga on his phone...

I was referring to "forget this game project of yours". OP does not have the luxury of time to go back to basics. Never mind, it was a whimsical comment.

@CharlieHanson This is a project which would take about 30 minutes of actual work once you know how to perform the basics.  An evening of learning those basics should be all that is needed.  Without learning those basics the project will fail, so it must therefore be sensible, since there is now nothing to lose, to spend the rest of what time is left trying to learn those basics with the hope of having 30 minutes at the end to actually write the code.  In fact, for someone like you or I probably nearer 10 minutes is needed.

So...can u plz use the 10 minutes to write it to make it work then? just this once?

I agree with Majenko. Forget this game and learn how to code in C. If you don't know, and want us to write your code for you, then you will be fraudulently passing this test. Even if you don't care about that, someone will, one day. Imagine your teacher asks you a simple question about the code: "why did you do X?".  Your complete inability to explain the code, or modify it, will expose that someone else wrote it.

regardless of the convincing nature of your argument, the idea is pass now, learn later. I realize that this is far from good, but, hey, it's all that can  work now. However, if not acceptable, can you at least tell me what I missed?

"can you at least tell me what I missed?" @errr About 6 lectures by the sound of things.  We are not going to do your work for you.

the teacher has not taught anything. He said cheating is fine, if you know where to look. It's digital electronics, he doesn't know anything at all, in fact even less than  me, about arduino ide @majenko

how is telling me I missed 6 lectures useful@majenko

Instead of posting your question four or five times here, how about using the time on your hands constructively by learning some coding? The IDE comes with examples. There are lots of web sites about how to program in C. No-one will want to do your homework for you. the teacher has not taught anything. He said cheating is fine - especially now.

how is telling me I missed 6 lectures useful ... He said cheating is fine  - how is cheating useful? You pass a course by cheating? Does that mean you then design an aircraft without knowing what you are doing because you cheated your way through the course? Please supply your teacher's name so we can write to his supervisor. That teacher should be sacked. If you are telling the truth, that is. Which I doubt.


text:
How to wire Christmas lights with LEDs to use for Arduino Project?
First things first, I am new here and this is my first post. So if this is in the wrong place I apologize and please just let me know.
I am a programmer that is getting into working with an Arduino compatible board, so my questions are 99% of the time with the hardware side and not the software side.
I just went through a tutorial on how to connect LEDs in parallel to a shift register so that I can control each LED individually.
My project goal is to make a Christmas house for a family member that will use some predefined songs to blink the lights to. So what I am actually looking for suggestions for is how to make a string of LEDs (5mm) that I can hook up to a small house without it looking messy. I was thinking I could maybe use 2 wires to run along the + and - of all the LEDs and then maybe there is some kind of connector I can use to split the 8 LEDs off to their respected hookups on the shift register.
Any good ways of doing this and keeping the metal unexposed?
I thank you in advance for your answers and your time!

Honestly? Find yourself a string of WS2812s and use that instead of trying to tear apart a conventional string of lights.

I have no idea what that is. I am trying to make my own string of lights using 5mm LEDs.

Here is a string of Stripleds operated from a CPU 12V supply with built-in double-sided tape under the hand rail in one of my homes. Red downstairs and blue upstairs.
Now define your input and output attributes to modulate the current.

"in one of my homes" .... +1 for being subliminally ostentatious ;-)

( that I have previously lived in)FYI  +0  value added comment


text:
Problem interfacing CR95HF with Arduino Uno
I am interfacing a CR95HF with an Arduino to detect NFC tags. I have taken the code from this link as reference. I am able to get the response to the IDN command, and also set the protocol (ISO/IEC 14443-A). But the tag is not detected. What should I do to detect the tag?

is the tag functional?

yes tag is working ,I have tested with other nfc reader


text:
How to create real-time WASD control over an Arduino Uno?
I am trying to figure out how to use the WASD keys on my computer, to go through the USB cable and then spin the Arduino servos in real-time. So if I press the “a” key, it should start to move left with little time delay. How do I do this?

do it is steps ... first write code to get data from the PC to the arduino .... when you are successful, add code to move servos

why this way? you could start some serial terminal program which sends the character immediately, but much simpler is to put 4 buttons on breadboard or to use a small joystick

In any case you need some software on your PC to send the key events to the Arduino. The simplest solution can be the Serial Monitor of the IDE. Try this and if you have problems with the Arduino sketch, feel free to [edit] your questions. BTW, you might like to take the [tour] and learn [ask].


text:
Device Security - EEPROM data
I'm writing code for Arduino that I plan to distribute. But I worry about piracy (the .HEX can extracted from the board and reuploaded to another).
With that in mind, I am storing data to the EEPROM.
Since I am storing data to the EEPROM, can the data be extracted in some way?

You can set the lock fuses to prevent people from reading the flash memory containing your program. I’m not sure if these lock fuses will also protect the eeprom? You could add some very simple encryption. I’ve heard of companies XORing the data with a secret byte.

the only way to protect your program is to not distribute it. .... if someone really wants to copy your program, and they have physical access to the device, then they will find a way to copy the program .... even if it is encrypted, they do not have to decrypt it to copy it

IMHO, due to the amount of code you can fit on an AVR, I (or any coder) can recreate a sketch from hand in a few days (worst-case). The idea is the idea, not the code.

@gre_gor - OP is asking if the EEPROM can be secured, not the firmware

Nothing is 100% secure. For example, EEPROM and flash can be read using techniques like Scanning Probe Microscopy & Scanning Electron Microscope, even if the security bit is set. IMO, the goal to safely securing your data is to make it extremely hard. You should take a look at the ATAES132a from MicroChip.

The first device in the AES family, the ATAES132A, is a high-speed, high-security, 32K Serial EEPROM that enables authentication and confidential nonvolatile data storage

It also boast a tamper resistant hardware

The ATAES132A device contains physical security features to prevent an attacker from determining the
  internal secrets. ATAES132A includes tamper detectors for voltage, temperature, frequency, and light, as
  well as an active metal shield over the circuitry, internal memory encryption, and other various features.
  The ATAES132A physical design and cryptographic protocol are designed to prevent or significantly
  complicate most algorithmic, timing, and side-channel attacks.


text:
Reading text from SD card is returning weird characters
I have an ebook which is converted to a .txt file saved on an SD card, which is connected to the Arduino. I'm trying to display the words from the book on a 16x2 LCD display, one word at a time. It works mostly except when it reads a word that has an apostrophe or a pipe symbol: it does not display correctly to the LCD or the serial output.
For example the word "author's" will be displayed as "authorâs" (edit: there is actually two boxes between the "â" and the s that is not displaying on this forum) on both the LCD and serial output.
I've spent an entire day now with this one problem hopefully there is a mistake someone can pick up on :/
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 53;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

char nextChar;
String wordBuffer = "";

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt");
  if (dataFile) {
    while (dataFile.available()) {
      nextChar = dataFile.read();
      if (isWhitespace(nextChar)){
        lcd.print(wordBuffer);
        Serial.println(wordBuffer);
        lcd.display();
        delay(500);
        wordBuffer = "";
        lcd.clear();
      } else {
        wordBuffer = wordBuffer + nextChar;
        wordBuffer.trim();
      }
    }
    dataFile.close();
  } else {
    // if the file isn't open, pop up an error:
    Serial.println("error opening datalog.txt");
  }
}

void loop() {
}

When you look into the .txt file and look for that word and show the hexadecimal values for that word, can you see if that is normal ascii code or something else? You show the sketch, but I think the problem is the way the ebook is converted to a .txt file.

I checked the .txt file and it's in utf-8. I used calibre to save it as ascii but now in the text document a lot of letters have been replaced with question marks. Converting to ascii is not really going to work if things like apostrophes become question marks. maybe I can find a different format that will work.

The text file is not ASCII, it is UTF-8. You will either have to convert it to pure ASCII, or write (or obtain) a conversion routine to approximate the UTF-8 characters using ASCII on the Arduino.
Maybe this can help you.


text:
Convert float to hexadecimal value
I am trying to convert a float value to a 4-byte hexadecimal value.
For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.
My program is:
void setup() {
  Serial.begin(9600);
  float z = 128;
  unsigned i;
  unsigned char *chpt;
  chpt = (unsigned char *)&z;
  Serial.print("Float Value             : ");
  Serial.println(z);
  Serial.print("4 Byte hexadecimal Value: ");
  for (i = 0; i < sizeof(z); i++) {
    Serial.print(chpt[i],HEX);
    //Serial.print(" ");
  }
  Serial.println();
}
void loop() {
}

My current output is:
Float Value             : 128.00
4 Byte hexadecimal Value: 00043

This value looks pretty correct to me. It is stored in little endian thou.
0x43000000 is the actual value.
Serial.print(x, HEX) truncates leading zeros. so 00 gets 0
So your output is 0 0 0 43 which corresponds to the little endian representation of the above.
Make yourself familiar with the floating point representation IEEE-754.
Also try the online FoatConverter.
Try the following:
char floatString[9];
sprintf(floatString, "%02X%02X%02x%02x", chpt[3], chpt[2], chpt[1], chpt[0]);
floatString[8] = '\0';
Serial.print(floatString);

Thanks for the reply @kwasmich If I input the float value say Float Value                  : 235.56 I am getting values like this.
4 Byte hexadecimal Value: 5C8F6B43 Any changes in the program that you would like to suggest to obtain the result as 436B8F5C

I just added some sample code that should give you what you wanted in the first place.

printf is a powerful tool. %02X means, print the value as hex (x) with at least 2 places width (2), padded with zeros(0).

Thanks a lot!!!!!!!!!!!!! I as able to get my output. But then I am manually entering the float values. What should I change in the program so as to input a float value from Serial monitor and get the output in serial monitor?

I don't have a ready made solution for that. But the steps would be similar but in reverse. Use String string = Serial.readString(); to obtain the entire string in one block. Use sscanf(string.c_str, "%02X%02X%02X%02X", &chpt[3], &chpt[2], &chpt[1], &chpt[0]); to transfer the read hex values into the byte array. Something like that.

Thanks it helped me

You're welcome. Consider accepting my answer as the solution to the problem and let others know your question has been solved.

Sure ... !!! It has been solved and it worked very well


text:
Timer CTC Set and Clear modes -- How to un-Clear and un-Set?
Nick Gammon's cheatsheet for the Ardunino UNO's ATmega328P (below) shows some hints on the Clear Timer on Compare (CTC) modes of AVR chips.  Most of the examples for CTC mode I find use the COMxxx registers of 01 = toggle to control the OCxx pin, which would give a 50% duty cycle at 1/2 the frequency of the timer clearing.
My question is about using the non-toggling COMxxx modes of Clear and Set, which don't seem to provide an automatic way to reset into the opposite state, as in the PWM modes.
For example:

void setup() {
  // put your setup code here, to run once:

   // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
   // Output on OC1B
   // Clear at OCR1B
   // WGM =15 0b0100

   DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
   TCCR1C = 0;  // Note that it is good to initialize the timer
                // into a known mode before trying to set interesting TOPs
   OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
   OCR1B  = OCR1A/2;    //  ~50% duty cycle
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  //OCR1B = 62500U/4-1; // 25% duty cycle.
}

If I try the above code, I get a 0.125Hz ( 8s period signal) on PB5 and a constant low on PB6.
What is the way to set OC1B high to be cleared by the timer match?  And similarly, vice versa: clearing OC1B to be set by the timer match?
Is there a direct way or do you fiddle with COM1Bx, trigger FOC1B, and then fiddle COM1B back?

This code uses the TCCR1C:FOC1B register to set the bit by messing with the TCCR1A:COM1Bx bits, but it seems awkward:
void setup() {
   // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
   // Output on OC1B
   // Clear at OCR1B
   // WGM =15 0b0100

   DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
   TCCR1C = 0;  // Note that it is good to initialize the timer
                // into a known mode before trying to set interesting TOPs
   OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
   OCR1B  = OCR1A/2;    //  ~50% duty cycle
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
   TCNT1 = 0 ;
}

void loop() {
  int saveCOM;
  Serial.println(TCCR1A,BIN);
  delay(7000); // 7 seconds
  saveCOM = TCCR1A;
  TCCR1A |= bit(COM1B1) | bit(COM1B0) ; // config for set OC1B
  TCCR1C = bit(FOC1B); // force a compare to set bit
  TCCR1A = saveCOM ; // restore mode
}

This code has the 0.125Hz on OC1A, and a semi-random series of 1-4 second long pulses on OC1B.
I was interested in playing with the CTC modes for doing long cycle/low frequency PWM.  With the normal PWMs you could range from a 1-bit 50% PWM at 8MHz to a 16 bit PWM at a frequency of 0.119Hz (8.388s)  With the CTC modes, if you could manage the sets and clears in an TIMERx_OVF_vect with a couple 16 bit registers, you could extend it to 32 bits of PWM resolution with a period up to 152 hours.

If you don't set the WGM mode before you set the TOP/OCR1A/ICR1, it could be truncated to 8 (, 9, or 10?) bits from the Arduino default WGM=5=0b0101 modes.

You can set the output using digitalWrite(10, HIGH). On compare match it's cleared. If it was already cleared, nothing happens. This would be useful to create a single pulse of a precise length.

@Gerben Maybe it's my Teensy 2.0, but putting digitalWrite(PIN_B6,HIGH) or digitalWrite(15, HIGH) seems to stay high forever after the CTC config, or be cleared immediately if before the CTC setup. Checking TCCRA1, it seems that digitalWrite(PIN_B6,HIGH) unsets COM1B1 and COM1B0.

Sorry, stupid me. The digitalWrite implementation will disable PWM. Instead do something like PORTB |= _BV(PB2).

@Gerben.  Stiil nope.  it seems that the PORTB bit value is inhibited/overriden by the OC1B state.  "If one or both of the COMnB1:0 bits are written to one, the OCnB output overrides the normal port func- tionality of the I/O pin it is connected to. If one or both of the COMnC1:0 bits are written to one, the OCnC output overrides the normal port functionality of the I/O pin it is connected to." in the TCCR1A section of my datasheet.  If I toggle COM1Bxx on and off with an underlying high PORTB, it toggles the voltage off and on at the pin.

Teensy2.0 atmega32u - my cheat sheet was for the Atmega328P. Things are likely to be a bit different.

It is a bit different, e.g., the atmega32u has an OC1C, and they are on different bits, but the basic functionality appears to be much the same.

http://arduino.stackexchange.com/questions/30507/timer2-clear-oc2b-on-compare-match-not-working-as-expected-in-ctc-mode/30529#30529 is related

@NickGammon:  On a Atmega328P, is there a convenient way to un-set or un-clear a timer in CTC clear-on-match, or set-on-match mode?  I tried a three-step process of inverting the COM mode, forcing a match, and resetting the COM mode, but that seems awkward.

@DaveX I think (without testing it) that you would write 0 to TCNT1, possibly stopping the timer first.

@NickGammon  -- I'm sorry, I asked the wrong question.  I meant how do I set the OC1A pin when i'm using the clear-on-match CTC mode (and vice versa)  I know toggle changes it every match, but I don't understand how to use the non-toggle modes.

@DaveX If you have another question, please post an actual question. This site is not a forum.

The comment by the OP under the question is:

I meant how do I set the OC1A pin when i'm using the clear-on-match CTC mode (and vice versa) I know toggle changes it every match, but I don't understand how to use the non-toggle modes.

This code toggles OC1A (D9 on the Uno) at a frequency of 19kHz giving an overall frequency of 38kHz:
void setup()
 {
  pinMode (9, OUTPUT);
  TCCR1A = bit (COM1A0);  // toggle OC1A on match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  (F_CPU / 38000L) - 1;       // zero relative
  }  // end of setup

void loop()
  {
  }

The non-toggle modes aren't particularly useful. When it matches it sets the output high, or low, which doesn't really achieve much in this case.
I suppose if you had a long CTC time (big prescaler and large amount to count up to) then you could use it to set that pin to high or low when the time elapsed.

On a Atmega328P, is there a convenient way to un-set or un-clear a timer in CTC clear-on-match, or set-on-match mode?

Do you mean the timer output? Not really because setting those bits means the timer controls the output pin. What you could possibly do is turn off the output control (bit (COM1A0)), change the pin yourself, and put it back, but I'm not sure if that would switch it back to the timer output.

Yes, I mean the timer output.  It seems as if the CTC+set or CTC+clear modes could be a reasonable choice for using a timer to do a one-shot, but the reset seems uncertain.  In higher frequency toggling modes one can often ignore the initial state, but for a one-shot behavior you need to know/control the initial state. // So one can't unset the timer output within a CTC set-on-match mode, and to do so you must exit the mode.  And that OC1A might be initialized using the PORTB:1 bit when the you turn on the output control (bit COM1A0).  I'll experiment with it.

@DaveX For the long periods you are describing it is probably easier to just have it trigger an interrupt and set the pin in the interrupt handler.


text:
Thermocouple and multimeter
I've put together this script that should allow my Arduino Mega to be show thermocouple readings on the serial monitor, whilst also showing readings of voltage and ohms across a given component. I'd be grateful for any advice on how it can be improved/streamlined:

#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int raw = 0;
int Vin = 5;
float Vout = 0;
float R1 = 220;
float R2 = 0;
float buffer = 0;
float volt = 0;
int input = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);
  tempSensor.begin();

  if (tempSensor.isConnected()) {
    Serial.println("Device will acknowledge!");
  }
  else {
    Serial.println("Device did not acknowledge! Freezing.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Device ID is correct!");
  }
  else {
    Serial.println("Device ID is not correct! Freezing.");
    while (1);
  }

  pinMode(A4, INPUT);
}

void loop() {

  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }

  raw = analogRead(analogPin);
  if (raw)
  {
    buffer = raw * Vin;
    Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

"should allow": does it, or doesn't it?

Does the code work as it is? I see you’re defining some variables  (like Vin, R1, analogPin) that are never changed and actually only used as constants. You should define them as “const” or use #define (for example for the analog port numbers).

Your code is not very long, but I already see a few things that I would change.
int analogPin = 0;
[...]
pinMode(A4, INPUT);

These usages of pins are inconsistent. I personally prefer settings at the beginning of the file, so I'd expect
int analogPin = 0;
int whateverPin = A4;  // I don't have a good name yet

While you have
pinMode(A4, INPUT);

there's no
pinMode(analogPin, INPUT);

The main loop is doing 2 things: a) show temperature reading and b) show the component specs. This would be more obvious if written like this:
void loop() {
  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  showTemperatureReadings();
  showComponentReadings();
}

Now, that looks a bit strange, don't you think? What about the stuff before these two big show...() methods? These two lines clearly belong into showComponentReadings().
Now, a lot of variables are declared outside of methods. This makes them global variables. It's possible to change them from anywhere in the code. When the project grows, side effects are evil. Let's remove as many of them as possible.
You can get rid of:
int input = 0;
float volt = 0;
float buffer = 0;
float R2 = 0;
float Vout = 0;
int raw = 0;

After this change, I think the setup() method could be more concise. A lot of stuff just deals with the temperature sensor. I would extract a method as well.
The error messages like

Device did not acknowledge! Freezing.

could not mean very much to the user. A message like

Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.

could give more meaningful instructions.
The final code with these suggestions applied:
#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int whateverPin = A4;
float R1 = 220;
int Vin = 5;

void setupTemperatureSensor() {
  tempSensor.begin();
  if (tempSensor.isConnected()) {
    Serial.println("Temperature sensor acknowledged.");
  }
  else {
    Serial.println("Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Temperature sensor ID is correct.");
  }
  else {
    Serial.println("The temperature sensor ID does not have the expected value. Do you use a different sensor type? Use a SparkFun MCP9600.");
    while (1);
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);

  setupTemperatureSensor();

  pinMode(whateverPin, INPUT);
  pinMode(analogPin, INPUT);
}

void showTemperatureReadings() {
    if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }
}

void showComponentReadings() {
  int input = analogRead(whateverPin); //analogRead function is used to receive analog data
  float volt = (input * 5.0) / 1024.0; //formula using for perform action
  int raw = analogRead(analogPin);
  if (raw)
  {
    float buffer = raw * Vin;
    float Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    float R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

void loop() {
  showTemperatureReadings();
  showComponentReadings();
}

With code folding active, I'd say it's now very simple to get an overview of what the code is doing and what can be configured:

Edit:
After you linked to the schematics, I would

rename whateverPin to voltageDividerPin.
change the calculation float volt = (input * 5.0) / 1024.0; to a mapping, because it maps the 1024 input values to 5V, so float volt = map(voltageReading, 0, 1024, 0, Vin);
remove analogPin completely, because it's not used in the original code as well.

I also hope that read the article and you understood the consequences of using a 220 Ohm resistor.

Re “I'm not sure whether analogRead() works [with 0 as an argument]”: It does. analogRead() treats A0 (defined as 54 on the Mega) as equivalent to 0.

The ohmmeter code came from here: http://www.circuitbasics.com/arduino-ohm-meter/
I'm guessing the circuit layout is still fine?

@Chris: I've updated the answer according to the schematics

It'll be 220mOhm in my case as the unknown resistance should be around there. Thanks again!

@Chris: 5V/440mOhm=11A. The Arduino can handle a maximum of 500 mA on its 5V pin. Also, you need a 28W resistor to handle the power, otherwise it'll go up in flames. It's ok, if you have considered all the electrical stuff. I just don't consider that the "normal" Arduino usage.

I'm using 1kOhm resistors to keep the overall circuit resistance down. There are three connecting the breadboard to the 5V source, GND and the analog-read pin.  But fundamentally I need the Arduino to identify the unknown resistance, which just happens to be tiny in this case.


text:
Yun - FileSystem.Open prevents client.println from outputting to web page
The below code is meant to display lines stored in a text file to an arduino based web page (it's a IR gate monitoring solution).
When I visit
I can execute client.println("hello") and I see the word "hello" on the page.
Then I loop round the SD card rows and I can Serial.print (by char) in the Serial Monitor all the lines in the text file. Great - so far so good.
But when I attempt to print to screen (instead of Serial Monitor) it does not work.  The offending line (but don't know why) is the FileSystem.Open - this prevents any further output to screen.
Why does FileSystem.Open prevent client.print from working?

  void loop() {

  YunClient client = server.accept();

  if (client) {
    String command = client.readString();
    command.trim();
    Serial.println(command);

    if (command == "today")
    {
        //client.println("hello");

        // Get a timestamp
        String strTS = getTimeStamp();
        String strFileName = strTS;

        // Build the file name containing the
        strFileName.replace("-", "_");
        strFileName.replace("/", "-");
        strFileName.replace(":", "-");
        strFileName = strFileName.substring(0, 8);
        strFileName = "/mnt/sd/BeerLogger/" + strFileName + ".txt";

        // Display the file name in the serial window
      //  Serial.println((strFileName).c_str());

        // Print the contents of the text file to screen
        File myFile = FileSystem.open(strFileName.c_str(), FILE_READ);

        if (myFile) {
           while (myFile.available()) {
              char c = myFile.read();
              if ( c == '\n') {
                //client.println("");
              }
              Serial.print(c);
              client.print(c);
          }
          myFile.close();
      }
    }

    // Terminate the client connection so we may resume
    client.stop();
    //Serial.println("client disconnected");

  } else {
      MonitorIRGate();
  }
}


text:
Suggest me some good seller for Arduino UNO
I want to start a new project with arduino uno and want to make some amazing mini projects, but i am confused that from where should i buy. So please suggest me some affordable robotic stores.

I'm sorry, this is an opinion-based question. Your question is very likely to be deleted. But as stated below, you can always check aliexpress.com.

I recently bought some arduino nano V3 on Aliexpress. It cost me €1.75,- so I immediately bought 4 :P arrived within 10 days. Also the arduino uno R3 (non-official) is only €3,-. Worth the try? I would say definitely, because if you need it for a project you want to leave it in not take it out because you have another idea. Hope this helps.

Thanx weaverworm for this suggestion.

I would comment, but my rep is not high enough so consider this a comment:
Welcome to StackExchange. You should maybe take a look at some guidelines on how to ask good questions.
First of all: mind your tune! ASAP in capitals is very impolite and implies a request we MUST fulfil - no we don't. Try to use please and thank you and everyone will be happy.
Second: this is a Q&A Site to help people now and in the future, so most of the time questions like: where can I buy this or what book is good are not what this is made for because they won't be valid for very long and have been asked many times before (but answers lost their validity as mentioned above).
and last but not least: Google it. Ebay, Aliexpress, Amazon... whatever you fancy. There are many Arduino clones for low prices around. I bought a few UNOs for like 6€ each. They work fine.
With that in mind: welcome again. I hope you find many useful answers around.

ok i understand, this is a first and last mistake.


text:
Assemble or typecast byte array to float
The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays
0.00
0.00
0.00 etc.
Here is the code:
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[3];
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    float yawAngle = *((float*)(yawData));
    Serial.println(yawAngle);

    byte pitchData[3];
    pitchData[0] = Serial2.read();
    pitchData[1] = Serial2.read();
    pitchData[2] = Serial2.read();
    pitchData[3] = Serial2.read();
    float pitchAngle = *((float*)(pitchData));

    byte rollData[3];
    rollData[0] = Serial2.read();
    rollData[1] = Serial2.read();
    rollData[2] = Serial2.read();
    rollData[3] = Serial2.read();
    float rollAngle = *((float*)(rollData));
  }
}

I made sure the data coming to Serial2 is not 0.
UPDATE: The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

Your byte array is 3 bytes length, while you're assuming it's 4 bytes !

@KiraSan Thanks for the hint! Made an edit because of a new problem... Maybe you know some more magic tricks? ;)

Did you try the code in my answer? maybe you should inverse the bytes order to get the correct values.

@KiraSan Yep, tried it, gives me not a single correct reading :/

I have edited my answer since that time. please check it out.

But it's still about the Byte order, right? Checked that, doesn't work...

Can you show me the code running on the sender of these bytes?

I'm using a pretty good firmware for my the IMU from which the data it coming. The file with the output code can be found on Github.

You might also want to take a look at this Processing sketch, as it demonstrates reading the data successfully.

Let us continue this discussion in chat.

I tried the code below and it worked for me, don't miss the delay() part:
Sender Code:
void setup() {
  Serial.begin(9600);
}

void loop() {
    float yaw = 10.5;
    float pitch = 20.15;
    float roll = 100.10;
    float ypr[3];
    ypr[0] = yaw;
    ypr[1] = pitch;
    ypr[2] = roll;
    Serial.write((byte*) ypr, 12);  // No new-line
    delay(1000);

}

Receiver Code:
void setup() {
  Serial.begin(9600);
}

void loop() {

}

void serialEvent() {
    if (Serial.available() == 12){
      byte yawData[4];
      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawAngle = *((float*)(yawData));
      Serial.println(yawAngle);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawPitch = *((float*)(yawData));
      Serial.println(yawPitch);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawRoll = *((float*)(yawData));
      Serial.println(yawRoll);
    }
}

Results:

If you must do it that way I'd recommend using a union:
typedef union {
    float val;
    uint8_t bytes[4];
} floatval;

floatval v;
v.bytes[0] = Serial2.read();
v.bytes[1] = Serial2.read();
v.bytes[2] = Serial2.read();
v.bytes[3] = Serial2.read();
Serial.println(v.val);

A better solution is to just write and read the raw float data:
// Sender:
Serial.write((const char *)&myfloat, sizeof(float));

// Receiver
Serial2.readBytes((char *)&myfloat, sizeof(float));

Even better still is to define a struct which is the packet of data you wish to send:
typedef struct {
    float yaw;
    float pitch;
    float roll;
} attitude;

attitude myatt;
myatt.yaw = 14.9;
myatt.pitch = 23.4;
myatt.roll = 11.49;

Serial.write((const char *)&myatt, sizeof(attitude));

// receive:

attitude myatt;
Serial2.readBytes((char *)&myatt, sizeof(attitude));
Serial.println(myatt.yaw);
Serial.println(myatt.pitch);
Serial.println(myatt.roll);

First of all, thanks! I tried the method with a struct and it works for about a second until the data seems to be corrupted. Maybe a few bits are being dropped from time to time? How can I prevent this?

For that you need to construct a proper packet. I have a good library that can help. Google "Arduino ICSC"

What if you write
yawData[3] = Serial2.read();
yawData[2] = Serial2.read();
yawData[1] = Serial2.read();
yawData[0] = Serial2.read();

i.e. you change the endianness of the representation

I already told him about it, but it turned out that it's not the problem, by looking at the sender's code, the bytes are in the same order as expected by the reader code.

try use memcpy, i think it might work:
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[4];
    float yawAngle = 0;
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    memcpy(&yawAngle, &yawData,sizeof(float));
    Serial.println(yawAngle);

    // same for others ...
  }
}


text:
Problem with analog pins' name when trying to connect Arduino board and Processing
I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:
import processing.serial.*;
import cc.arduino.*;

Serial myport;
Arduino arduino;

color off = color(4, 79, 111);
color on = color(84, 145, 158);
int val=0;
float value=0;
void setup() {
  size(600, 600);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(0, Arduino.INPUT);
}

void draw() {
  stroke(on);
  value = arduino.analogRead(0);
  println(value);
  ellipse(300,300,value,value);
  delay(100);
}

My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob.
Thanks

Have you uploaded the firmata to arduino? (instructions from arduino playground - "Run Arduino, open the Examples > Firmata > StandardFirmata sketch, and upload it to the Arduino board."

Yes, I already did that. Also tried different values as the port number but still the outputs are always zero

you have a typo in code? val = arduino.analogRead(0); shouldn't it be value? Because after you only use value and never val

it was typo in the code here but in my original code it is correct.

strange... your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing screenshot. if it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

I downloaded the new version of Firmata for Arduino and now it works. Strange! But it is solved anyway.
Thank you very much.

@Personagem it seems your comment led the author to solving his problem. You should bump it down to an answer and hopefully the OP will accept it for you :)

(as suggested in comments to bump it down)
your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing

If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

Just a comment that can help others is that list of ports is important in order to find the right port.


text:
Including Class with .h and .cpp files
I am trying to use a class in .ino file. The code is:
  .ino file
#include <LED.h>

int Pin1 = 13;
int Pin2 = 12;
int Pin3 = 11;
LED led;
void setup() {
  pinMode(Pin1,OUTPUT);
  pinMode(Pin2,OUTPUT);
  pinMode(Pin3,OUTPUT);
  digitalWrite(Pin1,LOW);
  digitalWrite(Pin2,LOW);
  digitalWrite(Pin3,LOW);
}

void loop() {
  led.on(Pin1);
  delay(2);
  led.on(Pin2);
  delay(2);
  led.on(Pin3);
  delay(2);
}

.h file
#ifndef LED_h
#define LED_h

class LED{
public:
    void on(int);
    void off(int);
};

#endif

.cpp file
#include <stdio.h>
#include <Arduino.h>
#include "LED.h"

void LED::on(int PIN){
    digitalWrite(PIN,HIGH);
}

void LED::off(int PIN){
    digitalWrite(PIN,LOW);
}

Arduino compiler picks the object declaration error:
LEDC:6: error: 'LED' does not name a type
LEDC.ino: In function 'void loop()':
LEDC:17: error: 'led' was not declared in this scope
How should I declare objects in Arduino then?
The way that I am putting the files in folders is like the attached image:

There is nothing syntactically wrong with your program - it compiles perfectly in UECIDE. My guess is it's something to do with the Arduino IDE.  Which version of the IDE are you using? I know that recently they have made some changes to how the compilation works (or maybe doesn't work).

It is Arduino 1.5.6

Your LED.cpp and LED.h files are in an LEDD subfolder. In your LEDC.ino file you should use #include "LEDD/LED.h"

That version of the IDE (it seems to change from version to version) differentiates between includes with <...> and includes with "...".
If you use <...> it only looks in the system and library areas.  If you use "..." it also looks inside your sketch.
So in your main INO file change the LED include from:
#include <LED.h>

To:
#include "LED.h"

and it should compile.

Still does not compile. Maybe the way that I am putting the files in folders is not right? See the image in main question.

I did it by adding two new tabs - LED.cpp and LED.h and pasting your code into them.

All you need to do is this in the (.ino)
#include <LED.h>

int Pin1 = 13;
int Pin2 = 12;
int Pin3 = 11;
LED led1;
LED led2;
LED led3;
void setup() {
  pinMode(Pin1,OUTPUT);
  pinMode(Pin2,OUTPUT);
  pinMode(Pin3,OUTPUT);
  digitalWrite(Pin1,LOW);
  digitalWrite(Pin2,LOW);
  digitalWrite(Pin3,LOW);
}

void loop() {
  led1.on(Pin1);
  delay(2);
  led2.on(Pin2);
  delay(2);
  led3.on(Pin3);
  delay(2);
}


text:
Cannot program Mega2560 using Atmel Studio 6.2 and avrdude
So I will admit that I am a noob to Arduino. I have some experience programming microcontrollers, and that was back in the day (about 4 years ago - such as the Freescale 68HC12) so up until this point I thought I was experienced enough to get this Arduino Mega2560 rocking with AVR C using Atmel Studio and avrdude by lunch...
Wrong.
I believe I'm getting held up at what's possible...
What I want to accomplish: Write and compile a program in AVR C within Atmel studio. Use the hex file that was built and download that to the Mega. (Keep in mind I was planning on using USB and Arduino as my programmer between PC and ATMega2560 as per this gentleman's example... https://balau82.wordpress.com/2011/03/29/programming-arduino-uno-in-pure-c/ -- however, I was not using his code and he was compiling using avr-gcc...)
Question: Is this possible?
Using avrdude when attempting to write the file I get this message... (and my blinking LED goes dark for a few seconds before returning to normal operation)

When I searched the internet for this issue it was never related to avrdude, but rather a communications issue. I've verified my bootloader is still ok (uploaded other sketches with no issues).
It's certain that I am missing something minor, but this is my first day using Arduino so go easy on me!
Thanks

try -c wiring instead of -c arduino. Thats what the IDE uses when uploading to a mega.

Unfortunately, I tried that and I get - avrdude: Can't find programmer id "wiring"

Ok so I've got it to the point of actually uploading to the Mega... and that happened using this line - avrdude -F -V -c wiring -p m2560 -P COM3 -b 115200 -D -U flash:w:tmp\BlinkLED.hex:i but unfortunately I'm getting no blinking! But I think that it's a code/ports pin thing. Thanks for the help guys!


text:
Wifi Data Logger without Delay
I am really new to Arduino so please bear with me.
I am running an Arduino Uno with several sensors to capture some data related to a fish tank. Here is basically what it does:

Capture data (light, temperature, etc.)
Display data on an LCD screen when a button is pressed
Upload data to thingspeak every 5 minutes, using a ESP8266
Feed the fish every 4 hours through a servo
An RGB led blinks at various colors to let me see what's happening (e.g. red when connecting to wifi).

Everything is working reasonably well. That being said, my code is super messy and I am not sure I have the right approach. With the code I have:
 - Nothing can be done while the Arduino uploads the wifi
 - Nothing can be done when the fish are fed.
This is not so much about the servo, it is more about the wifi problem. How would you suggest that I rewrite my code so that (1) I can run the wifi more than once every 5 minutes and (2) it does not block my sensors and LCD display while I am doing it.
Sorry for the poor quality of the code. Newbie here.

//Include LCD Libraries
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <stdlib.h>

//Include Water Probe library
    #include <OneWire.h>

//Include DHT11 Libraries
    #include <dht11.h>

//Include Servo Libraries
    #include <Servo.h>

//Set Peripherals
    dht11 DHT11;
    LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
    Servo myservo;  // create servo object to control a servo

//Pins for LCD are SDA=A4 and SCL=A5

//Variables for sensors
    String sunlight;
    String watertemp;
    float airtemp;
    float airhumid;
    OneWire  ds(10); //water temperature, pin 10

//Variables for LCD button
    #define BUTTON_PIN A3    // Set pin Buttons for Backlight LCD.
    unsigned int currentLcdLightOnTime = 0; // For calculating the lcd light on time.
    unsigned long lcdLightOn_StartMillis;
    boolean isLcdLightOn;
    int buttonState = 0;// For checking push-button state.

// Variables for Status LED
    int ledState = LOW;             // ledState used to set the LED
    long previousMillis = 0;
    long interval = 1000;           // interval at which to blink (milliseconds)

//Variables to display LCD Numbers
    char bufferhours[5]; //Output of the itoa function for hours
    char bufferminutes[5]; //Output of the itoa function for minutes
    // We don't care for seconds. It's irrelevant.
    int moisture;

//Variables for Wifi Update
    //long DELAYWIFI = 10000; //For test purposes
    long DELAYWIFI = 300000; //Every 5 minutes
    long endtimewifi;
    long nowwifi;

//Variables for Servo
    long FEEDINGDELAY = 14400000; // Feed every 4 hours
    //long FEEDINGDELAY = 30000; //For test purposes
    int pos = 0;    // variable to store the servo position
    long endtime;
    long now;
    long timeuntilfeeding;

//Variables for Sunlight
    float percent; //transform number above into a percent

// Variables for Wifi Updates

    #include <SoftwareSerial.h>

    //Hardware Serial
    #define _baudrate 9600

    //Software Serial
    #define _rxpin      0
    #define _txpin      1
    SoftwareSerial esp8266( _rxpin, _txpin ); // RX, TX

    //Thingspeak and Wifi Information
    #define SSID "xxx"
    #define PASS "yyy"
    #define IP "zzz" // ThingSpeak IP Address: 184.106.153.149

    // GET /update?key=[THINGSPEAK_KEY]&field1=[data 1]&filed2=[data 2]...;
    String GET = "GET /update?key=www";

// Initiates special characters. http://omerk.github.io/lcdchargen/

byte thermometer[8] = //icon for thermometer
{
    B00100,
    B01010,
    B01010,
    B01110,
    B01110,
    B11111,
    B11111,
    B01110
};

byte droplet[8] = //icon for water droplet
{
    B00100,
    B00100,
    B01010,
    B01010,
    B10001,
    B10001,
    B10001,
    B01110,
};

byte degree[8] = { // degree centigrade
  B01000,
  B10100,
  B01000,
  B00011,
  B00100,
  B00100,
  B00011,
  B00000
};

byte sun[8] = {
    0b00100,
    0b10001,
    0b01110,
    0b11111,
    0b11111,
    0b01110,
    0b10001,
    0b00100
};

void setup()
{
  lcd.init();// initialize the lcd

//Initialize DHT/
    DHT11.attach(2);

// set the digital pin as output for LED:
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(11, OUTPUT);

//Connect to Wifi
    Serial.begin(9600);
    esp8266.begin(9600);
    boolean wifi_connected=false; //not connected yet...

    sendesp8266("AT");
    delay(2000);
    for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
    {
    if(connectWiFi()) //are we connected?
    {
    wifi_connected = true; //yes
    break; //get outta here!
    }
    }

//Initiate characters
    lcd.createChar(0, thermometer);
    lcd.createChar(1, droplet);
    lcd.createChar(2, degree);
    lcd.createChar(3, sun);

}

void loop(){
    now = millis();
    endtime = now + FEEDINGDELAY;

    while(now < endtime) {   // While loop for the feeding
    timeuntilfeeding = endtime - millis();
    now = millis();

    nowwifi = millis();
    endtimewifi = nowwifi + DELAYWIFI;

    while(nowwifi < endtimewifi) {   // While loop for wifi update
    nowwifi = millis();

//We capture sensors

    //Sunlight
    float value_sunlight = analogRead(A2);
    percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
    String sunlight =String(percent);// turn integer to string

    //Water Temperature
    float value_watertemp = getTemp();
    String watertemp= String(value_watertemp);// turn integer to string

    //Air Temperature and Humidity
    int chk = DHT11.read(); //Read DHT11 Sensor
    float airtemp=float(DHT11.temperature);// turn integer to string
    float airhumid=float(DHT11.humidity);// turn integer to string

    // LED Blinking
    unsigned long currentMillis = millis();
    if(currentLcdLightOnTime == 0){ //We only blink when LCD is not on
    if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    // set the LED with the ledState of the variable:
    digitalWrite(11, ledState);
    }}

  buttonState = digitalRead(BUTTON_PIN);// Check the state of the push-button.

  if (buttonState == HIGH){// Button pressed.

      digitalWrite(11, LOW);

    lcdLightOn_StartMillis = millis();
    currentLcdLightOnTime = 0;
    isLcdLightOn = true;
    lcd.setBacklight(1); // switch on the backlight

    //Screen 0 Presentation

    lcd.setCursor(0, 0);
    lcd.print(" Aquaponics Bot ");

    lcd.setCursor(0, 1);
    lcd.print("  Version 1.0      ");
  }

  else{
    // Button not pressed.

    //Serial.println("Button not pressed - LOW");

    if(isLcdLightOn){
      currentLcdLightOnTime = millis() - lcdLightOn_StartMillis;

        //Screen 2
        if(currentLcdLightOnTime > 3000 && currentLcdLightOnTime <= 6000){

    //Screen 2 - Air Temperature & Humidity

    //Line 1
    lcd.setCursor(0, 0);
    lcd.print("  Air Sensors  ");

    //Line 2
    lcd.setCursor(0, 1);
    lcd.write(0);
    lcd.print(": ");
    lcd.println(airtemp);
    lcd.setCursor(5, 1);
    lcd.write(2);

    lcd.print(" - ");
    lcd.write(1);
    lcd.print(": ");
    lcd.print(airhumid);
    lcd.setCursor(14, 1);
    lcd.print("%   ");

        }

        //Screen 3
        if(currentLcdLightOnTime > 6000 && currentLcdLightOnTime < 9000){

     //Screen 3 - Water Data

    //Line 1
    lcd.setCursor(0, 0);
    lcd.print(" Water Sensors ");

    //Line 2
    lcd.setCursor(0, 1);
    lcd.write(0);
    lcd.print(": ");
    lcd.println(watertemp);
    lcd.setCursor(5, 1);
    lcd.write(2);

    lcd.print(" -  soon   ");

   }

    //Screen 4

        if(currentLcdLightOnTime > 9000 && currentLcdLightOnTime < 12000){

   //Screen 4 - Light Sensors

    //Line 1
    lcd.setCursor(0, 0);
    lcd.print(" Light Sensors  ");

    //Line 2
    lcd.setCursor(0, 1);
    lcd.write(3);
    lcd.print(": ");
    lcd.println(sunlight);
    lcd.setCursor(5, 1);
    lcd.print("% - soon   ");

      }

            if(currentLcdLightOnTime > 12000 && currentLcdLightOnTime < 15000){

     //Screen 5 - Next Feeding

                long hours=0;
                long mins=0;
                long secs=0;

                secs = timeuntilfeeding/1000; //convect milliseconds to seconds
                mins=secs/60; //convert seconds to minutes
                hours=mins/60; //convert minutes to hours
                secs=secs-(mins*60); //subtract the coverted seconds to minutes in order to display 59 secs max
                mins=mins-(hours*60); //subtract the coverted minutes to hours in order to display 59 minutes max
                //Display results
                itoa(hours, bufferhours, 10);//Convert the number of hours into readable by LCD
                itoa(mins, bufferminutes, 10);//Convert the number of minutes into readable by LCD
                lcd.setCursor(0, 0);
                lcd.print("Fish Feeding: ");
                lcd.setCursor(0, 1);
                lcd.print(bufferhours);
                lcd.print(" hours ");
                lcd.print(bufferminutes);
                lcd.print(" min.   ");

   }

        // Turn Off the Screen
      if(currentLcdLightOnTime > 15000){
        lcd.clear();
        isLcdLightOn = false;
        lcd.setBacklight(0); // switch off the backlight

        currentLcdLightOnTime = 0; //So that the blinking can start again.
        ledState = LOW;
      }
    }
  }

    } // End of the while wifi loop

    // Make sure we are still connected to the internet

    esp8266.begin(9600);
    boolean wifi_connected=false; //not connected yet...

    sendesp8266("AT");
    delay(2000);
    for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
    {
    if(connectWiFi()) //are we connected?
    {
    wifi_connected = true; //yes
    break; //get outta here!
    }
    }

    digitalWrite(13, HIGH);

    //We capture sensors again to send the value

    //Sunlight
    float value_sunlight = analogRead(A2);
    percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
    String sunlight =String(percent);// turn integer to string

    //Water Temperature
    float value_watertemp = getTemp();
    String watertemp= String(value_watertemp);// turn integer to string

    //Air Temperature and Humidity
    int chk = DHT11.read(); //Read DHT11 Sensor
    String airtemp=String(DHT11.temperature);// turn integer to string
    String airhumid=String(DHT11.humidity);// turn integer to string

    updateTS(sunlight,watertemp, airtemp, airhumid);
    delay(3000); //
    digitalWrite(13, LOW);

  } // End of the while feeding loop

  // Double Swipe to Feed the Fish

    //Intialize Servo
    myservo.attach(3);  // attaches the servo on pin 3 to the servo object
    //Display that the fish is being fed.
    digitalWrite(13, HIGH);

    for(pos = 0; pos < 180; pos += 5)  // goes from 0 degrees to 180 degrees
      {                                  // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
       }

    for(pos = 180; pos>=0; pos-=5)     // goes from 180 degrees to 0 degrees
       {
         myservo.write(pos);              // tell servo to go to position in variable 'pos'
         delay(15);                       // waits 15ms for the servo to reach the position
       }

    myservo.detach();  // detattaches the servo from pin 3
    //Clears display
    digitalWrite(13, LOW);

    // SEND AN EMAIL OR UPDATE A DATABASE..

    }

    //----- update the  Thingspeak string with 4 values
    void updateTS( String L, String W , String T, String H)
    {
    // ESP8266 Client
    String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
    cmd += IP;
     cmd += "\",80";
    sendesp8266(cmd);
      delay(2000);
    if( Serial.find( "Error" ) )
    {
      esp8266.print( "RECEIVED: Error\nExit1" );
    return;
    }

     cmd = GET + "&field1=" + L +"&field2="+ W + "&field3=" + T + "&field4=" + H +"\r\n";
     Serial.print( "AT+CIPSEND=" );
     Serial.println( cmd.length() );
     if(Serial.find( ">" ) )
     {
     esp8266.print(">");
     esp8266.print(cmd);
     Serial.print(cmd);
     }
     else
     {
     sendesp8266( "AT+CIPCLOSE" );//close TCP connection
     }
     if( Serial.find("OK") )
     {
     esp8266.println( "RECEIVED: OK" );
    }
    else
    {
    esp8266.println( "RECEIVED: Error\nExit2" );
     }
     }

    void sendesp8266(String cmd) //Send info to esp8266
     {
    esp8266.print("SEND: ");
     esp8266.println(cmd);
     Serial.println(cmd);
     }

     boolean connectWiFi()
      {
     digitalWrite(11, LOW);
     digitalWrite(12, HIGH);
     Serial.println("AT+CWMODE=1");//WiFi STA mode - if '3' it is both client and AP
     delay(5000);
     //Connect to Router with AT+CWJAP="SSID","Password";
     // Check if connected with AT+CWJAP?
     String cmd="AT+CWJAP=\""; // Join accespoint
     cmd+=SSID;
     cmd+="\",\"";
     cmd+=PASS;
     cmd+="\"";
     sendesp8266(cmd);
     delay(15000);

     digitalWrite(12, LOW);

     if(Serial.find("OK"))
     {
      esp8266.println("RECEIVED: OK");
      return true;
     }
     else
     {
       esp8266.println("RECEIVED: Error");
       return false;
     }

     cmd = "AT+CIPMUX=0";// Set Single connection
     sendesp8266( cmd );
     if( Serial.find( "Error") )
     {
     esp8266.print( "RECEIVED: Error" );
      return false;
     }
   }

   float getTemp(){ //Get the water temperature
    //returns the temperature from one DS18S20 in DEG Celsius

    byte data[12];
    byte addr[8];

     if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
     }

    if ( OneWire::crc8( addr, 7) != addr[7]) {
     Serial.println("CRC is not valid!");
     return -1000;
    }

    if ( addr[0] != 0x10 && addr[0] != 0x28) {
     Serial.print("Device is not recognized");
      return -1000;
    }

    ds.reset();
    ds.select(addr);
    ds.write(0x44,1); // start conversion, with parasite power on at the end

     byte present = ds.reset();
    ds.select(addr);
    ds.write(0xBE); // Read Scratchpad

    for (int i = 0; i < 9; i++) { // we need 9 bytes
     data[i] = ds.read();
    }

    ds.reset_search();

    byte MSB = data[1];
    byte LSB = data[0];

    float tempRead = ((MSB << 8) | LSB); //using two's compliment
    float TemperatureSum = tempRead / 16;

    return TemperatureSum;

    }

I'd suggest to use the timer one to do stuff as well. Since the timer one can be used to do things along side with the main program. Just search on Google for timer one arduino and read the tutorial.

You're sending AT commands hea? Usually they'll give an response, I'd rather check the response instead of using a delay and then another AT command to verify it?

If i follow you correctly, why would you read sensors while uploading data? Even on a full pc you would first collect data then act and report.

You can use several approaches.
Lesto already pointed out the finite state machine, but this approach will run the code as fast as possible and this might not be the behaviour you want. It's a good approach to manage, for instance, wifi connections and other communications but it won't let you schedule a task in a fixed pace.
Other options:
1) In the arduino default examples there's "Blink without delay" (\examples\digital), here you can read the code explanation. It's different from what you used
(while(now < endtime))
because your code execution is kept inside the while.
If you otherwise use an
if (currentMillis - previousMillis >= interval)
the code will do the check but it  continues to run other instructions until the right time has come.
2) Use a scheduler!
This is handy if you have several different tasks that should run at a constant (and relatively slow for the MCU) pace.
For instance:
#include "leOS.h"
leOS myOS

void setup() {
  myOS.begin();
}
void setup() {
  myOS.begin();
  myOS.addTask(updateTS, scheduleTime[30000, SCHEDULED]);
}

With this code you'll run the updateTS function every 5 min, without blocking the execution of other tasks.

Instead of using a delay, you may use some variable (maybe a struct or an object) to keep the status of your transmission or reading; every things that need a delay became a new state in this state-machine, every loop, based on witch status you have, you check if there are the information to execute the next step.
You may have multiple thing with status, but if they share a resource you'll need to add an abstraction layer on that resource to take care of that. (Like an event system or a message router or an output buffer)
Also you may have a status in witch you wait for a status in another state machine.

Thanks for your message. Would you have an example?

i think you need to learn some basic programming pattern, in this case we are talking about a "finite state machine", see http://en.wikipedia.org/wiki/Finite-state_machine


text:
HC05 to HC05 Handshake Communication
I am attempting to connect an Arduino Uno to a Modern Device RBB Arduino. One is the base and the other the remote. They need to set up a simple handshake to communicate an on and off condition from the remote.The hardware and software work for both the base and remote using Tera Term to simulate the opposite node. I am running Tera Term on a notebook connecting to the node through a BT dongle. In other words if I manually respond to the opposite node on the Tera Term they both operate as they should individually. When I try to get them to interact autonomously they will not handshake. The HC05s are paired and connected but the handshake data will not flow back and forth.
Remote Code:

 int pinInt =2; //interrupt pin

 int ack = 2; //acknowledge

 void setup() {

  pinMode(3,OUTPUT); //power to bluetooth

  pinMode(pinInt,INPUT); //interrupt pin mode

}
// Still needs sleep and interrupt processing

  void loop() {

  delay(5000);//sim sleep remove or adjust for wake up delay

  digitalWrite(3,HIGH);//switches power to bluetooth

  delay(10000);//BT active adjust as necessary

  Serial.begin(9600);

  Serial.print('?');//send am I connected

   while(Serial.available()==0){}//idle until incoming serial

     int heatCall=digitalRead(pinInt);//read interrupt pin

     if (Serial.available() > 0) {ack = Serial.read();}//read ack

     if (ack=='1'){Serial.print(heatCall);}//send state of heatCall

  while(Serial.available()==0){}//idle until incoming serial

    if (Serial.available() > 0) {ack = Serial.read();}//read ack

    if (ack=='0'){Serial.end();digitalWrite(3,LOW);}//BT off

   //sleepNow();//put back to sleep

}

Base Code:
int relayPin =13; //relay pin

 char itsOn = 0; //remote calling variable

 int heatCall = 0; //state of TH135

 int ack = 2; //hand shake

  void setup() {

  pinMode(relayPin,OUTPUT); //power to relay
  Serial.begin(9600);
}

  void loop() {

  while (Serial.available()==0);{}//idle until incoming serial

  if (Serial.available() > 0) {itsOn = Serial.read();//remote calling

    if (itsOn=='?')ack=1;Serial.print(ack);}//send connected ack

  while (Serial.available()==0);{}//idle until incoming serial

  if (Serial.available() > 0) {heatCall = Serial.read();}//incoming heatCall

    if (heatCall=='1'){digitalWrite(relayPin,HIGH);}//turn zone relay ON

     else {digitalWrite(relayPin,LOW);}//turn zone relay OFF

  delay(5000);
  ack=0;
  Serial.print(ack);//turn remote BT OFF
  }

Is there some BT protocol that I am missing?
UPDATE: I have determined that data is being transferred from remote to base and back. The data is not the expected values.


text:
Micro is not recognised as HID device
Being a completely noob with Arduino (but not with coding though) I'm trying to create a simple buttonbox with a Micro unit.
For now, I can not figure out what should I do to make my Windows 10 recognize the Arduino as a HID device (joystick actually). What did I miss?

How should we be able to tell you, what you missed? You didn't give us any information at all. Provide the code, that you use. Also: Have you tried the examples from the Arduino IDE? For me they worked pretty well

@chrisl, Sorry, I thought it lays beyond arduino coding. I use a pretty simple matrix solution with Keyboard.h library. It works ok: all buttons are being recognized correctly (I use println for debug). Next thing I need is to make Win see the arduino as game controller. But no new devices are found in device list, no any devices available to add and so on. Should I make some extra steps to achieve that? As I know Micro board has a sort of HID controller in it's chip (sorry for missnaming if any) so it should be recognized in Windows by default. Should I use some extra library or something?

I don't quite understand, what you are trying to achieve. With the Keyboard library, the Micro will behave like a keyboard, which is by definition a HID device. I don't understand, where you mean it should appear in Windows and why? Gamecontrollers and keyboards are both HID devices, but they are not the same

this box should be a gamecontroller at the end. I sow a bunch of guides about how to make it and there no any steps described how to make Windows work with arduino as a game controller. So I have a gamepad now, what should I do to make Windows work with it when connected in USB?

As I wrote, Windows already works with it, treating it like a keyboard (as you told the Micro to behave like one). Generally Windows doesn't do much here. I guess you want, that it identifies itself as game controller. Then you cannot use the Keyboard library. Have you tried the Joystick library?

My bad. I mean I use Keypad.h not Keyboard.h Anyway, If I need Windows to see it as a game controller I have to use Joystick library https://github.com/MHeironimus/ArduinoJoystickLibrary, correct?

I think yes, though I haven't used it yet.

Joystick (github.com/MHeironimus/ArduinoJoystickLibrary) lib did the job. @chrisl, thx for the patience.


text:
Arduino Mega LED doesn't light as expected
I wrote this for my Arduino Mega 2560:
int LED[14] = { 28,29,30,31,32,33,34,35,36,37,38,39,40,41 } ;
...
... (some other code like setup(), etc. Note:pinmode output for this 14 leds wich pins is defined in
... array named LED[]
...
void intro(){
  for(int j=1; j<100; j++ ){
    for(int r=1; r<15; r++ ){ digitalWrite(LED[r],HIGH); delay(100);  }
    delay(100);
    for(int r=1; r<15; r++ ){digitalWrite(LED[r],LOW); delay(100);}
    delay(100);
  }
  Serial.print("Pattern started");
  delay(1000);
}

So when I run this script, I expect that each LED will light up in the sequence and remain lit until the second loop to turn it off, but I see that when lighting each LED, when lighting the 9th LED, the first 8 LEDs shut off inexplicably and LEDs 9 through 14 light one by one, remaining lit. That I expected but why do the first 8 LEDs shut off before the loop ends and the second loop starts?

maybe you are overloading the data pins

for (int r = 0; r < 14; r++). first index is zero and the size of the array is 14

While it is true that your loop is incorrect, the coding error is unlikely to cause the behaviour that you have described.
Please ensure that a current limiting resistor is placed in series with each LED. Since you have 14 LEDs, you will need 14 current limiting resistors. 470 Ohm resistors (or similar) should be adequate for this purpose.
As per the other comments, C++ Arrays start at 0, not 1. The last element is the size of the array minus 1. In your case 14 - 1 = 13. Thus the loop can continue as long as the index is < 14 (or <= 13)
Thus your loops should read:
for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}

your for statements with r=1 need to be changed to r=0;r<14  Arrays always start with the first item being 0, so yours is 0 to 13.

and how does it cause the described behavior of the code?