body:
I installed the Arduino IDE according to the arduino.cc instructions (invoking `install.sh`) rather than `sudo apt install ...`. The ports `/dev/ttyACM*` were present when the following Linux command is issued.

`ls -l /dev/ttyACM*`

This shows that the devices have membership in the `dialout` group. It is necessary to add myself as a user to the group `dialout`.

`sudo usermod -a -G dialout <username>`

I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.

I deleted the IDE and reinstalled and the ports disappeared.

I have applied this [fix for using the Arduino IDE on Linux][1].

From the description of the fix the instruction is to issue the following commands:

    wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

    sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

Next reboot Linux.

According to [this page on Arduino for Linux][2] there ought to be some devices at `/dev/ttyACM*` but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.

The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.

  [1]: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup
  [2]: https://www.arduino.cc/en/Guide/Linux/

title: missing /dev/ttyACM* on Ubuntu

Answers: 6

body:
> According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM*

That is not the case. On a "traditional" Arduino board, like the Uno, you have two chips: the main MCU which you program, and a USB interface chip, which is pre-programmed with code to present a CDC/ACM interface to the computer (which it then creates a /dev/ttyACMx device for).

With the feather you don't have that. You have one single chip. That chip is both the USB interface and the chip that you program - and most importantly, it is *your* program that provides the CDC/ACM device *if you choose*. If your program doesn't provide a CDC/ACM device then the computer will never see one, so it will never create /dev/ttyACMx.

In general the Arduino core always adds a CDC/ACM device whether or not you ask for it, since it is often used to initiate a reset into the bootloader. However if your sketch stops working for whatever reason then the CDC/ACM port is no longer there.

The M0 on the feather has a neat trick though - if you reset the board with the reset button *twice* the startup code recognises that fact and forces it to run the bootloader. That bootloader then presents the needed CDC/ACM device to the computer allowing you to upload new code.

Of course, if your program that you upload then doesn't initialise its own CDC/ACM device, or crashes, the CDC/ACM device will not be presented until you do the double-reset trick again.

body:
> /dev/ttyACM* mine are missing.

I think that something udev rules issue, you can define another rules with add `Feather32u4.rules` and remove `99-adafruit-boards.rules` file before.

    SUBSYSTEM=="usb", ATTRS{idProduct}=="0c9f", ATTRS{idVendor}=="1781", MODE="0660", GROUP="dialout"
    ATTRS{idVendor}=="239a", ENV{ID_MM_DEVICE_IGNORE}="0"
    ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
    SUBSYSTEM=="tty", ATTRS{idProduct}=="8011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
    SUBSYSTEM=="tty", ATTRS{idProduct}=="0011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"

after saved and copy your files to /etc/udev/rules.d/

    sudo cp Feather32u4.rules /etc/udev/rules.d/

and then restart your udev

    sudo reload udev

or,

    sudo udevadm control --reload-rules
    sudo udevadm trigger

don't forget to restart your service

    sudo systemctl restart ModemManager.service

check again your port with following ll `/dev/tty*`, if it appear with named `/dev/ttyUSBx` or `/dev/ttyACMx` add a user to your group

    sudo usermod -a -G plugdev <user>

also try to automatically reset button with add a delay into your sketch

    while(!Serial){
      delay(1000);
    }
    Serial.begin(115200);

if it not showed port on `/dev/tty` list, try

 - Enabled **verbose upload** in the Arduino Preferences.
 - Open the Blink example.
 - and add automatically reset above.

that will showed as the Bootloader COM/Serial Port with bootloading mode.

**If** didn't work, i advice install driver on [Adafruit_Driver Windows only][1] using Wine or PlayOnLinux, and remove udev files. also check again your `/dev/tty*` list.

Hope this helps.

  [1]: https://learn.adafruit.com/adafruit-feather-32u4-adalogger/using-with-arduino-ide#install-drivers-windows-only-6-7

body:
If the Arduino IDE does not show the port or does not allow you to select the port, load a known to be working program (such as Example > Blink), start a download, and then double-click the board's reset button.

For the same advice plus extraneous information view this [help page on the particular Feather, the 32u4 micro-controller board][1], which seems to suggest the use of a verbose download mode but that seems to be unnecessary because you can just try again if it failed. The verbose download mode is enabled in preferences. Even though it is unnecessary I eventually decided to always use the verbose download mode because it gives what appears, to me at least, more immediate and obvious feedback about success and failure.

  [1]: https://learn.adafruit.com/adafruit-feather-32u4-basic-proto/feather-help

body: So I tried EVERYTHING... turns out my USB cable was a cheaper cable that didn't have the data pins in it. It is worth making sure your cable supports data transfer by plugging it into something else to make sure it w

body: `ttyACM*` didn't show up on my /dev/ also, but as soon as I changed the USB port I was working with, the arduino board started blinking differently. So I checked the IDE again and under `Tools` > `port` > `Serial Port` I saw ttyACM0 came up. Didn't make sense to me but it worked.

body:
For my situation, where I'm using a custom Linux kernel, I was missing the **cdc_acm** driver.

This excellent page on the Gentoo Wiki helped me find it:
https://wiki.gentoo.org/wiki/Arduino


body:
I am using NodeMCU (ESP8266 12E) module from some days. I am trying to connect to Alexa for voice controlling. I have Amazon Alexa Echo 2 from which I am trying to discover my nodemcu as a smart home device.

Here is my sketch I am trying to use to detect.
<!-- language-all: lang-cpp -->

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <fauxmoESP.h>

    fauxmoESP fauxmo;

    const char* ssid = "myssid";
    const char* password = "mypassword";

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

      fauxmo.enable(true);

      fauxmo.addDevice("light one");
      fauxmo.addDevice("light two");

    // this is not able to detect .onSetState function I am not sure about the reason.

    //  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
    //        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
    //    });
    }

    void loop() {
        fauxmo.handle();

    }

    void wifisetup() {
      pinMode(2, OUTPUT);
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      IPAddress ip(192, 168, 1, 243); // this 3 lines for a fix IP-address
      IPAddress gateway(192, 168, 1, 1);
      IPAddress subnet(255, 255, 255, 0);
      IPAddress dns(192, 168, 1, 1);
      WiFi.config(ip, dns, gateway, subnet);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      while (WiFi.waitForConnectResult() != WL_CONNECTED) {
        Serial.println("Connection Failed! Rebooting...");
        delay(10000);
        digitalWrite(2, HIGH);
        ESP.restart();
      }
      if (WiFi.status() == WL_CONNECTED) {
        digitalWrite(2, LOW);
        Serial.println("");
        Serial.println("Your ESP is connected!");
        Serial.println("Your IP address is: ");
        Serial.println(WiFi.localIP());

        delay(100);
      }

    }

I am using https://bitbucket.org/xoseperez/fauxmoesp library to do the setup. Alexa is not able to detect my device. Not sure whats the issue with this, but in the Serial Monitor I can see the logs which is showing that I am getting ping from Alexa to my ESP8266.

Taking an output pin is compulsory? I have tried that too although but no output found.

Thank you!

title: Connecting to Alexa with FAUXMOESP library not detecting the device

Answers: 1

body:
If you are using fauxmoESP library version 3.0 and above your device will not be detected by alexa, i dont know why this is.
You may degrade fauxmoESp version to 2.4.0 so that your issue ie. .onSetState will be resolved.

Are you able to connect wifi?


body:
I am having trouble getting `SPI.transfer(buffer, size)` to work as expected.

Here is the code:

    // inslude the SPI library:
    #include <SPI.h>

    // set pin 10 as the slave select for the digital pot:
    const int slaveSelectPin = 10;

    uint16_t SPI_message = 0xABCD;

    void setup() {
      // set the slaveSelectPin as an output:
      pinMode(slaveSelectPin, OUTPUT);
      // initialize SPI:
      SPI.begin();

    }

    void loop() {

      SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
      SPI.transfer(0xEF);
      SPI.transfer(&SPI_message, 2);
      SPI.endTransaction();

      delayMicroseconds(300);

    }

Here is the output of logic analyzer:

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

As can be seen the call for `SPI.Transfer(0xEF)` works as expected. However `SPI.transfer(&SPI_message,2)` sends 0x0000 instead of 0xABCD on the bus.

**What am I doing wrong?**

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

title: SPI.transfer(buffer, size) does not send data from buffer

Answers: 1

body:
`SPI.transfer(&SPI_message,2)` is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; `SPI.transfer16(SPI_message)`.

To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.

There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].

Cheers!

Ref.

 1. https://www.arduino.cc/en/Reference/SPITransfer
 2. https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137


body:
I want to use the Arduino IDE serial monitor with my Digispark ATtiny85 over USB.

I can without problems upload this code(Digispark CDC example):

    #include <DigiCDC.h>
    void setup() {
      SerialUSB.begin();
    }
    void loop() {
      SerialUSB.println(F("TEST!"));
     //SerialUSB.delay(10);
    }

In a terminal, I can confirm, that it indeed creates a new devise:

    ll /dev/*usb*
    crw-rw-rw-  1 root  wheel   21,  89 27 Sep 10:36 /dev/cu.usbmodem1411
    crw-rw-rw-  1 root  wheel   21,  88 27 Sep 10:36 /dev/tty.usbmodem1411

When trying to start the Arduino serial monitor, I get the error:

     Error opening serial port '/dev/cu.usbmodem1411'. (Port busy)

I have confirmed that there are no open files or processes using the USB port. I have the same problem trying to use `cu` or `screen` in the terminal.

I have googled the problem, and found that several people has the same problem on new mac computers, but I have not been able to find a solution. -any ideas?

 - Digispark Rev3 (Chinese clone - with bootloader firmware 1.6 (1.06))
 - Arduino IDE 1.8.7
 - Mac OSX High Sierra 10.13.6

title: Serial communication mac to Digispark ATtiny85

Answers: 1

body:
SoftSerial and a real serial port on the mac will work. Or if you are careful use the DigiKeyboard and print the debug to the HID keyboard REMEMBERING to switch to a notepad equivalent window on the mac to receive and display the debugging text and not have it overwriting the arduino sketch by mistake.
DigiCDC is a kludge that does not work properly on modern operating systems sorry!


body:
I am using a SIM808 with a atmega2560.

I have setup the endpoint in Azure and that works when I try a http post via postman and/or an online http post tool (I get a 202 as result and see data comming into Azure)

I want to send a json package to an Azure http endpoint (smart app) using the function httpPOST in the [SIMCom library from itead][1].

  [1]: https://github.com/itead/ITEADLIB_Arduino_SIMCom

I am connecting to the network:

logging (I printed all that is written to GSM):

    AT+CIFSR
    DB:STARTING NEW CONNECTION
    AT+CIPSHUT
    DB:SHUTTED OK
    AT+CSTT="provider.net","","" DB:APN OK
    AT+CIICR
    DB:CONNECTION OK
    AT+CIFSR
    DB:ASSIGNED AN IP
    GPRS status=ATTACHED
    AT+CIPSTART="TCP","prod-13.westeurope.logic.azure.com",443
    DB:RECVD CMD
    DB:OK TCP

Then call the httpPost function from the library with the following variables:

    const char server[35] = "prod-13.westeurope.logic.azure.com";
    const int port = 443;
    const char path[200] = "/workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=/triggers/manual/run&sv=1.0&sig=someazuretoken";
    const char parameters[100] = "{\"device\":\"alive\",\"timestamp\":\"09270845\"}";

Part of the httpPost function from the library for sending the data

        int InetGSM::httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength)
             ....
        gsm.SimpleWrite("POST ");
        gsm.SimpleWrite(path);
        gsm.SimpleWrite(" HTTP/1.1\r\nHost: ");
        gsm.SimpleWrite(server);
        gsm.SimpleWrite("\r\n");
        gsm.SimpleWrite("User-Agent: Arduino\r\n");
        gsm.SimpleWrite("Content-Type: application/json\r\n");
        gsm.SimpleWrite("Content-Length: ");
        itoa(strlen(parameters),itoaBuffer,10);
        gsm.SimpleWrite(itoaBuffer);
        gsm.SimpleWrite("\r\n\r\n");
        gsm.SimpleWrite(parameters);
        gsm.SimpleWrite("\r\n\r\n");
        gsm.SimpleWrite(end_c);
    ....

Which gives this output on the serial monitor (I printed all that is written to GSM):

    AT+CIPSEND
    DB:>
    POST /workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=/triggers/manual/run&sv=1.0&sig=someazuretoken HTTP/1.1
    Host: prod-13.westeurope.logic.azure.com
    User-Agent: Arduino
    Content-Type: application/json
    Content-Length: 55

    {"device":"alive","timestamp":"09270845"}

    DB:SENT

And then it is waiting for a response:

    Starting read..
    Waiting for Data............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
    CLOSED

    Done..
    response:
    10

    CLOSED

which times out I guess.

And I see nothing coming into Azure.

(I am getting data when I try a httpGet on a random site. So hardware, sim and network is working ok I guess)

Any ideas?
thx!

title: HTTP post via GPRS (SIM808) to Azure http endpoint logic app is failing

Answers: 1

body:
Juraj's comments put me on the right track, for SSL you need to do more then just select the port.

I did some searching and got it to work using a different GSM library that also supports SSL:
[tinyGSM][1]

in combination with [ArduinoHttpClient][2]

  [1]: https://github.com/vshymanskyy/TinyGSM
  [2]: https://github.com/arduino-libraries/ArduinoHttpClient

Jeroen

EDIT: It works, but there is a big downside. It looks like there is major overhead, each message seems to uses 13Kb of data...? I suspect this comes from the data that is returned by the endpoint.
This is way too much over GPRS so now looking into MQTT.


body:
I had an Arduino mega 2560, suddenly Arduino didn't recognize my computer and I thought the problem is about Atmega 16u2 and I decided to copy hex file from another Arduino Atmega 16u2 and paste to damaged Arduino but it didn't work.
in fact, in our laboratory, we don't have any Linux and other software to reset or reprogram Atmega 16u2 on the other hand I know several methods to solve the problem but I need to know can I use the Arduino IDE to reset Atmega 16u2 without other software.
thanks a lot.

title: Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE?

Answers: 1

body: Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder `hardware/arduino/avr/firmwares/atmegaxxu2/` of the IDE installation folder is the hex file of the firmware `Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex`. The README.txt file in that folder has sample command line to upload the firmware with avrdude.


body:
I am using a led strip **WS2812b**, an **ESP8266 (NodeMCU 1.0)** and a gesture sensor **APDS9960**.
I want that when I move my hand from *left to right* and from *right to left* I change the colors of the strip of leds, previously saved in an array of strings:

    const char * colors [11] = {"CRGB :: White",
    "CRGB :: WhiteSmoke",
    "CRGB :: CadetBlue",
    "CRGB :: SteelBlue",
    "CRGB :: Teal",
    "CRGB :: SlateGray" ,
    "CRGB :: MediumPurple",
    "CRGB :: Purple",
    "CRGB :: PapayaWhip",
    "CRGB :: LightPink",
    "CRGB :: Crimson"};

But when I'm going to turn on the colors using the functions of the **[FastLed][1]** library in this way:

    for (int i = 0; i <NUM_LEDS; i = i + 1) {
           leds [i] = colors [2];
           FastLED.show ();
           delay (10);}

All I get is this error:

> invalid conversion from 'const char *' to 'uint32_t {aka unsigned
> int}' [-fpermissive]

I guess the problem is **me** when declaring the *array*, could someone help me?

  [1]: https://github.com/FastLED/FastLED

title: How to deal with this array correctly?

Answers: 1

body:
You don't want an array of strings containing the (badly formatted) names of variables. Instead you want an array of 32-bit integers containing the values held within those variables.

    const uint32_t colors[] = {
        CRGB::White,
        CRGB::WhiteSmoke,
        CRGB::CadetBlue,
        CRGB::SteelBlue,
        CRGB::Teal,
        CRGB::SlateGray,
        CRGB::MediumPurple,
        CRGB::Purple,
        CRGB::PapayaWhip,
        CRGB::LightPink,
        CRGB::Crimson
    };

Since colours are just numbers, in the (hexadecimal) form of `0xRRGGBB` you just store them as 32-bit unsigned integers.  The names you have there are just such (constant) variables used for easy reference (`CRGB::White` is `0xFFFFFF`).


body:
I'm trying to write a library encapsulating things that I do with a DS3231 real time clock. I have managed to compile a sketch using the library, but it apparently blows up when attempting to call clock methods such as `getTime()`.

Header:

    // JBP_DS3231.h
    #ifndef __JBP_DS3231_h__
    #define __JBP_DS3231_h__

    #include <SD.h>
    #include "DS3231.h"
    #include "Arduino.h"

    class JBP_DS3231
    {
      public:
        JBP_DS3231();
        String TimeStamp();
      private:
        DS3231* _realTimeClock;
    };

    #endif

cpp:

    #include <JBP_DS3231.h>
    #include <SD.h>
    #include "DS3231.h"
    #include "Arduino.h"

    JBP_DS3231::JBP_DS3231() {
      String thisTime = "";

      _realTimeClock = &DS3231(SDA, SCL);

      Serial.println("About to try to get time from RTC."); // Last line we hear from.

      thisTime = _realTimeClock->getTimeStr();
      Serial.print("Time in constructor is: ");
      Serial.println(thisTime);
    }

    String JBP_DS3231::TimeStamp() {
      String timeStamp = "";

      Serial.println("In TimeStamp().");
      timeStamp = _realTimeClock->getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
      Serial.print("Value of timestamp is: ");
      Serial.println(timeStamp);
      timeStamp.concat(" ");
      timeStamp.concat(_realTimeClock->getTimeStr());
      Serial.println(timeStamp);

      return timeStamp;
    }

Script:

    const String WHO_AM_I = "JBP_DS3231_library_test.ino";
    const    int VERSION = 0;

    #include <JBP_DS3231.h>

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

      JBP_DS3231 johnsRTC;
      Serial.println(johnsRTC.TimeStamp());
    }

    void loop() {
      return;
    }

    void AnnounceAwakening() {
      Serial.print("Sketch ");
      Serial.print(WHO_AM_I);
      Serial.print(" version ");
      Serial.print(VERSION);
      Serial.println(".");
      Serial.println("");
    }

title: Trying to instantiate a DS3231 real-time clock within a library

Answers: 1

body:
You appear to be providing a pointer to a constructor, not to an object.  Either create a *new* object with `new`, or instantiate the object separately and provide the pointer to the object:

    _realTimeClock = new DS3231(SDA, SCL);

Better still, extend the existing class and implement your own methods:

    clsss JBP_DS3231 : public DS3231 {
        public:
            JBP_DS3231(uint8_t d, uint8_t c) : DS3231(d, c) {
                String thisTime = "";
                Serial.println("About to try to get time from RTC."); // Last line we hear from.

                thisTime = getTimeStr();
                Serial.print("Time in constructor is: ");
                Serial.println(thisTime);
            }

            String TimeStamp() {
                String timeStamp = "";

                Serial.println("In TimeStamp().");
                timeStamp = getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
                Serial.print("Value of timestamp is: ");
                Serial.println(timeStamp);
                timeStamp.concat(" ");
                timeStamp.concat(getTimeStr());
                Serial.println(timeStamp);

                return timeStamp;
            }
    };

    void setup() {
        Serial.begin(115200);
        JBP_DS3231 myRTC(SDA, SCL);
        Serial.println(johnsRTC.TimeStamp());
    }

    void loop() {
    }

(Note: untested)


body:
I'm trying to control AD7091-8 using Arduino Due.

This IC calls for 16 bit SPI R/W. I'd read that I can change the transmit and receive bits of Arduino DUE by changing a register (bits 4-7 of SPI_CSR).

I was able to change the SPI of Due from 8 to 16 bits. Confirmed this by looking at SCLK and MOSI in the scope. However, the data I want to transfer is becoming intermittent.

I want to send 0x1000. On 8 bits, using the line

    SPI.transfer(10,0x10,SPI_LAST);

I really can see this being sent on MOSI.

However, when I'm on 16 bits, the line

    SPI.transfer(10,0x1000,SPI_LAST);

It's either becoming 0x0000 or 0x0008. I'm losing the bit or it's becoming LSB_FIRST. Not MSB_FIRST.

Below is the actual code.

    #include <SPI.h>
    #include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component\component_spi.h"
    #include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_spi0.h"

    #define CS 10

    void setup() {

      pinMode(CONV,OUTPUT);

      Serial.begin(9600);
      SPI.begin(CS);
      SPI.setDataMode(CS, SPI_MODE0);
      SPI.setClockDivider(CS,21);

      REG_SPI0_WPMR=0x53504900;
      REG_SPI0_CR=0x1;
      SPI0->SPI_CSR[0]=0x00001580;

      SPI.setBitOrder(MSBFIRST);
      delay(1);
    }

    void loop() {

      SPI.transfer(CS,0x1000,SPI_LAST);

      int a = SPI.transfer(CS,0x0000, SPI_LAST);
      delay(1000);

      Serial.println(a);
    }

How can I make my data reliable and the order still with MSB first?

title: 16 bit SPI on Arduino Due

Answers: 1

body:
Found the problem on the SPI library.

When I do the command SPI.transfer, the data is stored on a byte type variable. And I'm passing a 16 bit data on it.

I've changed line 84 of SPI.h to

    uint16_t transfer(byte _pin, uint16_t _data, SPITransferMode _mode = SPI_LAST);

so it will return and receive 16 bit data.

Also have to change the corresponding function on SPI.cpp (line 174)

    uint16_t SPIClass::transfer(byte _pin, uint16_t _data, SPITransferMode _mode)

so they will match.

I've copied and renamed the SPI library that I've changed so it won't affect other codes.


body:
i've made a project consisting of 3 DC motor pumps, Atmega328p on custom PCB, and a relay. I found a problem which causes my PCB custom arduino trips over and over again caused by 12V DC MOTOR. I fix it already by putting a flyback diode on motor. it runs much better but still have a small number of trips on my arduino.

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

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

probably i've a bad PCB design and lack of components.

is there a way to prevent these electromagnetic interference caused by motor?
or some improvements on my PCB board?

title: Preventing EMI on PCB

Answers: 3

body: Had a problem like this. I ended up using a separate power supply for my DC motor. Don't forget to connect the GND's.

body:
There are few things you can try. First thing that comes to mind is hooking up the power source to an oscilloscope and see if there is not a big voltage dip when motor starts running/runs. This could happen if the motor attempts to draw more current than the power source can deliver, hence the voltage of source would drastically drop and Arduino would restart.

Second thing, assuming this is EMI, which I doubt - You need a proper ground plane, not just a thin trace. That would definitely help. Third thing would be reducing loop areas, by which I mean putting power and GND lines close to each other, look at http://www.ti.com/lit/an/szza009/szza009.pdf. This is a very resourceful document.

Third thing is - put a decoupling capacitor as close to the Arduino as possible. This will even out any spikes you may get, or any unexpected instability.

Hope this helps

body:
The most critical failing of your PCB is the fact that you have no decoupling capacitors near your MCU power pins. These are absolutely required, and are not optional.

To modify your existing PCB, so you don't have to roll a new one, just solder a 0.1µF 0805 SMD capacitor between each VCC and GND pair of pins on the underside of the board.

You should also reduce both the ground impedance and the power supply impedance by replacing your ground traces with a ground pour, and fatten your power traces up a little.


body:
I have a Futaba S148 servo (https://servodatabase.com/servo/futaba/s148)
connected to an Arduino Uno.

As soon as the script attaches the servo, it rotates to its limit and gets stuck.

I've tried several scripts, and narrowed to the simplest:

    #include <Servo.h>  // servo library
 Servo servo1;  // servo control object
 void setup()
 {
   //  Attach the servo1 object to digital pin 4.
   servo1.attach(10);
 }
 void loop()
 {
 }

Also connected the servo to the board with this:

 #include <Servo.h>  // servo library
 Servo servo1;  // servo control object
 void setup()
 {
   //  Attach the servo1 object to digital pin 4.
   //servo1.attach(10); <--- notice this commented out
 }
 void loop()
 {
 }
and then the servo remains still.

I'm using a battery pack of 4.8 V which works fine with the servo and the RC radio, so the battery and the servo, works fine together with remote control.

I have another different [SG90 servo][1] running with its own power source and connected to the pin 9, and with a different sketch, it works perfectly.

  [1]: https://servodatabase.com/servo/towerpro/sg90

title: Servo going up to the limit as soon as attached

Answers: 1

body: https://www.arduino.cc/en/Reference/ServoAttach - This should answer it. The library you are using supports only 2 specific pins


body:
I'm wanting to analogRead the value off a MQ-135 gas sensor. I have tired this with both an Arduino Uno and an [TTGO ESP32 SX1276][1].

When reading the value of the sensor off the Uno, I get values approximately equal to 400 which is expected, as shown in this [video][2]. When doing the same on the TTGO, I get values close to 2000. For some reason, this person gets a similar value range as shown in this [video][3].

What I don't understand is how these values are different when only the board is being changed. Do different boards analogRead differently?

More or less, how do I get the TTGO to read the same values as the Uno?

Below is my code for both boards. Nothing is changed between the boards:

    #define sensor 2 //sensor pin

    int gasLevel = 0; //int variable for gas level

    void setup() {
      Serial.begin(9600); //start serial comms
      pinMode(sensor,INPUT); //set sensor for input
    }

    void loop() {
      gasLevel = analogRead(sensor);
      Serial.println(gasLevel);
      delay(1000);
    }

The following things I have tested:

 - Multiple boards of both the Arduino Uno and TTGO
 - Different pins, both analog and digital

I also am powering the sensor using 3.3V pin, so there is no variation in the voltage the sensor is receiving.

  [1]: https://primalcortex.wordpress.com/2017/11/24/the-esp32-oled-lora-ttgo-lora32-board-and-connecting-it-to-ttn/ "TTGO ESP32 SX1276"
  [2]: https://youtu.be/V1uOHOcVZrE?t=6m21s
  [3]: https://youtu.be/3tXRNusJhgs

title: Differing Serial Values Between Arduino Uno and TTGO ESP32 SX1276

Answers: 1

body:
> Do different boards analogRead differently?

Yes.

Your typical Arduino has a 10-bit ADC. That can give values between 0 and 1023 (210-1), with 400 falling just short of half way.

The ESP32 has a 12-bit ADC. That gives values between 0 and 4095 (212-1), which means that your 2000 falls, yes, just short of half way.

It is not the value from the ADC that is important - it is *what the value represents*. It is meaningless until you convert it into something meaningful, like a voltage.

Like asking "How heavy is it?" -- "It's 23." Completely meaningless, until you qualify it with units, and the units are different because of the different resolutions, so you need to "convert" it into units that have a meaning.

Typically the value represents a proportion of the supply voltage (but not necessarily: it's actually a proportion of the ADC reference voltage, which is often the same thing as the supply voltage).  On the Arduino the value is 1/1024th of the supply voltage. On the ESP32 it's 1/4096th.


body:
I was creating a scoring formula for a game.

The formula in question is

    millis() * 1.1 ^ (millis()/10000);

However, I'm having trouble understanding the different error messages that the Arduino IDE is projecting to me

> invalid operands of type to binary operator

I have declared the score as an `unsigned long`.

title: Formula creation

Answers: 1

body:
I would avoid calling `millis()` twice within the same expression. Not
really a big deal in your case, but the two calls can very well return
different values, which would make your formula slightly inconsistent.
Then, using the proper syntax for the power function, as explained by
Kwasmich:

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

    uint32_t t = millis();
    float score = t * pow(1.1, t/1e4);

Note that `1e4` is the scientific notation for `10000.0`. I personally
find the former more readable, as you don't have to count the zeros.

Now, it is worth noting that the `pow()` function is very expensive to
compute on this kind of 8-bit FPU-less processor. It involves both a
logarithm and an exponential. The second line is essentially equivalent
to

    float score = t * exp(t/1e4 * log(1.1));

The floating point division is also quite expensive. You could save
something like half the processing cycles by pre-computing
`log(1.1)/1e4` and using the result in your expression:

    float score = t * exp(t * 9.53e-6);


body:
I wish to obtain unix epoch timestamps in millisecond precision. I am using an ESP32 along with __DS3231__ RTC breakout board from adafruit.

Apparently the Repository is not maintained often but I see a [PR](https://github.com/adafruit/RTClib/pull/92) which overcomes the rollover for software timer and the developer provided a patch in the comment to use the unix timestamps in ms.

I went to the `libraries` folder where all the downloaded adafruit repos exist. But when I did  `git status` it mentions that the library download (from the library manager) is not a git repository.

I wan't to inculcate the changes to the `RTClib` library by using the patch provided. Should I just change the code directly via the Arduino IDE editor?

title: Apply patch to library for custom changes in Arduino IDE

Answers: 1

body:
Save the patch to a file, put it in the directory holding the library,
open a terminal on that directory and type:

    patch -p1 < patchfile

You may have to install the "patch" utility if you don't have it yet. On
a Debian-like OS (I don't know for other OSes):

    sudo apt install patch


body:
I want to pair a bluetooth keyboard to an arduino project, so that pressing a key on the keyboard causes an action to happen on the Arduino. Let's say that pressing Q on the keyboard makes an LED turn on, and pressing W makes it turn off.

I know that I need some sort of bluetooth module connected to the Arduino, and I need to pair the keyboard to the module. I also know that it must be a module that can act in Master mode and use the HID protocol. But I cannot find a module that does what I want. For example, the HC05 module cannot do HID.

Has anyone done this? Can you tell me which module you used please? I don't want to involve anything else, just an Arduino, a module, and a bluetooth keyboard.

title: Is there a module that will allow me to pair a bluetooth keyboard to an arduino?

Answers: 0


body:
 I want is to stop the loop and when it read  Greater than 900.00 again it will do task again.

I need condition. When it back to greater than 900.00 the code below will do task and then it will stop. And when it will reach the condition again it will do the code again and it will stop .. Please help me

    void loop(){
      float reading = analogRead(LIGHTSENSORPIN); //Read light level
      float square_ratio = reading / 1023.0;      //Get percent of maximum value (1023)
      square_ratio = pow(square_ratio, 2.0);      //Square to make response more obvious

      analogWrite(LEDPIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
      analogWrite(LED_BUILTIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
      Serial.println(reading);                    //Display reading in serial monitor

    if(reading >= 900.00){

      digitalWrite(smDirectionPin, LOW); //Writes the direction to the EasyDriver DIR pin. (LOW is counter clockwise).
        /*Turns the motor fast 1600 steps*/
          for (int i = 0; i < 400; i++){
        digitalWrite(smStepPin, HIGH);
        delayMicroseconds(700);
        digitalWrite(smStepPin, LOW);
        delayMicroseconds(700);
    }
    }

      delay(1000);

    }

title: Arduino - My problem is when the condition is greater than 900.00 it will continue the loop and do the code below once

Answers: 1

body:
    setup(){ ....
    ......
    }
    float old_reading=0;
    loop() {
    float reading = analogRead(LIGHTSENSORPIN); //Read light level
    // ... do this always (maybe empty)
    // in your code it is LED shining and printing
    if ((old_reading<=900) && (reading>900)) {
       // ... do this just just once when reading goes over 900 up
       // in your code it is manipulating motor
       }
    old_reading=reading;
    // ... do this always , but after special part (maybe empty)
    // in your code it is just delay
    }

- So on begining `old_reading` is just zero, but being declared outside `loop`, it keeps its value between different runs of `loop`.
- the `if (condition)` does not hit, as `reading` is less than 900 (if it starts with more then 900, see next part)
- the end with `old_reading=reading;` makes `old_reading` to be the last known value of `reading`
- when `reading` goes Greater than 900 for first time, the `old_reading` is Less or Equal 900 (as it was the last value of `reading` before it crossed 900 up.
- - so the `if (condiotion)` is true and you start moving motor
- - then (on the end) you set `old_reading=reading;` and `old_reading` is also larger then 900
- - while `reading` stays over 900 in next loops, the `old_reading` does so, and therefore the `if (condition)` does not hit - `(old_reading<=900)` is not true
- - when `reading` falls down 900 or lower, the `if(condition)` also does not hit, but after that the `old_reading=reading;` makes `old_reading` less or equal 900
- and so we are at the start again, skipping the part after `if(condition)` until `reading` gets Greater than 900 (then we run motor, set `old_reading` to something greater than 900 and we already was here and know, how it works :)


body:
[![enter image description here][1]][1]I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)

How this is possible..?

  [1]: https://i.stack.imgur.com/LJAgY.gif

title: 8relay module asks more than specs

Answers: 2

body:
Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.

Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.

The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.

body: it is solved by giving the relay module power with external transfo. Not by arduino


body:
It's my custom debounce code

It keeps the led on by flipping the required threshold value when triggered after the led has turned on to keep the led in a high state and vice verse triggered again, the comments on the code explain it in more detail.

    /*
     * This code is my custom debounce code, I made this but this isn't working as planned,
     * see the thing is that it turns on when I hold the button and if I release it,
     * it starts to flickers and then gradually turn off, what is wrong with my code ?
     * I can't see it.
     */

    const int ledPin = 13; // led connected to pin 13
    const int PushButton = 2; // a pushbutton connected to pin 2
    int switcher = HIGH; // the switcher changes it's value, we require this later
    int dilay = 1; // controls the delay
    unsigned long lastTrigger = 0; // records the last time the led was turned on

    void setup() {
      pinMode(ledPin, OUTPUT); // sets ledpin as output
      pinMode(PushButton, INPUT); // sets pushbutton pin as input
    }

    void loop() {
      int pushButtonState = digitalRead(PushButton); // stores the value of the pin each time the loop begins agian

      if((millis() - lastTrigger) >= dilay){ // my custom debounce code
        if(pushButtonState == switcher){ //  this is the trick, when the pushbutton pin is high it's equal to the switcher value
          digitalWrite(ledPin, HIGH); // it turns on the led
          int switcher = LOW; // now the switcher value will be low now the pushbutton pin value will also be low keeping the led on
        }else{
          digitalWrite(ledPin, LOW); // now if the led is on and pushbutton is high, then it will not be equal to the switcher because we had changed it in the previous statement
          int switcher = HIGH; // now the switcher is high and the pushbutton value low, switcher isn't equal to pushbutton so there by keeping the ledpin as low

        }

        if(pushButtonState == 1){ // if pushbutton is high
          int lastTrigger = millis(); // then  lastTrigger equals to the current time
        }
      }

    }

title: Custom Debounce Code Not Working

Answers: 1

body:
Change `int switcher = LOW/HIGH` to just `switcher = LOW/HIGH`.

Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).


body:
I'm currently working on a **Arduino** project that plays **audio** files from **SD card** through a **speaker**.

First Arduino sends the list of all music files, and when I send it a file name, the music is played.

The project is working well but there's no **GUI**. Everything has to be done via **serial**, and now I want to add a **TFT** screen that will list the music files on the screen, so that whenever I **touch** a file name  it should be played.

I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.

**If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.**

Any help would be appreciated.

title: listing sd card files on a tft screen

Answers: 1

body:
> If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.

A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.

If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.

The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.


body:
I'm working on a IOT project where three or more IOT device communicates with a web server. The IoT device will have **Arduino UNO** which is connected to a **ESP8266** so internet access is available. Arduino UNO reads **current sensor** data and post it to a website that I built and I also want to control a **single relay switch** from the same website. I am a beginner and most project I find is only single directional communication or making ESP8266 as web server. Please point me to right Direction.

I was able to post sensor data to thingspeak.com. I was also able to control The relay switch from a website but only separately. I was not able to make it work when I combined the two.

Directions:

 1. How to build **web APIS** to send and receive data to **Arduino UNO via esp8266**?
 2. How to send data and check the received data in **Arduino UNO VIA esp8266**?
 3. Can I send and receive data in JSON format **Arduino UNO**?
 4. How can the **Arduino UNO** filter required data from the received json?
 5. Is this project possible without Arduino and just by programming the ESP8266 module?

I know basic HTML, Basic CSS, Basic JavaScript, Basic Nodejs, json and a tiny bit of JQuery.

title: How to establish a connection between an Arduino and a web server via ESP8266

Answers: 1

body:
> Is this project possible without Arduino and just by programming the
> ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

> How to build web APIS to send and receive data to Arduino UNO via
> esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.

For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

> How to send data and check the received data in Arduino UNO VIA
> esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with [Arduino esp8266 core package][1] and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

> Can I send and receive data in JSON format Arduino UNO?
> How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.

  [1]: https://github.com/esp8266/Arduino/blob/master/README.md#installing-with-boards-manager
  [2]: https://github.com/jandrassy/Regulator


body:
I have a weird problem  , as I.m trying to connect to esp8266 01 with Arduino Uno when i try sending commands from the serial it doesn't work but if i send it in a function in the setup phase it works

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

    void setup()
    {
    Serial.begin(9600);
    esp8266.begin(9600);
    delay(1000);
    //sendData("AT", 1000);
    //sendData("AT+CWMODE=1", 1000);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    if(esp8266.available()) // check if the esp is sending a message
      {
          while(esp8266.available())
          {
              // The esp has data so display its output to the serial window
              char c = esp8266.read(); // read the next character.
              Serial.write(c);
          }
      }
      if(Serial.available())
      {
        delay(1000);
        String command="";
        while(Serial.available()) // read the command character by character
        {
            command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
      }
    }

    void sendData(String command, const int timeout) {
     String response = "";
     esp8266.println(command);
     long int time = millis();
     while ((time + timeout) > millis())
       while (esp8266.available()) {
         char c  = esp8266.read();
         response += c;
        }
     Serial.println(response);
    }

title: ESP8266 01 wifi module

Answers: 1

body:
I take your code as a test sketch and will not comment on the terrible way you read Serial input.

The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use `print` to send the command to esp8266.

Or set in Serial Monitor "No line ending" and let in sketch the `println` to send the command. `println` adds \r\n to printed string.

If you had only "New line" set in Serial Monitor and used `println` the resulting command was for AT firmware disturbing "AT\n\r\n".


body:
Hey all I am having some issues with the SPIFFS for this Wemos D1 mini ESP8266 controller.

This is my Arduino sketch:

    #include <FS.h>
    #include <ArduinoJson.h>

    struct RGBLA {
      uint8_t R;
      uint8_t G;
      uint8_t B;
      uint8_t L;
      uint8_t A;
    };

    void setup() {
      if (!SPIFFS.begin()) {
        Serial.println("error while mounting filesystem!");
      } else {
        // put your setup code here, to run once:
        RGBLA returnedVars = readSPIFFS();

        Serial.begin(115200);
        Serial.println();
        Serial.println("Starting...");

        Serial.println("readSPIFFS 1");
        Serial.print("R: ");
        Serial.println(returnedVars.R);
        Serial.print("G: ");
        Serial.println(returnedVars.G);
        Serial.print("B: ");
        Serial.println(returnedVars.B);
        Serial.print("L: ");
        Serial.println(returnedVars.L);
        Serial.print("AmbientLight: ");
        Serial.println(returnedVars.A);

        Serial.println("==================================");

        returnedVars = saveToSPIFFS(25,77, 107, 250, 155, false);
        Serial.println("saveToSPIFFS #1");
        Serial.print("R: ");
        Serial.println(returnedVars.R);
        Serial.print("G: ");
        Serial.println(returnedVars.G);
        Serial.print("B: ");
        Serial.println(returnedVars.B);
        Serial.print("L: ");
        Serial.println(returnedVars.L);
        Serial.print("AmbientLight: ");
        Serial.println(returnedVars.A);

        Serial.println("==================================");

        returnedVars = saveToSPIFFS(205,17, 68, 50, 15, true);
        Serial.println("saveToSPIFFS #2");
        Serial.print("R: ");
        Serial.println(returnedVars.R);
        Serial.print("G: ");
        Serial.println(returnedVars.G);
        Serial.print("B: ");
        Serial.println(returnedVars.B);
        Serial.print("L: ");
        Serial.println(returnedVars.L);
        Serial.print("AmbientLight: ");
        Serial.println(returnedVars.A);

        returnedVars = readSPIFFS();
        Serial.println("readSPIFFS 2");
        Serial.print("R: ");
        Serial.println(returnedVars.R);
        Serial.print("G: ");
        Serial.println(returnedVars.G);
        Serial.print("B: ");
        Serial.println(returnedVars.B);
        Serial.print("L: ");
        Serial.println(returnedVars.L);
        Serial.print("AmbientLight: ");
        Serial.println(returnedVars.A);

        Serial.println();
        Serial.println("END!");
      }
    }

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

    RGBLA saveToSPIFFS(uint8_t R, uint8_t G, uint8_t B, uint8_t L, uint8_t A, bool saveA) {
      File configFile = SPIFFS.open("/config.json", "w+");

      if (configFile.size() > 3072) {
        Serial.println("Config file size is too large.");
      } else {
        Serial.print("Writing json to Config file...");

        StaticJsonBuffer<200> jsonBuffer;
        JsonObject& json = jsonBuffer.createObject();

        //Get the old value and save it
        RGBLA returnedVars = readSPIFFS();

        Serial.println("Old Values?");
        Serial.print("R: ");
        Serial.println(returnedVars.R);
        Serial.print("G: ");
        Serial.println(returnedVars.G);
        Serial.print("B: ");
        Serial.println(returnedVars.B);
        Serial.print("L: ");
        Serial.println(returnedVars.L);
        Serial.print("AmbientLight: ");
        Serial.println(returnedVars.A);

        if (saveA) {
          //Save Ambient Light data
          json["R"] = returnedVars.R;
          json["G"] = returnedVars.G;
          json["B"] = returnedVars.B;
          json["L"] = returnedVars.L;
          json["A"] = A;

          //Now save the new data
          returnedVars.A = A;
        } else {
          //Save RGBL data
          json["R"] = R;
          json["G"] = G;
          json["B"] = B;
          json["L"] = L;
          json["A"] = returnedVars.A;

          //Now save the new data
          returnedVars.R = R;
          returnedVars.G = G;
          returnedVars.B = B;
          returnedVars.L = L;
        }

        json.printTo(configFile);
        configFile.close();

        //Read new saved values into struct
        //returnedVars = readSPIFFS();
        return returnedVars;
      }
    }

    RGBLA readSPIFFS() {
      bool exist = SPIFFS.exists("/config.json");

      if (exist) {
        Serial.println("YAY!");
      } else {
        Serial.println("Boo!");
      }

      File configFile = SPIFFS.open("/config.json", "r");
      std::unique_ptr<char[]> buf(new char[configFile.size()]);
      configFile.readBytes(buf.get(), configFile.size());
      DynamicJsonBuffer jsonBuffer;
      JsonObject& json = jsonBuffer.parseObject(buf.get());
      RGBLA returnedVars;

      String debugLogData;
      json.printTo(debugLogData);

      Serial.println("===============");
      Serial.println(debugLogData);
      Serial.println("===============");
      returnedVars.R = json["R"];
      returnedVars.G = json["G"];
      returnedVars.B = json["B"];
      returnedVars.L = json["L"];
      returnedVars.A = json["A"];

      configFile.close();

      return returnedVars;
    }

And this is the console output:

    Starting...
    readSPIFFS 1
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25
    ==================================
    Writing json to Config file...YAY!
    ===============
    {}
    ===============
    Old Values?
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 0
    saveToSPIFFS #1
    R: 25
    G: 77
    B: 107
    L: 250
    AmbientLight: 0
    ==================================
    Writing json to Config file...YAY!
    ===============
    {}
    ===============
    Old Values?
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 0
    saveToSPIFFS #2
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25
    YAY!
    ===============
    {"R":0,"G":0,"B":0,"L":0,"A":25}
    ===============
    readSPIFFS 2
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25

    END!

As you can see, the first **old values** has all **0's** which is incorrect. **AmbientLight** should be **25** at that point since **readSPIFFS 1** has **25**. So this should read:

    Old Values?
    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25

**saveToSPIFFS #1** is sending values **25, 77, 107, 250, 155 and false** which then outputs correctly as:

    R: 25
    G: 77
    B: 107
    L: 250
    AmbientLight: 0

But this time **AmbientLight** should still be **25** since it was sent **false**. It should have taken the **old value (25)** and placed it into the newer save.

    R: 25
    G: 77
    B: 107
    L: 250
    AmbientLight: 25

Moving on to **saveToSPIFFS #2** the values again are incorrect. The **AmbientLight** however is correct here. Instead of this output:

    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25

it should be gathering the **4** previous **old values**:

    R: 25
    G: 77
    B: 107
    L: 250
    AmbientLight: 25

The json after this should not be this:

    {"R":0,"G":0,"B":0,"L":0,"A":25}

It should be this:

    {"R":250,"G":77,"B":107,"L":250,"A":25}

And lastly, the output of **readSPIFFS 2**:

    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25

Is incorrect. It should output:

    R: 25
    G: 77
    B: 107
    L: 250
    AmbientLight: 25

Then after a **reset** it should have that and not the below for **readSPIFFS 1**:

    R: 0
    G: 0
    B: 0
    L: 0
    AmbientLight: 25

So, where am I messing up here?

**UPDATE**

    struct RGBLA {
      uint8_t R;
      uint8_t G;
      uint8_t B;
      uint8_t L;
      uint8_t A;
    };

    void setup() {
       RGBLA returnedValues = readSPIFFS();

       Serial.println("readSPIFFS 1");
       Serial.print("R: ");
       Serial.println(returnedVars.R);
       Serial.print("G: ");
       Serial.println(returnedVars.G);
       Serial.print("B: ");
       Serial.println(returnedVars.B);
       Serial.print("L: ");
       Serial.println(returnedVars.L);
       Serial.print("AmbientLight: ");
       Serial.println(returnedVars.A);

       returnedValues = saveToSPIFFS(205, 17, 68, 50, 15, false);

       Serial.println("saveToSPIFFS 1");
       Serial.print("R: ");
       Serial.println(returnedVars.R);
       Serial.print("G: ");
       Serial.println(returnedVars.G);
       Serial.print("B: ");
       Serial.println(returnedVars.B);
       Serial.print("L: ");
       Serial.println(returnedVars.L);
       Serial.print("AmbientLight: ");
       Serial.println(returnedVars.A);
    }

    RGBLA readSPIFFS() {
       RGBLA returnedVars;
       File configFile = SPIFFS.open("/config.json", "r");

       if (configFile ) {
         Serial.println("YAY!");
         configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
         configFile.close();
       } else {
         Serial.println("Boo!");
       }

       return returnedValues;
    }

    RGBLA saveToSPIFFS() {
       File configFile = SPIFFS.open("/config.json", "w+");

       if (configFile.size() > 3072) {
         Serial.println("Config file size is too large.");
       } else {
         Serial.print("Writing to Config file...");

         //Get the old value and save it
         RGBLA returnedVars = readSPIFFS();

         Serial.println("Old Values:");
         Serial.print("R: ");
         Serial.println(returnedVars.R);
         Serial.print("G: ");
         Serial.println(returnedVars.G);
         Serial.print("B: ");
         Serial.println(returnedVars.B);
         Serial.print("L: ");
         Serial.println(returnedVars.L);
         Serial.print("AmbientLight: ");
         Serial.println(returnedVars.A);

         if (saveA) {
           //Save Ambient Light data
           returnedVars.A = A;
         } else {
           //Save RGBL data
           returnedVars.R = R;
           returnedVars.G = G;
           returnedVars.B = B;
           returnedVars.L = L;
         }

         configFile.write((byte*) &returnedVars, sizeof(RGBLA));
         configFile.close();

         return returnedVars;
    }

title: ESP8266 SPIFFS not saving correctly?

Answers: 1

body:
You can write a struct to file as binary data. This example is from my project.

global data:

    struct Stats {
      int heatingTime; // minutes
      int consumedPower; // watts
    };

    Stats statsData;

snippet from setup():

      File file = SPIFFS.open(STATS_FILENAME, "r");
      if (file) {
        file.readBytes((byte*) &statsData, sizeof(statsData));
        file.close();
      }

snippet from statsSave() function:

      File file = SPIFFS.open(STATS_FILENAME, "w");
      if (file) {
        file.write((byte*) &statsData, sizeof(statsData));
        file.close();
      }

your updated readSPIFFS should be:

    RGBLA readSPIFFS() {

      RGBLA returnedVars;
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile ) {
        Serial.println("YAY!");
        configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
        configFile.close();
      } else {
        Serial.println("Boo!");
      }
      return returnedValues;
    }


body:
I have heard that

 1. The SPI hardware introduces a 9th, HIGH bit between bytes
 2. USART still uses start and stop bits when in synchronous mode

Are both these statements true? Can I modify the built-in SPI library to avoid #1? Or will I have to bit-bang the protocol needed?

title: USART, SPI or Bit-Bang for the continuous transfer of bytes without inserted extra bits

Answers: 1

body:
> Are both these statements true?

Neither of those statements are true.

SPI never inserts extra bits. That would break everything if it did. What you are probably seeing (or think you are seeing) is a delay between bytes being sent. That delay is irrelevant, since the data is only ever sampled on an edge of the clock signal (which edge depends on the mode of the SPI communication) and with no clock edge in that delay period there is no data.

USART in synchronous mode is SPI. There are no start or stop bits in synchronous mode, since the clock is used to synchronise the communication rather than needing start or stop bits.


body:
I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler  to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...

    void initTimer() {

     // ---Disable interrupts during timer initialization
     cli();

     // ---Counter compare value (make CTC interrupt fire every 10uS)
     OCR2A = 19;

     // ---Clear TCCR A register (not used)
     TCCR2A = 0;

     // ---Enable CTC mode with divide-by-8 prescaler
     TCCR2B = _BV( WGM22 ) | _BV( CS21 );

     // ---Enable Timer2 CTC interrupts for compare A match
     TIMSK2 |= _BV( OCIE2A );

     // ---Initialize timer 2 to zero (not really needed in my situation)
     TCNT2 = 0;

     // ---Turn interrupts back on
    sei();
    }

    SIGNAL( TIMER2_COMPA_vect ) {

        /*
        ** This should execute every 10uS, but for prescaler values
        ** below 64 the interval is many times longer than expected.
        */
    }

Can anyone point out my mistake?

title: Elegoo Nano timer prescaler problem

Answers: 2

body:
> Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.

At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions.  Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.

The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a `digitalWrite()` can overflow that many times over.

body:
Ok, I figured it out. It wasn't my timer initialization that was wrong, it was when I was doing it. Although I didn't show it in my original code sample, my initialization function actually returns a dummy boolean value so I could call it automatically if the .cpp file containing the function and the ISR is included in the project, like this...

    bool initTimer() {

        // ---Set up the timer for CTC interrupts with a 10uS period
        ---
        ---
        ---

        // ---This return value is necessary, but ignored
        return true;
    }

    bool dummy = initTimer();

That final line calls initTimer() during Arduino boot just by including this source file in the project. It's a nice way to "auto-configure" utility objects without needing to explicitly call an initialization function. The boolean dummy return value from initTimer() is needed since C/C++ compilers choke on calling functions this way without storing a return value.

    void initTimer() {

        // ---Do stuff...
    }

    // ---The compiler can't digest this...
    initTimer();

Anyway, I have used this technique many times over several decades in desktop and mobile applications, so I did it in this Arduino project without giving it too much thought, but I failed to consider that it would execute the timer2 initialization BEFORE the Arduino setup routines. Anything I did to timer2 was being overwritten by the Arduino boot code which ran after my initTimer() function. My initialization was having some effect on the operation of timer2 because the Arduino boot setup assumes the timer2 config registers are starting off empty (zeroed) so it just sets config bits without clearing everything first. Any bits I turn on stay on, but Arduino boot up sets additional bits so the resulting timer configuration is unpredictable. The solution was simple... call the initTimer() function from the standard Arduino setup() function instead to ensure it executes LAST.


body:
Thank you everyone for help on my last post, i managed to make it work.  I still keep trying to craft my skill with the arduino.  This time I need to make a coffee hot plate simulation.  When the sensor is not up to temp an LED will blink, once the sensor gets up to temp the LED will blink but turn off (go to low) after five seconds. This is the code i am working on.  The sensor is at temp and the LED is still blinking instead of turning off.  When its low it blinks as should.  I think the bug is in the millis() portion of code.  Any ideas would be greatly appreciated.  I also ran the println screen, and the temp is consistantly around 210-220.

    const int led         =  11;       // hot plate led on pin 11
    const int sensor      =   9;       // temp sensor on pin 9
    const int LOWER_BOUND = 174;       // lower temp
    const int UPPER_BOUND = 220;       // upper temp

    int val = 0;                       // analog reading

 unsigned const long period = 5000; // time it takes to turn led off at temp

 unsigned long startMillis;
    unsigned long currentMillis;

    void setup() {
        Serial.begin(9600);
        pinMode(led, OUTPUT);
        pinMode(sensor, INPUT);
        startMillis = millis();
    }

    void loop() {

        val = analogRead(sensor);      // temp recorder
        Serial.println(val);
        currentMillis = millis();

        if (val == UPPER_BOUND){
            digitalWrite(led, HIGH);
        }

        else if (val == UPPER_BOUND && currentMillis - startMillis == period) {
            digitalWrite(led, LOW);
        }

        else (val <= LOWER_BOUND); {
            digitalWrite(led, LOW);
            delay(200);
            digitalWrite(led, HIGH);
            delay(200);
        }
    }

title: Where is my BUG?

Answers: 2

body:
I see a couple of issues with your code. The biggest problem is that you capture startMillis in setup() and then compare it with currentMillis in your loop. If it takes more than five seconds for the pot to get hot enough you will never match (currentMillis - startMillis) == period because (currentMillis - startMillis) will already be > period before you start testing it. Changing "== period" to ">= period" will fix this, but it still won't behave the way you want since you should be setting startMillis when the pot first reached the target temp, not at program startup.

Also, your code does nothing when the temp is between LOWER_BOUND and UPPER_BOUND, which I suspect is not what you want. You don't specify whether "up to temp" means at or above LOWER_BOUND or at or above UPPER_BOUND. I'm going to assume that you want the LED to flash when the temp is below LOWER_BOUND, go solid on while the temp is between LOWER_BOUND and UPPER_BOUND, and then turn completely off five seconds after the pot reaches UPPER_BOUND.

Personally I would rewrite it like this, both for functionality and readbility...

    int val = 0;                       // analog reading

    unsigned const long period = 5000; // time it takes to turn led off at temp

    // ---We don't need this till later, zero it so the loop knows not to use it till then
    unsigned long startMillis = 0;

    void setup() {

        Serial.begin(9600);
        pinMode(led, OUTPUT);
        pinMode(sensor, INPUT);

    }

    void loop() {

        val = analogRead(sensor);      // temp recorder
        Serial.println(val);

        if ( val <= LOWER_BOUND ) {

            // ---Coffee temp is low, flash the LED
            digitalWrite(led, LOW);
            delay(200);
            digitalWrite(led, HIGH);
            delay(200);

        } else if ( val < UPPER_BOUND ) {

            // ---Coffee temp is medium, turn the LED solid on (assumes switched cathode)
            digitalWrite(led, LOW);

        } else {

            // ---Coffee is hot!
            if ( !startMillis ) {

                // ---Coffee just reached UPPER_BOUND... start timing (LED is already on)
                startMillis = millis();

            } else {

                // ---Has the period timed out yet?
                if ( ( millis() - startMillis ) >= period ) {

                      // ---More than 5 seconds has passed, make sure LED is off
                      digitalWrite(led, HIGH);

                }
            }
        }
    }

A couple of points about this implementation...

 1. I have not tested this code on a physical Arduino.
 2. Notice that we don't care to start storing or watching millis() until the pot first reaches UPPER_BOUND. Until then all the program cares about is the temp of the coffee.
 3. Like your original code, this implementation doesn't consider the wraparound of millis() every 50 days or so. It's unlikely a coffee pot will take over 50 days to reach the target temperature, so I wouldn't worry about it, but you should consider this situation when coding long-running applications (I refuse to call them "sketches").
 4. I based this on your original code, so like yours, once the temp reaches at least LOWER_BOUND it continuously writes to the LED pin every pass through the loop, even though it likely hasn't changed since the last iteration. If I was doing this for real I would restructure it so it only writes to the pin when the state of the LED actually changes. This is only an efficiency issue though... writing the same value to a pin repeatedly will work fine, it just isn't very elegant.
 5. If the coffee starts to cool down after reaching UPPER_BOUND then behaviour is undefined. I suspect that it would work normally when the coffee temp is low or medium, but if the coffee reached the UPPER_BOUND the second or more times I believe the LED would turn off immediately rather than after 5 seconds. It wouldn't be difficult to enhance the code to behave correctly no matter how many times the pot temp cycles up and down, but this solution was to the problem as you described it, which was a coffee pot warming up just once from cold to a target temperature.

body:
First, let me point out a few technical issues with your program:

1. `const int sensor = 9;` is wrong. On an Uno, you can only use
   `analogRead()` on the pins labeled `A0` through `A5`.

2. `if (val == UPPER_BOUND)`. Never test an analog reading for exact
   equality. The reading is noisy, and you shouldn't expect continuity.
   It can very well jump from `UPPER_BOUND-1` on one reading to
   `UPPER_BOUND+1` on the next one. Instead, test for
   `val >= UPPER_BOUND`.

3. `currentMillis - startMillis == period`. Again, you should not test
   for exact equality. This time it's for a more subtle reason that has
   to do with the implementation of `millis()`: some values (roughly one
   every 42) are skipped over. Here again, test for `>= period`.

There is also the issue, already pointed out by PhoenixRevealed, of
your code defining two thresholds, while your prose only mentions one.
This may well be just you being sloppy and not describing your
requirements precisely enough.

Next, and since you are interested in perfecting your learning process,
let me advise you on two techniques that are worth learning, because
they are extremely useful for mostly any Arduino project more complex
than just blinking an LED:

1. **Avoid using `delay()`**. While the Arduino is busy delaying, it can
   do nothing else. For instance, it cannot monitor the temperature
   changes on the hot plate. In this particular case, it may well be the
   case that you don't care, because the hot plate is so slow that you
   can afford to be 400 ms late. But if you get into the habit of
   relying on `delay()`, it will bite you sooner or later. So the sooner
   you learn to [blink an LED without using `delay()`][no-delay], the
   better.

2. Learn to program a **finite state machine**. This is a programming
   concept that is very well suited for describing reactive systems,
   i.e. systems that have to react to external “events”. It is a very
   useful concept for writing most programs that are meant to control
   hardware. There are quite a few tutorials out there. I would
   recommend [The Finite State Machine][fsm], by Majenko.

Here is my interpretation of your requirements in terms of a finite
state machine: your Arduino can be in any of 3 states: `COLD` (initial
state, the plate has not reached the required temperature), `WAITING`
(the plate reached the temperature and we are delaying five seconds),
`DONE` (the five seconds have elapsed). The rules for changing states
are:

* `COLD` → `WAITING`: when in the `COLD` state, if the temperature
  reaches a specified threshold, go to the `WAITING` state.
* `WAITING` → `DONE`: when in the `WAITING` state, once five seconds
  have elapsed since we entered the state, go to the `DONE` state.
* When we are in the `DONE` state... nothing more ever happens.

Here is the corresponding state diagram:

[![state diagram][1]][1]

Notice that once we reach the `DONE` state, the system gets stuck. This
situation can only be recovered from by rebooting the Arduino. You may
want to revise your specification in order accommodate a `DONE` → `COLD`
transition in some way. But from your specification _as written in your
question_, I assume you are fine with the system getting stuck.

I tried to implement this state diagram in code, using the traditional
`switch`/`case` construct. But then I got lazy and noticed that calling
[`exit()`][exit] is the easiest way of implementing the `DONE` state, as
this function is precisely designed to get the program stuck in a
do-nothing state. Then, since there are only two states left to care
about, a boolean can be used as a state variable. In the end, the code I
propose may not look like a finite state machine. However, it is
important to notice that, event if such case, the finite state machine
is a very useful concept for _thinking_ about your program and writing
down its requirements.

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

    // Pinout
    const uint8_t LED = 11;
    const uint8_t SENSOR = A0;

    // Threshold temperature reading.
    const int THRESHOLD_TEMP_READING = 220;

    // Timing.
    const uint32_t LED_TOGGLE_PERIOD = 200;
    const uint32_t WAIT_TIME = 5000;

    bool is_hot = false;
    uint32_t last_led_toggle;
    uint32_t wait_started;

    void setup()
    {
        pinMode(LED, OUTPUT);
        pinMode(SENSOR, INPUT);
    }

    void loop()
    {
        // Read the time once per loop.
        uint32_t now = millis();

        // Toggle the LED state.
        if (now - last_led_toggle >= LED_TOGGLE_PERIOD) {
            digitalWrite(LED, !digitalRead(LED));
            last_led_toggle = now;
        }

        if (is_hot) {
            // If the plate is hot, keep blinking during WAIT_TIME.
            if (millis() - wait_started >= WAIT_TIME) {
                digitalWrite(LED, LOW);  // turn off the LED
                exit(0);                  // stop everything
            }
        } else {
            // If the plate is cold, take note when it gets hot.
            if (analogRead(SENSOR) >= THRESHOLD_TEMP_READING) {
                is_hot = true;
                wait_started = now;
            }
        }
    }

[no-delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[fsm]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
[exit]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga137096a48cc0c731052cadfb69c39b34

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


body:
I'm using MCP2515 CAN controller and TJA1050 transceiver. I want to send some square waves to TJA1050 with digital write and delay instruction of Arduino. How can I do that? I also read the MCP2515's datasheet. It has 5 GPIOs. Can I use these pins to send square waves to the transceiver?
Here is the library I used:[https://github.com/Seeed-Studio/CAN_BUS_Shield][1]
The examples of this library contains a sample code as gpioread and gpiowrite but when I compile them I got error:
exit status 1
'class MCP_CAN' has no member named 'pinMode'

  [1]: http://github.com/Seeed-Studio/CAN_BUS_Shield

Thanks in advance.

title: MCP2515 CAN bus with Arduino

Answers: 1

body:
This is not really a general Arduino question but...

The compiler is telling you that the member function 'pinMode' is not available. A closer look at the commit history for the library reveals that they have recently rolled back to a "working version". There is a commit with the member functions 'pinMode', 'digitalRead' and 'digitalWrite' included.

Please see:
https://github.com/Seeed-Studio/CAN_BUS_Shield/commit/15c6bfb80a50c924a9c708117a66a66b54af5370


body:
I wander what is the best option for formatting strings in Arduino for output.
I mean what's a preferable way in the point of view of performance, memory usage  – things like that.
I see, people usually use direct Serial.print/println, like this:

      int x = 5;
      // 1st option
      Serial.print("x = ");
      Serial.println(x);

Or like this:

      // 2nd option
      Serial.println("x = " + String(x));

But what is wrong with, I believe, more traditional way of doing this:

      // 3rd optoin
      char strBuf[50];
      sprintf(strBuf, "x = %d", x);
      Serial.println(strBuf);

      // better one?

Answers: 5

body:
If you need the result in a single string then your 3rd option is the preferred way.

If you don't, then the first option of printing each part separately is the most efficient in terms of memory.

The second version, String concatenation, is the worst option in all respects and should be avoided at all costs.

I often use `sprintf` to a buffer if I need a specific format (for instance leading zeroes on a number).

If you want to avoid the extra code bloat of `sprintf` you can use various combinations of `strcpy`, `strcat` and `itoa` etc to build up a string into a memory buffer (if you really need to put it in a buffer).

Note that on an 8-bit Arduino `sprintf` has no float support - so you would still need to use `dtostrf` to format a float into a char buffer first, or print it directly.

body:
I agree with Majenko's answer.

I created a simple CStringBuilder class to combine the first and third approach mentioned in your question. It enables to build the c-string with printf and with Print functions, which can print float or IPAddress. It is available in StreamLib in library manager.

    #include <CStringBuilder.h>
    #include <IPAddress.h>

    const char* s = "Lorem ipsum";
    char c = 'X';
    int i = 42;
    float f = PI;
    IPAddress ipAddress(192, 168, 0, 1);

    void setup()
    {
      Serial.begin(115200);
      while (!Serial);

      char buff[150];
      CStringBuilder sb(buff, sizeof(buff));

      sb.print(F("Some text: "));
      sb.println(s);
      sb.print(F("Some char: "));
      sb.println(c);
      sb.print(F("HEX of char: "));
      sb.println(c, HEX);
      sb.print(F("Some integer: "));
      sb.println(i);
      sb.print(F("Some float: "));
      sb.println(f, 3);
      sb.print(F("IP address: "));
      sb.println(ipAddress);

      int l = sb.length();
      sb.print("this text doesn't fit in the remaining space in the buffer");
      if (sb.getWriteError()) {
        sb.setLength(l);
      }
      sb.println("test test");

      Serial.print("size to print: ");
      Serial.println(sb.length());
      Serial.println();
      Serial.println(buff);

      sb.reset();
      sb.printf(F("Formatted: %s;%c;d\r\n"), s, c, i);
      Serial.println(buff);
    }

    void loop()
    {

    }

Other classes in the library are BufferedPrint and ChunkedPrint.  Both support sprintf.

body: The printf() family of functions is far preferable to *me* as the programmer, but in a resource-constrained environment such as the smaller AVR (and other) processors, the extra code space may not be justified or available, or the performance hit of interpreting the format string may be limiting. And `sprintf(buf, ...); Serial.print(buf);` also takes a stack hit for the temporary buffer (compared to just `printf(...);` ) It's a trade-off between code size and speed vs. you having more flexibility to write the code to the create the output you want.

body:
The wrong thig with option 3 is the buffer length, you should use **snprintf** instead.

The other problem is that first you build the string, then you print the output, the program traverses the string twice. Option 2 creates object from string, then applies `+` operator to create a new string, then prints it - it is comfortable with short strings, but least efficient (depends on the compiler optimalizations).

Option 1 is most effective, since it directly prints arguments to the output char by char (see Arduino Print class) and traverses the arguments only once.

You can use stdarg.h to create one-liner with Serial.prints:

```
#include <stdarg.h>

void Serialprintln(const char* input...) {
  va_list args;
  va_start(args, input);
  for(const char* i=input; *i!=0; ++i) {
    if(*i!='%') { Serial.print(*i); continue; }
    switch(*(++i)) {
      case '%': Serial.print('%'); break;
      case 's': Serial.print(va_arg(args, char*)); break;
      case 'd': Serial.print(va_arg(args, int), DEC); break;
      case 'b': Serial.print(va_arg(args, int), BIN); break;
      case 'o': Serial.print(va_arg(args, int), OCT); break;
      case 'x': Serial.print(va_arg(args, int), HEX); break;
      case 'f': Serial.print(va_arg(args, double), 2); break;
    }
  }
  Serial.println();
  va_end(args);
}
```

Then you can use it like sprintf (but efficiently):

```
void setup() {
  int n = 42;
  float f = 42.42;
  const char* s = "answer";
  Serial.begin(9600);
  // The answer is 42 (101010 BIN, 2A HEX), in float 42.42
  Serialprintln("The %s is %d (%b BIN, %x HEX), in float %f", s, n, n, n, f);
}

void loop() {
}
```

body:
The third option, sprintf, is unsafe and may give buffer overruns if buffer is not sized correctly.  You can use snprintf instead.
However I would recommend my [SafeString library and tutorial][1]
for general string processing and output.

  [1]: https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html


body:
I have a led strip, and each led should be turned on sequentially, such as this one:
[http://1.bp.blogspot.com/-CTT6yvYtdos/VihhhBItwjI/AAAAAAAAAvM/q1jbUylMMdM/s400/ezgif.com-video-to-gif.gif][1]
The time delay between 2 consecutive leds is ts, and that time should be adjusted externally through a pushbutton switch. Each time the button is pressed, the time period shoud increment in a fixed amount.
I've already used the timerOne library, but it just works with a fixed time delay ts. How can I solve this issue with VARIABLE time delay?
I prefer to use interruptions rather than polling, since this system will be more complex (other buttons and variables will be involved).
Thanks!
Fernando

title: Timer with ajustable time delay

Answers: 2

body:
https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55

Defines the function in TimerOne called `SetPeriod()`. That will change the period.

body:
I've found the solution, through the function

    attachInterrupt(function,period);

inside

    loop()

In other words, I wrote

    loop(){
    Timer1.attachInterrupt(function,period);
    // rest of the code
    }

where "period" changes inside the ISR called when the external button is pressed.
Thanks a lot @jose can u c!!


body:
Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.

What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.

My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.

    #include <Adafruit_MLX90614.h>
    Adafruit_MLX90614 tempSensor;

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    Adafruit_MLX90614 mlx = Adafruit_MLX90614();

    double array[30];
    double rollingaverage=0;
    int i=0, j=0;
    double sum=0;
    double newreading;
    void setup() {

      Serial.begin(9600);
      lcd.begin(20,4);
      mlx.begin();
      Wire.begin();

    }

    void loop() {
      if(j=0){
          newreading = mlx.readObjectTempF();
          array[i] = newreading;
          sum += array[i];
          if(i>0){
              rollingaverage = sum/(i+1);
          }
          j=1;
      }
      else{
          newreading = mlx.readObjectTempF();
          array[i] = newreading;
          if(i < 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
              sum = sum + array[i] - array[i+1];
              rollingaverage = sum/30;
          }
          else{
              sum = sum + array[i] - array[0];
              rollingaverage = sum/30;
              i=0; //reset index to 0
          }
      }
      i++;

      lcd.clear();
      lcd.print("Belt: "); lcd.print(rollingaverage);
      lcd.setCursor(1,2);
      lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

    delay(2000);
    }

Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks

title: Code for a rolling average

Answers: 3

body:
Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.

I have a library that does it all for you that would make things easier for you:

* https://github.com/MajenkoLibraries/Average

body:
One way is to initialize the whole buffer to the first value. Your average won't be "true" in some sense, until the whole buffer has been replaced with read data, but as long as that first value isn't too different from the true temperature, your average during that period will be more sensible. I.e., it won't have to  ramp up from zero.

Another way is to use an Exponential Average instead of the Rolling- or Boxcar-Average. The Exponential Average doesn't depend on storing old samples and can adjust well - i.e. within a few samples, depending on 'X' (see below) - to a sudden change (which temperatures don't normally do, anyway).

It calculates a new average by summing X percent of the current average + (100-X) percent of the next sample - you choose the value of 'X' that works best in your own application.  I have good results averaging temperatures, even from analog sensors, using X=75. For fixed-point numbers such as the 4 binary places returned by the Max DS18b20 sensors, would be

    // (3 * avg + 1 * sample) / 4
    avg = (((avg<<2) - avg + sample) + 2) >> 2;

For floating point numbers, it would just be:

    avg = (3. * avg + sample)/4.;

Update:

> Initialization is as much an issue with an exponential average as it
> is with a boxcar average.

Yes, it is. I initialize my exponential averagers with the first sample and usually get along pretty well. It might not work so well if the averager was too heavily damped.

> ... a boxcar of width 30 ...

An exponential average, by its nature, can give recent samples more weight than older ones so giving so little weight as you suggest to the next sample will make it quite heavy-handed! X=75% has worked quite well *for me* to reduce noise without heavy-handed damping. What works well for one system may not work for another, but by running a saved sample-set through a few trials on your desktop will quickly get you to a reasonable X.

We don't know how that width (30) was arrived at; perhaps it is necessary? But averaging, by its nature, being both low-pass (usually desired) and delaying (generally not desired), spreads sudden features like spikes while it limits their amplitude. I've sometimes use a spike suppressor ahead of a lighter averaging filter, where the alternative average-only would have required enough averaging to damp significant signal features too heavily.

body:
The other answers address the problem with your code, however a better solution is to use a different algorithm.

I would use exponential smoothing (which is simpler to code, requires less data and produces a similar result). This is the technique I used to use when responsible for producing statistical performance reports. If readings are plotted this results in a smoother graph, which shows trends and discounts noise.

Briefly take the current sample, multiply by a discounting factor and add the a proportion of the current value.

  > s = x * α + (1-α) * s

To produce results from the start initialise the sample to the first reading then calculate.

See https://en.wikipedia.org/wiki/Exponential_smoothing

I would probably start with a smoothing factor of 0.3 - choose a smaller value to give more weight to past values.


body:
I have purchased a cigarette adapter that gives me 2 USB ports, however this gives me 5v and up to 2.4A.

Thats ok for powering the Arduino Uno, I need 12/24v to power the CAN crocodile.

I also want to drive quite a lot of NeoPixels.

How can I do this?

title: Powering Arduino Uno, CAN Crocodile and NeoPixels from Car

Answers: 1

body:
A reasonable estimate for current consumption of 5V NeoPixels is 60mA per pixel. For 186 pixels, that means about 11.16A at 5V; well over the 2.4A of the adapter being used for your other components.

There exist modules called "DC-to-DC Buck Converters", which can step down the 12-14V of your automobile to pretty much any voltage under the input voltage. To be safe, look for a buck converter of at least a 75W rating, and which meets your criteria for input and output range (minimum of 12V input, could be rated higher; output range inclusive of 5V.)

Be sure that the Ground connections for the NeoPixel power supply and the other supply are shared/connected, but don't share the +5V line between supplies.


body: Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.

title: Neopixle animation help

Answers: 1

body:
Yes absolutely it is possible. As a beginner, I suggest something like this:

<!-- 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/aXJm1.png)

<!-- End schematic -->

In your `setup` you will need to declare D4 - D7 as [inputs][1]. I have used D4 - D7 but you can choose whatever pins are available.

Then in the `loop` part of the code you want to look for the rising edge on the input (ie when the switch is pressed). [Switch debounce][2] is less important for this application as it is not a counter but rather a mode change.

I have written a good [answer for detecting a button press here][3].

Nick Gammon has an excellent switch tutorial [gammon.com.au/switches][4] that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)

I would imagine the code would look something like this:

    if( digitalRead(SW1) == HIGH )
        mode = 1;

    if( digitalRead(SW2) == HIGH )
        mode = 2;

    if( digitalRead(SW3) == HIGH )
        mode = 3;

    if( digitalRead(SW4) == HIGH )
        mode = 4;

You could then use a [switch-case statement][5] to run the various NeoPixel patterns.

For more programming reference see: [https://www.arduino.cc/reference/en/][6]

  [1]: https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/
  [2]: https://whatis.techtarget.com/definition/debouncing
  [3]: https://arduino.stackexchange.com/a/48307/19409
  [4]: http://www.gammon.com.au/switches
  [5]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/
  [6]: https://www.arduino.cc/reference/en/


body: I have 4 BLDC motors, and 4 ESCs, one for each motor. But I have one LiPo battery from which I want to power one Arduino Mega and all the 4 ESCs. Can I remove the connectors from the ESCs and put them on a breadboard in a single column/row so that they are connected together, and then connect the + and - of the battery (after removing its connector as well) to the respective breadboard column/row, so that they are essentially connected together to power all the ESCs? Also, I would want to use a jumper from the Arduino Vin and GND pins to the same column/row on the breadboard. Will this method of powering all the 4 ESCs and the Arduino from a single LiPo work?

title: Interfacing 4 ESCs and an Arduino with a single LiPo battery

Answers: 1

body:
Powering all the ESCs from a single LIPO is not an issue.

Using a breadboard to distribute this power is highly unlikely to work, breadboard connectors are usually only good to a few hundred mA, 1A is you want to push your luck.  Most ESCs and BLDC motors are in the 5A to 50A range (each, your power bus has to handle 4 times this current).

Also, ESCs tend to inject a lot of noise into the power bus.  If you connect the arduino to the ESC power bus, you will likely get random resets and really poor noise performance on the ADCs.  Keep in mind that some ESCs actively brake the motors using regenerative braking, which puts the kinetic energy of the motor back into the power bus.  This can increase the voltage on the power bus to more than the nominal battery voltage and can have large voltage spikes on it causing a failure on the Arduino.

If you are prototyping, use a separate power supply/battery for the arduino and connect all the grounds together instead of using a single supply.  If you are building a rover/uav/whatever and don't want a second battery, use a high quality BEC (or the BEC output from a high quality ESC) and remember that the 5V output on a BEC/ESC can be significantly higher than 5V in reality).

ESC = Electronic Speed Controlled
BEC = Battery eliminator circuit (I think, basically a 5V-ish regulator)
BLDC = Brushless DC motor (three phase in this case)