# Question
Title: how can I stop my Arduino code after 1 second?
I want to send message NRF24L01 to NRF24L01. I want to see if I can send just one second. How can I stop code after 1 second?

# Answer
You can use different ways:

**Use `setup` only**

Instead of putting code in the `loop` function, put it in `setup`, which is only executed once (use a `for` loop to send around 1 second.

**`millis()` excluding `setup`**

It is better to use the `millis` function and compare it against the start of sending; when 1 second is reached, don't send anything or use an infinite `while` loop.

Use something like:

```
unsigned long time_start;

void setup()
{
    // Your normal code

    time_start = millis();
}

void setup()
{
    if (millis() - time_start >= 1000)
    {
        while(1) {};
    }

    // your normal code (which should not take many ms,
    // otherwise the above code is not reached.

```

**millis() including `saetup`** (Thanks to Edgar Bonnet):

```
 void loop()
 {
     if (millis() >= 1000)
     {
        while(1) {};
     }
 }

```

This will stop exactly after 1 s after startup (excluding the `setup`). It will start counting after `millis` start counting, which is before the `setup` function.

Actually, in none of the above the Arduino 'stops', it just is doing endlessly nothing (well internally endlessly checking against the `true` condition which never changes).
> 0 votes

---
Tags: arduino-uno, programming, timing
---


# Question
Title: Programming ESP8266 to avoid random exceptions?
Below is the code that I have done on `Lolin Wemos D1 R2 and mini` it works fine but it throws exceptions every time, I tried understanding my problem by reading this: NodeMCU 1.0 - Exception 9 \`Fatal exception 9(LoadStoreAlignmentCause):\` but couldn't!

```
#include <FirebaseArduino.h>
#include <SoftwareSerial.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
//#include "FS.h"

//---------firebase creds---------
#define FIREBASE_HOST "homeauto-3130d.firebaseio.com"
#define FIREBASE_AUTH ""

//--------wifi creds--------
#define WIFI_SSID "********"
#define WIFI_PASSWORD "***************"

SoftwareSerial esp(D2,D8); //rx tx

//--------data from arduino to esp-------
float temp_fb;
float gas_fb;
float hum_fb;

//-------checking time elapsed b4 printing ------
unsigned long last_chk = 0 ;
unsigned long time_elapsed;

//-----ctrlling sending rate to firebase----
bool t_ar , h_ar , g_ar = false ; //chk arrival of all data b4 sending
char r;
int found = 1;

//-----setting feeder pos from firebase
String feed_load = "0" ;

//-----getting time stamp from ntp server
char time_stamp[12];
int len;
const long utcOffsetInSeconds = 19800; //gmt+5hrs:30mins => 19800 sec
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

//------------------------schedule vars----------------------------

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

  SPIFFS.begin();

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  if(Firebase.failed())
     {
      Serial.print("failed...");
      Serial.println(Firebase.error());
     }
  timeClient.begin();
}

void loop()
{
  time_elapsed = millis();
  if(time_elapsed - last_chk > 5000)
  {
    Serial.println("checking for data from arduino...");

    last_chk = time_elapsed;
    time_elapsed = millis();
  }
   while(esp.available()>0)
  {

     if(found == 1)
     {
      Serial.println("................found data...............") ;
      timeClient.update();
      len = sprintf(time_stamp , "%d:%d:%d" , timeClient.getHours() , timeClient.getMinutes() , timeClient.getSeconds() ) ;
      Serial.print("Time stamp:\t");
      Serial.println(time_stamp);
      found = 0;
     }
     r = esp.read();

     switch(r)
     {

      case 't':
      {
        Serial.print("got t...") ;
        t_ar = true;
        temp_fb = esp.parseFloat();
        Serial.println(temp_fb);
        break ;
      }

      case 'g':
      {
          Serial.print("got g...") ;
          g_ar = true;
          gas_fb = esp.parseFloat();
          Serial.println(gas_fb);
          break ;
      }

      case 'h':
      {
        Serial.print("got h...") ;
        h_ar = true;
        hum_fb = esp.parseFloat();
        Serial.println(hum_fb);
        break ;
      }
      default: break;

     }

  }

  found = 1 ;

  if(g_ar and t_ar and h_ar)
  {
     //writing to firebase
     Serial.println("got the set.. to fb now");
     Firebase.pushString("Time stamp" , time_stamp);
     Firebase.setFloat("GAS SENSORinst" ,gas_fb);
     Firebase.setFloat("HUMIDITY SENSORinst" ,hum_fb);
     Firebase.setFloat("TEMP SENSORinst" ,temp_fb);
     Firebase.pushFloat("GAS SENSOR" ,gas_fb);
     Firebase.pushFloat("HUMIDITY SENSOR" ,hum_fb);
     Firebase.pushFloat("TEMP SENSOR" ,temp_fb);

  }

  t_ar , h_ar , g_ar = false ;

  feed_load = Firebase.getString("feeder");

  if (feed_load != "0")
   {
    Serial.println("\trecd req to feed");
      esp.print('w');
      esp.print(feed_load);
      feed_load = "0";
      Serial.println("\tsetting feeder to close in firebase");
      Firebase.setString("feeder" , "0");

   }

}

```

Here's the error log:(I've only pasted the exceptions, they just repeat over and over again)

```
Exception (28):
epc1=0x4020cda0 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000034 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffc50 end: 3fffffc0 offset: 01a0
3ffffdf0:  0000000b 3ffeeb28 3fff0e18 40206e5c
3ffffe00:  3ffe8857 000001bb 3fff0e18 40207d34
3ffffe10:  3ffe890b 0000003b 3fff0e18 4020817c
3ffffe20:  0000003b 3fffff00 3ffeec64 40203eb0
3ffffe30:  3ffffe78 0000003b 3ffffe60 40209018
3ffffe40:  3ffeeb24 3ffffe60 3ffe890b 3ffffee0
3ffffe50:  3ffeeb24 3ffffea4 3fff0e14 402057ab
3ffffe60:  3fff10bc 003b003f 00fffea4 3fff0f4c
3ffffe70:  000c000f 00ffff5c 3fff0ef4 001d001f
3ffffe80:  00fe876b 3ffeeb20 3fffff62 3ffffee0
3ffffe90:  3ffeeb24 3ffe8888 3fff0ca4 402034ec
3ffffea0:  3ffe876b 3fff0f38 3fff0ec4 3ffeea78
3ffffeb0:  3fffff5c 3ffffee0 3ffe876b 40203e74
3ffffec0:  3ffffee8 3fffff00 3fffff00 3ffeea78
3ffffed0:  3fffff5c 3fff0ca4 3ffeeb20 40204765
3ffffee0:  3ffeeb60 3fff0ed0 05e353f7 40205fef
3ffffef0:  3ffeeb20 3ffeeb20 3fffff50 402047a6
3fffff00:  00220000 3fff0174 3ffeea78 402068ca
3fffff10:  00000006 00000002 40205fbc 402067ac
3fffff20:  00c3c10e 00000006 3fffff5c 40209018
3fffff30:  3ffeeb20 3fffff5c 3ffe8804 4020904e
3fffff40:  3ffeeb20 3ffe851c 3ffeea61 40201438
3fffff50:  3ffe0000 3fffff80 80feeb84 64656566
3fffff60:  00007265 86595cc2 3ffeeb00 4020113a
3fffff70:  00000000 00000000 feefeffe feefeffe
3fffff80:  00000000 00000000 00000001 40100580
3fffff90:  3fffdad0 00000000 3ffeec74 3ffeecb4
3fffffa0:  3fffdad0 00000000 3ffeec74 40209f08
3fffffb0:  feefeffe feefeffe 3ffe8584 401012d1
<<<stack<<<

Exception (9):
epc1=0x4020cda0 epc2=0x00000000 epc3=0x00000000 excvaddr=0x65656663 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffc50 end: 3fffffc0 offset: 01a0
3ffffdf0:  0000000b 3ffeeb28 3fff0e18 40206e5c
3ffffe00:  3ffe8857 000001bb 3fff0e18 40207d34
3ffffe10:  3ffe890b 0000003b 3fff0e18 4020817c
3ffffe20:  0000003b 3fffff00 3ffeec64 40203eb0
3ffffe30:  3ffffe78 0000003b 3ffffe60 40209018
3ffffe40:  3ffeeb24 3ffffe60 3ffe890b 3ffffee0
3ffffe50:  3ffeeb24 3ffffea4 3fff0e14 402057ab
3ffffe60:  3fff0f1c 003b003f 00fffea4 3fff0f04
3ffffe70:  000c000f 00ffff5c 3fff0eac 001d001f
3ffffe80:  00fe876b 3ffeeb20 3fffff62 3ffffee0
3ffffe90:  3ffeeb24 3ffe8888 3fff0c7c 402034ec
3ffffea0:  3ffe876b 3fff0ef0 3fff0cbc 3ffeea78
3ffffeb0:  3fffff5c 3ffffee0 3ffe876b 40203e74
3ffffec0:  3ffffee8 3fffff00 3fffff00 3ffeea78
3ffffed0:  3fffff5c 3fff0c7c 3ffeeb20 40204765
3ffffee0:  3ffeeb60 3fff0cc8 a7ae147a 40205fef
3ffffef0:  3ffeeb20 3ffeeb20 3fffff50 402047a6
3fffff00:  00220000 3fff0174 3ffeea78 402068ca
3fffff10:  00000006 00000002 40205fbc 402067ac
3fffff20:  00c15609 00000006 3fffff5c 40209018
3fffff30:  3ffeeb20 3fffff5c 3ffe8804 4020904e
3fffff40:  3ffeeb20 3ffe851c 3ffeea61 40201438
3fffff50:  3ffe0000 3fffff80 80feeb84 64656566
3fffff60:  00007265 86461819 3ffeeb00 4020113a
3fffff70:  00000000 00000000 feefeffe feefeffe
3fffff80:  00000000 00000000 00000001 40100580
3fffff90:  3fffdad0 00000000 3ffeec74 3ffeecb4
3fffffa0:  3fffdad0 00000000 3ffeec74 40209f08
3fffffb0:  feefeffe feefeffe 3ffe8584 401012d1
<<<stack<<<

```

**edit1** decoding error stack, this is what i get...

```
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads
PC: 0x402141d4: HTTPClient::connected() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 472
EXCVADDR: 0x00000040

Decoding stack results
0x40206e64: HTTPClient::disconnect(bool) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 435
0x40207d3c: HTTPClient::end() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x40208184: HTTPClient::begin(String, unsigned short, String, String) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 379
0x40203eb8: std::string::_Rep::_M_destroy(std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 452
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x402057b3: FirebaseHttpClientEsp8266::begin(std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient_Esp8266.cpp line 51
0x402034f4: FirebaseRequest::sendRequest(std::string const&, std::string const&, char*, std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\Firebase.cpp line 73
0x40203e7c: std::basic_string  , std::allocator  >::basic_string(char const*, std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 218
0x4020476d: FirebaseArduino::getRequest(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 101
0x40205ff7: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1954
0x402047ae: FirebaseArduino::getString(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 132
0x402068d2: SoftwareSerial::rxBits() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 394
0x40205fc4: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1931
0x402067b4: std::_Function_handler ::_M_invoke(const std::_Any_data &, unsigned int &&) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 393
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x4020919a: String::String(char const*) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 36
0x40201440: loop() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 151
0x40201142: setup() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 72
0x40100580: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020a054: loop_wrapper() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

Exception 9: LoadStoreAlignmentCause: Load or store to an unaligned address
PC: 0x402141d4: HTTPClient::connected() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 472
EXCVADDR: 0x65656663

Decoding stack results
0x40206e64: HTTPClient::disconnect(bool) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 435
0x40207d3c: HTTPClient::end() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x40208184: HTTPClient::begin(String, unsigned short, String, String) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 379
0x40203eb8: std::string::_Rep::_M_destroy(std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 452
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x402057b3: FirebaseHttpClientEsp8266::begin(std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient_Esp8266.cpp line 51
0x402034f4: FirebaseRequest::sendRequest(std::string const&, std::string const&, char*, std::string const&, std::string const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\Firebase.cpp line 73
0x40203e7c: std::basic_string  , std::allocator  >::basic_string(char const*, std::allocator  const&) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2\bits/basic_string.tcc line 218
0x4020476d: FirebaseArduino::getRequest(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 101
0x40205ff7: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1954
0x402047ae: FirebaseArduino::getString(String const&) at C:\Users\Admin\Documents\Arduino\libraries\firebase-arduino-master\src\FirebaseArduino.cpp line 132
0x402068d2: SoftwareSerial::rxBits() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 394
0x40205fc4: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data &, const std::_Any_data &, std::_Manager_operation) at c:\users\admin\documents\arduinodata\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506\xtensa-lx106-elf\include\c++\4.8.2/functional line 1931
0x402067b4: std::_Function_handler ::_M_invoke(const std::_Any_data &, unsigned int &&) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SoftwareSerial\src\SoftwareSerial.cpp line 393
0x40209164: String::copy(char const*, unsigned int) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 214
0x4020919a: String::String(char const*) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\WString.cpp line 36
0x40201440: loop() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 151
0x40201142: setup() at C:\Users\Admin\Desktop\dummy\iot1\tonodemcu/tonodemcu.ino line 72
0x40100580: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020a054: loop_wrapper() at C:\Users\Admin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

```

Read from here: NodeMCU Exception 28 - intermitent problem that `exception 28` maybe because of some functions not returning values and I can take that because, i just connected the ESP without arduino just to check what happens, but during other times I only recall `exception 9` being repeated

The var `String feed_load` is read from firebase , which gets the value from a app made from MIT app inventor , I store 0 or value of load in it (a float) ; but app inventor stores it as a string, so i am reading it as a string , i tried putting `char feed_load[5]` but it gave a error saying string cannot be stored in char\[5\]

kindly help in fixing this problem , there's some more code to be written for scheduling activities , so i don't want the board to be constantly resetting or restarting

# Answer
> 1 votes
I don't know if this is the actual fix for the problem ,but instead of FirebaseArduino library i used FirebaseESP8266 library and the random exceptions did not come up (yet)

FirebaseESP8266 https://github.com/mobizt/Firebase-ESP8266/

P.S. sorry for not reverting back quicker !!

---
Tags: arduino-uno, esp8266, softwareserial, iot
---


# Question
Title: How can I add a potentiometer and more buttons to my custom game controller?
I'm new to using Arduino, and know next to nothing about programming. I'm currently trying to add a potentiometer, and possibly a few more button inputs to my 3D-printed guitar controller project

It uses an Arduino Pro Micro, the code is just an example file from this joystick library that I mostly just played around with using trial and error, and this pinout diagram from Sparkfun, with this being what I ended up with:

```
#include <Joystick.h>

Joystick_ Joystick;

void setup() {
  // Initialize Button Pins
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 0;

// Last state of the button
int lastButtonState[11] = {0,0,0,0,0,0,0,0,0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index <= 10; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      Joystick.setButton(index, currentButtonState);
      lastButtonState[index] = currentButtonState;
    }
  }

  delay(10);
}

```

This is the original example code that I used:

```
// Simple example application that shows how to read four Arduino
// digital pins and map them to the USB Joystick library.
//
// Ground digital pins 9, 10, 11, and 12 to press the joystick
// buttons 0, 1, 2, and 3.
//
// NOTE: This sketch file is for use with Arduino Leonardo and
//       Arduino Micro only.
//
// by Matthew Heironimus
// 2015-11-20
//--------------------------------------------------------------------

#include <Joystick.h>

Joystick_ Joystick;

void setup() {
  // Initialize Button Pins
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);
  pinMode(11, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 9;

// Last state of the button
int lastButtonState[4] = {0,0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 4; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      Joystick.setButton(index, currentButtonState);
      lastButtonState[index] = currentButtonState;
    }
  }

  delay(50);
}

```

I started this project in late February/early March, but only got to the Arduino part recently. I've had my v1 working for a little over a month using this code, and I've been working on the v2 design (adding a whammy bar and repositioning the start and select buttons) since then. I only just got to the point where I need to change the code last week.

From the comments in the example and some trial and error, I figured out that "const int pinToButtonMap = 9" is the lowest-numbered pin that it will use, and "for (int index = 0; index \< 4; index++)" seems to determine the rest of the pins, so I changed 9 to 0, and "\< 4" to "\< 18" (the number of usable pins), and it kind of worked. Pins 0-10 and 14-16 now worked as button inputs, but button 14 (which would've been on pin 13, which doesn't exist on the Pro Micro) reads as constantly pressed, and pins A0-A3 (digital pins 18-21) don't read anything. If instead, I change it to "\< 19", "\< 20", etc. It just stops working completely, and if I change it to "\< 11" or "\<= 10" (my current code), all the pins from 0-10 work, and there are no phantom button presses

Also, I'm honestly not planning on learning any kind of real programming anytime soon. Maybe in the future, but for now, I just need enough to get this working with a 10k potentiometer (the same type that official Guitar Hero controllers use for their whammy bars) and possibly a few more button inputs (I might add a tilt sensor and maybe a D-pad in a future version)

# Answer
Beautiful work with the 3D-printed guitar! You have already spent a lot of time and effort with the physical design and construction of the controller, so I recommend you plan on spending some quality time with basic Arduino programming, including the basic pin layout for the Pro Micro and the basics of programming in the Arduino language (basically C++)

You can find all you need to know in the example programs that come with the Arduino IDE (File -\> Examples - 01.Basics) and with the many available tutorials (search for Arduino tutorial). Here's one that seems to be pretty clear https://www.youtube.com/watch?v=QO\_Jlz1qpDw

You'll also need to look at one of the many Arduino pinout diagrams for the Pro Micro, like this one https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

From the diagram, it appears you can use pins 2-10 and 16-21 for digital I/0 (for your buttons), but you'll need to use one of 10, 18-21 for your potentiometer input. So, as one other poster already noted, you should use an array of pin numbers and then read each pin by indexing into the array.

For the potentiometer interface, one of the supplied examples in '01.Basics' is the 'AnalogReadSerial' program, which should get you started. To use this program, connect the center pin of a potientiometer to pin 18(A0), and the other two to VCC & GND. Upload the program to the Pro Micro, and you should get some console printouts that vary when you change the potientiometer setting.

Make your programs very small to start with - think of them as disposable snippets that will later be incorporated into the final program. One snippet just for the potentiometer, and another snippet just for, say, 4 buttons that connect to pins 2, 9, 16 & 21 just to make sure your array indexing scheme works. Then when all is working, the snippets can be combined into a 'final' (nothing is ever really final in the Arduino world).

And lastly, use serial 'print' statements liberally for test & debug; they will save you no end of trouble & frustration. You can comment them out after all testing has been done, or just leave them in. In most projects the Serial.print statements don't take up enough time or memory to matter.

Welcome to the Arduino world! You'll love it!

Frank
> 1 votes

# Answer
It seems pins 11, 12 and 13 do not exist as input pins and pins 0 and 1 are used for RX/TX which you don't want to use neither probably.

So instead of using a `for` loop iterating over indices, you should create an array with pin numbers and use that instead, something like:

Create globally:

```
int input_pins = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, ... };

```

Use in `loop`:

```
for (int index = 0; index < sizeof(input_pins) / sizeof(int); index++)
{
    int currentButtonState = digitalRead(input_pins[index]);

```

You can use the same `for` to set the pin modes in the `setup`:

```
for (int index = 0; index < sizeof(input_pins) / sizeof(int); index++)
{
    pinMode(input_pins[index], INPUT_PULLUP);
}

```

`sizeof(input_pins) / sizeof(int)` will give the amount of items within the array. You can now easily change it depending on the pin numbers.

I suggest you learn a bit of coding to at least understand what you change, it will make your life much easier as you progress.

In case you want more pins beyond the actual existing pins, you need to use a multiplexer like 74HC595; there are plenty examples how to use this.
> 0 votes

---
Tags: button, potentiometer, arduino-pro-micro, digital, analog
---


title: Cannot compile F() macro with R"string"

text:
# Question
Title: Cannot compile F() macro with R"string"
I am trying to compile the following code:

```
logger.log_info(F(R"(some text here that may take
    multiple lines
    and here it is done.)"));

```

But the compiler exists with the following error:

> error: unterminated raw string

I am able to use either `R` or `F`, but not both together. **How should I be able to use them together?**

# Answer
> 5 votes
If you put:

```
    #define DO_NOTHING(s) (s)

    DO_NOTHING(R"xyz(Hello
    World)xyz")

```

you can see g++ choke on preprocessing the raw string literal in the macro invocation with the latest esp8266 board package as of writing (version 2.7.4). This comes with g++ 4.8.2 for xtensa.

```
    ~/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/xtensa-lx106-elf-g++ -E  donothing.h

```

You may need to adjust the command-line for your system. donothing.h is just the macro and invocation described above.

Result:

```
# 1 "donothing.h"
# 1 "<command-line>"
# 1 "donothing.h"

donothing.h:3:13: warning: missing terminating " character [enabled by default]
 DO_NOTHING(R"xyz(Hello
             ^
(R"xyz(Hello World)
donothing.h:4:10: warning: missing terminating " character [enabled by default]
 World)xyz")
          ^
      xyz")

```

This does not happen with g++ 9.3.0 on an amd64 Linux target.

As a workaround you can reconstruct (more or less) what the F() macro does with the following:

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

    void loop() {
      static const char pgm_str[] PROGMEM = (R"xyz(Hello
    World)xyz");

      Serial.println(FPSTR(pgm_str));
      delay(4000);
    }

```

---
Tags: esp8266, c++, c, string
---


# Question
Title: Where to store critical data in power outage situation on ESP8266
I want to store a counter that is always changing, but I want it to remain and be able to retrieve it on after a power loss.

It's only one long number data, but as it is always changing, I don't know where to store it to not over wear the memory space.

I'm aware that writing to much on ESP's EEPROM or SPIFFS would damage it. I've seen that post, but it doesn't help in my case.

The data to be saved is the volume of water pumped with a water pump during it's entire life.

Of course I could save it only once a while to reduce the number of writes, but I would lose some acccuracy.

# Answer
> 1 votes
If you worry about the maximum number of write cycles, you could write the data to an SD card or some FRAM connected to the ESP8266, or you could send the data to a (web) server (if you have access to one) using WiFi. The server can then store the data.

If you really care about the data, you could do both. Having a backup is the only protection against catastrophic failure.

# Answer
> 1 votes
A local solution would be to use *EERAM*. This is an EEPROM and an SRAM coupled together with some intelligent power management circuitry - writes get stored in SRAM until the power goes (or an instruction to save is sent) when the contents of SRAM get copied into EEPROM using the power stored in a large capacitor.

A good choice is the 47C16 (5V) or 47L16 (3.3V).

---
Tags: esp8266, eeprom, spiffs, littlefs
---


# Question
Title: Reading and Writing to a JSON File on the Desktop from Arduino?
I'm fairly new to Arduino. I'm working on a project where I'm making HTTP requests using a python code and this lets me read and write to a JSON file on my desktop. I have an Arduino with sensors that records values and I want to take those recorded values and update them to the JSON file on my desktop in real-time. I looked online and many suggested using some Arduino library, but it was only for reading. I'm still confused about reading and writing to the JSON file on my desktop. I appreciate any help to guide me in the right direction. Thank you.

# Answer
The Arduino cannot access files on a desktop computer.

However you can write software on your computer (you already use Python, so why not use that?) to accept information over Serial, process it, and store it in any way you like (including JSON), or return data from the computer to the Arduino if needed.
> 1 votes

---
Tags: arduino-ide, http, json
---


# Question
Title: Unreliable function of transistor, pump and ESP32
I have a 12 VDC pump, 8.5A, connected to a MOSFET transistor PSMN5R6-100PS,127.

The connection from the transistor to transformer, pump and a ESP32:

1 Gate --\> port to ESP32

2 Drain --\> (-) pump

3 Source --\> Gnd ESP32, (-) transformer

(+) transformer to (+) pump

This is, as I understand it, how it ought to work. But with this configuration it doesn't... But changing **3 Source --\> (-) transformer**, removing the Gnd connection to the ESP32, then it works. It, however, seems to be some kind of leakage in terms of current because the pump has a "clucking" sound, not fully activating, just making a sound. Sometimes it doesn't work at all, where a reset makes it work again. Any ideas how I can fix it reliably?

# Answer
As can be seen from the datasheet for the PSNB5R6 (Fig 7) at 3.3V the MOSFET is barely even beginning to switch on.

You need to select a more suitable MOSFET that switches on fully at a voltage well below 3.3V, such as the STP40NF04L.
> 2 votes

---
Tags: esp32, transistor
---


title: DIY CNC Machine Power Requirements

text:
# Question
Title: DIY CNC Machine Power Requirements
I want to make a CNC machine that uses 5 NEMA 17 rated for 2A and a RAMPS 1.4 to control it all. I have a power supply that can deliver 1.5A at 12V. Is it enough? I am worried that when all 5 motors are under load, the amperage will get distributed and there will be very low amperage per motor.

# Answer
Figuring out your current needs is simply a matter of adding everything up. If you have 5 2 amp motors, you'll need 5 x 2, or 10 amps just to drive the motors.

You should probably have at least 20% extra capacity, so I'd suggest having a 12V power supply that can put out at least 12A.

15A would be better.

The stiffer your power supply the less it will "bobble" as the load varies.
> 1 votes

---
Tags: arduino-mega, power, motor, stepper
---


title: Memory problem? dtostr() and strcat()

text:
# Question
Title: Memory problem? dtostr() and strcat()
I've been dealing with this for quite a while now and searching all over for answers.. I'm trying to put together two floats into a char\*. Separated by a ",". This is the code I'm working with.

```
#include <DHT.h>
#include <RH_ASK.h>
#include <SPI.h>

#define DHT_pin 10
#define DHT_type DHT11

DHT dht(DHT_pin, DHT_type);
RH_ASK rf_driver;

float temp;
float hum;

char ch_temp[6];
char ch_hum[6];
char msg_out[12] = "";

void setup() {
  Serial.begin (115200);
  dht.begin();
  if (rf_driver.init()) {
    Serial.println("Radio transmitter initiated..");
  }
  else {
    Serial.println("Radio transmitter failed to initiate..");
    delay(1000);
  }
}
void loop() {
  temp = dht.readTemperature();
  hum = dht.readHumidity();

  dtostrf(temp, 5, 2, ch_temp);
  dtostrf(hum, 5, 2, ch_hum);
  strcat(msg_out, ch_temp);
  strcat(msg_out, ",");
  strcat(msg_out, ch_hum);

  Serial.println(msg_out);
  rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
  rf_driver.waitPacketSent();
  Serial.print("data sent, package size: ");
  Serial.println(strlen(msg_out));
  delay(1000);

}

```

I have tried using different sizes of the char arrays, but it just goes crazy. This is the console output:

```
Radio transmitter initiated..
22.00,34.00
data sent, package size: 11
⸮⸮Radio transmitter initiated..
22.00,34.00
data sent, package size: 11

```

So on its way through the second loop it fails, restarts and then on its third way through it just gives up... What am I doing wrong? :( Really sad over this.

# Answer
If you remove the RF and sensor code, the sketch seems to work correctly when printing to the serial monitor. The first time you call `rf_driver.send()` in the loop, it works. The second time through the loop, and every time there after, it starts printing corrupted data. I don't have a definitive answer why this is happening, but I do have a way to "fix" it (or a "hack", if you prefer to call it that).

Using `memset()` to set the `msg_out` char array to all 0's **before** you use it seems to fix the problem. Here is a test sketch which is very similar to yours. I'm using some hard coded values for the sensor data because I don't have one of those sensors.

```
#include <RH_ASK.h>
#include <SPI.h>
RH_ASK rf_driver;

float temp;
float hum;

char ch_temp[6];
char ch_hum[6];
char msg_out[12] = "";

void setup() {
  Serial.begin (9600);
  if (rf_driver.init()) {
    Serial.println("Radio transmitter initiated..");
  }
  else {
    Serial.println("Radio transmitter failed to initiate..");
    delay(1000);
  }
}
void loop() {

  // Set the buffer contents to all 0's
  memset(msg_out, 0, sizeof(msg_out));

  temp = 12.345;
  hum = 67.890;

  dtostrf(temp, 5, 2, ch_temp);
  dtostrf(hum, 5, 2, ch_hum);
  strcat(msg_out, ch_temp);
  strcat(msg_out, ",");
  strcat(msg_out, ch_hum);

  Serial.println(msg_out);
  rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
  rf_driver.waitPacketSent();
  Serial.print("data sent, package size: ");
  Serial.println(strlen(msg_out));
  delay(1000);
}

```
> 2 votes

# Answer
Your sketch is running on borrowed memory.
Every time the loop function runs, the new text is concatenated with `strcat()` and the buffer `msg_out` is never reset. The first time 12 bytes are used, the second time 23 bytes, the third time 34, and so on.

The solution in the answer by @VE7JRO will fix that, but I prefer not to use `dtostrf()` and transmit binary data.

I see a few other problems as well:

* Why do you want to transmit readable ASCII text? Use binary data. Either float numbers or integers. For example an integer in 1/100 degrees.
* The RadioHead library uses a lot of memory. You can not use an other library that uses also a lot of memory.
* The value of '5' for dtostrf is the **minimal** width, so you better make those arrays for example 20 bytes. I prefer to put those arrays temporarily on the stack.
* The DHT11 is not accurate. If you upgrade to a better sensor with I2C, then you need more libraries (the Wire library and a sensor library), and you might run out of sram memory.
* When using the RadioHead library in default mode, it uses three pins (rxPin=11, txPin=12, pttPin=10). You better add a comment section to your sketch to explain that you should not use those pins. You have already a conflict at pin 10 for the DHT sensor and the pttPin.

---

The old and no longer supported VirtualWire library has some bugs, but it uses less memory than the RadioHead library. The RadioHead library is not optimized for Arduino boards like the Uno, Nano, Leonardo, and others. It even requires to `#include <SPI.h>` because that is often used with transceivers, even if the SPI bus is not used in RH\_ASK mode (thanks to @VE7JRO for explaining this in the comment below).

---

**The easiest way** to transmit more than one value is with an array.

```
float myData[2];
myData[0] = 23.456;
myData[1] = 68.0;
rf_driver.send((uint8_t *)myData, sizeof(myData));

```

The `sizeof()` is not a real function, it tells the compiler to fill in the size of that variable. Since a `float` is 4 bytes, you may also fill in the number 8 for the second parameter.

There are a number of solutions for the receiver. I like to use a pointer to the buffer, but perhaps it is easier to copy them to variables with `memcpy()`.

```
float myData[2];
if (driver.recv(buf, &buflen)) {
  if (buflen == sizeof(myData) {  // extra check
    memcpy((uint_8 *)myData, buf, sizeof(myData));
    Serial.println(myData[0]);
    Serial.println(myData[1]);
  }
}

```

When the receiver is also an Arduino board, then there should be no problem. When the receiver is something else, you might have to check if the byte-order is the same. The `float` variable of a Arduino is 100% IEEE compatible, but sometimes it is easier to use only integers.

**The most common way** is to use a `struct`. A `struct` is a package that can hold all sorts of data (integers, bytes, arrays, and so on). The receiver and the sender should have exactly the same definition for the `struct` of course.
> 2 votes

# Answer
I'm late to the party, but here goes:

`msg_out[]` is a global but it doesn't need to be. Move it's definition and initialization into loop(), the only function that uses it. Then it gets initialized at every entry to loop() rather than just once at program initialization. There's no need to clear the array; just zeroing the zero-th element of it initializes it for character-string use, and that is what your initializer now does (but only once).
> 1 votes

---
Tags: arduino-nano, memory-usage
---


# Question
Title: BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1
Arduino Uno R3

Windows 10

Bascom AVR

The ON is alright.

The LED flickers now and then.

The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.

Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this. The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.

So I hope you can use easy terms. Thank you.

# Answer
I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader. It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol. The arduinoisp.ino sketch also implements stk500v1. So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2. STK500v2 has been used in some of the larger arduino "Mega" boards.

So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud. If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO. If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.
> 1 votes

# Answer
Have you tried a different USB cable?

I was having trouble flashing and the cable turned out to be the issue.
> 0 votes

---
Tags: arduino-uno, avr
---


title: Timer with Webserver ESP8285

text:
# Question
Title: Timer with Webserver ESP8285
this is my first Project on an ESP. I found a Code for a coffee-grinder-timer, which is programmed for a ESP8266, but unfortunately meanwhile the Sonoff changed to the ESP8285 with internal Flash. I presume this is the reason for a memory problem. By default the times are according to the code 1000ms and 2000ms, but on the WebPage are the following times are displayed:

* Singleshot: 16711680ms
* Doubleshot: 807611680ms

Beside this problem I can't change these values by pressing the save-button. what is my mistake?

```
// Libraries
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <TTBOUNCE.h>
#include <EEPROM.h>
extern "C" {
#include "user_interface.h"
}

//======SERVER PART======================================================
const char* ssid     = "SSID";
const char* password = "password";
ESP8266WebServer server ( 80 );
char htmlResponse[3000];
//======LOKALER PART======================================================
os_timer_t myTimer;
bool tickOccured;
bool timerrunning;
int RelaisPin = 13;                 // GPIO13 Blaue LED auf dem Sonoff
TTBOUNCE b = TTBOUNCE(0);

int time_ss = 1000;
int time_ds = 2000;

void handleRoot() {

  snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
<html lang=\"en\">\
  <head>\
    <meta charset=\"utf-8\">\
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
  </head>\
  <body>\
          <h1>Zeiten für Singleshot und Doubleshot</h1>\
          <h3>Singleshot: %d% ms </h3>\
          <input type='text' name='date_ss' id='date_ss' size=2 autofocus> ms \
          <h3>Doubleshot: %d% ms</h3>\
          <input type='text' name='date_ds' id='date_ds' size=2 autofocus> ms \
          <div>\
          <br><button id=\"save_button\">Save</button>\
          </div>\
    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\
    <script>\
      var ds;\
      var ss;\
      $('#save_button').click(function(e){\
        e.preventDefault();\
        ss = $('#date_ss').val();\
        ds = $('#date_ds').val();\
        $.get('/save?ss=' + ss + '&ds=' + ds, function(data){\
          console.log(data);\
        });\
        location.reload();\
      });\
    </script>\
  </body>\
</html>",

time_ss,
time_ds
);

   server.send ( 200, "text/html", htmlResponse );

}

void handleSave() {
  if (server.arg("ss")!= ""){
    Serial.println("Singleshot: " + server.arg("ss"));
    time_ss = server.arg("ss").toInt();
    eeWriteInt(0, server.arg("ss").toInt());
  }
    if (server.arg("ds")!= ""){
    Serial.println("Doubleshot: " + server.arg("ds"));
    time_ds = server.arg("ds").toInt();
    eeWriteInt(4, server.arg("ds").toInt());
  }

}

// start of timerCallback
void timerCallback(void *pArg) {
Serial.println("Tick OccurredCB");
      tickOccured = true;
}

void setup() {
//======SERVER PART======================================================
  // Start serial
  Serial.begin(115200);
  delay(100);
WiFi.mode(WIFI_STA);
  // Connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  server.on ( "/", handleRoot );
  server.on ("/save", handleSave);

  server.begin();
  Serial.println ( "HTTP server started" );
//======LOKALER PART======================================================
  os_timer_setfn(&myTimer, timerCallback, NULL);
  pinMode(RelaisPin, OUTPUT);       // GPIO13 als Ausgang definieren
  b.attachClick(click);         //attach the click method to the click event
  b.attachDoubleClick(doubleClick);//attach the double click method to the double click event
  b.attachPress(press);        //attach the press method to the press event
  delay(50);
  digitalWrite(RelaisPin, HIGH);  // turn LED ON
  tickOccured = false;
  timerrunning = false;
   EEPROM.begin(8);  //Initialize EEPROM
   time_ss = eeGetInt(0);
   time_ds = eeGetInt(4);
}

void loop() {
//======SERVER PART======================================================
  server.handleClient();
//======LOKALER PART======================================================
  b.update();
  delay(10);

   if (tickOccured == true)
 {
    Serial.println("Timer ausgelaufen");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
 }

 yield();  // or delay(0);
}

void click(){
  if (!timerrunning)
  {
    Serial.println("Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ss, false);
    timerrunning = true;
  }
  else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void doubleClick(){
    if (!timerrunning)
  {
    Serial.println("DoubleClicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds, false);
    timerrunning = true;
  }
    else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void press(){
  if (!timerrunning)
  {
    Serial.println("long_Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds-time_ss, false);
    timerrunning = true;
  }
 else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

 void eeWriteInt(int pos, int val) {
    byte* p = (byte*) &val;
    EEPROM.write(pos, *p);
    EEPROM.write(pos + 1, *(p + 1));
    EEPROM.write(pos + 2, *(p + 2));
    EEPROM.write(pos + 3, *(p + 3));
    EEPROM.commit();
}

int eeGetInt(int pos) {
  int val;
  byte* p = (byte*) &val;
  *p        = EEPROM.read(pos);
  *(p + 1)  = EEPROM.read(pos + 1);
  *(p + 2)  = EEPROM.read(pos + 2);
  *(p + 3)  = EEPROM.read(pos + 3);
  return val;
}

```

# Answer
> 1 votes
At least one problem is this:

```
          <h3>Singleshot: %d% ms </h3>\

```

If you want a literal percent sign, you would need to double it, a form of escaping:

```
          <h3>Singleshot: %d%% ms </h3>\

```

It's not entirely clear how this implementation of snprintf handles %\<space\>, but experiments here show that it isn't being forgiving and merely interpreting it as %%.

In C and C++ and by proxy "arduino", adjacent string literals are concatenated at compile time into one logical string literal, so you can do that rather than \\, which you may find cleaner.

It should also be possible to just .print the chunks of your payload to the stream rather than to cobble together one large string as a payload.

---
Tags: esp8266
---


# Question
Title: Multiple external power sources and one Arduino
really noob question..

I am thinking of using a 12v power source and a 5v power source as an external power supply for my 5v relay (and some other stuff that I might add up to my project that will need 5V) and the 12v is for my 12V solenoids. Is it right to connect all ground wires to the ground of the Arduino? I am really sorry that I have to ask this question cause all tutorials I see online are only connecting one external power supply to their Arduino.

Any form of correction is highly appreciated. Thank you so much

# Answer
> 1 votes
Besides connecting all the grounds, a "good idea" whenever working with solenoids or magnetic (as opposed to solid state) relays is to add protection against inductive kickback, which can create really high voltages (hundreds of volts) when the current through an inductor changes suddenly. (The voltage is the product of the inductance and the rate-of-change of the current.) The protection is simple: Put a rectifier diode across each coil, with the arrow pointing to positive (reverse-biased). The rectifier has to handle a big spike of current as well as the high voltage, so use something like 1N4004. This protection will reduce the likelihood of spikes causing mysterious state changes in your circuits.

---
Tags: arduino-uno, arduino-mega, power
---


# Question
Title: Change/declare a constant in setup and use it in loop
I want to change or declare a constant in the `setup()` and then, I want to access it in the `loop()`.

I have searched a lot, but the only questions I found could be solved by declaring the constant in the beginning of the program. That doesn't work for me because I am using the Adafruit BMP388 and I can't use the pressure before `setup()`.

I also tried declaring the variable before `setup()` and changing it inside `setup()`, but it didn't change when I used it in `loop()`.

How can I solve this?

# Answer
> 0 votes
You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:

why not try something roughly like this (untested and incomplete)?

```
Adafruit_BMP3XX bmp;
float startPressure;
float difference;

void setup() {
  bmp.begin_I2C();
  startPressure = bmp.readPressure();
}

void loop() {
  difference = startPressure - bmp.readPressure();
}

```

Or, better:

```
Adafruit_BMP3XX bmp;

void setup() {
  bmp.begin_I2C();
}

void loop() {
  static const float startPressure = bmp.readPressure();
  static float difference;
  difference = startPressure - bmp.readPressure();
}

```

---
Tags: arduino-uno, c++, variables
---


# Question
Title: variable name standards, e.g best method to send motion_detect=true
I am working with some sensors and sending data to a public web server via http, I was thinking this server can be possibly used by more people to send their data and server displays a chart.

I was wondering if there is a IOT industry standard when sending certain type of data, so that in future I don't need to rename this or change documentation to be more compatible or more intuitive.

For example when sending a "motion detected" ping, do I go with `pir=true`, `pir=1`, `motion_detect=true` ?

Then for example when sending temperature, it would be much better `temp_celsius=30` then just `temp=30`.

It should also make developers job much easier if there is a certain standard. Is there one ?

# Answer
No, there is no "industry standard". You are free to choose what you like.

If you want to be completely generic you could choose to do something like:

```
p1name=Temperature&p1units=celcius&p1value=23.4&p2name=Humidity&p2units=%25&p2value=43.8

```

(`%25` is a `%` when URL encoded)

Or you could use:

```
p1=Temperature/Celcius/23.4&p2=Humidity/%25/43.8

```

That's just two examples. There is no end to how you could do it.
> 2 votes

# Answer
I don't think there is. It also kind of depends on how you are going to store the data.

I'd go with `motion=true` instead of `pir=true`, as it describes what you are detecting, instead of what sensor type you used. What if you decide to change the PIR sensor to a radar-based sensor. Now the variable name doesn't make sense.

Secondly, what happens if you add a second motion sensor somewhere else? I'd add something unique to the request. Something like a node-id. That way, you can differentiate between the two. Something like `?nodeid=1&motion=1`. You can that also add additional info like the battery voltage for that node; `?nodeid=1&motion=1&voltage=3.1`.

I don't think differentiating between C and F makes a lot of sense. But if it does you'd store this somewhere on the server, as it should never really change. Something like; the `temperature` value coming from `nodeid` 6, is the temperature in the "livingroom", and is specified in "C", and should be shown on a graph with Y-axis of "10 C" to "30 C".
> 2 votes

# Answer
Yes, there are systems designed to continuously receive such data and the data exchange is standardized, even some Units are standardized.

### OPC DA

An example is OPC Data Access for real time values. It seems you want to build a graph, so OPC Historical Data Access is more what you're looking for.

One would set up the data points on the server side once, i.e. configure the type and unit that you're gonna receive on that "channel" or "port" or whatever you call it.

Unfortunately, OPC DA and OPC HDA use XML and building XML is not trivial. It's not very suitable for IoT devices.

*Lessons learned*: configure the unit on server side and let the client send data only. Do not use XML for data transfer.

### OPC UA

Then there is OPC Unified Architecture. They also learned their lesson and removed XML and added security. They now use a binary protocol. The specification is more than 1000 pages, so understanding it will be difficult and is in fact so difficult that even OPC UA implementations of different companies do not work together well.

OPC UA defines 25 data types and ways of defining other data types.

The address space in OPC UA is hierarchical - and probably a device can exist in multiple hierarchies, e.g. physical topology like floors and rooms or logical topology that fits into the structure of the machine.

*Lessons learned*: make the protocol simple and think about security, i.e. if you want to do URL encoding (`GET`), then use HTTP**S** at least. AFAIK, devices ESP32 support encryption, so it's no longer a problem for tiny devices. People will use very strange data types, like 18 bit integers. Also, do not only provide a flat list of devices, but let them arrange stuff as needed.

### MQTT and NodeRed

Now these were quite heavy protocols and models driven by companies. Of course there are also protocols better suited for IoT, like MQTT. MQTT is widely known and uses the also well known Node Red software for handling it. You can define workflows how the data should be handled, converted, stored and whether alarms shall be triggered above or below thresholds.

They already think of connection loss, reconnect and how to send all the data that was already recorded but could not be sent.

*Lessons learned*: People want more than just data storage and a graphics.

## Units

openHAB tries to come up with a List of units. I am a radio amateur. I am measuring electromagnetic fields. I am still missing

* SWR (standing wave ratio)
* dBu (dB µW)
* dBc (dB relative to the strongest signal)
* dBV, dBmV (dB for Volts instead of Watts)

### Personal experience

I was working for a company that made software for industry. There are devices that send a measurement value every 100 ms. Let's say this is a simple temperature value of just 1 byte, that's still 315'000'000 records per year.

How do you display such data? On a Full HD screen you would still need to combine 150'000 measurement values on a single column of pixels.

*Lessons learned*: you need sophisticated data crunching skills to generate the graphics. The users probably want some control over the time span they are viewing. They want zooming and panning.

### Conclusion

> I was thinking this server can be possibly used by more people to send their data and server displays a chart.

IMHO, sorry, it's hardly needed. People do not want to send their data to a random HTTP server. Some want to set it up at home only, so that no data ever reaches the Internet. Some people want to do more than just displaying a grpahics (especially alarms). MQTT and Node Red runs locally, on a Raspberry, on a server and even in the cloud, whatever you want.

You do not only need `pir=true, pir=1, motion_detect=true`, you also need

* an ID for the device,
* a timestamp when the data was recorded
* potentially a way to send bulk data after the server was offline for an hour of maintenance
* a system for units
* encryption

That's quite an effort. Node Red has \> 4000 commits.
> 2 votes

---
Tags: http, variables, iot, coding-standards
---


title: Running an Arduino without the computer

text:
# Question
Title: Running an Arduino without the computer
I am having trouble getting my Arduino Uno to run my code when I disconnect it from my computer.

I have a 9V battery to power it and it is turning on, however, it is not doing anything at all. What can I do to make it run the code when it is using the battery and not connected to the computer?

# Answer
> 1 votes
Use a fresh 9V battery, or better, a proper power supply or some AA batteries in series, just to make sure the power supply isn't the problem.

BTW on some Arduinos (though probably not yours) it often pays off to check if there is a `while (!Serial);` or some such in the code. If there is, it is blocking code execution until the USB is connected and the serial monitor is opened.

# Answer
> 0 votes
And Arduino should run the last program installed to it when you apply power to the barrel connector. IT powers up, does a reset, and begins executing the sketch that's installed.

As others have mentioned, the small rectangular 9V batteries have very low current output and total power storage. You will run a fresh 9V battery down to nothing in a short time with just an Arduino, and with other components also drawing power it will happen even faster. I suggest getting a ≥ 1 amp 7V - 9V DC transformer and plugging that into the barrel connector.

You need to tell us what components you are using in your project and their current requirements.

If you are just running a "bare" arduino and very little else then you should get like 24 hours out of a fresh 9V battery, as mentioned by @ocrdu

---
Tags: arduino-uno
---


title: use Nodemcu to program Attiny85

text:
# Question
Title: use Nodemcu to program Attiny85
I have a dev board for my attiny85. when connecting it to the computer I get "unknown USB device(device descriptor request failed)" although I have the needed drivers, so I thought of trying using my nodemcu. Tried connecting the SPI (to the nodemcu hmiso;hmosi;hcslk;hcs)and upload using "arduino as ISP" and compitable settings(https://www.hackster.io/arjun/programming-attiny85-with-arduino-uno-afb829). pressing "burn bootloadre" using this way gives me errors:

"avrdude: stk500\_recv(): programmer is not responding

avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x03

......

avrdude: stk500\_recv(): programmer is not responding

avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x03

Error while burning bootloader."

\***EDIT:

After changing a line(#define USE\_OLD\_STYLE\_WIRING) in ArduinoISP (from example) the error code changed a bit and it shows up much faster:

"Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ATtiny25/45/85, ATtiny85, Internal 8 MHz"

avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x04

avrdude: stk500\_getsync() attempt 2 of 10: not in sync: resp=0x30

avrdude: stk500\_getsync() attempt 3 of 10: not in sync: resp=0x61

avrdude: stk500\_getsync() attempt 4 of 10: not in sync: resp=0x67

avrdude: stk500\_getsync() attempt 5 of 10: not in sync: resp=0xc1

avrdude: stk500\_getsync() attempt 6 of 10: not in sync: resp=0xc4

avrdude: stk500\_getsync() attempt 7 of 10: not in sync: resp=0xc5

avrdude: stk500\_getsync() attempt 8 of 10: not in sync: resp=0xa1

avrdude: stk500\_getsync() attempt 9 of 10: not in sync: resp=0xcc

avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0xe2

Error while burning bootloader."

Any help on how to use nodemcu to program attiny85 will be great thanks

# Answer
> 3 votes
# Modifications to the ArduinoISP.ino sketch

I made the following changes to the ArduinoISP.ino file it exists in IDE version 1.8.13, and uploaded it to the NodeMCU board.

In short, I commented out (by way of #if 0) the heartbeat, err, etc LED related stuff. Not doing this causes the board to reset for reasons that would probably be apparent if I researched it, but I haven't and since I don't plan on using the LEDs and that you may not, I figured I would get this to you sooner.

I changed RESET to be SS which on NodeMCU is D8.

## Why LED related code causes resets

... Out of curiosity I just went and looked at the ESP-12F and ESP8266EX datasheets. GPIO7, GPIO8, GPIO9 all go to the ESP-12F's SPI flash (program storage), so ostensibly monkeying with them interferes with the modules ability to keep executing from the SPI flash. They're not routed to NodeMCU pins, probably for that reason. So there's the answer to that.

## Differences

```
@@ -70,7 +70,7 @@
 // The standard pin configuration.
 #ifndef ARDUINO_HOODLOADER2

-#define RESET     10 // Use pin 10 to reset the target rather than SS
+#define RESET     SS // Use pin 10 to reset the target rather than SS
 #define LED_HB    9
 #define LED_ERR   8
 #define LED_PMODE 7
@@ -216,15 +216,17 @@

 #endif

 void setup() {

   SERIAL.begin(BAUDRATE);

+#if 0
   pinMode(LED_PMODE, OUTPUT);
   pulse(LED_PMODE, 2);
   pinMode(LED_ERR, OUTPUT);
   pulse(LED_ERR, 2);
   pinMode(LED_HB, OUTPUT);
   pulse(LED_HB, 2);
+#endif

 }

@@ -276,6 +278,7 @@
 }

 void loop(void) {
+#if 0
   // is pmode active?
   if (pmode) {
     digitalWrite(LED_PMODE, HIGH);
@@ -291,6 +294,7 @@

   // light the heartbeat LED
   heartbeat();
+#endif
   if (SERIAL.available()) {
     avrisp();
   }

```

# NodeMCU to ATTiny85 ISP Wiring

The board is wired to the ATTiny85 as follows:

```
NODEMCU 3.3V -> ATTINY85 PIN 8
NODEMCU GND  -> ATTINY85 PIN 4
NODEMCU D5   -> ATTINY85 PIN 7
NODEMCU D6   -> ATTINY85 PIN 6
NODEMCU D7   -> ATTINY85 PIN 5
NODEMCU D8   -> ATTINY85 PIN 1

```

On the NodeMCU you'll find all 6 of these together on the right.

# Verifying AVRDUDE functioning

avrdude -P /dev/ttyUSB0 -c stk500v1 -b 19200 -p attiny85

```

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

avrdude: Device signature = 0x1e930b (probably t85)

avrdude: safemode: Fuses OK (E:FF, H:DF, L:71)

avrdude done.  Thank you.

```

I've been playing with this chip, so don't be surprised that I don't have the same fuse values you have.

---
Tags: nodemcu, attiny
---


# Question
Title: utility/spi_com.h error when compiling Marlin for Arduino mega with Ramps 1.4
I am using win 8.1 and trying to load Marlin 2.0.x onto Arduino Mega with an attached Ramps 1.4 board fitted with 3 8825 Drivers. Unfortunately everytime I try to compile It concludes with the following error. Can anyone please help.

```
Alternatives for utility/spi_com.h:
[]ResolveLibrary(utility/spi_com.h)  -> candidates: []In file included from C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.cpp:23:0:C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.h:28:12: fatal error: utility/spi_com.h:
No such file or directory   #include <utility/spi_com.h>

compilation terminated.
Using library SPI at version 1.0 in folder: C:\Users\Dad\Downloads\arduino-1.8.13-windows\arduino-1.8.13\hardware\arduino\avr\libraries\SPI
exit status 1
Error compiling for board Arduino Mega or Mega 2560.

```

# Answer
> trying to load Marlin 2.0.x onto Arduino Mega

I have no specific knowledge of Marlin.

For the moment, I'm ignoring the fact that it seems to be looking for STM32 files which would seem to play no role on an Arduino Mega.

I cloned the Marlin github repo and found no mention of a file "MarlinSPI.h" in the 2.0.x branch. There is however a MarlinSPI.h in tag 1.1.9.1

You appear to be working with the code for the wrong version (or branch) of Marlin.
> 2 votes

---
Tags: compilation-errors
---


title: Powering a system using batteries

text:
# Question
Title: Powering a system using batteries
I made an arduino nano IR sensor based auto liquid dispenser. Currently it is being powered by a 12V 2 amps adapter. The 12v adapter is connected to a LM2596 DC to DC buck converter which converts the 12V to 5V and powers the arduino, IR sensor and a regular green LED. Also I am using a RO valve solenoid (rated upto 24V DC) which is being powered by the 12V adapter. So whenever the IR sensor is triggered, the DC motor (5V 200mA) and solenoid (12V 300-500mA) are turned on for 3 seconds.

Now, I intend to power this system via batteries. I am considering the following 3 options.

a.) Lithium batteries in series (4 of 3.7V batteries). But again here I believe things would be complex as I have to make a BMS and charger for this. Is anything available off the shelf so that I can directly integrate the battery and charger with my existing system ?

b.) Connect 8 AAA batteries in series to get 12V. But how long would these batteries last for my application ?

c.) Connect 2 9V batteries in series. Again, can you guys please tell me how long these may last in the system.

Arduino nano I believe consumes 20mA and the IR sensor probably around another 10- 20mA. If it wasnt for the solenoid, I was considering connecting a mobile power bank to power the system.

# Answer
I think you should go with 3 lithium batteries in series and for proper balance charging of batteries, you can use an off the shell 3s lithium charging circuit like this here.So you will get 4.2\*3 = 12.6V on full charge and on full discharge you will get 3.7\*3=11.1v out of the battery.

So still I think your pump motor would work on 11v and ther are chances that your solanoid also work on 11v it will just draw more current then usual.
> 1 votes

# Answer
Consider using a 12V sealed cell lead-acid battery. Those are fairly cheap and easy to find in a wide variety of capacities, and chargers are also simple and easy to find.

A car battery would power your system approximately forever, since they have such huge capacity.

Figuring out how long a given type of battery will last is a simple question of math. Figure out the average current draw of your entire project, in milliamps. (You need to include the power consumed by your voltage regulator. The linear regulators built into Arduinos are quite inefficient, and work by dissipating excess voltage as heat.)

The total power of a battery is expressed in milliamp/hours. (where 1 milliamp/hour is a milliamp of power drawn for a full hour.) If you your system draws 2 amps, or 2000 milliamps average current, and your battery is rated for 2000 mAh, or 2 amp/hours, the battery will last 1 hour.

For battery-powered systems you should think about skipping the built-in linear regulator in your Arduino and instead using a switching regulator and providing regulated 5V directly to the board. Switching regulators can run at 90%+ efficiency, compared to something like 40% - 50% efficiency for linear regulators (I don't have a specific efficiency figure for linear regulators on hand, and it depends on input voltage compared to output voltage. The 40% - 50% number is an educated guess.)
> 1 votes

---
Tags: arduino-nano, power, battery
---


# Question
Title: Generate 1khz square signal with Arduino Mega
I want to generate a 1khz square signal with an Arduino Mega.

I have read the MCU contains several timers. What i want to do is to configure one of this timers.

My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ? Look at my code: i need to write a line in ISR(TIMER1\_OVF\_vect). Some MCU can do that but i did not find any information about it on documentation. (Some pins are connected on timer outputs, by hardware conception).

My second question is: What is wrong on my calculation on my code ? I want 1khz and i get 990Hz

Here is what i've done:

* Arduino Mega runs at 16Mhz = 16000Khz
* I have set a /8 prescaler, so timer's frequency is 8000Khz
* The frequency should by divide by two because i have 2 states (HIGH and LOW): 4000Khz
* The interupt is fired when the counter reach 65536. So if i load 65536-1000 in TCNT1, the timer should count 1000 times in order to fire the interupt. So my frequency is 4000khz/1000 = 1khz.

What is wrong ?

Thanks a lot

```
void setup() {
  pinMode(14,OUTPUT);

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 65536 - 1000;
  TCCR1B |= (1 << CS11);    // Prescaler clock / 8
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = 65536 - 1000;
  digitalWrite(14, digitalRead(14) ^ 1);
}

void loop() {

}

```

# Answer
As explained in the previous answer, you forgot to account for the time taken by the CPU to handle the interrupt prologue. As a general rule, if you want consistent timing, you should *never* reset the timer by software after the initialization.

If you want to run the timer in normal mode, and use it to schedule interrupts at a period that is not the timer's own period, it is possible, but you should not use the overflow interrupt for this purpose. You should instead use any of the “compare match” interrupts, and adjust the compare register in the IRS in order to schedule the next interrupt. For example:

```
void setup() {
    pinMode(14,OUTPUT);

    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS11);    // clock @ F_CPU/8
    TCNT1  = 0;            // clear timer
    OCR1A  = 1000;         // first COMPA match in 1000 cycles
    TIFR1  = _BV(OCF1A);   // clear interrupt flag
    TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
}

ISR(TIMER1_COMPA_vect) {
    OCR1A += 1000;      // schedule next interrupt
    PINJ   = _BV(PJ1);  // toggle PJ1 = digital 14
}

```

Note that the line `OCR1A += 1000;` can cause a wrap around, but this is no problem, as the addition wraps around in exactly the same way as the timer itself.

The advantage of this technique is that you can schedule up to three different tasks, having different periods, with only one timer. And you can even schedule tasks in a non-periodic fashion.

That being said, if you do not need the timer for anything else other than scheduling a single periodic task (or up to four tasks sharing the same period), then a better solution is to let the timer handle the period all by itself. Configure the timer in mode 12 or 14 (CTC or fast PWM, with TOP = ICR1), and set the period with `ICR1 = 999;`. Then the ISR is reduced to:

```
ISR(TIMER1_COMPA_vect) { PINJ = _BV(PJ1); }

```

and you save a few cycles. This would be my preferred solution if I absolutely had to output the signal on pin 14.

Note that this solution should give you the right *average* frequency, but you will still have some jitter, because the interrupt can occasionally be delayed by other interrupts. If you are free to choose the output pin, then the best solution is to let the timer handle the PWM generation all by itself. Set the timer to any PWM mode (fast PWM is the simplest) and use one of the waveform generators in order to generate the PWM signal. Only the PWM-capable pins (those marked with a “~” symbol) can be used this way. For example, Timer 1 can output to pins 11 (OC1A), 12 (OC1B) and 13 (OC1C).

**Edit** answering the question:

> what is the goal of `TIFR1 = _BV(OCF1A); // clear interrupt flag`?

Whenever the timer value matches the contents of the compare register `OCR1A`, the interrupt flag `OCF1A` (Output Compare Flag of timer 1, channel A) is raised. This flag controls the interrupt request when the `OCIE1A` bit (Output Compare Interrupt Enable 1A) is set. The flag is automatically cleared when the ISR runs, and can be manually cleared by writing a logic 1 to it (yes, it is kind of backwards).

It is quite likely that the flag raises early in the start process, while the Arduino library is initializing. If the flag is up when you enable the interrupt, an interrupt request is immediately triggered. In order to avoid that, the common practice is to clear the flag before enabling the interrupt.
> 3 votes

# Answer
> My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ?

Yes. It's called PWM with a 50% duty cycle.

You need to read up on **19. Output Compare Modulator (OCM1C0A)** in the datasheet.

> My second question is: What is wrong on my calculation on my code ? I want 1khz and i get 990Hz

You have to take into account the number of CPU cycles it takes to start executing your ISR. There's a short bit of code *before* your code is run that preserves any used registers on the stack and allocates any room needed for local variables. That takes time, and must be calculated into your timing factor.
> 4 votes

---
Tags: timers, frequency
---


title: Onboard led HIGH and LOW seems reversed

text:
# Question
Title: Onboard led HIGH and LOW seems reversed
On an `ESP32` board I am trying this simple code to control the onboard led.

But if I set it to `HIGH`, led is **OFF**, if I set it to `LOW`, led is **ON** (fully bright). What could cause this ?

The board has one red and one blue leds, the blue one is the one that can be controlled.

```
#define onboard_led 2

void setup() {
  pinMode(onboard_led, OUTPUT);
}

void loop() {
    digitalWrite(onboard_led, HIGH);
    // digitalWrite(onboard_led, LOW);
}

```

**Edit:** it was a board like this ("Geekcreit" I think):

# Answer
> 4 votes
As this image from Okdo Page on LED Driving shows, there are two ways to drive an LED from a GPIO output pin:

In the Active HIGH case, a HIGH output on the GPIO will turn the LED on since that will source current out of the pin and through the LED into ground.

In the Active LOW case, a LOW output on the GPIO will sink current from the +V supply into the pin.

In your case the LED is hooked up in the Active LOW configuration and so to turn it ON you must set the pin to LOW.

I'll add that these ESP32 boards are made by many different manufacturers and they are not all identical.

---
Tags: led, pins, esp32, debugging, digitalwrite
---


# Question
Title: Input state is stuck HIGH when function called using input also uses same input to call another function
I'm writing a choose-your-own-adventure style project for a class project. My Arduino Uno is set up with a 16-digit LCD display and two pushbuttons with pulldown resistors. I'm wanting each function to display text on the LCD and then take two user inputs, Yes or No, from the pushbuttons, and then call another function respective of which input is pressed. Each successive function will also take the two inputs to then call the next function in the series, and so on.

My issue is that after the first time a pushbutton is pressed, its state does not change. When `question1()` is called, and the user presses `button1`, `question2` is called. However, the function runs and never waits for user input, and `question4` is called right away because the state of `button1` seemingly stays `HIGH` after the first time it is pressed.

What am I missing? Is there a better way to be gathering the user input? My pushbuttons are properly wired with the resistor pulling down to ground so my issue must be with my code.

Thanks in advance for any help.

```
void loop()
{
  question1();
}

void question1()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q1 == false)
  {
    text1();
  }

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q2 == false)
  {
    text2();
  }

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

```

# Answer
There needs to be a `delay()` after the button state is read to allow time for it to return `LOW`, dumba\**.

You already have enough `delay()` in your `textN()` functions, just check the button state *after* calling that function, not before. Code should be as follows:

```
void loop()
{
  question1();
}

void question1()
{
  if (q1 == false)
  {
    text1();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  if (q2 == false)
  {
    text2();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

```

This solves the issue completely.
> 2 votes

---
Tags: button, input, loop, functions
---


title: Use Android on Arduino TFT

text:
# Question
Title: Use Android on Arduino TFT
I don't know whether this is possible or not but is there any way that I can run something similar to Android on a normal TFT. I want to make complex graphics but can't program those complex programs using the Adafruit TFT library.

Arduino Mega 2560 with Elegoo TFT 2.8"

# Answer
> 2 votes
No. Not even remotely. Android runs on a powerful computer not a tiny embedded microcontroller.

---
Tags: arduino-mega, programming, display, android, tft
---


# Question
Title: Pass Color to a function without using a specific Adafruit_NeoPixel
I'm initializing my strips as an array:

```
// Declare NeoPixel strip array:
Adafruit_NeoPixel strip[] = {
  Adafruit_NeoPixel(LED_COUNT[0], LED_PIN[0], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[1], LED_PIN[1], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[2], LED_PIN[2], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[3], LED_PIN[3], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[4], LED_PIN[4], NEO_RGBW + NEO_KHZ800)
};

```

and when I pass Color to a function, I'm arbitrarily using my first strip to create the Color:

```
  everyother( strip[0].Color( 0, 255, 0), strip[0].Color( 255, 0, 0), 500);

```

but in the subroutine I use those colors to set pixels to every strip of the array in a loop:

```
// set every other color to color1 or color2
void everyother( uint32_t color1, uint32_t color2, int wait) {
  for(int k=0; k<NUM_STRIPS; k++) {
    for( int j=0; j<LED_COUNT[k]; j++) {
      if( j%2 == 0) strip[k].setPixelColor(j, color1);
      else strip[k].setPixelColor(j, color2);
    }
  }
  for(int k=0; k<NUM_STRIPS; k++) strip[k].show();
  delay(wait);
}

```

Is there another way to define Color that isn't using a real Adafruit\_NeoPixel? Yes, it works this way but it feels sloppy.

# Answer
> 2 votes
Looking at the library at https://github.com/adafruit/Adafruit\_NeoPixel/blob/master/Adafruit\_NeoPixel.h, you can see that the Color method is static (see line 307):

```
static uint32_t   Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;

```

This means instead of

```
strip[0].Color( 0, 255, 0)

```

You can use:

```
Adafruit_NeoPixel::Color( 0, 255, 0)

```

Your call to `everyother` will be:

```
everyother(Adafruit_NeoPixel::Color( 0, 255, 0),
           Adafruit_NeoPixel::Color( 255, 0, 0),
           500);

```

And since `everyother` is now not a good name, you can think of a better one, e.g. `fillLeds` (always start a method name with a verb).

Offtopic:

* A subroutine is barely used anymore, I think the last time I heard it, is from the Basic programming language
* A function is now used instead
* But when a function is inside a class, it's not called a function, but called method.

---
Tags: arduino-uno, programming, adafruit, neopixel, led-strip
---


title: TFMini Sensors with Arduino

text:
# Question
Title: TFMini Sensors with Arduino
I have three TFMini sensors I need all of them to detect. I only got one to work , pins 4,5 . My info in coding is basic . I really appreciate your help . Thanks in advance.

I think the problem is with Library I can't add TFMini\_1.

Here is my code,

```
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfmini;
TFMini tfmini1;

//Declaring variables and constants
TFMini TFFront;
TFMini TFRight;
TFMini TFLeft;
SoftwareSerial SerialTFMini (4,5);    //(RX, TX)
SoftwareSerial SerialTFMini_1 (6,7);    //(RX, TX)
SoftwareSerial SerialTFMini_2(8,9);     //(RX, TX)

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if(SerialTFMini.available())

  {
    // Serial.println( "tfmini serial available" );
    rx[i] = SerialTFMini.read();

    if(rx[0] != 0x59) {
      i = 0;
    } else if(i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if(i == 8) {
      for(j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if(rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else
    {
      i++;
    }
  }
}

       //Threshold distance in "cm"; speak only when any object is nearer than this distance

void setup()
{

  //Initializing Baud Rates
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  SerialTFMini.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
tfmini.begin(&SerialTFMini);
}

void loop()
{
   int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while(!distance) {
    getTFminiData(&distance, &strength);
    if(distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
   }

delay(100);

}

```

# Answer
First: Why are you including, declaring and initializing the library's tfmini object, if you then don't use it for reading the sensor?

Your problem will be, that you can only listen to exactly 1 `SoftwareSerial` interface at a time. If you listen to the first interface and the sensor on the second interface is sending something, you will miss that data.

I suggest, you switch the Uno for a board with more hardware Serial interfaces (which work via hardware, thus can work in parallel). The Arduino Mega for example has a total of 4 hardware Serial interfaces.

Though you might get away with the Uno when working with the external trigger mode. The TFMini library has an example named `SingleReading`. It sets the `SingleScanMode` in `setup()`. Then it issues an external trigger and then reads the sensor. I suggest trying the following: In your code you initiate all 3 TFMini objects with their respective `SoftwareSerial` object. Then in `loop()` you go through these 3 items, first calling `listen()` on the corresponding `SoftwareSerial` object. Then you issue the external trigger on the corresponding `TFMini` object and read the data from it. Then you go to the next `SoftwareSerial` interface and call `listen()` on it, and so on. The idea is, that with an external trigger you can control, when you will get a valid data frame. I'm not sure, if the sensor will also send some data between the triggers, but that data should just be discarded without any problem.

Note: I cannot test this idea, because I don't have the corresponding hardware. You will have to test that yourself.
> 0 votes

---
Tags: arduino-uno, programming, sensors, c++
---


# Question
Title: 2 SPI Slaves with 2 different SPI modes on one Arduino Mega
I am working on a project where I read 8 MAX31856 thermocouple sensors using the Adafruit Library. This works just fine and prints the read outs to serial.

I want to also save the readings to a microSD card. And this is where I hit a snag.

I am trying to use the `SdFat.h` library. I can loop through my MAX31856 thermocouples, and write once to my SD card, but after that it hangs the SPI bus.

the MAX31856 works on SPI\_MODE1 (as per Adafruit Library) and the microSD card works on SPI\_MODE0, I believe. I am trying to switch SPI bus modes before and after writing to the SD card but I think there is something wrong after first successful write to the SD card. After the first loop iteration, it seems like all data is basically noise on the SPI bus.

I am using the Adafruit ADA254 microSD breakout Board, which has a card detect pin, so I first check to see if an SD card is inserted, and then write to the file.

**Question:** Is there another or better way to switch SPI\_MODES on each loop? is there anything more I need to consider so I end up back to SPI\_MODE1 appropriately for the MAX31856 thermocouples?

Below is the pertinent code for what I have going on...

```
void setup(){
   int sdCard = 36;
   char filename[10] = "test.txt";
}

void loop(){
....code to read thermocouples ...

///THEN THIS

  //lets confirm SD card is still in socket before writing
  CardDetect = digitalRead(37);
  if(CardDetect == HIGH){

     SPI.setDataMode(SPI_MODE0);
     SPI.setClockDivider(SPI_CLOCK_DIV4);
     SPI.setBitOrder(LSBFIRST);
     digitalWrite(sdCard, LOW);
     sd.begin(sdCard, SD_SCK_MHZ(1));
    //LETS START SAVING DATA
          myFile.open(filename, O_WRONLY | O_CREAT | O_EXCL);
          myFile.write(now.unixtime());
          myFile.write(",");
            for(int i = 0; i<8; i++){
              myFile.print(TEMP[i]);
              myFile.write(",");
            }
          myFile.println();
          myFile.close();
          digitalWrite(sdCard, HIGH);
          SPI.setDataMode(SPI_MODE1);
          SPI.setClockDivider(SPI_CLOCK_DIV16);
          SPI.setBitOrder(MSBFIRST);
          delay(200);
    }

}

```

# Answer
> 2 votes
For anyone who has a similar issue with the SPI Bus, `SdFat` library has a Software SPI option built in (example here).

You need to modify your `SdFat/SdFatConfig.h` file, but that is minimal. Once you have the microSD card module on a separate bus, it will not corrupt the main SPI Bus.

Switching the SD Card module to it's own bus rectified the issue. Keep in mind that Software SPI comes with a speed penalty.

---
Tags: spi, sd-card
---


# Question
Title: MKR ZERO is not detected in IDE / MKR ZERO not showing up in windows 8.1/
I m connect it with my IDE software and its work perfectly yesterday, but today morning I'm connected it to software to upload another sketch but its didn't detect the port and the charge led is not on yesterday but today is on. I tried every resolution which is given on website but its didn't work. please help me through this I'm new to this board.

# Answer
> 0 votes
A few possibilities come to mind:

1. Your USB cable is bad. Try a known good one.
2. Your USB port has failed. Try a different port or try plugging something else into this one to verify that it's still OK.
3. Your MKR ZERO has become damaged somehow.

---
Tags: arduino-ide, windows, mkrzero
---


# Question
Title: How to use an Arduino Speaker module with DFPlayer Mini?
I've bought an Arduino speaker module. How should I connect the module, if I want to use it with DFPlayer Mini? The problem is that the speaker module has 3 pins: `GND`, `VCC`, and `IN`; though the DFPlayer Mini has 2 pins for connecting a speaker: `SPEAKER +` and `SPEAKER -`.

# Answer
> 3 votes
The DFPlayer already has an amplifier on it, so you can connect the speaker directly.

You can just leave out the board you bought from AliExpress, and only use the speaker.

---
Tags: speaker
---


# Question
Title: How can we know the status of the DC Motor whether it is ON or OFF
A DC motor is operated using an L298n driver and Arduino UNO. How can I get to know whether the Motor is ON or OFF? Using a code in Arduino.

# Answer
Unfortunately, the L298N does not return a status, so you are going to have to add sensors to detect motor movement.

Here are a few options you can try:

* Current sense. Add a small resistor to the output of the L298N and measure the voltage differential across that resistor. If there is current being supplied to the motor then you will have a voltage differential.
* Rotation sensor. This can be in the form of a quadrature encoder wheel, tooth sensor or Hall effect sensor detecting a magnet on the shaft. If you see pulses from the sensor then you know the motor is spinning.
* Optical sensor. A camera system or other optical sensor to detect motor movement. Probably too complex for a simple application. There are however off the shelf sensors that will turn on an output if they see movement in their field of view. Alternatively you could use a PIR sensor from a home alarm system if the movement is course enough.
> 1 votes

# Answer
This may be too simple, but for completeness: You *can* read back the state of the output bit, in case your code doesn't save its current state. That will tell you if the motor is literally "on" or "off". Not rotating despite being "on" is another matter; an error.

If you need error detection then you need additional hardware support. Some possibilities:

* Sense rotation with a cam and a micro-switch or an optical sensor and a slotted disk;
* Sense the motor current - a stalled motor will draw a high current;
* Sense vibration in the motor platform;
* (apply imagination here... ;-)
> 0 votes

---
Tags: arduino-uno, c++, motor, raspberrypi, l298n
---


# Question
Title: Arduino sketch uses too much memory storage space?
I've never used arduino before but am using one for a school project. I am using an arduino leonardo and I've uploaded the sample code below

```
#include "Adafruit_CCS811.h"
Adafruit_CCS811 ccs;

void setup() {
    Serial.begin(9600);
    Serial.println("CCS811 test");
    if(!ccs.begin()){
        Serial.println("Failed to start sensor! Please check your wiring.");
        while(1);
    }

    //calibrate temperature sensor
    while(!ccs.available());
    float temp = ccs.calculateTemperature();
    ccs.setTempOffset(temp - 25.0);
}

void loop() {
    if(ccs.available()){
        float temp = ccs.calculateTemperature();
        if(!ccs.readData()){
            Serial.print("CO2: ");
            Serial.print(ccs.geteCO2());
            Serial.print("ppm, TVOC: ");
            Serial.print(ccs.getTVOC());
            Serial.print("ppb Temp:");
            Serial.println(temp);
        } else {
            Serial.println("ERROR!");
            while(1);
        }
    }
    delay(500);
}

```

But when I upload it, all I see a message that states

```
Sketch uses 8830 bytes (30%) of program storage space. Maximum is 28672 bytes.
Global variables use 487 bytes (19%) of dynamic memory, leaving 2073 bytes for local variables. Maximum is 2560 bytes.

```

Does this mean there is not enough storage in my computer or is there not enough space in the arduino? This arduino was given to me second hand.

I'm unsure if it is now appropriate to be able to see results show up on the serial monitor? Because nothing is showing up.

# Answer
There is no problem here, please read the message carefully!

It says you are ONLY using 30% of the available program memory and 19% of the dynamic memory.

You have a LOT more room left.
> 3 votes

# Answer
What you are seeing there is not an error message, it is only for information. It shows how much memory you have left on the Arduino.

> Sketch uses 8830 bytes (30%) of program storage space. Maximum is 28672 bytes.

This is about the program storage, also known as flash storage (which is the type of storage technology used here). It is, where the actual program is saved, and is non-volatile (which means, that it holds the data/your code even during power loss). The message tells you, that the Arduino Leonardo has a total of 28672 bytes of storage for your program. When you write bigger programs, you will also use more of the flash/program storage. That means, that the size of the flash/program storage (which is a hardware limit in the microcontroller) gives you an upper limit to the size of the compiled program, as it cannot be more than 100% of the maximum given there and still upload. Though note, that the compiler does a lot of optimization to your code, so there is no easy relation between C/C++ code size and compiled code size. **You need to actually compile your code to see, what size it will be and if it fits onto your Arduino.** And that is exactly, what this message is meant for.

The message tells you, that you are using 30% of the flash/program storage. Thus you are very well inside the limits.

> Global variables use 487 bytes (19%) of dynamic memory, leaving 2073 bytes for local variables. Maximum is 2560 bytes.

The second line is about the memory, where variables are stored, aka dynamic memory aka RAM. Of course this means the RAM inside of the Arduino. The RAM is volatile, which means, that every data in it will vanish, when the Arduino is powered off or reset.

Every time, that you declare a variable in your code, this variable is put into the RAM. Calculating the maximum amount of RAM, that will be used in your code, is rather complex, as variables are created and destroyed very often, when calling functions or other programming constructs. But global variables (the ones declared outside of any function) are created right at the start of the program, thus the compiler can easily calculate their size.

This message gives you a hint, if you are going to run out of RAM with your program. It is only a hint. Because of that, the compiler will show a warning at that point, if you are going in the realm of 75% or higher of the available RAM, that this might not leave enough room for local variables and thus risks instability in the program. (Note, that I'm not sure about the exact limit, from which on the warning is displayed. You may try to research this detail).

When you program runs out of RAM, it will fail or producing instability. So you want to prevent that from happening. Currently you are at 19%. Also you are using few local variables, so you are save here.

> I'm unsure if it is now appropriate to be able to see results show up on the serial monitor? Because nothing is showing up.

You should at least be able to see the message `CCS811 test` on the Serial monitor. If not, please make sure, that you really uploaded the code (by clicking on the upload button, not on the verify button). In the preferences you can turn on verbose output for compilation and upload, to find possible problem sources. Also make sure, that you chose the correct port and that your Serial Monitor is configured for the same baudrate as your sketch (in this case 9600 baud).

If that still doesn't give any output at all, try to upload the `Blink` example, that you can find in the Arduino IDE in the menu under examples -\> Basics. If it uploads successfully, watch, if the buildin LED starts to blink. If yes, that code is working correctly.

If the init message is showing up, but the temperature values are not, you need to first check for your connections. Then you could try to upload the standard I2C scanner sketch, that shows you, what devices can be found on the I2C bus and what addresses they have.
> 1 votes

---
Tags: arduino-leonardo, memory, error
---