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

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.

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


sender: user

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

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?

sender: assistant

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.


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

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

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.


message:
Arduino and AVR Serial Communication over USB

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?

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.


message:
Datalogger with interruputs

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");
        }
      }
    }

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


message:
9x servo on Arduino Nano?

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"

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.


message:
Flashing NodeMCU with .ino file?

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"

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.


message:
NodeMCU capable of key injection?

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

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.


message:
Serial.begin(9600); in Arduino

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

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


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

# 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

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.


message:
Correct way of having loop end when required?

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/

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.


message:
PIR motion wake ESP8266 from deepsleep

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

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


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

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.

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)`


message:
Difference between these two NodeMCU boards?

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

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 !


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

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?

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


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

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.

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


message:
Writing to serial LCD seems to interfere with servos

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

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.


message:
Arduino IDE and subfolders

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.

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


message:
RGB LED strip controlled through PySerial only somewhat functional

I am trying to set up an LED-strip of 30 RGB LEDs (model WS2801). The strip is connected to an Arduino Uno and an external power supply and the goal is to send colors to the arduino using PySerial which are then shown on the LED strip.

I have been trying to wrap my head around the communications, which I am having a hard time with, especially due to the loose typing of python.

I wrote some code that generates smooth color transitions and got the strip to actually show a fairly smooth color transition, unfortunately the colors are the wrong ones.

Now I am guessing something overflows somewhere, especially since colors such as 0xFF0000 (red) show as a yellow tone, which indicates that on top of red some green gets added as well.

The Python code using pySerial:

    @classmethod
    def set_lights(self: RGBHardware, colors: List[int]) -> None:
        for i in range(len(colors)):
            rgb = color_to_rgb(colors[i])
            self.arduino.write(chr(76).encode()) # 'L'
            self.arduino.write(chr(i).encode())
            self.arduino.write(chr(rgb[0]).encode())
            self.arduino.write(chr(rgb[1]).encode())
            self.arduino.write(chr(rgb[2]).encode())
        self.arduino.write(chr(90).encode()) # 'Z'

    @classmethod
    def turn_on(self) -> None:
        self.arduino = serial.Serial('/dev/ttyACM0', 115200)
        if self.arduino.isOpen:
            self.arduino.close()
        self.arduino.open()
        pass

The code running on the Arduino Uno:

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif

      Serial.begin(115200);
      strip.begin();
      // Update LED contents, to start they are all 'off'
      strip.show();
    }

    void loop() {
       while (Serial.available()) {
            uint8_t serial = Serial.read();
            if (serial == 'Z') {
                strip.show();
            } else if (serial == 'L') {
                int i = getNextInput();
                int r = getNextInput();
                int g = getNextInput();
                int b = getNextInput();
                strip.setPixelColor(i, Color(r,g,b));
            }
       }
    }

    uint8_t getNextInput() {
      while(!Serial.available()); // wait for a character
      return Serial.read();
    }

I am having the strong feeling I am just missing a miniscule detail and it is quite frustrating.

Any help would be greatly appreciated!

EDIT:
So I recorded some data and pasted the results below. I found that always not the whole LED-strip was updated and none of it with the correct color. Once even the character "Z" seemed to go missing (that causes the strip to fully refresh) so no color was showing at all.

What I also forgot to mention earlier was that I am using Celery in Python to do the light switching as a background task.

To record the results I used

`print("i, R,G,B: " + str(i) + ", " + str(rgb[0]) + "," + str(rgb[1]) + "," + str(rgb[2]))` to print the data in python and

`Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));` to do the same on the Arduino.

Sending color red from Python:

    [2018-07-23 16:13:57,121: WARNING/ForkPoolWorker-7] i, R,G,B: 0, 255,0,0
    [2018-07-23 16:13:57,122: WARNING/ForkPoolWorker-7] i, R,G,B: 1, 255,0,0
    [2018-07-23 16:13:57,123: WARNING/ForkPoolWorker-7] i, R,G,B: 2, 255,0,0
    [2018-07-23 16:13:57,125: WARNING/ForkPoolWorker-7] i, R,G,B: 3, 255,0,0
    [2018-07-23 16:13:57,126: WARNING/ForkPoolWorker-7] i, R,G,B: 4, 255,0,0
    [2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 5, 255,0,0
    [2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 6, 255,0,0
    [2018-07-23 16:13:57,128: WARNING/ForkPoolWorker-7] i, R,G,B: 7, 255,0,0
    [2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 8, 255,0,0
    [2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 9, 255,0,0
    [2018-07-23 16:13:57,131: WARNING/ForkPoolWorker-7] i, R,G,B: 10, 255,0,0
    [2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 11, 255,0,0
    [2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 12, 255,0,0
    [2018-07-23 16:13:57,133: WARNING/ForkPoolWorker-7] i, R,G,B: 13, 255,0,0
    [2018-07-23 16:13:57,134: WARNING/ForkPoolWorker-7] i, R,G,B: 14, 255,0,0
    [2018-07-23 16:13:57,136: WARNING/ForkPoolWorker-7] i, R,G,B: 15, 255,0,0
    [2018-07-23 16:13:57,137: WARNING/ForkPoolWorker-7] i, R,G,B: 16, 255,0,0
    [2018-07-23 16:13:57,139: WARNING/ForkPoolWorker-7] i, R,G,B: 17, 255,0,0
    [2018-07-23 16:13:57,140: WARNING/ForkPoolWorker-7] i, R,G,B: 18, 255,0,0
    [2018-07-23 16:13:57,141: WARNING/ForkPoolWorker-7] i, R,G,B: 19, 255,0,0
    [2018-07-23 16:13:57,142: WARNING/ForkPoolWorker-7] i, R,G,B: 20, 255,0,0
    [2018-07-23 16:13:57,144: WARNING/ForkPoolWorker-7] i, R,G,B: 21, 255,0,0
    [2018-07-23 16:13:57,145: WARNING/ForkPoolWorker-7] i, R,G,B: 22, 255,0,0
    [2018-07-23 16:13:57,146: WARNING/ForkPoolWorker-7] i, R,G,B: 23, 255,0,0
    [2018-07-23 16:13:57,147: WARNING/ForkPoolWorker-7] i, R,G,B: 24, 255,0,0
    [2018-07-23 16:13:57,148: WARNING/ForkPoolWorker-7] i, R,G,B: 25, 255,0,0
    [2018-07-23 16:13:57,149: WARNING/ForkPoolWorker-7] i, R,G,B: 26, 255,0,0
    [2018-07-23 16:13:57,150: WARNING/ForkPoolWorker-7] i, R,G,B: 27, 255,0,0
    [2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 28, 255,0,0
    [2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 29, 255,0,0

Received color red on the arduino:

    i, R,G,B: 0, 195,191,0
    i, R,G,B: 1, 195,191,0
    i, R,G,B: 2, 195,191,0
    i, R,G,B: 3, 195,191,0
    i, R,G,B: 4, 195,191,0
    i, R,G,B: 5, 195,191,0
    i, R,G,B: 6, 195,191,0
    i, R,G,B: 7, 195,191,0
    i, R,G,B: 8, 195,191,0
    i, R,G,B: 9, 195,191,0
    i, R,G,B: 10, 195,191,0
    i, R,G,B: 11, 195,191,0
    i, R,G,B: 12, 195,191,0
    i, R,G,B: 13, 195,191,0
    i, R,G,B: 14, 195,191,0
    i, R,G,B: 15, 195,191,0
    i, R,G,B: 16, 195,191,0
    i, R,G,B: 17, 195,191,0
    i, R,G,B: 18, 195,191,0
    i, R,G,B: 19, 195,191,0
    i, R,G,B: 20, 195,191,0
    i, R,G,B: 21, 195,191,0
    i, R,G,B: 22, 195,191,0
    i, R,G,B: 23, 195,191,0
    i, R,G,B: 24, 195,191,0
    i, R,G,B: 25, 195,191,0
    i, R,G,B: 26, 76,27,195

Sending color green from Python:

    [2018-07-23 16:22:34,374: WARNING/ForkPoolWorker-8] i, R,G,B: 0, 0,255,0
    [2018-07-23 16:22:34,376: WARNING/ForkPoolWorker-8] i, R,G,B: 1, 0,255,0
    [2018-07-23 16:22:34,377: WARNING/ForkPoolWorker-8] i, R,G,B: 2, 0,255,0
    [2018-07-23 16:22:34,378: WARNING/ForkPoolWorker-8] i, R,G,B: 3, 0,255,0
    [2018-07-23 16:22:34,380: WARNING/ForkPoolWorker-8] i, R,G,B: 4, 0,255,0
    [2018-07-23 16:22:34,381: WARNING/ForkPoolWorker-8] i, R,G,B: 5, 0,255,0
    [2018-07-23 16:22:34,382: WARNING/ForkPoolWorker-8] i, R,G,B: 6, 0,255,0
    [2018-07-23 16:22:34,383: WARNING/ForkPoolWorker-8] i, R,G,B: 7, 0,255,0
    [2018-07-23 16:22:34,384: WARNING/ForkPoolWorker-8] i, R,G,B: 8, 0,255,0
    [2018-07-23 16:22:34,385: WARNING/ForkPoolWorker-8] i, R,G,B: 9, 0,255,0
    [2018-07-23 16:22:34,386: WARNING/ForkPoolWorker-8] i, R,G,B: 10, 0,255,0
    [2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 11, 0,255,0
    [2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 12, 0,255,0
    [2018-07-23 16:22:34,388: WARNING/ForkPoolWorker-8] i, R,G,B: 13, 0,255,0
    [2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 14, 0,255,0
    [2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 15, 0,255,0
    [2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 16, 0,255,0
    [2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 17, 0,255,0
    [2018-07-23 16:22:34,391: WARNING/ForkPoolWorker-8] i, R,G,B: 18, 0,255,0
    [2018-07-23 16:22:34,392: WARNING/ForkPoolWorker-8] i, R,G,B: 19, 0,255,0
    [2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 20, 0,255,0
    [2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 21, 0,255,0
    [2018-07-23 16:22:34,394: WARNING/ForkPoolWorker-8] i, R,G,B: 22, 0,255,0
    [2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 23, 0,255,0
    [2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 24, 0,255,0
    [2018-07-23 16:22:34,396: WARNING/ForkPoolWorker-8] i, R,G,B: 25, 0,255,0
    [2018-07-23 16:22:34,397: WARNING/ForkPoolWorker-8] i, R,G,B: 26, 0,255,0
    [2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 27, 0,255,0
    [2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 28, 0,255,0
    [2018-07-23 16:22:34,399: WARNING/ForkPoolWorker-8] i, R,G,B: 29, 0,255,0

Received color green on the Arduino:

    i, R,G,B: 0, 0,195,191
    i, R,G,B: 1, 0,195,191
    i, R,G,B: 2, 0,195,191
    i, R,G,B: 3, 0,195,191
    i, R,G,B: 4, 0,195,191
    i, R,G,B: 5, 0,195,191
    i, R,G,B: 6, 0,195,191
    i, R,G,B: 7, 0,195,191
    i, R,G,B: 8, 0,195,191
    i, R,G,B: 9, 0,195,191
    i, R,G,B: 10, 0,195,191
    i, R,G,B: 11, 0,195,191
    i, R,G,B: 12, 0,195,191
    i, R,G,B: 13, 0,195,191
    i, R,G,B: 14, 0,195,191
    i, R,G,B: 15, 0,195,191
    i, R,G,B: 16, 0,195,191
    i, R,G,B: 17, 0,195,191
    i, R,G,B: 18, 0,195,191
    i, R,G,B: 19, 0,195,191
    i, R,G,B: 20, 0,195,191
    i, R,G,B: 21, 0,195,191
    i, R,G,B: 22, 0,195,191
    i, R,G,B: 23, 0,195,191
    i, R,G,B: 24, 0,195,191
    i, R,G,B: 25, 0,195,191
    i, R,G,B: 26, 76,28,0

Sending color blue from Python:

    [2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 0, 0,0,255
    [2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 1, 0,0,255
    [2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 2, 0,0,255
    [2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 3, 0,0,255
    [2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 4, 0,0,255
    [2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 5, 0,0,255
    [2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 6, 0,0,255
    [2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 7, 0,0,255
    [2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 8, 0,0,255
    [2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 9, 0,0,255
    [2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 10, 0,0,255
    [2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 11, 0,0,255
    [2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 12, 0,0,255
    [2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 13, 0,0,255
    [2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 14, 0,0,255
    [2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 15, 0,0,255
    [2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 16, 0,0,255
    [2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 17, 0,0,255
    [2018-07-23 16:26:52,425: WARNING/ForkPoolWorker-2] i, R,G,B: 18, 0,0,255
    [2018-07-23 16:26:52,426: WARNING/ForkPoolWorker-2] i, R,G,B: 19, 0,0,255
    [2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 20, 0,0,255
    [2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 21, 0,0,255
    [2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 22, 0,0,255
    [2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 23, 0,0,255
    [2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 24, 0,0,255
    [2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 25, 0,0,255
    [2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 26, 0,0,255
    [2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 27, 0,0,255
    [2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 28, 0,0,255
    [2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 29, 0,0,255

Received color blue on the Arduino:

    i, R,G,B: 0, 0,0,195
    i, R,G,B: 1, 0,0,195
    i, R,G,B: 2, 0,0,195
    i, R,G,B: 3, 0,0,195
    i, R,G,B: 4, 0,0,195
    i, R,G,B: 5, 0,0,195
    i, R,G,B: 6, 0,0,195
    i, R,G,B: 7, 0,0,195
    i, R,G,B: 8, 0,0,195
    i, R,G,B: 9, 0,0,195
    i, R,G,B: 10, 0,0,195
    i, R,G,B: 11, 0,0,195
    i, R,G,B: 12, 0,0,195
    i, R,G,B: 13, 0,0,195
    i, R,G,B: 14, 0,0,195
    i, R,G,B: 15, 0,0,195
    i, R,G,B: 16, 0,0,195
    i, R,G,B: 17, 0,0,195
    i, R,G,B: 18, 0,0,195
    i, R,G,B: 20, 0,0,195
    i, R,G,B: 23, 191,76,26

Sending color orange from Python:

    [2018-07-23 16:29:20,725: WARNING/ForkPoolWorker-9] i, R,G,B: 0, 255,128,0
    [2018-07-23 16:29:20,726: WARNING/ForkPoolWorker-9] i, R,G,B: 1, 255,128,0
    [2018-07-23 16:29:20,727: WARNING/ForkPoolWorker-9] i, R,G,B: 2, 255,128,0
    [2018-07-23 16:29:20,728: WARNING/ForkPoolWorker-9] i, R,G,B: 3, 255,128,0
    [2018-07-23 16:29:20,729: WARNING/ForkPoolWorker-9] i, R,G,B: 4, 255,128,0
    [2018-07-23 16:29:20,731: WARNING/ForkPoolWorker-9] i, R,G,B: 5, 255,128,0
    [2018-07-23 16:29:20,732: WARNING/ForkPoolWorker-9] i, R,G,B: 6, 255,128,0
    [2018-07-23 16:29:20,733: WARNING/ForkPoolWorker-9] i, R,G,B: 7, 255,128,0
    [2018-07-23 16:29:20,734: WARNING/ForkPoolWorker-9] i, R,G,B: 8, 255,128,0
    [2018-07-23 16:29:20,735: WARNING/ForkPoolWorker-9] i, R,G,B: 9, 255,128,0
    [2018-07-23 16:29:20,736: WARNING/ForkPoolWorker-9] i, R,G,B: 10, 255,128,0
    [2018-07-23 16:29:20,737: WARNING/ForkPoolWorker-9] i, R,G,B: 11, 255,128,0
    [2018-07-23 16:29:20,738: WARNING/ForkPoolWorker-9] i, R,G,B: 12, 255,128,0
    [2018-07-23 16:29:20,739: WARNING/ForkPoolWorker-9] i, R,G,B: 13, 255,128,0
    [2018-07-23 16:29:20,740: WARNING/ForkPoolWorker-9] i, R,G,B: 14, 255,128,0
    [2018-07-23 16:29:20,741: WARNING/ForkPoolWorker-9] i, R,G,B: 15, 255,128,0
    [2018-07-23 16:29:20,742: WARNING/ForkPoolWorker-9] i, R,G,B: 16, 255,128,0
    [2018-07-23 16:29:20,743: WARNING/ForkPoolWorker-9] i, R,G,B: 17, 255,128,0
    [2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 18, 255,128,0
    [2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 19, 255,128,0
    [2018-07-23 16:29:20,745: WARNING/ForkPoolWorker-9] i, R,G,B: 20, 255,128,0
    [2018-07-23 16:29:20,746: WARNING/ForkPoolWorker-9] i, R,G,B: 21, 255,128,0
    [2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 22, 255,128,0
    [2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 23, 255,128,0
    [2018-07-23 16:29:20,749: WARNING/ForkPoolWorker-9] i, R,G,B: 24, 255,128,0
    [2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 25, 255,128,0
    [2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 26, 255,128,0
    [2018-07-23 16:29:20,751: WARNING/ForkPoolWorker-9] i, R,G,B: 27, 255,128,0
    [2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 28, 255,128,0
    [2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 29, 255,128,0

Received color orange on the Arduino:

    i, R,G,B: 0, 195,191,194
    i, R,G,B: 1, 195,191,194
    i, R,G,B: 2, 195,191,194
    i, R,G,B: 3, 195,191,194
    i, R,G,B: 4, 195,191,194
    i, R,G,B: 5, 195,191,194
    i, R,G,B: 6, 195,191,194
    i, R,G,B: 7, 195,191,194
    i, R,G,B: 8, 195,191,194
    i, R,G,B: 9, 195,191,194
    i, R,G,B: 10, 195,191,194
    i, R,G,B: 11, 195,191,194
    i, R,G,B: 12, 195,191,194
    i, R,G,B: 13, 195,191,194
    i, R,G,B: 14, 195,191,194
    i, R,G,B: 15, 195,191,194
    i, R,G,B: 16, 195,191,194
    i, R,G,B: 17, 195,191,194
    i, R,G,B: 18, 195,191,194
    i, R,G,B: 19, 195,191,194
    i, R,G,B: 76, 23,195,191
    i, R,G,B: 194, 128,0,76

Received color orange on the Arduino (again):

    i, R,G,B: 0, 195,191,194
    i, R,G,B: 1, 195,191,194
    i, R,G,B: 2, 195,191,194
    i, R,G,B: 3, 195,191,194
    i, R,G,B: 4, 195,191,194
    i, R,G,B: 5, 195,191,194
    i, R,G,B: 6, 195,191,194
    i, R,G,B: 7, 195,191,194
    i, R,G,B: 8, 195,191,194
    i, R,G,B: 9, 195,191,194
    i, R,G,B: 10, 195,191,194
    i, R,G,B: 11, 195,191,194
    i, R,G,B: 12, 195,191,194
    i, R,G,B: 13, 195,191,194
    i, R,G,B: 14, 195,191,194
    i, R,G,B: 15, 195,191,194
    i, R,G,B: 16, 195,191,194
    i, R,G,B: 17, 195,191,194
    i, R,G,B: 18, 195,191,194
    i, R,G,B: 128, 0,76,24
    i, R,G,B: 27, 195,191,194

Another Edit:
What is also interesting is that the main color (e.g. when I send red most of the LEDs are yellow) stays the same every time I tried.
But the amount of LEDs that gets passed differs with each try. The same goes for the last one or two LEDs the Arduino receives. Their colors and indexes are all over the place.

body:
This

    ...
      self.arduino.write(chr(76).encode()) # 'L'
      self.arduino.write(chr(i).encode())
      self.arduino.write(chr(rgb[0]).encode())
      self.arduino.write(chr(rgb[1]).encode())
      self.arduino.write(chr(rgb[2]).encode())
    self.arduino.write(chr(90).encode()) # 'Z'
    ...
should be spelled:

      self.arduino.write(b'L')
      self.arduino.write(i.to_bytes(1,'big'))
      self.arduino.write(bytes(rgb))
    self.arduino.write(b'Z')

It is much more readable this way; you could refactor even further:

      sout = b'L' + i.to_bytes(1,'big') + bytes(rgb)
      self.arduino.write(sout)
    self.arduino.write(b'Z')
Your also wasting effort here:

    Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));
This should be said more like this:

    Serial.print(i);
    Serial.print(", ");
    Serial.print(r);
    Serial.print(", ");
    Serial.print(g);
    Serial.print(", ");
    Serial.println(b);

This eliminates three temporary String objects you were creating with String().

The rest of the code looks like it should work so you should try trouble shooting, you could:

 - Lower the baud rate till it works
 - Try 9600 baud and increase it until it stops working
 - Try the a serial sample program, make sure the serial portion is working correctly first
 - Write your own minimal test program, make sure the serial is working correctly at first.


message:
In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?

I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.

I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?

body:
You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.

Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.


message:
Do I need an external power supply for the SG90 micro servo?

I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?

I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.

body:
I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, [SG90 Specifications][1], you'll see the "stall current" can be between 570mA and 730mA. You may want to test your servo under this condition before deciding to power it with an Uno.

  [1]: https://arduino.stackexchange.com/a/49755/37523


body: Does your servo have to push or pull anything? Or is this just to practice writing code for an unattached SG90 and see it move? If it's the former, the servo will draw more current than an Arduino can deliver so you'd need a separate power supply. If it's the latter, you can get away with it. The SG90 is about the least demanding (of current) servo available and you can drive an *unloaded* one directly off the Arduino. It's current-peaks should be short enough to limit thermal damage to the Arduino pin driver. Just make short test runs and don't leave it see-sawing for any length of time.


message:
What is the difference between Arduino board and Genuino Board?

I've got an Arduino UNO REV3 SMD EDITION.

In the Arduino Editor, I've selected `Arduino/Genuino Uno`.

In a tutorial, I saw `Hardware required : Arduino or Genuino Board`

What is the difference between Arduino board and Genuino Board?

body:
The name Genuino grew out of the split between Massimo and Gianluca (aided in part by Microsoft of course, and a trademark wrangle that went wrong). Each side wanted to appear to be more "genuine" than the other. That lead to the "Genuino" name (a *genuine* Arduino), and a version number war with the IDE.

Both sides started making their own variants of boards, with some only available from the USA (Arduino) and others only outside the USA (Genuino).

Since they have patched up their differences now the two boards are one and the same. A Genuino Uno and an Arduino Uno are the exact same board. They always have been, there has just been arguments over the name.


message:
Do I need to power off the Arduino board before doing something?

Is it safe to build a circuit while the Arduino board is powered?

Should I power the board only when I have to upload the program?

body:
It can be dangerous, not only to the Arduino, but to whatever you are connecting, if you do so with the power applied.

Current can end up flowing where it shouldn't, and components can become damaged.

However if it's something as simple as an LED then it really doesn't matter.


body:
It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.

Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.

So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.

You switch on the board, when the building is done and you want to program it, or use the already present program.


message:
How to properly link an Arduino and its sensors

To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB ([example][1]).

**What is the recommended method to have a strong, clean link between the two ?**

  [1]: http://a.co/aeGIzCB

body:
You could solder those modules to a prototype shield.  If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

* Prototype shield:

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

* Right-angled headers:

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

  [1]: https://i.stack.imgur.com/YL7nR.jpg
  [2]: https://i.stack.imgur.com/117lf.jpg


message:
Reconstruct uint32_t from char array to RTC.set

I am currently experimenting with a Digistump ATTiny85. Since it has no Serial, I use the basic `DigiUSB` library for communication. The RTC library used is this one: https://github.com/JChristensen/DS3232RTC/. The DigiUSB library is from Digispark.

I attached a DS3232 via TWI to the Digistump, because I want to use this construct as a USB-Realtime-Clock.

Initially setting the time in the `setup` method works as follows

      RTC.set(1532341020);

But I am unable to transfer the time via the pseudo serial connection and set it remotely. What I've tried so far:

* Using `union` with `char` and `uint32_t`. Althougt the char representation is correct (tried DigiUSB.println()), the `uint32_t` representation of this union is not what I need.
* Tried to adapt to some shifting examples, but seriously got lost here. All examples where about 4 byte streams.
* `atoi` and some other functions with no success.

Here is my current sketch

    #include <DS3232RTC.h>
    #include <DigiUSB.h>

    //union ArrayToInteger {
    //  char array[10];
    //  uint32_t integer;
    //};

    unsigned char foo[10];
    uint32_t num;

    void setup() {
      RTC.begin();
      //RTC.set(1532341020);
      DigiUSB.begin();
    }

    void loop() {
      if (DigiUSB.available() >= 10) {
        for (int i=0; i<=10; i++) {
        foo[i] = DigiUSB.read();
      }
      RTC.set((uint32_t)foo);
      DigiUSB.delay(100);
      DigiUSB.refresh();
      //DigiUSB.println(_foo.array);
      DigiUSB.println(RTC.get());
    } else {
      DigiUSB.refresh();
      DigiUSB.println(RTC.get());
      DigiUSB.refresh();
      DigiUSB.delay(1000);
      }
    }

In the end I need the a `char _foo 0123456789` represented as/converted to `uint32_t num 0123456789`

Kinda stuck here. Can anyone point me in the right direction ore provide an example?

body:
There are several possible issues here:

* can you send the number, as a string, from the PC to the ATtiny?
* can you convert the string to an actual number?
* can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the
conversion. However that is easily handled with `atol()`. Here is a test
program I tried on my Uno:

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

    void setup() {
        char time_string[] = "1532341020";
        uint32_t time_number = atol(time_string);

        Serial.begin(9600);
        Serial.print("string: \"");
        Serial.print(time_string);
        Serial.print("\", number = ");
        Serial.println(time_number);
    }

The output is:

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

    string: "1532341020", number = 1532341020


body:
Answering this question based on the help from above. It works with this code. Thank you all for the help. The clock does not reply the newly set time instantly, but after a few seconds.

    #include <DS3232RTC.h>
    #include <DigiUSB.h>
    char foo[10];

    void setup() {
      RTC.begin();
      DigiUSB.begin();
    }

     void loop() {
       if (DigiUSB.available() >= 10) {
         for (int i=0; i<=10; i++) {
           foo[i] = DigiUSB.read();
       }
       RTC.set(atol(foo));
       DigiUSB.delay(100);
       DigiUSB.refresh();
       DigiUSB.println(RTC.get());
    } else {
       DigiUSB.refresh();
       DigiUSB.println(RTC.get());
       DigiUSB.refresh();
       DigiUSB.delay(1000);
       }
    }


message:
Rc car controller using the RC-switch library

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Kl5eP.png)

<!-- End schematic -->

(Newbie in arduino)
Hi so i have a project which involves creating an rc car which uses the 433Mhz rf module and an arduino nano with a servo motor and an ultrasonic parking sensor.

I'm having problems with the code both on the transmitter and receiver,
Here is the code for the transmitter.

     #include <RCSwitch.h>
    RCSwitch mySwitch = RCSwitch();
    // Assigning controller buttons to Digital Pins
     const int forward = 8;
     const int reverse = 9;
     const int rightTurn = 10;
     const int leftTurn = 11;

     int Fwd = 0
     int Bwd = 0
     int Lt  = 0
     int Rt  = 0

    void setup () {
      pinMode (forward, INPUT);
      pinMode (reverse, INPUT);
      pinMode (rightTurn, INPUT);
      pinMode (leftTurn, INPUT);
      mySwitch.enableTransmit(7);
      Serial.begin (9600);         // Debugging only
      Serial.println ("Transmitting");
    }

    void loop () {
      Fwd = digitalRead(forward);
      Bwd = digitalRead(reverse);
      Rt  = digitalRead(rightTurn);
      Lt  = digitalRead(leftTurn);

      if (Fwd == HIGH) {
        mySwitch.send('1');
        Serial.println ("Forward");
        delay(100);
      }

      if (Bwd == HIGH) {
        mySwitch.send('2');
        Serial.println ("Reverse");
        delay(100);
      }

      if (Rt == HIGH) {
        mySwitch.send('3');
        Serial.println ("Left Turn");
        delay(100);
      }

      if (Lt == HIGH) {
        mySwitch.send('4');
        Serial.println ("Right Turn");
        delay(100);
      }
    }

And here's the code for the receiver

    #include <RCSwitch.h>
    #include <Servo.h>

    const int IN1 = 3;
    const int IN2 = 4;
    const int trigPin = 5;
    const int echoPin = 6;
    int distance = 0;

    RCSwitch mySwitch = RCSwitch();
    Servo myservo;

    void setup () {
      mySwitch.enableReceive(2);
      myservo.attach(7);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin (9600);    // Debugging only
      Serial.println ("Receiver Ready");
    }

    void loop () {
     if (mySwitch.available()) {

        int value = mySwitch.getReceivedValue();

          if(value == '1') {
            forward ();
            Serial.println (" = forward");
          }

          if(value == '2'){
            backward ();
            Serial.println (" = backward");
          }

          if(value == '3') {
            left ();
            Serial.println (" = left");
          }

          if(value == '4') {
            right ();
            Serial.println (" = right");
          }
          Serial.print(" ");
        }

    }

    void forward () {
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }
    long duration;
    int value = mySwitch.getReceivedValue();
    void backward () {
      if ((distance > 10)&& (value == '2'))
      {
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, LOW);
      }
      else if ((distance < 10)&& (value == '2'))
      {
      digitalWrite (IN1, HIGH);
      digitalWrite (IN2, LOW);
      }
      delayMicroseconds(10);
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance= duration*0.034/2;
      // Prints the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance); //distance is the returned integer,
    }

    void right () {
      myservo.write(0);
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }

    void left () {
      myservo.write(90);
      digitalWrite (IN1, LOW);
      digitalWrite (IN2, HIGH);
    }

The problem is when i run the code the buttons start getting pressed even if I'm not pressing them and even when i disconnect them from the arduino. and also the receiver cant receive any data.
Please help

body:
As you wrote in your comment, you didn't use  pullup or pulldown resistors for connecting the buttons. In this case the pin is floating, whenever the corresponding button is not pressed. It will pick up random noise from the environment and change it's state randomly.

A pullup or pulldown resistor defines a specific value for the pin, if the button is not pressed (LOW or HIGH). The value of such is a resistor is not critical, as long, as it isn't a too big load. Pick some value in the kiloohms (for example 10kOhm).

But you don't need external resistors for this. The Atmega328, which is the heart of the Arduino Nano, already has buildin pullup resistors for each digital output pin. You can activate them by using

    pinMode(pin_number, INPUT_PULLUP);

In this case you will have to change the if-statements to check for `LOW` instead of `HIGH` and connect the button to ground instead of 5V, because with a pullup resistor in idle state the pin will be pulled up to 5V and the button can then pull it down to ground.


message:
For Arduino, is there a meaningful difference between carriage returns?

Serial.write(0x0d); // hex

  Serial.write(13);   // ASCII

  Serial.write('\r');  // char

Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)

body:
> Is one more efficient?

after compilation it is same for all notations. the function and the value are the same for all 3 notations.


body: There is no difference between all the lines of code in your question. All representations stand for one value, containing one byte. There is only one implementation of `Serial::write()`, which has a `uint8_t` as parameter. So all the different representations result in a `uint8_t` anyway.


body:
As mentioned before they are all the same. The thing you have to rememeber is that the compiler takes the human readable code you write and turns it into the instructions the processor can understand. If you want to explore ways the compiler does thing you can compile the program into the hex file and then compare. Or for even less detail, but much easier, look at the size of the file created when you compile in the IDE
using just the one line in question inside the setup function

    write(0x0d)  ----> 1334 bytes
    write(13)    ----> 1334 bytes
    write('\r')  ----> 1334 bytes

For this simple example we can assume that all three of these are producing the exact same hex file.   There are many more complicated example of different ways to do the same task that may produce more or less efficient code, but in this case the compiler is going to produce the same instruction set to the processor.

As pointed out in the comments, I am not saying that because they are the same size they must be the same hex code. As any single byte being written would produce the same size code, but not the same result. But when comparing two methods that we know are the same functionality ( 0x0d and '\r') and they produce the same size binary, then we can assume the compiler reduced them to the same code.


message:
Can't burn Bootloader on Atmega328P Using Arduino Uno

I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from [here][1].

I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.

However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.

I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.

By the way, I've used the following connections.

    Arduino Digital Pin 13 to SCLK
    Arduino Digital Pin 12 to MISO
    Arduino Digital Pin 11 to MOSI
    Arduino Digital Pin 10 to RESET
    Arduino 5V to VCC
    Arduino GND to GND

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.

When I press 'Burn Bootloader', I'm getting this error message.

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

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.

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

  [1]: https://www.arduino.cc/en/Main/Standalone
  [2]: https://i.stack.imgur.com/095Gh.png

body:
I have had this problem in the past and it has always been one of two solutions

 1. The wires __were__ misconfigured, and I only saw it after the Nth time
 2. Wrong chip, I was trying to program a 328 when it expected a 328p

And the secret third option:

 3. Some chip/wire/etc. was busted/burned/bad.

Unfortunately These were the only outcomes to ever come for me when I encountered that particular error.


body:
The design is missing 0.1uF caps on VCC, AVCC, and Aref.

Aref should not connect to 5V directly. It is connected internally thru a mux and only needs the 0.1uF to Gnd.  If Aref is direct connected and then the sketch selects the internal 1.1V reference, it can/will damage the chip.

Change the 220 ohm resistor on D13/SCK to 1K.  220 ohm puts quite a load on the SCK line for a Programmer. 1K will result in a plenty bright LED.

Do you have a 0.1uF between DTR of a Serial programmer and the Reset pin?  A Programmer needs direct control of the Reset line, a Serial programmer (such as an FTDI Basic module) needs to go thru a cap so a Reset pulse is created.


body:
[![Arduino on breadboard][1]][1]
here is a Link... https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

If bootloader is burned with arduino uno in atmega328 then code will be uploaded for once and run correctly but next time you tried to burn code in atmega328 then code will not burn in atmega328. I also tried this way but it just work one time for me then I bought usbasp(price 1.5$) to burn bootloader permanently. after burning bootloader with usbasp then its works perfect for me.
Just connect crystall with filtering capacitor thats enough to burn bootloader. above config is just in case you want to use it as MCU.

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