body:
Problem 1: LED1 needs to be on only when button1 is held down. Right now it takes several presses to turn on and off and stays on.
Problem 1: LEDs 2,3,4 do not turn off with buttons 2,3,4. They are all turned off by button1, which is what I want, but I also need them to turn of with their respective button presses.

I need buttons 2,3,4 to light up LEDs 2,3,4 and stay lit until I press the respective buttons again OR button1 which turns off all lights, and the LED for button1 must only stay on when button1 is held down.

I am half way there with just a few minor problems. The first is LED1 stays on rather than when I hold the button1 down only. And the other problem is, it takes many presses to turn the LEDs on or off. I fixed this on 2,3,4 by removing the following code for each pin:

<!-- language-all: lang-cpp -->

    if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
      { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
        ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
      }

After I remove that code the LEDs light straight away and stay on until I press button 1 which is what I want. But I would also like LEDs 2,3,4 to turn off with their respective button press. With that code removed LEDs 2,3,4 no longer work independently of button1.

Full Code:

    // set pins
    const int buttonPin1 = 2;                 // Pin1's pushbutton
    const int buttonPin2 = 4;                 // Pin2's pushbutton
    const int buttonPin3 = 6;                 // Pin3's pushbutton
    const int buttonPin4 = 8;                 // Pin4's pushbutton
    const int ledPin1 = 3;                    // Pin1's LED
    const int ledPin2 = 5;                    // Pin2's LED
    const int ledPin3 = 7;                    // Pin3's LED
    const int ledPin4 = 9;                    // Pin4's LED

    // set variables
    int ledPin1_status = 0;
    int ledPin2_status = 0;
    int ledPin3_status = 0;
    int ledPin4_status = 0;

    void setup() {  //initialize pins
      pinMode(buttonPin1, INPUT); // set PINn as INPUT
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      pinMode(buttonPin4, INPUT);
      pinMode(ledPin1, OUTPUT);   // set LEDn as OUTPUT
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);
    }

    // the following variables are unsigned longs because the time, measured in
    // milliseconds, will quickly become a bigger number than can be stored in an int.
    unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
    unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

    void loop() {
      if (digitalRead(buttonPin1) == HIGH) { // check if buttonPin1 was pressed (be sure to use a resistor?)
        if (ledPin1_status == 0) {           // check if ledPin1 was not already pressed
          digitalWrite(ledPin1, HIGH);       // turn ledPin1 on
          ledPin1_status = 1;                // 1 = on, set ledPin1_status to 1
        }
        else {
          digitalWrite(ledPin1, LOW);        // turn ledPin1 off
          ledPin1_status = 0;                // 0 = off, set Pin1_status to 0
          digitalWrite(ledPin2, LOW);        // turn ledPin2 off
          ledPin2_status = 0;                // 0 = off, set Pin2_status to 0
          digitalWrite(ledPin3, LOW);        // turn ledPin3 off
          ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
          digitalWrite(ledPin4, LOW);        // turn ledPin4 off
          ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
        }
      }

      if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin2, HIGH);       // turn ledPin2 on
          ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
        }
      }

      if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
          ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
        }
      }

      if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin3 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin3, HIGH);       // turn ledPin3 on
          ledPin3_status = 1;                // 1 = on, set ledPin3_status to 1
        }
      }

      if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin3, LOW);       // turn ledPin3 on
          ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
        }
      }

      if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin4, HIGH);       // turn ledPin4 on
          ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
        }
      }

      if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
        { digitalWrite(ledPin4, LOW);       // turn ledPin4 on
          ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
        }
      }

title: Control multiple LEDs with multiple buttons

Answers: 1

body:
First thing, you need to debounce your buttons. The fact that you
declared the (unused) variable `debounceDelay` suggests you have though
about debouncing, but you did not implement it.

Next thing, you should look for button _press_ and _release_ events.
That's when the button pin changes state from `LOW` to `HIGH` or vice
versa. It is not enough to check whether the pin is `HIGH` or `LOW`, you
have to check for the _changes_ in state. This is usually called _edge
detection_.

With enough effort, you could probably do that yourself. However, to
make your life easier, you can use a debouncing library that does edge
detection, such as the quite popular [Bounce2][]. This library provides,
for each button it debounces, a `rose()` method that tells you when the
input signal rose (i.e. transitioned from `LOW` to `HIGH`) and a
`fell()` method that tells you when it fell (transitioned `HIGH`
→ `LOW`). Using these methods, your problem can be coded in a fair
natural way. For example (not tested):

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

    #include <Bounce2.h>

    const int     BUTTON_COUNT = 4;
    const int16_t DEBOUNCE_DELAY = 50;
    const uint8_t buttonPins[BUTTON_COUNT] = {2, 4, 6, 8};
    const uint8_t ledPins[BUTTON_COUNT] = {3, 5, 7, 9};

    Bounce buttons[BUTTON_COUNT];
    uint8_t ledStates[BUTTON_COUNT];

    void setup() {
        for (int i = 0; i < BUTTON_COUNT; i++) {
            buttons[i].attach(buttonPins[i], INPUT);
            buttons[i].interval(DEBOUNCE_DELAY);
            pinMode(ledPins[i], OUTPUT);
            ledStates[i] = LOW;
            digitalWrite(ledPins[i], ledStates[i]);
        }
    }

    void loop() {

        // Update the debouncers.
        for (int i = 0; i < BUTTON_COUNT; i++)
            buttons[i].update();

        // When the first button is pressed:
        if (buttons[0].rose()) {

            // Light up the first LED.
            digitalWrite(ledPins[0], HIGH);

            // and turn off all the others.
            for (int i = 1; i < BUTTON_COUNT; i++) {
                ledStates[i] = LOW;
                digitalWrite(ledPins[i], ledStates[i]);
            }
        }

        // When the first button is released:
        if (buttons[0].fell()) {

            // turn off the first LED.
            digitalWrite(ledPins[0], LOW);
        }

        // When any other button is pressed:
        for (int i = 1; i < BUTTON_COUNT; i++) if (buttons[i].rose()) {

            // Toggle its state.
            ledStates[i] = !ledStates[i];
            digitalWrite(ledPins[i], ledStates[i]);
        }
    }

[Bounce2]: https://github.com/thomasfredericks/Bounce2

**Edit**: In order for the first button to only turn off LEDs 1 and 2,
the lines

    // and turn off all the others.
    for (int i = 1; i < BUTTON_COUNT; i++) {
        ledStates[i] = LOW;
        digitalWrite(ledPins[i], ledStates[i]);
    }

should be replaced by:

    // and turn off LEDs 1 and 2.
    for (int i = 1; i <= 2; i++) {
        ledStates[i] = LOW;
        digitalWrite(ledPins[i], ledStates[i]);
    }


body:
I am using the ADF7030 on the breakout board (not motherboard) and I am trying to interface it with an Arduino Uno. I want to load the transceivers configuration file onto the chip using SPI. To do this, I need to include the ".cfg" file but when I use the C style array (as in the datasheet - code below) it says that it can't find the file in the .ino sketch.

 `const unit8_t Radio_Memory_Configuration [ ] = {
     #include "Settings_ADF7030-1.cfg"
}`

How could I include this file?

title: How do I include a file that is not a .h, .c or .cpp file?

Answers: 1

body:
From looking at the [arduino-builder source][1] only files with the following extensions are copied to the build directory: .ino .pde .h .c .hpp .hh .cpp .s

So you will need to use one of those extensions.

  [1]: https://github.com/arduino/arduino-builder


body:
I have some quite long code to copy a file from an SD to the same card, but under a different name. I have one version where the file names are built-in to the sketch, but to make it more portable, i have implemented a serial file selection system. There are 3 phases; choosing the input file, choosing the output file, and the copying. I have included checks to see if the files exist, confirmation for the names and so on. However, in the middle of my code, just before the copying phase, the input file disappears, and the arduino does not find it. It finds it in the first phase, finds the output file, but can't find the input file in the copying phase. SD.exists() and SD.open() both confirm this, but if i remove the sd card and put it into a computer, the file is there.

My code:

    #include <SoftReset.h>
    #include <SPI.h>
    #include <SdFat.h>
    #define csPin 4
    #define roundTo 64

    SdFat SD;
    File sourceFile;
    File outputFile;

    int bufSize;
    uint32_t lastPos = 0, timeLast, timeNow;
    #define BAUD 115200
    //make timeBetweenChars the time it takes (in milliseconds) between each char being transferred over serial, and make it at least one
    unsigned long timeBetweenChars = max(1000 / (BAUD / 8), 1);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(BAUD);
      while (!Serial) {
      }
      Serial.print(F("Initializing SD card..."));
      /******************************************************************************/
      // see if the card is present and can be initialized:
      if (!SD.begin(csPin, SPI_FULL_SPEED)) {
        Serial.println(F("Card failed, or not present"));
        soft_restart();
      }
      Serial.println("Card initialized.");

      Serial.println(F("Files on card:"));
      SD.ls();
      //******************************************************************************
      //START OF INPUT FILE NAME
      //******************************************************************************
    enterInputFileName:
      Serial.println(F("Enter input file name:"));
      while (!Serial.available()); // wait till serial available
      char inbuf[64];
      /******************************************************************************/
      //create variable to store how many valid (not newline or carriage return) chars have been read
      byte pos = 0;
      //read into array as long as not getting newline char
      while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
        inbuf[pos] = Serial.read();
        pos++;
        //wait so there is time for the next char to arrive in the buffer
        delay(timeBetweenChars);
      }
      while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
        //remove next char from buffer
        Serial.read();
        //wait in case there is another char to be cleared
        delay(timeBetweenChars);
      }
      //end array at pos
      inbuf[pos] = '\0';
      /******************************************************************************/
      //create new array with correct size for input file name
      char inputFileName[pos];
      //copy data from inbuf to inputFileName
      strcpy(inputFileName, inbuf);
      /******************************************************************************/
      //confirm if you entered the right file name
    confirmInputFileName:
      Serial.print(F("Select file '"));
      Serial.print(inputFileName);
      Serial.println(F("'? Y/N"));

      while (!Serial.available()); // wait till serial available
      char confirm = Serial.read();
      bool tooManyChars = 0;
      // wait for the next chars
      delay(timeBetweenChars);
      while (Serial.available()) {
        //read next char
        char extra = Serial.read();
        //if it isn't a newline or carriage return
        if (extra != '\n' && extra != '\r') {
          //too many characters entered
          tooManyChars = 1;
        }
        //wait for next char
        delay(timeBetweenChars);
      }
      /******************************************************************************/
      if (tooManyChars) {
        Serial.println(F("Enter 1 char"));
        goto confirmInputFileName;
      }

      //if only 1 char entered
      switch (confirm) {
        case 'Y': break;
        case 'y': break;
        case 'N': goto enterInputFileName; break;
        case 'n': goto enterInputFileName; break;
        //invalid char entered
        default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
      }
      /******************************************************************************/
      Serial.print(F("Using file '"));
      Serial.print(inputFileName);
      Serial.println("' as input file");
      if (SD.exists(inputFileName)) {
        Serial.println(F("File exists"));
      }
      else {
        Serial.println(F("Error, file does not exist. Please choose another file"));
        goto enterInputFileName;
      }
      //******************************************************************************
      //END OF INPUT FILE NAME
      //******************************************************************************

      //******************************************************************************
      //START OF OUTPUT FILE NAME
      //******************************************************************************
    enterOutputFileName:
      //clear input buffer
      for (byte w = 0; w < (sizeof(inbuf) / sizeof(inbuf[0])); w++) {
        inbuf[w] = '\0';
      }
      Serial.println(F("Enter output file name:"));
      //wait for some chars to arrive
      while (!Serial.available());
      /******************************************************************************/
      //create variable to store how many valid (not newline or carriage return) chars have been read
      pos = 0;
      //found here Serial.print(SD.exists(inputFileName));
      //read into array as long as not getting newline char
      while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
        //file found on first loop, but not after that
        // found here Serial.println(SD.exists(inputFileName));
        inbuf[pos] = Serial.read();
        //not found here Serial.println(SD.exists(inputFileName));
        pos++;
        //wait so there is time for the next char to arrive in the buffer
        delay(timeBetweenChars);
      }
      //input file not found here
      while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
        //remove next char from buffer
        Serial.read();
        //wait in case there is another char to be cleared
        delay(timeBetweenChars);
      }
      //end array at pos
      inbuf[pos] = '\0';
      /******************************************************************************/
      //create new array with correct size for output file name
      char outputFileName[pos];
      //copy data from inbuf to outputFileName
      strcpy(outputFileName, inbuf);
      /******************************************************************************/
      //confirm if you entered the right file name
    confirmOutputFileName:
      Serial.print(F("Select file '"));
      Serial.print(outputFileName);
      Serial.println(F("'? Y/N"));

      while (!Serial.available()); // wait till serial available
      confirm = Serial.read();
      tooManyChars = 0;
      // wait for the next chars
      delay(timeBetweenChars);
      while (Serial.available()) {
        //read next char
        char extra = Serial.read();
        //if it isn't a newline or carriage return
        if (extra != '\n' && extra != '\r') {
          //too many characters entered
          tooManyChars = 1;
        }
        //wait for next char
        delay(timeBetweenChars);
      }
      /******************************************************************************/
      if (tooManyChars) {
        Serial.println(F("Enter 1 char"));
        goto confirmOutputFileName;
      }

      //if only 1 char entered
      switch (confirm) {
        case 'Y': break;
        case 'y': break;
        case 'N': goto enterOutputFileName; break;
        case 'n': goto enterOutputFileName; break;
        //invalid char entered
        default: Serial.println(F("Enter Y/N")); goto confirmOutputFileName; break;
      }
      /******************************************************************************/
      Serial.print(F("Using file '"));
      Serial.print(outputFileName);
      Serial.println("' as output file");

      if (SD.exists(outputFileName)) {
        Serial.println(F("File already exists. Overwrite? Y/N"));
    confirmOverwrite:
        while (!Serial.available()); // wait till serial available
        confirm = Serial.read();
        tooManyChars = 0;
        // wait for the next chars
        delay(timeBetweenChars);
        while (Serial.available()) {
          //read next char
          char extra = Serial.read();
          //if it isn't a newline or carriage return
          if (extra != '\n' && extra != '\r') {
            //too many characters entered
            tooManyChars = 1;
          }
          //wait for next char
          delay(timeBetweenChars);
        }
        /******************************************************************************/
        if (tooManyChars) {
          Serial.println(F("Enter 1 char"));
          goto confirmOverwrite;
        }

        //if only 1 char entered
        bool overwrite = 0;
        switch (confirm) {
          case 'Y': overwrite = 1; break;
          case 'y': overwrite = 1; break;
          case 'N': goto enterOutputFileName; break;
          case 'n': goto enterOutputFileName; break;
          //invalid char entered
          default: Serial.println(F("Enter Y/N")); goto confirmOverwrite; break;
        }
        if (overwrite) {
          Serial.println(F("Removing output file"));
          SD.remove(outputFileName);
        }
      }
      Serial.println(F("Creating output file"));
      outputFile = SD.open(outputFileName, FILE_WRITE);
      outputFile.close();
      //******************************************************************************
      //END OF OUTPUT FILE NAME
      //******************************************************************************

      //******************************************************************************
      //START OF COPYING
      //******************************************************************************
      //read source and write to output
      sourceFile = SD.open(inputFileName);
      timeLast = micros();
      //debug line
      Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
      if (sourceFile) {
        pinMode(LED_BUILTIN, OUTPUT);
        digitalWrite(LED_BUILTIN, HIGH);
        Serial.println(F("Copying"));
        while (sourceFile.available()) {
          //make buffer size 50% of free ram, or amount of bytes left if smaller
          int ram = round((freeRam() * 0.5) / roundTo) * roundTo;
          bufSize = min(ram, sourceFile.available());
          //round to nearest value of roundTo
          bufSize = round(bufSize / roundTo) * roundTo;
          byte data[bufSize];
          sourceFile.readBytes(data, bufSize);
          lastPos = sourceFile.position();
          sourceFile.close();
          outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
          outputFile.write(data, bufSize);
          outputFile.close();
          sourceFile = SD.open(inputFileName);
          sourceFile.seek(lastPos);
          //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
          printStats();
        }
        sourceFile.close();
        outputFile.close();
        Serial.println(F("Finished"));
        unsigned int sec = millis() / 1000;
        unsigned int mins = sec / 60;
        sec -= mins * 60;
        Serial.print(F("Time taken: "));
        Serial.print(mins);
        Serial.print(':');
        Serial.print(sec);
        Serial.print(F("Speed: "));
        Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
        Serial.print(F(" KB/s"));
      }
      // if the file isn't open, pop up an error:
      else {
        Serial.println("error opening files");
        Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
        SD.initErrorHalt();
      }
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);
      delay(200);
      digitalWrite(LED_BUILTIN, LOW);
      delay(200);
    }

    int freeRam () {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

    void printStats() {
      timeNow = micros();
      uint32_t timeTaken = timeNow - timeLast;
      float sent = sourceFile.position() / 1000.0;
      float fileSize = sourceFile.size() / 1000.0;
      float left = fileSize - sent;
      float speed;
      speed = 1000000UL / timeTaken * bufSize;
      speed /= 1000;
      unsigned int sec = millis() / 1000;
      unsigned int mins = sec / 60;
      sec -= mins * 60;
      int estSec = (left / speed);
      int estMin = estSec / 60;
      estSec -= estMin * 60;
      Serial.print(F("\tSent (KB): ")); Serial.print(sent);
      Serial.print(F("\tLeft (KB): ")); Serial.print(left);
      Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
      Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
      Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
      Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
      Serial.print(F("\tBuf: "));       Serial.print(bufSize);
      Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
      //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
      Serial.print('\n');
      timeLast = micros();
    }

My serial output(I chose Nova.mp3 as input file and output.mp3 as output file):

    Initializing SD card...Card initialized.
    Files on card:
    output.mp3
    Nova.mp3
    Eclipse.wav
    Enter input file name:
    Select file 'Nova.mp3'? Y/N
    Using file 'Nova.mp3' as input file
    File exists
    Enter output file name:
    Select file 'output.mp3'? Y/N
    Using file 'output.mp3' as output file
    File already exists. Overwrite? Y/N
    Removing output file
    Creating output file
    Exists(I,O): 01
    error opening files
    Exists(I,O): 01
    No error found.

I know i am not running out of memory, and have no compiler errors, but i have no clue what is going wrong. Is it possible I have put in some unnecessary code? Also, if it was possible to have multiple files open at a time, would i spped up my read/write speed?

title: FIle not being found on sd card

Answers: 1

body: The problem is that you have the char arrays for zero terminated c-string one char shorter then needed. I see you assign the terminating zero to inbuf[pos] and then you allocate pos chars for the filename and copy pos count of characters. That leaves out the terminating zero and the c-string of the filename is not terminated by 0 and continues in memory with random content.


body: My Arduino has all of its LEDs on. The `Rx`, `Tx` and `L` LEDs are all on and my computer can’t see it (it's an SMD edition).

title: The Arduino IDE can’t find my Arduino Uno

Answers: 3

body:
It can have many reasons, but you can try the following:

**First time use?**

- Check if you need to install a special driver for CH340

**Environment/Software problems**

- Try another USB port
- Change USB cable
- Restart Arduino IDE
- Restart computer
- Reinstall Arduino IDE

**Hardware problems**

- Test using another Arduino
- Test using another computer/laptop
- Replace USB cable
- The Arduino is (partly) broken, nothing much to do here

body:
The USB interface chip controls the Rx & Tx lights.  I suspect you fried it.
Does the '328P feel warm or hot to the touch? That's usually a sign that it has been damaged.

body:
Is it an "official" Arduino purchased from their website? If it isn't, chances are you need to install CH340 drivers for your computer before the Arduino will be recognized. Drivers can be found [here][1] Have you successfully used this device with your computer before?

  [1]: https://sparks.gogo.co.nz/ch340.html


body:
I have some boards with the atmega32u4 that they were working perfectly before. I'm using an unnoficial UNO board to program them via ICSP. To power the uC I'm using two lithium batteries and a step-down converter to drop it to 5 V.

This started happening when I tried to upload code via ISCP when the target chip was not powered by mistake.

This is my error message:

    Arduino: 1.8.5 (Windows 10), Placa:"Arduino Leonardo"

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

What I've already tried:

 - Different programmer (another Uno board);
 - Uploading to a proper Leonardo board via ICSP, it worked;
 - Uploading to another of my boards via ICSP, it worked;
 - Running with the portable Arduino version;
 - Check if the chip is being powered with 5 V;
 - Changed wires and checked the connections;
 - The chip does not get hot;

I've been around this two days straight, any help would be much appreciated.

title: Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead?

Answers: 1

body:
Mostly this error is due to connections/powering issues (as already mentioned in your output ).

 - Check connections, especially power and ground also check the
   resistance between Vcc and GND of your target MCU. (If it's less than
   100ohm that means something is off in your circuitry or your MCU is
   already fried.)

 - Check if your MCU is actually getting enough power (voltage and current) also check if it's getting excess voltage.

 - Make sure there is proper "common grounding" done between devices.

 - If you are sure that the above points are checked and you still get the error try the override flag `-F` (avrdude through shell/command-line) and if you are still not able to upload try the manually changing the address (not recommended ) in your arduino's library so that it matches with the signature it's receiving.

 - Finally try using a direct USB interface with atmega32u4 as atmega32u4 supports it and upload the bootloader again through an old software called **[Flip][1]** after that try again.

After all this if you are not able to upload then probably your MCU is dead and it might be due to an unnoticed wrong power connection or short circuit or unintentional fuse reconfiguration (highly unlikely).

  [1]: https://www.microchip.com/developmenttools/ProductDetails/FLIP#additional-summary


body:
I would like to create an Arduino system that sends the temperature in a place outdoors to a server.

I've read in Internet forums that there might be alternatives to GSM and GPRS technology for sending data remotely, but I'm not sure about them. In absence of WiFi, is GSM the best technology today, even that you have to use the SIM plan to use it?

title: Is there a real alternative now to using GSM for data sending?

Answers: 1

body:
GSM (or more realistically now, LTE) is really the only option.

Simply put: you need some method of accessing the internet, and unless you create your own local infrastructure that means using the mobile phone system. It's the only system that is virtually everywhere and doesn't require you to install your own communication system.

So that means some modem device that can communicate with the mobile phone system. GSM is what it used to be, although some mobile companies are now deprecating the GSM system and only really providing UMTS (3G) and LTE (what will eventually be 4G), but LTE modems are quite expensive still.

So yes, you need a SIM to do it. You can't access a mobile phone network without one.

One option that could be a cheaper possibility would be to get a cheap second hand smartphone off eBay (or dig out your old one from the bottom of the desk drawer) and use that as your own mobile WiFi hotspot. Your Arduino device connects to the phone with WiFi, and the phone connects to the UMTS or LTE network using a cheap PayG SIM.

----

LoRA is a technology that is gradually becoming more popular and allows long range wireless communications at low power and low cost. There are areas where LoRA is becoming available, such as [in Munich](https://www.thethingsnetwork.org/community/munich/). Should LoRA become available in your area, or should you invest in your own infrastructure, that could become a viable alternative to using the mobile phone network.


body:
I recently have tried to connect an LCD to my Arduino Uno. [The tutorial][1]
tells me I need a 220 Ohm resistor, but the only ones I have are 330 Ohm. Does it matter?

Here's the Fritzing diagram by the way:

[![enter image description here][3]][3]

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal
  [3]: https://i.stack.imgur.com/i3JfE.jpg

title: Resistors on LCD - does a small difference matter?

Answers: 2

body: No, it doesn't matter. That resistor is just for the backlight LEDs. The larger the resistor the dimmer the backlight will be.  As @VE7JRO suggests, you can always put two 330Ω resistors in parallel, which will halve the resistance to 165Ω, which will give a brighter backlight.

body: Nope. The lcd has backlight led which needs to powered separately. More resistance, dimmer it will be. Higher voltage decreases life span of your lcd backlit.


body:
I have a Arduino Uno Rev3 and I would like to use a AVR development toolchain to write a program that performs serial communication over USB.

Doing this using the Arduino IDE is fairly simple:

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

    void loop() {
       int i;
       while(1) {
          Serial.write("hello\n");
          delay(5000);
       }
    }

Then from Linux, I can simply read from `/dev/ttyACM0` and every 5 seconds I get "hello\n".

I found a blog post titled [Simple Serial Communications With AVR libc](https://appelsiini.net/2011/simple-usart-with-avr-libc) that explains how to perform serial communication using an AVR development toolchain. The simplified version of the above Arduino sketch is below.

    #ifndef F_CPU
    #define F_CPU 8000000UL
    #endif

    #ifndef BAUD
    #define BAUD 9600
    #endif

    #include <stdio.h>
    #include <avr/io.h>
    #include <util/delay.h>
    #include <util/setbaud.h>

    void uart_init() {
        // Upper and lower bytes of the calculated prescaler value for baud.
        UBRR0H = UBRRH_VALUE;
        UBRR0L = UBRRL_VALUE;

        // Configure data frame size to 8-bits.
        UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

        // Configure to enable transmitter.
        UCSR0B = _BV(TXEN0);
    }

    void uart_putchar(char c) {
        // Wait until the register to write to is free.
        loop_until_bit_is_set(UCSR0A, UDRE0);

        // Write the byte to the register.
        UDR0 = c;
    }

    void uart_putstr(char *data) {
        // Loop until end of string writing char by char.
        while(*data){
          uart_putchar(*data++);
        }
    }

    int main() {
        uart_init();

        while(1) {
            uart_putstr("hello\n");
            _delay_ms(5000);
        }

        return 0;
    }

The problem is, this doesn't actually work. I can build and flash the ATmega328p but reads to `/dev/ttyACM0` block forever. I suspect what is happening is that the serial communication is occurring on some pins and not over USB, but I am not sure.

Anyone have any idea on how I can emulate `Serial.write` using an AVR development toolchain and have the output be written over USB?

title: Arduino and AVR Serial Communication over USB

Answers: 1

body: Turns out the problem was with my `Makefile`. `avr-gcc` was missing the `-mmcu=atmega328p` flag. Once I added that and changed `F_CPU` to `16000000UL` everything works.


body:
I'm trying to do a data logger. Writes into SD card has to stop when `millis()`=1000. Maybe I have a problem between `millis()` and my interrupt, because datalogger doesn't stop after `millis()`=1000. I'm working with Arduino Mega.

<!-- language: lang-cpp -->

    #include <SPI.h>
    #include <SD.h>
    volatile unsigned int cuenta = 0;
    unsigned char contador = 0x00;
    const int chipSelect = 53;
    long currentMillis = 0;
    long previousMillis = 0;
    long interval = 1000;

    void setup() {
      DDRA = B11111111;
      cli();//stop interrupts
      TCCR0A = 0;// set entire TCCR2A register to 0
      TCCR0B = 0;// same for TCCR2B
      TCNT0  = 0;//initialize counter value to 0
      // set compare match register for 10000khz increments
      OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
      // turn on CTC mode
      TCCR0A |= (1 << WGM01);
      // Set CS01 and CS00 bits for 64 prescaler
      TCCR0B |= (1 << CS01) | (1 << CS00);
      // enable timer compare interrupt
      TIMSK0 |= (1 << OCIE0A);
      sei();//allow interrupts
      //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
      Serial.begin(9600);
      while (!Serial) {
        ;
      }
      Serial.print("Initializing SD card...");
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        while (1);
      }
      Serial.println("card initialized.");
    }

    ISR(TIMER0_COMPA_vect) {
      cuenta++;
      if (cuenta > 9) {
        PORTA = ++contador;
        cuenta = 0;
      } else {
        PORTA = 0X00;
      }
    }

    void loop() {
      currentMillis = millis();
      if (currentMillis - previousMillis <= interval)
      {
        String dataString = "";
        for (int analogPin = 0; analogPin < 1; analogPin++) {
          int sensor = analogRead(analogPin);
          dataString = String(sensor);

          if (analogPin = 1) {
            dataString += ",";
          }
        }
        File dataFile = SD.open("datalog2.txt", FILE_WRITE);
        if (dataFile) {
          dataFile.println(dataString);
          dataFile.close();
          // print to the serial port too:
          Serial.println(dataString);
        }
        else {
          Serial.println("error opening datalog.txt");
        }
      }
    }

title: Datalogger with interruputs

Answers: 1

body:
The `millis()` function is based on a counter which [is incremented by
the Timer 0 overflow interrupt][TIMER0_OVF_vect]. Since you reconfigured
that timer to never overflow, that counter is not incremented anymore.

If you want to configure an Arduino timer for your own purposes, you
have to either:

* use _any_ timer other than Timer 0, or
* loose the Arduino standard timekeeping functions: `millis()`,
  `micros()` and `delay()`.

I would favor the first option, especially on the Mega which has quite a
few spare timers.

[TIMER0_OVF_vect]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/wiring.c#L42-L63


body:
I saw this project with multiple servos: [In Servo We Trust! Let's control 135 servos with a single Arduino!][1] I wanted to miniaturize this project.

BUT instead of triangles i will use SQUARES.

:EDIT: summing UP

For now project stops, not forever. I bought 9 servos on aliexpress and im waiting for them to be delivered. Also, im making a 3D project in AutoDesk Maya 2018, planning and will sbow you the results soon how im gonna make it work.
I was thinking about adding 1 more servo and hc sr06 distance sensor. I was thinking about the sensor will detect person, servos and mirrors will also follow the person. But idk if im gonna make it to the final project.

 - I bought arduino nano that will be powered from the battery
 - All servos will be powered with electricity from the wall 5V 5A.The servos wont be on heavy load so it will be enough i think.If any problem occurs I will use 10A.

ALSO SORRY for not editing this POST earlier.

I would like to thank everybody for giving me such a great advices, I will post my AutoDesk project soon.

[![Fritzing Diagram][2]][2]

  [1]: https://create.arduino.cc/projecthub/Maya/in-servo-we-trust-6725f1?ref=search&ref_id=mirror panels servo&offset=13
  [2]: https://i.stack.imgur.com/YF5bS.jpg "Fritzing Diagram"

title: 9x servo on Arduino Nano?

Answers: 5

body:
> I'm afraid that with PWM controler I won't be able to do that.

Chances are that any PWM controller is going to let you control each output independently.

According the the [servo][1] library documentation, the library can handle up to 12 servos on a single Arduino, so your project should be feasible. It will however reduce the number of PWM pins available from 6 down to 4.

> Will a 9V battery power all these servos?

No! Not a chance.

Typical 9g servos consume 150 mA without any load, and stall at ~700-900 mA. A typical 9v has ~500 mAh capacity, and most data sheets show loads of ~100-150 mA max. Your 9v might be able to supply a few amps for a few seconds before they heat up and slow down.

If your load is very light 9 servos will consume ~900 mA; an ideal 9v would last at most 30 min with this load, but real batteries aren't ideal and will heat up and loose efficiency.

Near maximum load your 9 servos will draw ~7000-9000 mA, well beyond the capabilities of a 9v. However those numbers are for 5v so you could cut them all in half.

If you used an appropriate 5v step-down DC-DC supply you might be able to power all 9 servos for a few seconds before the batter overheats and gives up.

If you powered them directly, the servos will have to dissipate more heat, and will draw extra power, could damage the servos if the batter could supply enough juice.

  [1]: https://www.arduino.cc/en/Reference/servo

body:
Here are the specifications of the SG90 (from [FEETECH (Fitec) FS90 9G Mini Servo with Accessories][1])

> [![SG90 specifications][2]][2]

The FG90 is similar in specification to the SG90. From the website:

> The FS90 is a 9 g analog servo from FEETECH (formerly known as Fitec) which is similar in form and function to the Towerpro SG90. The specifications state that this servo has a 120° operating angle for standard servo pulses between 900 µs and 2100 µs. As with most servos, the pulse range can be expanded to achieve an expanded operating angle, but the limits of which are not specified by FEETECH.

From [this answer][3] to [Power supply circuit for powering SG90 servo. How to handle high current requirements?][4], lets assume each servo (best case) needs 250 mA, as you state that the load per servo is relatively low.

Let's say that the Nano requires 280 mA, see [this answer][5] to https://arduino.stackexchange.com/questions/926/what-is-the-maximum-power-consumption-of-the-arduino-nano-3-0

Using a single 5V supply to power both servos and Arduino. The current rating needs to need at least:

    I = (9 x 0.25) + 0.28
    I = 2.53 A

Or power rated

    P = I x V = 2.53 x 5
    P = 12.65 W

You probably want more than that, so get a 5 V 5 A supply to be on the safe side. So, no, a battery will not suffice.

  [1]: https://www.addicore.com/FS90-Mini-Servo-p/113.htm
  [2]: https://i.stack.imgur.com/qjidl.png "SG90 specifications"
  [3]: https://electronics.stackexchange.com/questions/246642/power-supply-circuit-for-powering-sg90-servo-how-to-handle-high-current-require#answer-339548
  [4]: https://electronics.stackexchange.com/questions/246642/power-supply-circuit-for-powering-sg90-servo-how-to-handle-high-current-require
  [5]: https://arduino.stackexchange.com/questions/926/what-is-the-maximum-power-consumption-of-the-arduino-nano-3-0#answer-932

body:
Cheapest way is that you should buy couple of LM7805 wire it in parallel now power arduino and other servos from this 7805. Connect pwm pins of servos to the nano.

Voltage regulator built inside arduino cant provide much current to all servos.

Also connect ground of all of your power sources together.

body:
Servos don't use PWM, not really. What they need is a pulse that is ~ 1mS wide every 20mS (50 Hz) to turn full one direction, ~ 1.5mS wide to be centered, and about 2mS wide to turn fully the other direction.  Or centered, +/- ~ 60-75 degrees or so.

(0.9mS to 2.1mS per the data above).

body:
You can drive upto 20 servos on an Arduino Nano - here's the EXCELLENT software for this: http://www.lamja.com/?p=504

Most servos can run well using high voltages (e.g. 9v) while still accepting PWM signals much lower (e.g. 3.3v) - here's a video showing that working fine:  https://youtu.be/9ZCiQgjcx3k

See Greenonline's answer table (or servo datasheets) to work out your power budget.  9v will work, but is probably more than the servos would like: 6v is more usual.


body:
I'm brand new to the Arduino world. I recently purchased a NodeMCU in order to have it act as a sort of foothold to get into Arduinos as it's something I've always wanted to do. However, it was only after I had received the NodeMCU that I realised that there was no default option in the Arduino IDE to flash to a NodeMCU and soon found out that this is because the NodeMCU is in fact not an Arduino and therefore has its own proprietary flashing software for .bin files. This initially confused me as an outsider as I assumed all devices of that nature must be Arduinos.

I recently came across a [Homebridge][1] plugin by affix called [homebridge-mcu-lamp][2] which uses a NodeMCU running an HTTP server to control a relay. Interestingly, the script he has included in the repository which he claims to have running on his NodeMCU is a .ino file which really confused me.

My question is: how would I flash a `.ino` file to a NodeMCU like the one mentioned above as I have no experience with `.bin` files and would much more value to treat the NodeMCU as an Arduino instead (i.e. programming in C++)?

I understand this may sound like a very simple/dumb question for most of you on this forum but it is something that has had me stumped for days and would really appreciate some guidance on.

I would also find it useful if someone could explain to me the difference between a NodeMCU and an ESP8266 as I see the two words being used interchangeably when referring to the same looking board.

This is what my NodeMCU looks like:

[![NodeMCU][3]][3]

  [1]: https://github.com/nfarina/homebridge
  [2]: https://github.com/affix/homebridge-mcu-lamp
  [3]: https://i.stack.imgur.com/xImLw.jpg "NodeMCU"

title: Flashing NodeMCU with .ino file?

Answers: 1

body:
Last question first: The ESP8266 is the main IC on the NodeMCU board.

This is similar to the idea that an ATMega328 is the IC on Arduino Uno.

A normal 'clean' Arduino IDE install can work with an Uno ('flash with an INO'), but not with an ESP8266 based board. For this, you will need the ESP8266 addon for the Arduino IDE, after which, the NodeMCU board is available as an option.

This page documents the ESP8266 addon:
https://github.com/esp8266/Arduino

Long story short, open preferences (File -> Preferences) , under Additional Board Manager URLs, add http://arduino.esp8266.com/stable/package_esp8266com_index.json

Click on Tools>Board>Board Manager (assuming you have Arduino IDE 1.6.4 or later) and search for ESP8266 and install the option that includes NodeMCU.


body:
Short version: Is the NodeMCU capable of key injection in the same way that an Arduino Teensy can be programmed with [Duckuino script][1] to function as a HID?

Long version: Recently, my 7+ year old iMac suddenly stopped working and now I am unable to boot into the Mac which is a right pain. Even more of a pain is that due to the fact that the iMac has a wireless keyboard as opposed to a USB meaning that I am unable to boot into Single User mode, recovery mode, safe boot etc. This is a pain as I am currently stuck with an iMac in an unsuccessful boot loop. I understand that the best option would be to buy a USB keyboard and use this separately; however, it turns out that one of my friends has a spare NodeMCU and said he's willing to lend it to me as he is pretty sure that the Duckuino script will work on it meaning that I could use the NodeMCU as a sort of impromptu keyboard to hold down the shift key on boot, effectively removing the need for me to buy and wait for a new USB keyboard.

I had found this video here on YouTube which explains the process of turning an Arduino into a "USB Rubber Ducky" but there is no mention of this working with a NodeMCU. Assuming that I have the ESP8266 addon for the Arduino IDE and was able to put the Duckuino script onto the NodeMCU, would the NodeMCU function as intended with the Duckuino script or is the NodeMCU hardware such that this would be impossible?

Thank you for any assistance,

Kind regards,
John

P.s. This is what my NodeMCU looks like:

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

  [1]: https://nurrl.github.io/Duckuino/
  [2]: https://i.stack.imgur.com/CyJhr.jpg

title: NodeMCU capable of key injection?

Answers: 1

body:
No, you can't use a NodeMCU for this.

To emulate a USB keyboard you have to have a device with a main MCU on it which is directly connected to USB. The ESP8266 on the NodeMCU is not a USB-capable MCU, and so it uses a USB to UART bridge chip to connect the ESP8266 to the USB of your computer.

You can't program that bridge chip, so you can't make it anything other than a serial port.

Common devices that are directly USB connected and can emulate a keyboard include:

* Arduino Micro
* Teensy 3.X
* Fubarino Mini / SD
* Arduino Leonardo
* chipKIT Lenny

And there are many more.

For 8-bit Arduino boards you need to look at the MCU it uses. If it's an ATMega32U4 as the main MCU then you can program it to be a keyboard.

----

Addendum: There are ways of making non-USB boards work as a keyboard. For ATMega328P based Arduinos and similar that use an ATMega16U2 chip as the USB to UART bridge, that bridge chip can be reprogrammed to appear as a keyboard.  For other MCUs there may be software "bit-banged" USB implementations available (such as V-USB), though YMMV with those implementations, and they require building extra hardware to interface the chip to the USB port.


body: I want to know what Serial.begin(9600); does and if it is necessary to write it in the code.

title: Serial.begin(9600); in Arduino

Answers: 1

body: It enables the UART port and sets it to 9600 baud.  Without it you can't use `Serial.print` etc.


body:
# General

I have a library with a class constructor `class Math(&foo1,&foo2);`, which I would like to put into a library for `class Algebra()`, where `foo1` and `foo2` are defined in `Algebra.cpp`

My current constructor `Algebra::Algebra():Math(&Algebra::foo1,&Algebra::foo2)` is returning an error in the Arduino IDE to the effect of:

`error: no matching function for call to 'Math::Math(void (Algebra::*)(long unsigned int, byte), byte (Algebra::*)(long unsigned int))':Math(&Algebra::foo1, &Algebra::foo2)`

*Meta Note: I believe this is on topic because I'm dealing specifically with developing code for the Arduino Mega using libraries and hardware components designed for Arduino. If I am in error, and there is a better exchange for this question please let me know*

----------

# Specifically,

I'm writing a library to combine [Adafruit's I2C FRAM][1] with the [Extended database library][2] (I have validated that the libraries work when called into a sketch independently, but I'd like to combine them to be more easily inheritable in [*Big_Machine_api.h*] that I will be making later)
I'm testing my library with this sketch:

    /*
     EDB_AT24C1024.pde
     Extended Database Library + Adafruit_FRAM_I2C EEPROM Test Sketch

     The Extended Database library project page is here:
     http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

     The Adafruit_FRAM_I2C library project page is here:
     https://github.com/adafruit/Adafruit_FRAM_I2C

     */
    #include "Arduino.h"
    #include <Wire.h>
    #include <Adafruit_FRAM_I2C_EDB.h>
    #define TABLE_SIZE 131072

    // Arbitrary record definition for this table.
    // This should be modified to reflect your record needs.
    struct LogEvent {
      int id;
      unsigned long Rotations;
    }
    logEvent;

    // Create an EDB object with the appropriate write and read handlers
    Adafruit_FRAM_I2C_EDB db;

    // Run the demo
    void setup() {
      Serial.begin(115200);
      Serial.println("DONE");
    }

    void loop() {
    }

My ADAFRUIT_FRAM_I2C_EDB.h file:

    #ifndef ADAFRUIT_FRAM_I2C_EDB_h
    #define ADAFRUIT_FRAM_I2C_EDB_h

    #include <Arduino.h>
    #include <Adafruit_FRAM_I2C.h>
    #include <EDB.h>

    #define MB85RC_DEFAULT_ADDRESS        (0x50) /* 1010 + A2 + A1 + A0 = 0x50 default */

    class Adafruit_FRAM_I2C_EDB : public EDB {
     public:
      Adafruit_FRAM_I2C_EDB(uint8_t addr = MB85RC_DEFAULT_ADDRESS);
      void getDeviceID(uint16_t *manufacturerID, uint16_t *productID);

     private:
      Adafruit_FRAM_I2C _fram;
      uint8_t _FRAMaddr;
      void writer(unsigned long address, byte data);
      byte reader(unsigned long address);

    };
    #endif

My ADAFRUIT_FRAM_I2C_EDB.cpp file:

    #include "Arduino.h"
    #include "Adafruit_FRAM_I2C.h"
    #include "EDB.h"
    #include "Adafruit_FRAM_I2C_EDB.h"
    Adafruit_FRAM_I2C_EDB::Adafruit_FRAM_I2C_EDB(uint8_t addr)
    :_FRAMaddr(addr),EDB(&Adafruit_FRAM_I2C_EDB::writer, &Adafruit_FRAM_I2C_EDB::reader) {
      _fram = Adafruit_FRAM_I2C();
      _fram.begin(_FRAMaddr);
    }

    void Adafruit_FRAM_I2C_EDB::getDeviceID(uint16_t *manufacturerID, uint16_t *productID) {
      _fram.getDeviceID(manufacturerID, productID);
    }

    void Adafruit_FRAM_I2C_EDB::writer(unsigned long address, byte data) {
      _fram.write8(address, data);
    }

    byte Adafruit_FRAM_I2C_EDB::reader(unsigned long address) {
      return _fram.read8(address);
    }

Full Error List:

    C:[...]\Arduino\libraries\Adafruit_FRAM_I2C_EDB\Adafruit_FRAM_I2C_EDB.cpp:16:84: note: candidates are:

    In file included from C:[...]\Arduino\libraries\Adafruit_FRAM_I2C_EDB\Adafruit_FRAM_I2C_EDB.cpp:3:0:

    C:[...]\Arduino\libraries\EDB-master/EDB.h:54:5: note: EDB::EDB(void (*)(long unsigned int, uint8_t), uint8_t (*)(long unsigned int))

         EDB(EDB_Write_Handler *, EDB_Read_Handler *);

         ^

    C:[...]\Arduino\libraries\EDB-master/EDB.h:54:5: note:   no known conversion for argument 1 from 'void (Adafruit_FRAM_I2C_EDB::*)(long unsigned int, byte) {aka void (Adafruit_FRAM_I2C_EDB::*)(long unsigned int, unsigned char)}' to 'void (*)(long unsigned int, uint8_t) {aka void (*)(long unsigned int, unsigned char)}'

    C:[...]\Arduino\libraries\EDB-master/EDB.h:50:7: note: constexpr EDB::EDB(const EDB&)

     class EDB {

           ^

    C:[...]Arduino\libraries\EDB-master/EDB.h:50:7: note:   candidate expects 1 argument, 2 provided

    C:[...]Arduino\libraries\EDB-master/EDB.h:50:7: note: constexpr EDB::EDB(EDB&&)

    C:[...]\Arduino\libraries\EDB-master/EDB.h:50:7: note:   candidate expects 1 argument, 2 provided

    exit status 1
    Error compiling for board Arduino/Genuino Mega or Mega 2560.

  [1]: https://www.adafruit.com/product/1895
  [2]: http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

title: How do I inherit a class that requires &foo() in its constructor?

Answers: 1

body:
You just pass the variables to the parent constructor in the initialization list of the child. No need for qualifications or anything like that.

Here's an example that compiles:

    class Math {
        private:
            int _foo1;
            int _foo2;

        public:
            Math(int &foo1, int &foo2) : _foo1(foo1), _foo2(foo2) {}
    };

    class Algebra : public Math {
        private:
            int myFoo1 = 12;
            int myFoo2 = 34;

        public:
            Algebra() : Math(myFoo1, myFoo2) {}
    };

Math's constructor takes two integers passed by reference.  The Algebra constructor's initialization list calls the parent Math constructor with two of its own member integers that are then automatically passed by reference, since that is what the constructor calls for.

However, that isn't what your actual problem is. You're asking about one thing, then showing an error that is for a completely different problem.

You have a constructor (actually any function will do the same) that expects a pair of pointers to two functions:

* `void (*)(long unsigned int, uint8_t)`
* `uint8_t (*)(long unsigned int)`

That is, you need two functions, such as:

    void reader(unsigned long a, uint8_t b) {
    }

and

    uint8_t writer(unsigned long a) {
        return 3;
    }

But instead you are attempting to pass member functions of a class.  The problem here is that although they *look* the same, because they are class members they *aren't* the same.

Any class member function has an additional implied parameter, which is a pointer to the containing class instance and is called `this`.  So your functions actually look more like:

    void reader(Adafruit_FRAM_I2C_EDB *this, unsigned long a, uint8_t b) {
    }

and

    uint8_t writer(Adafruit_FRAM_I2C_EDB*this, unsigned long a) {
        return 3;
    }

(Note: that's only an approximation - it's actually a lot more involved than that, but it serves to illustrate the problem).  As you can see that doesn't match what is expected, and so you can't pass those functions to the parent constructor - they're simply wrong.

This is a commonly occuring problem - often seen when trying to use a class member function with `attachInterrupt()`. You just can't do it.  Or not like that anyway.

The only way of passing a member function directly is for that member function to be `static`. That then acts like a normal function, and there is no `this` parameter. However, it can only act on other `static` variables and functions. So using it takes a little more care - plus of course `static` functions and variables are shared between all instances of a class.


body:
I'm brand new to Arduinos. I'm currently trying to modify a script from [here][1] which at the moment, simply turns an LED on or off depending on which HTTP GET request it receives. However, I want to modify this to have the LED modulate on/off when presented with the On HTTP GET request and then simply turn off all together when presented with the Off HTTP GET request. However, I have two conflicting methods that I have found about how to achieve this; the first is:

    int value = LOW;
        if (request.indexOf("/LED=ON") != -1)  {
          value = HIGH;
          do
          {
          digitalWrite(ledPin, HIGH);
          delay(3000);
          digitalWrite(ledPin, LOW);
          delay(5000);
          value = HIGH;
          } while (value = HIGH);
        }
        if (request.indexOf("/LED=OFF") != -1)  {
          digitalWrite(ledPin, LOW);
          value = LOW;
        }

Wheareas the other is:

      int value = LOW;
        if (request.indexOf("/LED=ON") != -1)  {
          value = HIGH;
          void loop() {
          digitalWrite(ledPin, HIGH);
          delay(3000);
          digitalWrite(ledPin, LOW);
          delay(5000);
          value = HIGH;
          }
        }
        if (request.indexOf("/LED=OFF") != -1)  {
          digitalWrite(ledPin, LOW);
          value = LOW;
        }
As you can see, the first uses [do...while][2] and the second uses [loop()][3]. I have a feeling that the first of the two scripts would be more suitable as it should cut out as soon as `value` is set to `LOW` (i.e. when requested to turn off)

However, I would really appreciate it if someone could look through the two scripts and tell me which of the two is the correct way to achieve this sort of cut off when the HTTP GET Off is requested (if either for them even is the correct way to do this!).

Thank you in advance for your help,

Kind regards,
Tom

  [1]: https://github.com/aaqib12/NodeMcu-Esp8266-Homebridge-Switch/blob/master/NODEMCU_CODE.ino
  [2]: https://www.arduino.cc/reference/en/language/structure/control-structure/dowhile/
  [3]: https://www.arduino.cc/reference/en/language/structure/sketch/loop/

title: Correct way of having loop end when required?

Answers: 1

body:
As pointed out by Ignacio Vazquez-Abrams and jsotola, you need to use a
state machine, like the one from the [Blink Without Delay][blink]
Arduino tutorial. Yours would be slightly more complicated because you
need a way to turn it on and off, and because you use different on and
off periods. Here is an example code that abstract the blinking logic
into three functions:

* `update_led()` takes care of the blinking, and it has to be called
  quite often in order to achieve a smooth blinking
* `start_blinking()` and `stop_blinking()`, as their names suggest, are
  used to turn the blinking state machine on and off.

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

    const uint32_t ON_TIME  = 3000;
    const uint32_t OFF_TIME = 5000;

    bool led_blinking;     // are we blinking the LED?
    bool led_on;           // is the LED currently on?
    uint32_t last_toggle;  // last time it toggled while blinking

    void update_led() {
        if (!led_blinking) return;
        uint32_t now = millis();
        if (led_on && now - last_toggle >= ON_TIME) {
            digitalWrite(ledPin, LOW);
            led_on = false;
            last_toggle = now;
        }
        if (!led_on && now - last_toggle >= OFF_TIME) {
            digitalWrite(ledPin, HIGH);
            led_on = true;
            last_toggle = now;
        }
    }

    void start_blinking() {
        digitalWrite(ledPin, HIGH);
        led_blinking = true;
        led_on = true;
        last_toggle = millis();
    }

    void stop_blinking() {
        digitalWrite(ledPin, LOW);
        led_blinking = false;
        led_on = false;
    }

You then have to call these functions from `loop()` as follows:

    void loop() {
        // Keep the LED blinking if necessary.
        update_led();
        ...
        if (request.indexOf("/LED=ON") != -1)  {
            start_blinking();
        }
        if (request.indexOf("/LED=OFF") != -1)  {
            stop_blinking();
        }
        ...
    }

[blink]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay

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

**Edit**, in response to jsotola’s comments:

When answering the question, I was initially tempted to make a
`BlinkingLed` class, with the functions as its public interface and the
variables private. I resisted the temptation on the grounds that, given
the apparent OP’s level of C++ knowledge, that could end up being well
over his head. Instead, I used documentation as an informal way of
separating the public from the private: you are only supposed to use
what is documented, i.e. the functions. You don't “take a shortcut in
your program and clear `led_blinking` directly”.

You could, of course, make the `led_blinking` variable part of the
public interface. That could even be a nice simplification, as you don't
need the start/stop function anymore. But then you loose control over
the initial phase of the blinking pattern. That may not be an issue, but
if you want the LED to turn on as soon as you set `led_blinking` to
`true`, then you have to do something like

    void update_led() {
        uint32_t now = millis();
        if (!led_blinking) {
            digitalWrite(ledPin, LOW);
            led_on = false;
            last_toggle = now - OFF_TIME;  // fix initial phase
            return;
        }
        ...
    }

Note that the subtraction can overflow, but that's not as issue because
it follows the rules of modular arithmetics.

I actually kind of like this option, with all the logic in a single
function. This way the variables `led_on` and `last_toggle` can be made
static local to the function, which provides true encapsulation without
a class. However, from a pedagogic point of view, I think my initial
proposal is easier to understand.


body:
I'm trying, what I thought would be simple, to wake a sleeping ESP8266 via motion detected by a PIR.

There are a lot of schematics around and they all seem to go about it more or less the same way, and the simplest form seems to be this:

[![wake esp from pir][1]][1]

Where RST is the RST pin of the ESP8266 and Trigger is the PIR's trigger line.

The problem I'm finding is that this is not working.

The PIR is working fine, and throws out almost 3v for 2 seconds when triggered and 0 when no motion is detected.

My ESP is being woken up when the PIR trigger is OVER, not when it STARTS. So if the PIR senses motion for a long time, the ESP will only wake up when the motion STOPS.

The PIR is [one of these][2].

The ESP is currently a [NodeMCU][3] on breadboard, but the final product will be a [Wemos D1 Mini][4].

What am I doing wrong here?

  [1]: https://i.stack.imgur.com/yHLOd.png
  [2]: https://www.banggood.com/5Pcs-Mini-IR-Infrared-Pyroelectric-PIR-Body-Motion-Human-Sensor-Detector-Module-p-1020426.html?rmmds=myorder&cur_warehouse=CN
  [3]: https://www.amazon.ca/gp/product/B01F5ALLFM/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
  [4]: https://www.banggood.com/5Pcs-Wemos-D1-Mini-V2_3_0-WIFI-Internet-Of-Things-Development-Board-Based-ESP8266-ESP-12S-4MB-FLASH-p-1230990.html?rmmds=myorder&cur_warehouse=CN

title: PIR motion wake ESP8266 from deepsleep

Answers: 1

body:
What you need is an edge detector. As long as the PIR output is hight, the ESP stays in reset mode.

You can use a capacitor to do the trick, as shown in the following schematic.
You'll probably want to get rid of the pull-down resistor R1 since you're using an open-collector output.

![Edge detector][1]

If the voltage at the collector is the blue curve, then the resulting voltage at the output of the circuit will be similar to the yellow curve. (Note that this simulation used an ideal square wave as input, produced by a push-pull output from a CMOS chip, for example. An open-collector output will have slightly different characteristics, the high peak won't be as high.)

![Simulation][2]

At the instant when the collector voltage drops to (almost) zero, the voltage across C1 will be 0V, so the output is close to 0V as well. Then the capacitor immediately starts to charge through R2, so the voltage on the reset pin rises exponentially.

To prevent a high voltage peak when the PIR turns off, a diode is used to discharge the capacitor more quickly. If the resistor at the collector is large enough, this might not be an issue at all.

The same principle is used in the Arduino UNO, for example, to reset the ATmega when DTR goes low.

  [1]: https://tttapa.github.io/Images/reset_with_diode.png
  [2]: https://tttapa.github.io/Images/with_diode.png


body:
I transported two float values with pyserial to COM3 and Arduino accepted the values.

But it displayed the first value correctly on LCD, the second value can't be read and showed "nan" on LCD.

Python code:

<!-- language: lang-py -->

    import serial
    import struct
    ser =serial.Serial("COM3", 115200, timeout=2)

    ##======Get  Ready================
    print("Connecting to Arduino.....")
    for i in range (1,10):
        rv=ser.readline()
        print("Loading...")
        #Debug print (rv) # Read the newest output from the Arduino
        print (rv.decode("utf-8"))
        ser.flushInput()
        sleep(1) # Delay for one tenth of a secon
        Str=rv.decode("utf-8")
        #Debug print(Str[0:5])
        if Str[0:5]=="Ready":
              print("Get Arduino Ready !")
              break
    ##------------------------------------------------------
    d = 77.25
    a = 111.32
    ser.write(struct.pack('>2f',d,a))

Arduino code:

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

    #include <LiquidCrystal.h>
    float x;
    byte *xdata = (byte *) & x;
    float y;
    byte *ydata = (byte *) & y;
    int num = 0;
    char coor[2];

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      Serial.begin(115200); // set the baud rate
      Serial.println("Ready"); // print "Ready" once
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
    }

    void loop(){
      while(Serial.available() > 0){
        for(int i = 0; i < 2; i++){
          coor[i] = Serial.read();
          }
        if(coor[0] == 'B' ){
          xdata[3] = coor[0];
          ydata[3] = coor[1];
          num = 1;
        } else if(num == 1){
          xdata[2] = coor[0];
          ydata[2] = coor[1];
          num++;
        } else if(num == 2){
          xdata[1] = coor[0];
          ydata[1] = coor[1];
          num++;
        } else if(num == 3){
          xdata[0] = coor[0];
          ydata[0] = coor[1];
          num = 0;
        // use the values
        Serial.write(xdata,4);
        Serial.write(ydata,4);
        lcd.print(x);
        lcd.setCursor(8,0);
        lcd.print(y);
          }
        }

The LCD monitor will show 77.25 and nan. It can't show 111.32 correctly.

title: Can't display the two float values correctly from pyserial on Arduino's LCD

Answers: 1

body:
I don't understand why you read the bytes this way. Your original version was reading only the bytes of the first float into xdata and -1 into ydata. (`read` returns -1 if no data is available, it doesn't wait.) Now when two bytes are read with `readBytes`, first two bytes of the first float are written one into xdata[0] and second into ydata[0].

read first float with `readBytes(xdata, 4)` and the the second with `readBytes(ydata, 4)`


body:
I recently received a NodeMCU (identical to the one shown in the first picture below) and originally, I was unable to connect it to my computer which eventually turned out to be driver issues; however, during my initial panic, I found that there seems to be two variations of the NodeMCU board.

As you can see from the pictures below, at first glance there seems to be no difference to the boards, however, some of the more noticeable differences are that the first one has only one "orange" chip whereas the second one has two. Moreover, the first one has a large square chip towards the USB port wheareas the second seems to have a rectangular one.

First one:
[![1st one][1]][1]

Second one:
[![2nd one][2]][2]

I would really appreciate if someone could enlighten me to what these small differences are between the two boards are and also what are the implications of these differences (if there are any).

Thank you in advance for any help,

Kind regards,
John

  [1]: https://i.stack.imgur.com/qqLam.jpg
  [2]: https://i.stack.imgur.com/UI40Q.jpg

title: Difference between these two NodeMCU boards?

Answers: 2

body:
The top one is a real NodeMCU version 1 board (ESP-12E module).

The bottom one is a knock-off copy - looks like the same module on it.

The biggest difference is the USB interface. The real one uses a CP2102 USB to UART bridge. The copy uses a CH340G chip.  The CH340G is notoriously unstable and liable to die at a moments notice.  The CP2102 is far more reliable.  I recently accidentally nuked a Wemos D1 Mini pro which has the same CP2102 on it with 12V.  It took out the voltage regulator. It took out the ESP8266 chip.  I replaced both those, and the CP2102 was proved to still be working fine. More than could be said for a CH340G - glance at one of those wrong and they die.

body: I have several of the second version and they all have the CP2102 USB to UART bridge. So I wouldn't say it's a copy or a clone. These are now made by several manufacturers, mine came from DOITING not AI Thinker, so the components can vary and come in different colours ! AND, Chinese is Good !


body: How do I reset my arduino installation back to its original state? i.e., no extra downloaded libraries, etc.  If I delete Documents/Arduino/libraries is there any other state that needs to be cleaned up?

title: How do I reset my libraries back to original condition?

Answers: 2

body:
1. Delete the Documents -> Arduino -> Libraries to remove all your libraries.

2. Delete the User -> AppData -> Local -> Arduino15 folder to remove all the preferences.

3. Uninstall Arduino IDE.

4. Install a fresh one.

body:
Directory to suppress for reset config.

- C:\Users\YourName\\.arduinoIDE
- C:\Users\YourName\AppData\Local\Arduino15
- C:\Users\YourName\AppData\Local\Programs\Arduino IDE
- C:\Users\YourName\AppData\Local\arduino-ide-updater
- C:\Users\YourName\Documents\Arduino
- C:\Users\YourName\AppData\AppData\Roaming\Arduino IDE
- C:\Users\YourName\AppData\AppData\Roaming\arduino-ide


body:
I'm looking to build an Arduino-based "camera flash logger" to detect when a camera flash goes off, and maintain a log of those events. My thinking is to use a photoresistor to measure light level, and watch for sudden changes using a loop. Something like:

    const int ldrPin = A0;

    // no idea what this number would end up being
    // just putting something here to start with
    const int threshold = 10;
    int currentLevel, lastLevel = 0;

    void setup() {
        Serial.begin(9600);
        pinMode(ldrPin, INPUT);
    }

    void loop() {
        lastLevel = currentLevel;
        currentLevel = analogRead( ldrPin );

        // look for a sudden change
        if( abs( lastLevel - currentLevel ) > threshold ) {

            // serial out here to simplify the example.
            // I'll be logging outputs (with timestamps) to an SD card.
            Serial.println( currentLevel );
        }
    }

A couple of things I'm not sure of though:

 1. will the response time of a photoresistor be fast enough to respond to the very short (sometimes less than 1ms) burst from a camera flash?

 2. is a loop measuring level changes the best way to go about this, or would something like a state change interrupt be better? The ambient light level will vary depending on time of day, so it's an edge detection problem, as opposed to just reading a light level.

Apologies if this comes across as a "you haven't done your homework yet" question. I haven't started the project yet, so all I'm hoping for is a little direction on which way to proceed.

title: Detect a camera flash? Light sensor, photoresistor?

Answers: 1

body:
A photo-resistor would not be recommended to detect a camera flash accurately.  For example, the Jameco Part #202403 ([Part PDF][1]) has a response time of 50 to 75 milliseconds.  Photo-resistors are more suitable for general light levels, for instance, like how bright it is in a room.
On the other hand, photo-transistors are suitable for very fast reaction times.  The Jameco Part #2129385 ([Part PDF][2]) has a response time of 15 microseconds, which is more than 1000 times faster.  A photo-resistor will be able to respond to the light change, but it will be nowhere as sensitive.

As with any product, however, search for the product PDF before buying it.

  [1]: https://www.jameco.com/Jameco/Products/ProdDS/202403.pdf
  [2]: https://www.jameco.com/Jameco/Products/ProdDS/2129385.pdf


body:
I have an OBD-based Arduino project (OBD adapter link below) which uses two servos and a serial LCD from Sparkfun (link below). My problem: writing to the LCD seems to interfere with the servos. Details:

1) When all LCD-related code is excluded, the servos work smoothly.
2) When LCD-related code is included, but the servos are not hooked up, the LCD displays everything OK.
3) When the LCD-related code is included, even if the LCD itself is NOT hooked up, the problem occurs. There's a brief noise from the servos every time I write to the LCD (the servos don't move much, they just make a brief noise).

Any idea what's causing this? Below are the relevant parts of the code (OBD, servo, LCD):

    #include <Arduino.h>
    #include <Wire.h>
    #include <OBD.h>
    #include "MPU6050.h"
    #include <SoftwareSerial.h>
    #include <Servo.h>

    int servoPin1=13;
    int servoPin2=12;

    Servo servo1;
    Servo servo2;

    COBDI2C obd;
    SoftwareSerial lcd(2,3);

    void clearDisplay() {
      lcd.write(0xFE);
      lcd.write(0x01);
    }

    void setLCDCursor(byte cursor_position) {
      lcd.write(0xFE);
      lcd.write(0x80);
      lcd.write(cursor_position);
    }

    void Show() {
      setLCDCursor(0);
      lcd.print("Test");
    }

    void setup() {
      lcd.begin(9600);
      clearDisplay();
      setLCDCursor(0);
      lcd.print("OBD");

      pinMode(servoPin1,OUTPUT);
      pinMode(servoPin2,OUTPUT);
      servo1.attach(servoPin1);
      servo2.attach(servoPin2);
      servo1.write(0);
      delay(200);
      servo2.write(100);
      delay(200);

      obd.begin();
      conn=obd.init(PROTO_AUTO);
      lcd.print("Connected");

      Wire.begin();
    }

    void loop() {
      conn=obd.readPID(PID_RPM,rpm);
      if (condition) {
         servo2.write(50);
        delay(500);
        servo1.write(100);
        delay(500);
      }
      Show();
      delay(1000);
    }

[![Schematic][1]][1]

[OBD adapter][2]
[Serial LCD][3]

  [1]: https://i.stack.imgur.com/u4MqT.png
  [2]: https://freematics.com/pages/products/arduino-obd-adapter/
  [3]: https://www.sparkfun.com/products/10097

title: Writing to serial LCD seems to interfere with servos

Answers: 2

body:
The [servo control][1] [PWM][2] signal is generated in HW.  So should be stable if left alone with adequate power despite what the code is doing.  Servos are analog devices.  So any perturbation in the shape or length of the wave form may affect the servo.

Consider, once the servo has reached the desired position, turning off the PWM signal which, for most servos, simply leaves them motionless where they are.

  [1]: https://en.wikipedia.org/wiki/Servo_control
  [2]: https://en.wikipedia.org/wiki/Pulse_width_modulation

body:
You are using SoftwareSerial which turns interrupts off when sending/receiving in order to precisely time gaps between bits. The Servo library may use hardware timers, but to work on pins 12 and 13 would require interrupts to "copy" the pulses to those pins. Thus the copies will be distorted when writing to, or reading from, SoftwareSerial.

I suggest using hardware serial (pins 0 and 1) for talking to the LCDs, which does not turn interrupts off. Alternatively, implement the servo positioning using the hardware timers yourself, which (once set up) won't change the pulse widths if interrupts are turned off.


body:
I have a sketch with multiple source files and folders arranged like so. I've divided up the project like this to keep things clean.

    |
    \---project
        |   project.ino
        |   types.h
        |
        +---sub1
        |       gadget1.c
        |       gadget1.h
        |       gadget2.c
        |       gadget2.h
        |
        \---blarg
                foobar.c
                foobar.h

The sketch file includes the headers via quoted include directives (rather than the lib alternative with angled brackets). This seems to work for compilation.

However, when the IDE tries to link, all references to implementations (c source files) in the subfolders generate "undefined reference" errors. Almost as if the IDE is completely ignoring the C source files.

In trying to resolve this I've discovered that apparently the handling of subfolders by the IDE seems to be all over the place. Some versions only acknowledge headers in subfolders, others work if you put everything in a "src" folder (I've also seen mention of a "utility" folder), some people suggest modifying environment variables, etc. I've even tried manually adding source files via the "sketch/add file" option which makes the files visible in the IDE but does not solve the linking problems. All these methods seem to depend on IDE version, and I couldn't distill what was the correct way vs a hack or work-around.

So my question is what is the correct/current way of organizing the above project so that it can be compiled/linked using the IDE? I am using IDE version 1.8.5 which I believe is either the latest version, or close too it.

title: Arduino IDE and subfolders

Answers: 1

body:
From Arduino IDE 1.6.10 onward the Arduino IDE compiles all source files in the `src` subfolder of the sketch and recursively through all folders under the `src` folder.

Support for compilation of sketch subfolders was added one or two IDE versions before 1.6.10 and was originally not limited to the `src` folder but a lot of problems were reported by people who had stored separate programs in subfolders of their sketch that caused compilation errors so this feature was [restricted](https://github.com/arduino/arduino-builder/pull/148) to the `src` subfolder only.

So if you structure a sketch like this:

<!-- language: lang-none -->

    foo
    |_foo.ino
    |_src
       |_bar.cpp
       |_bar.h

And use this `#include` directive in your sketch:

<!-- language: lang-cpp -->

    #include "src/bar.h"

it will work fine.

>Almost as if the IDE is completely ignoring the C source files.

Arduino sketches are converted to C++ before being compiled. They are not C. If you want to use C in C++ code you need to wrap it in `extern "C" {}`

<!-- language: lang-cpp -->

    extern "C" {
    #include "src/sub1/gadget1.h"
    }

>what is the correct/current way of organizing the above project

<!-- language: lang-none -->

    project
    |_project.ino
    |_types.h
    |_src
       |_sub1
       |  |_gadget1.c
       |  |_gadget1.h
       |  |_gadget2.c
       |  |_gadget2.h
       |_blarg
          |_foobar.c
          |_foobar.h