body:
`randomSeed(analogRead(x))` will only produce 255 sequences of numbers, which makes it trivial to try all combos and produce an oracle that can couple to your output stream, predicting all the output 100%. You are on the right track however, it's just a numbers game, and you need a LOT more of them. For example, taking 100 analog reads from 4 ADCs, summing them all, and feeding that to `randomSeed` would  be much better. For max security, you need both unpredictable input and non-deterministic mixing.

I'm not a cryptographer, but I've spent thousands of hours researching and building hardware and software random generators, so let me share some of what I've learned:

**Unpredictable Input:**

* analogRead() (on floating pins)
* GetTemp()

**Potentially Unpredictable Input:**

* micros() (w/ a non-deterministic sample period)
* clock jitter (low-bandwidth, but usable)
* readVCC() (if not battery-powered)

**External Unpredictable Input:**

* temp, humidity, and pressure sensors
* microphones
* LDR voltage dividers
* reverse-bias transistor noise
* compass/acceleration jitter
* esp8266 wifi hotspot scan (ssid, db, etc)
* esp8266 timing (the background wifi tasks make scheduled micros() fetches indeterminate)
* esp8266 HWRNG - `RANDOM_REG32` -extremely fast and unpredictable, a 1-stop

**collecting**
The last thing you want to do is spit out entropy as is comes along. It's easier to guess a coin flip than a bucket of coins. Summing is good. `unsigned long bank;` then later `bank+= thisSample;` is good; it will roll-over. `bank[32]` is even better, read on. You want to collect at least 8 samples of input for each chunk of output, ideally much more.

**Guarding against poisoning**
If heating the board causes a certain max clock jitter, that's an attack vector. Same with blasting RFI towards the analogRead() inputs. Another common attack simply unplugging the unit thus dumping all the accumulated entropy. You should not output numbers until you know it's safe to do so, even at the cost of speed.

This is why you want to keep some entropy around long-term, using EEPROM, SD, etc. Look into the [Fortuna PRNG](https://en.wikipedia.org/wiki/Fortuna_(PRNG)), which uses 32 banks, each one updated half as often as the one before it. That makes it difficult to attack all 32 banks in a reasonable amount of time.

**Processing**
Once you collect "entropy", you have to clean it up and divorce it from the input in a hard-to-reverse way. SHA/1/256 is good for this. You can use SHA1 (or even MD5 really) for speed since you don't have a plaintext vulnerability. To harvest, never use the full entopy bank, and ALWAYS ALWAYS add a "salt" to the output that's different each time to prevent identical outputs given no entropy bank changes: `output = sha1( String(micros()) + String(bank[0]) + [...] );` The sha function both conceals inputs and whitens output, protecting against weak seeds, low accumulated ent, and other common issues.

To use timer inputs, you need to make them indeterministic. This is a simple as `delayMicroseconds(lastSample % 255)`; which pauses an unpredictable amount of time, making "successive" clock reads non-uniform in difference. Do that semi-regularly, like `if(analogRead(A1)>200){...}`, provided A1 is noisy or hooked to a dynamic input. Making each fork of your flow rather difficult to determine will prevent cryptoanalysis on decompiled/ripped output.

Real security is when the attacker knows your whole system and is still helpless to overcome it.

Lastly, check your work. Run your output through [ENT.EXE](http://www.fourmilab.ch/random/) (also available for nix/mac) and see if it's any good. Most important is the chi square distribution, which should usually be between 33% and 66%. If you get 1.43% or 99.999% or something edgy like that, more than one test in a row, your random is crap. You also want the entropy ENT reports as close to 8 bits per byte as possible, > 7.9 for sure.

TLDR:
The simplest fool-proof way is to the uthe ESP8266's HWRNG. It's fast, uniform, and unpredictable. Run something like this on an ESP8266 running the Ardunio core, and use serial to talk to the AVR:

    // ESP8266 Arduino core code:
    void setup(){
     Serial.begin(9600); // or whatever
    }

    void loop() {
      // Serial.write((char)(RANDOM_REG32 % 256)); // "bin"
      Serial.print( String(RANDOM_REG32, HEX).substring(1)); // "hex"
    }

--------------
** edit

here is a bare-board HWRNG sketch I wrote a while back, operating as a not just a collector, but a whole CSPRNG spitting out of the serial port. It's built for a pro-mini but should be easily adaptable to other boards. You can use just floating analog pins, but it's better to add stuff to them, prefereably different things. Like microphones, LDRs, thermistors (trimmed to max spread around room temp), and even long wires. It does pretty well in ENT if you have even moderate noise.

The sketch integrates several notions I've mentioned in my answer and follow-up comments: accumulating entropy, stretching by over-sampling less-than-ideal entropy (von neumann said it's cool), and hashing to uniformity. It forgoes entropy quality estimation in favor of "gimme anything possibly dynamic" and mixing using a cryptographic primitive.

    // AVR (ardunio) HWRNG by dandavis. released to public domain by author.
    #include <Hash.h>

    unsigned long read[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    const int pincount = 9; // adjust down for non pro-mini boards
    int pins[9] = {A0, A1, A2, A3, A4, A5, A6, A7, A0}; // adjust for board, name analog inputs to be sampled
    unsigned int ticks = 0;
    String buff = ""; // holds one round of derivation tokens to be hashed.
    String cache; // the last read hash

    void harvest() { // String() slows down the processing, making micros() calls harder to recreate
      unsigned long tot = 0; // the total of all analog reads
      buff = String(random(2147483647)) + String(millis() % 999);
      int seed =  random(256) + (micros() % 32);
      int offset =  random(2147483647) % 256;

      for (int i = 0; i < 8; i++) {
        buff += String( seed + read[i] + i + (ticks % 65), HEX );
        buff += String(random(2147483647), HEX);
        tot += read[i];
      }//next i

      buff += String( (micros() + ticks + offset) % 99999, HEX);
      if (random(10) < 3) randomSeed(tot + random(2147483647) + micros());
      buff = sha1( String(random(2147483647)) + buff + (micros()d) + cache); // used hash to uniform output and waste time
      Serial.print( buff ); // output the hash
      cache = buff;
      spin();
    }//end harvest()

    void spin() { // add entropy and mix
      ticks++;
      int sample = 128;
      for (int i = 0; i < 8; i++) { // update ~6/8 banks 8 times
        read[ read[i] % 8] += (micros() % 128);
        sample = analogRead(  pins[i] ); // a read from each analog pin
        read[ micros() % 8] += ( read[i] % 64 ); // mix timing and 6LSBs from read
        read[i] += sample; // mix whole raw sample
        read[(i + 1) % 8] += random(2147483647) % 1024; // mix prng
        read[ticks % 8] += sample % 16; // mix the best nibble of the read
        read[sample % 8] += read[ticks % 8] % 2147483647; // intra-mix banks
      }

    }//end spin()

    void setup() {
      Serial.begin(9600);
      delay(222);
      int mx = 2028 + ((analogRead(A0)  + analogRead(A1) + analogRead(A2)  + analogRead(A3)) % 256);
      while (ticks < mx) {
        spin();
        delay(1);
        randomSeed(read[2] + read[1] + read[0] + micros() + random(4096) + ticks);
      }// wend
    }// end setup()

    void loop() {
      spin();
      delayMicroseconds((read[ micros() % 8] %  2048) + 333  );
      delay(random(10));
      //if (millis() < 500) return;
      if ((ticks % 16) == (millis() % 16) ) harvest();
    }// end loop()


sender: user

message:
Getting a truly random number in Arduino

What is the best method to get a truly (as opposed to pseudo) random number in Arduino, or at least the best possible approximation? From my understanding, the function randomSeed(analogRead(x)) it's not random enough.

If possible the method should leverage the basic Arduino setup alone (no additional sensors). Solutions with external sensors are welcome if they improve significantly the randomness over the basic setup.

sender: assistant

body:
From my experience, `analogRead()` on a floating pin has very low
entropy. Maybe one or two bits of randomness per call. You definitely
want something better. The watchdog timer's jitter, as proposed in
per1234's answer, is a good alternative. However, it generates entropy
at a pretty slow rate, which can be an issue if you need it right when
the program starts. dandavis has quite a few good suggestions, but they
generally require either an ESP8266 or external hardware.

There is one interesting entropy source that has not been mentioned yet:
the contents of the uninitialized RAM. When the MCU is powered up, some
of its RAM bits (those that happen to have the most symmetrical
transistors) start up in a random state. As discussed in this
[hackaday article][], this can be used as an entropy source. It is only
available on a cold boot, so you can use it to fill an initial entropy
pool, which you would then periodically replenish from another,
potentially slow source. This way your program can start its work
without having to wait for the pool to slowly fill up.

Here is a example of how this could be harvested on an AVR-based
Arduino. The code snippet below XORs the whole RAM in order to build a
seed that it later feeds to `srandom()`. The tricky part is that the
harvesting has to be done _before_ the C runtime initializes the .data
and .bss memory sections, and then the seed has to be saved in a place
the C runtime will not overwrite. This is done by using specific
[memory sections][].

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

    uint32_t __attribute__((section(".noinit"))) random_seed;

    void __attribute__((naked, section(".init3"))) seed_from_ram()
    {
        const uint32_t * const ramstart = (uint32_t *) RAMSTART;
        const uint32_t * const ramend   = (uint32_t *) RAMEND;
        uint32_t seed = 0;
        for (const uint32_t *p = ramstart; p <= ramend; p++)
            seed ^= *p;
        random_seed = seed;
    }

    void setup()
    {
        srandom(random_seed);
    }

Note that, on a _warm_ reset, the SRAM is preserved, so it still has the
whole contents of you entropy pool. This same code can then be used to
preserve the collected entropy across a reset.

**Edit**: fixed an issue in my initial version of `seed_from_ram()` that
worked on the global `random_seed` instead of using a local `seed`.
This could lead to the seed being XORed with itself, destroying all the
entropy harvested so far.

[hackaday article]: http://hackaday.com/2015/06/29/true-random-number-generator-for-a-true-hacker/
[memory sections]: http://www.nongnu.org/avr-libc/user-manual/mem_sections.html


body:
If you don't really need entropy and simply want to get a different sequence of pseudo-random numbers on every startup, you can use EEPROM to iterate through consecutive seeds. Technically the process will completely deterministic, but in practical terms it's much better than `randomSeed(analogRead(0))` on an unconnected pin, which will often make you start with the same seed of either 0 or 1023. Saving the next seed in EEPROM will guarantee that you start with a different seed each time.

    #include <EEPROM.h>

    const int seed_addr = 0;
    unsigned long seed;

    void setup() {
        seed = EEPROM.read(seed_addr);
        EEPROM.write(seed_addr, seed+1);
        randomSeed(seed);
    }

If you need real entropy, you can collect it either from clock drift, or by amplifying external noise. And if you need a lot of entropy, external noise is the only viable option. Zener diode is a popular choice, especially if you have a voltage source above 5-6V (it will work with 5V too with an appropriate Zener diode, but will produce less entropy):

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

([source](https://www.maximintegrated.com/en/app-notes/index.mvp/id/3469)).

The amplifier output has to be connected to an analog pin, which will produce several bits of entropy with each `analogRead()` up to tens of MHz (faster than Arduino can sample).

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


message:
Coding force sensitive resistor to give output based on time used?

I have a basic set up of having a force sensitive resistor being used to power an LED as can be seen below. I am wondering how I can code it so that the LED is lit after a pressure has been applied to the FSR for a specified amount of time. Leading on from that I would like to use an RBG LED and have it so that after specified intervals on continuous pressure the LED changes colour.
Any advice would be greatly appreciated.

    //Constants:
    const int ledPin = 3;     //pin 3 has PWM funtion
    const int sensorPin = A0; //pin A0 to read analog input

    //Variables:
    int value; //save analog value

    void setup(){

      pinMode(ledPin, OUTPUT);  //Set pin 3 as 'output'
      Serial.begin(9600);       //Begin serial communication

    }

    void loop(){

      value = analogRead(sensorPin);       //Read and save analog value from potentiometer
      Serial.println(value);               //Print value
      value = map(value, 0, 1023, 0, 255); //Map value 0-1023 to 0-255 (PWM)
      analogWrite(ledPin, value);          //Send PWM value to led
      delay(100);                          //Small delay

    }

body:
You'll need to declare a variable to hold the start time (`millis()`) of when the force has exceeded the threshold.

You'll need to declare a constant to hold the threshold value (with analog data, you likely don't want to have your pressure threshold be "anything greater than 0", because noise and other things like small vibrations will trigger.

Also declare a constant to hold your "hold-off time" in milliseconds.

In your `loop()`, when you have an analog value that exceeds the pressure threshold, store the value of `millis()`. Also in your `loop()`, when the current `millis()` minus the start value  is greater than the "hold-off time", activate your LED.

For RGB, same setup, but you can set your color based on **how much** greater the time difference is than the hold-off time.


message:
Send serial data to local server

I am new to arduino coding.
I am reading data from serial port and storing it in char array.
I want to send that data to the local server but it is not getting converted to string

Code :

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    ESP8266WebServer server;
    char* ssid = "Office RTPL";
    char* password = "********";
    char data[64];
    char data1[64];
    String str;
    void setup()

    {
      // put your setup code here, to run once:
      WiFi.begin(ssid,password);
      Serial.begin(115200);
      while(WiFi.status()!= WL_CONNECTED)
      {
        Serial.print(".");
        delay(500);
      }
      Serial.println("");
      Serial.print("IP Address: ");
      Serial.print(WiFi.localIP());
      server.on("/",[](){server.send(200,"text/plain","Data Test");});
      server.on("/toggle",serialData);
      server.begin();
    }
    void loop()
    {
      // put your main code here, to run repeatedly:
      server.handleClient();
     ;
    }
    void serialData()
    {
      if(Serial.available() > 0)
          {

            server.send(200,"text/plain","Data");
             for(int n=0; n<64; n++)
             {
               data[n] = (Serial.read());

             }
             String str (data);
             server.send(200,"text/plain",str);

      else
            {
            String no_data = "No Serial Data";
            server.send(200,"text/plain",no_data);
            delay(5000);
            }

    }

Please help

body:
As I mention in [my answer about serial communication](https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino/19757#19757):

> Before reading, always make sure data is available. For example, this is wrong:

>     if (Serial.available ())
      {
          char a = Serial.read ();
          char b = Serial.read ();  // may not be available
      }

> The Serial.available test only ensures you have **one** byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

>     if(Serial.available() > 0)
        {
        server.send(200,"text/plain","Data");
         for(int n=0; n<64; n++)
         {
           data[n] = (Serial.read());

So you know that **one** byte is available, but you are reading 64. No, that won't work.


message:
Switch case does not work after booting system

int value1;
    int value2;
    int runs1 = 0;
    int runs2 = 0;

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 16, 2);
    int inPin = 6;
    int val = 0;
    int push_count = 0;
    int buttonState = 0;
    unsigned long previousMillis = 0;
    const long interval = 1800000;
    int currentTime;

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

    void loop() {

      unsigned long currentMillis = millis();
      currentTime = 30-(currentMillis - previousMillis)/60000;
      if (currentMillis - previousMillis >= interval || previousMillis == 0) {
        previousMillis = currentMillis;

      measure();
      }

      buttons();
    }

    void measure() {
     value1=300;
     value2=300;

      if (value1 <= 650)
    {
       lcd.setCursor(8,0);
       lcd.print("Plant");
       lcd.setCursor(10,1);
       lcd.print("1");
       delay(2000);

    }
    else
    {
      lcd.clear();
      lcd.print("Pump 1 turned ON");
      lcd.setCursor(0,1);
      lcd.print("Water for 40 sec");
      runs1++; // increment the number of times pump 1 has run

    }

      if (value2 <= 550)
    {
       lcd.setCursor(8,0);
       lcd.print("Plant");
       lcd.setCursor(10,1);
       lcd.print("2");
       delay(2000);
       Serial. print("Pump 2 OK");
    }
    else
    {
      lcd.clear();
      lcd.print("Pump 2 turned ON");
      lcd.setCursor(0,1);
      lcd.print("Water for 40 sec");
      runs2++; // increment the number of times pump 2 has run
      Serial. print("Pump 2");
    }
      }

    void buttons() {
      val = digitalRead(inPin);

      if (val != buttonState && val == HIGH){
        push_count++;
      }
          else {
          // do nothing
        }

      buttonState = val;
      switch (push_count) {
        case 0:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Sensor 1 reads");
          lcd.setCursor(0,1);
          lcd.print(value1);
          delay(20);
          Serial. print("Case 0");
          push_count++;
          break;
        case 1:
          Serial. print("Case 1");
          break;
        case 2:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Sensor 2 reads");
          lcd.setCursor(0,1);
          lcd.print(value2);
          delay(10);
          push_count++;
          break;
        case 3:
          break;
        case 4:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Pump 1 ran");
          lcd.setCursor(0,1);
          lcd.print(runs1);
          lcd.setCursor(5,1);
          lcd.print(" times");
          delay(10);
          push_count++;
          break;
        case 5:
          break;
        case 6:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Pump 2 ran");
          lcd.setCursor(0,1);
          lcd.print(runs2);
          lcd.setCursor(5,1);;
          lcd.print(" times");
          delay(10);
          push_count++;
          break;
        case 7:
          break;
        case 8:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Next cycle in");
          lcd.setCursor(0,1);
          lcd.print(currentTime);
          lcd.setCursor(5,1);
          lcd.print(" Minutes");
          delay(10);
          push_count++;
          break;
        case 9:
          break;
        default:
          push_count=0;
      }
    }

When I boot the system (standalone atmega328p circuit) the connected LCD either shows

> Plant

> 2

originating from

       lcd.setCursor(8,0);
       lcd.print("Plant");
       lcd.setCursor(10,1);
       lcd.print("2");
       delay(2000);
       Serial. print("Pump 2 OK");

or in my real code (where value1 and value2 are actually measured)

> Pump 2 turned ON

> Water for 40 sec

originating from

      lcd.clear();
      lcd.print("Pump 2 turned ON");
      lcd.setCursor(0,1);
      lcd.print("Water for 40 sec");
      runs2++; // increment the number of times pump 2 has run
      Serial. print("Pump 2");

after I use the button to cycle through all the cases everything works fine. On the next button press I get to case 2 (-> 3).
After a full cycle case 0 (-> 1) gets displayed correctly.

The above MCVE runs perfectly on my breadboard setup, but not in the real setup.

Here's the schematic of the real setup.

So somewhere in the real setup has to be something that my code does not handle properly. The breadboard setup is minimal, just all GND and VCC connections, a 16 Mhz crystal with 22 pF caps.

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

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

body:
You haven't ever set `value1` or `value2`, but your if-else statements depend on them.

Before you can test a variable to have a specific value, you must set the variable at some point prior to using it. In your code, `value1` and `value2` are declared global, but never initialized and never set, so they are undefined and could have any value in them at the start.


body:
Personally I don't like the way you handle the "state machine", and I'd implement it in what I perceive is a more robust way (I may be wrong, though).

Moreover if you have a button please add a debounce; I usually do this with the Bounce2 library (or alternatives I code which are modified versions of that library). So... Let's change the things in the way I prefer.

    // Include the library
    #include <Bounce2.h>

    // declare a bounce object
    Bounce buttonDebounce = Bounce();

    //in the setup:
    pinMode(IN_PIN, INPUT); // or INPUT_PULLUP?
    buttonDebounce.attach(IN_PIN);
    buttonDebounce.interval(5);

    //in the loop:
    buttonDebounce.update();

Then in the `loop` you can use the `buttonDebounce.rose()` function or `buttonDebounce.fell()` to detect the button presses.

Now, for the state machine. You have four meaningful states (let's call them DISPLAY_1 to 4). It's better to give them more meaningful names. And let's add an invalid state. I usually prefer to use const bytes to force the size rather than enums or defines, but.. whatever ;)

So outside loop or setup declare the values and the state variable:

    const byte SM_ErrorState = 0;
    const byte SM_Display_1 = 1;
    const byte SM_Display_2 = 2;
    const byte SM_Display_3 = 3;
    const byte SM_Display_4 = 4;
    const byte SM_Display_5 = 5;
    byte SM_currentState;

Now, the function `buttons` can be implemented in the classical way I learned to implement state machines, which is first make a switch case to test whether you have to advance, then advance to the next state if necessary and perform the entry action.

    void buttons()
    {
     buttonDebounce.update();

     nextState = SM_currentState;

     // Check if a new state is requested
     switch (SM_currentState)
     {
     case SM_Display_1:
      if (buttonDebounce.rose())
       nextState = SM_Display_2;
      break;
     case SM_Display_2:
      if (buttonDebounce.rose())
       nextState = SM_Display_3;
      break;
     case SM_Display_3:
      if (buttonDebounce.rose())
       nextState = SM_Display_4;
      break;
     case SM_Display_4:
      if (buttonDebounce.rose())
       nextState = SM_Display_5;
      break;
     case SM_Display_5:
      if (buttonDebounce.rose())
       nextState = SM_Display_1;
      break;
     default:
      nextState = SM_Display_1;
      break;
     }

     // If an advancement is requested, advance and then perform the entry action
     if (nextState != SM_currentState)
     {
      SM_currentState = nextState;
      switch (SM_currentState)
      {
      case SM_Display_1:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Sensor 1 reads");
       lcd.setCursor(0,1);
       lcd.print(value1);
       delay(20);
       Serial. print("Case 0");
       break;
      case SM_Display_2:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Sensor 2 reads");
       lcd.setCursor(0,1);
       lcd.print(value2);
       delay(10);
       break;
      case SM_Display_3:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Pump 1 ran");
       lcd.setCursor(0,1);
       lcd.setCursor(5,1);
       lcd.print(runs1);
       lcd.print(" times");
       delay(10);
       break;
      case SM_Display_4:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Pump 2 ran");
       lcd.setCursor(0,1);
       lcd.print(runs2);
       lcd.setCursor(5,1);;
       lcd.print(" times");
       delay(10);
       break;
      case SM_Display_5:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Next cycle in");
       lcd.setCursor(0,1);
       lcd.print(currentTime);
       lcd.setCursor(5,1);
       lcd.print(" Minutes");
       delay(10);
       break;
      default:
       break;
      }
     }
    }

Now, the initialization. Remember that I told you to add an error state? This way you can force a state change on initialization by setting the variable to the `SM_ErrorState` value.

Then, the millis management in the loop. I'd avoid the particular case of the variable equal to 0 to trigger an immediate execution, since this will lead to errors later. Then I also prefer to sum the interval, to avoid having a drift. So I changed your way to another one. I also changed some code for better readability (for instance, letting the "timer" reset every minute rather than every 30 minutes, and changing the defines accordingly).

Here is my complete code; I left out the measure function since it does not impact the other code.

Let me know if this solves your problem. Oh, BTW, UNTESTED CODE, so some bugs may appear...

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

    LiquidCrystal_I2C lcd(0x3F, 16, 2);

    int value1; // I think it is better if these
    int value2; // two variables are initialized
    int runs1 = 0; // Unsure if this is needed
    int runs2 = 0; // Unsure if this is needed
    int val = 0; // Unsure if this is needed

    int inPin = 6;
    unsigned long previousMillis = 0;
    const unsigned int millisInOneMinute = 60000U;

    byte elapsedMinutes;
    const byte intervalMinutes = 30;

    Bounce buttonDebounce = Bounce();

    void setup() {
     Serial.begin(9600);
     lcd.begin();
     pinMode(inPin, INPUT);
     buttonDebounce.attach(inPin);
     buttonDebounce.interval(5);
     previousMillis = millis();
     elapsedMinutes = intervalMinutes; // Force a new measure
    }

    void loop() {
     if (((unsigned int)(millis() - previousMillis)) >= millisInOneMinute)
     {
      previousMillis += millisInOneMinute; // Avoid drifting
      elapsedMinutes++;
     }

     if (elapsedMinutes >= intervalMinutes)
     {
      elapsedMinutes = 0;
      measure();
     }

     buttons();
    }

    void measure() {
     // do your stuff
    }

    void buttons()
    {
     buttonDebounce.update();

     nextState = SM_currentState;

     switch (SM_currentState)
     {
     case SM_Display_1:
      if (buttonDebounce.rose())
       nextState = SM_Display_2;
      break;
     case SM_Display_2:
      if (buttonDebounce.rose())
       nextState = SM_Display_3;
      break;
     case SM_Display_3:
      if (buttonDebounce.rose())
       nextState = SM_Display_4;
      break;
     case SM_Display_4:
      if (buttonDebounce.rose())
       nextState = SM_Display_5;
      break;
     case SM_Display_5:
      if (buttonDebounce.rose())
       nextState = SM_Display_1;
      break;
     default:
      nextState = SM_Display_1;
      break;
     }

     if (nextState != SM_currentState)
     {
      SM_currentState = nextState;
      switch (SM_currentState)
      {
      case SM_Display_1:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Sensor 1 reads");
       lcd.setCursor(0,1);
       lcd.print(value1);
       delay(20);
       Serial. print("Case 0");
       break;
      case SM_Display_2:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Sensor 2 reads");
       lcd.setCursor(0,1);
       lcd.print(value2);
       delay(10);
       break;
      case SM_Display_3:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Pump 1 ran");
       lcd.setCursor(0,1);
       lcd.setCursor(5,1);
       lcd.print(runs1);
       lcd.print(" times");
       delay(10);
       break;
      case SM_Display_4:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Pump 2 ran");
       lcd.setCursor(0,1);
       lcd.print(runs2);
       lcd.setCursor(5,1);;
       lcd.print(" times");
       delay(10);
       break;
      case SM_Display_5:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Next cycle in");
       lcd.setCursor(0,1);
       lcd.print(elapsedMinutes);
       lcd.setCursor(5,1);
       lcd.print(" Minutes");
       delay(10);
       break;
      default:
       break;
      }
     }
    }

**EDIT**: Generic implementation of a state machine

Ok, here I post my generic scheme for a state machine. Usually I use the "state-based" state machine, which is actions are linked to states; sometimes I also saw "transition-based" state machines, where actions were linked to transitions, but... Ok, I'm not a real expert, so I don't want to write a lot of (wrong) things.

In this kind of machines, each state can have up to three kind of actions and a check:

 - actions you perform when you ENTER the state
 - actions you perform continuously when you are INSIDE the state
 - actions you perform when you EXIT the state
 - and of course, you have to CHECK whether you need to make a transition to another state

For instance, when you have in a microwave a state corresponding to the ON state, you have to:

 - when you ENTER the state, turn on the heater
 - when you are INSIDE the state, update the timer value
 - when you are done and you are EXITing the state, turn off the heater
 - when during the CHECK you see that the timer has expired or the stop button was pressed, you switch to another state

So there are four kind of actions: ENTER, INSIDE, EXIT and CHECK. For linearity I learned that it is much better to write each of them in a separate switch case. This is my usual implementation scheme:

    void stateMachine()
    {
     byte nextState = currState; // currState of course is defined outside

     switch (currState)
     {
     // Here you have to CHECK, for each state, the conditions
     // needed to switch to another state; if you switch, put
     // the new state in nextState
     }

     if (nextState != currState)
     {
      switch (currState)
      {
      // Perform the EXIT functions for each state
      }

      // Advance to the next state
      currState = nextState;

      switch (currState)
      {
      // Perform the ENTER functions for each state
      }
     }
     else // See note below
     {
      switch (currState)
      {
      // Perform the actions to be performed continuously
      // INSIDE each state
      }
     }
    }

NOTE: the `else` can be omitted or not. If you leave it, in the cycle that you detect the change you do not perform the INSIDE action; if you omit it, the INSIDE action will be performed. This is useful in different cases.

Now, usually (and yours is one of these cases) you only need the CHECK and ENTER sections (if you look at the code, you will see that only these two sections were implemented). Once in a while you will need also the INSIDE section, and once in your life you will also need the EXIT ;) (at least in my experience)


body:
    int buttonState = 0;

So buttonState is initially zero (LOW).

      val = digitalRead(inPin);

      if (val != buttonState && val == HIGH){
        push_count++;
      }

Since you have an external pull-up on inPin it will read HIGH initially. Thus push_count will be incremented immediately.

      switch (push_count) {
        case 0:
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Sensor 1 reads");
          lcd.setCursor(0,1);
          lcd.print(value1);
          delay(20);
          Serial. print("Case 0");
          push_count++;
          break;
        case 1:
          Serial. print("Case 1");
          break;

Therefore you execute case 1 initially.

---

Also, I don't see how this works:

     value1=300;
     value2=300;

      if (value1 <= 650)
    {
       lcd.setCursor(8,0);
       lcd.print("Plant");
       lcd.setCursor(10,1);
       lcd.print("1");immediately
       delay(2000);

    }
    else
    {
      lcd.clear();
      lcd.print("Pump 1 turned ON");
      lcd.setCursor(0,1);
      lcd.print("Water for 40 sec");
      runs1++; // increment the number of times pump 1 has run

    }

      if (value2 <= 550)
    {
       lcd.setCursor(8,0);
       lcd.print("Plant");
       lcd.setCursor(10,1);
       lcd.print("2");
       delay(2000);
       Serial. print("Pump 2 OK");
    }
    else
    {
      lcd.clear();
      lcd.print("Pump 2 turned ON");
      lcd.setCursor(0,1);
      lcd.print("Water for 40 sec");
      runs2++; // increment the number of times pump 2 has run
      Serial. print("Pump 2");
    }

Since you are doing both `if` tests it seems likely (indeed certain) that you will display "Plant 1" and then immediately* overwrite it with "Plant 2" so quickly that you wouldn't notice it.

\* apart from the 2-second delay of course. :)


message:
Using a rotary switch

I don’t have a sketch for this project, just doing some thinking before I pullout the keyboard (this is my phone).  I was interested in writing a program that uses a predetermined time limit, for instance having a definition like...

    #define RUNTIME 30000

So the game runs for 30 seconds.
By doing this it would be a simple matter of changing the 30000 to 60000 and uploading to the Arduino.

After thinking about that a while, I would prefer to be able to adjust the time using a selector switch.
So my question is....  if I use a 1p4t (on-on-on-on) rotary selector switch,  assign each position to a pin and run 5v to the common. Each pin would defined as RUNTIME and a different time limit, 30000, 60000, 90000, 120000, three pins would be LOW and one HIGH depending on position.
Then using IF and ELSE statements in the loop setup would I be able to switch the times?  I know once the Arduino is powered up the selector switch would need to be at the correct location and if you choose to change the “RUNTIME” a reset would need to be pressed.

Thank you for any assistance or ideas.

body:
If I understand you well, it's very easy.

Assuming the 4 outputs of the switch will be connected to 4 GPIO's you just can check for the state of each GPIO and act on it

    // Pin numbers where switch 1 to 4 are attached to.
    #define PIN_SWITCH_1  8
    #define PIN_SWITCH_2  9
    #define PIN_SWITCH_3 10
    #define PIN_SWITCH_4 11

    unsigned long timer_value = 1000; // No switch selected

    void setup()
    {
         // Set switch pins to input mode.
         pinMode(PIN_SWITCH_1, INPUT);
         pinMode(PIN_SWITCH_2, INPUT);
         pinMode(PIN_SWITCH_3, INPUT);
         pinMode(PIN_SWITCH_4, INPUT);

         // Check switches
         if (digitalRead(PIN_SWITCH_1) == HIGH)
         {
             timer_value = 30000;
         }
         else if (digitalRead(PIN_SWITCH_2) == HIGH)
         {
             timer_value = 60000;
         }
         else if (digitalRead(PIN_SWITCH_3) == HIGH)
         {
             timer_value = 90000;
         }
         else if (digitalRead(PIN_SWITCH_4) == HIGH)
         {
             timer_value = 120000;
         }
         else
         {
             // Keep default value
         }
     }

     void loop()
     {
         // Here you can use timer_value to check for the end of the game.
     }


message:
Power Down Interrupt Arduino

Does anyone know a way to call an interrupt when an Arduino loses power to have it fire a small function real quick?

It'd be a quick EEPROM write of one variable.

I know you can use interrupts on certain pins when they get pulled low, I'm just not sure if it's possible on the power pin.

Or if there would still be enough power in the controller to finish that function.

I have the Node MCU board but it's programmed in Arduino c++.

body:
Not directly, no.  When an Arduino or ESP8266 has lost power it's lost power. You need external circuitry to keep providing power after the power input has been removed, and alert your target chip that power has gone.

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

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

<!-- End schematic -->

C1 wants to be massive. The ESP8266, because of the WiFi interface in it, consumes a lot of power.  Also, writing to EEPROM or Flash (which the ESP8266 has instead of EEPROM) takes extra power.

Ideally, C1 wants to be a small Super-Cap to keep the physical size small.  For an ESP8266 you're probably talking thousands of uF.

An alternative is to use the [47L16](https://majenko.co.uk/product/47l16-eeram-breakout) (or similar) EERAM chip which is designed to save its internal SRAM contents to internal EEPROM when power is lost using its own dedicated capacitor-based power reservoir.


message:
function returning String-Array

i'm still new to arduino and also to C++ and have a short question.
What i want to do is to write a function (in my case to parse the query-string of an URL) to get the parameter names and values (varying number of parameters).

My function looks like the following:

    String function readParams()
    {
       String params[x]; // x: number of params

       // fill params[0]... params[x] with parameter names

       return params;
    }

    void loop()
    {
       // do some stuff

       String params[x] = readParams();

       for(int i=0; i < x; i++)
       {
          debug(params[i]);
       }
    }

What is the correct return-type for the readParams() function in this case?
And how to access the params in the main (loop) -function?

I hope the code makes it clear what i want to do.

Thanks,
Marius

body:
Some tips:

1. Don't use `String`.
2. Use `char *` and slice the string in-place.
3. Pass a pointer to an array of pointers and fill that with pointers to the portions of the string you have sliced.
4. Return the number of entries in the array you used.

I do something similar in my [CLI](https://github.com/MajenkoLibraries/CLI/blob/master/CLI.cpp#L206) library.  I use a custom "getWord" function, but similar can be done with `strtok()`.

You can read more about working with C strings [here](https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/).


body:
I'm inclined to agree with Majenko that you shouldn't use String in the first place, but if you want to, you can pass by reference:

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

    const int numParams = 2;

    void readParams(String (& params) [numParams])
      {
      params [0] = "foo";
      params [1] = "bar";
      }

    void setup()
    {
      Serial.begin (115200);
      String params [numParams];
      readParams (params);
      for (int i = 0; i < numParams; i++)
        Serial.println (params [i]);
    }

    void loop() { }

An easier thing is to make the parameters a global variable.


message:
How to work with analog readings using RPi and Firmata?

For context: I'm working on a project where I need to use sensors to figure out the current state of the environment. This process is done using an Arduino UNO and a RPi. The easiest way that I found to perform communication between both boards is by uploading Standard Firmata and reading the code from RPi using Serial communication. I'm using [pyfirmata](https://github.com/tino/pyFirmata) to write the code in Python on the RPI side. Also, the Arduino is powered by the RPi using the USB port.

My problem was: The ADC component in the Arduino uses as the analog reference the 5V provided by the USB. When I tested the integration, I was using my laptop. So, the computer was providing 5V to the Arduino. So far so good. When I integrated the Arduino board to the RPi, I got some problems related to the precision of the sensor. I figured out that the RPi was only giving 4.75 V to the Arduino Board. This was messing with my readings since the ADC was using 4.75V while my code had 5V to compute things. After adjusting the code, everything proceeded as planned. Both 4.75 V and 5 V were hardcoded in my code.

So, these are my questions:

* Is there a way to [read the Vcc](https://forum.arduino.cc/index.php?topic=356752.msg2459412#msg2459412) using pyfirmata to figure out the correct voltage without having this hardcoded?
* Is there a way to modify the [analog reference](https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/) to use the INTERNAL reference of 1.1V?

About the analog reference, I found this: https://github.com/firmata/arduino/issues/39 . So, pyfirmata implements send_sysex method, I just have to execute these steps, but I still don't know how.

body:
It does not appear that Firmata has proceeded with the ability to change the analog reference source. You referenced one of the issues opened for it, but I don't see anywhere where it committed to the current master branch.

There's no way for an Arduino to read a voltage without some reference, and as you are experiencing, the default reference is Vcc. That means everything must be compared to Vcc, and if you compare Vcc to itself, you will always find out that Vcc is equal to Vcc.

The pull request to implement is [here](https://github.com/firmata/arduino/pull/40/files/ba4b94bb11e9763bd303c55fe8375077592a4b65#diff-f0b20b136350815986002392fb31de7b), so you could play around with it yourself.


message:
Change Arduino Uno clock from 16MHz external to 1MHz internal

I've got a project where I need to program an ATmega328P on an Arduino Uno board, then transplant it into a custom PCB - however, this board does not have an oscillator installed, and so I need to run the microcontroller off its internal clock.

My goal here is to be able to code my software with the Arduino IDE, insert a factory-fresh ATmega328P straight from the tube into the socket on the Arduino Uno board, then move the device from the board to the PCB without any changes along the way. What's the best way to go about this?

body:
That will not work. To change the clock source, you'd need to change the fuses. I don't know of any way to do this while the chip is inside the UNO.

Secondly, a factory fresh 328P won't work in an UNO board, because it doesn't have the correct fuses, and doesn't have the bootloader programmed.

I'd suggest placing the 328P chips in a breadboard; connect the ISP pin to the UNO, and use the [Arduino-as-ISP](https://www.arduino.cc/en/Tutorial/ArduinoISP) to change the fuses, and upload your program.

PS why run at 1Mhz. The internal oscillator runs at 8Mhz. By default the divide-by-8 fuse is set, so it runs at 1Mhz out of the factory, but you can unset this fuse.

PPS use this website http://www.engbedded.com/fusecalc/ to generate the right fuse settings for your project.


body:
You can set the fuses to run on the internal oscillator easily enough. You can still run at 8 MHz which the IDE supports (choose Lilypad in the IDE) and then the delays, serial prints, etc. will still work properly.

As for programming a new chip, you can use an Arduino as ISP, an external ISP programmer (available cheaply from eBay), or see [my page about uploading hex files](http://www.gammon.com.au/uploader) which just needs a few hook-up cables, and a $15 SD card adapter like this:

[![SD card adapter][1]][1]

You upload the sketch onto your Uno to make it into a programmer. Then you compile the code for your target chip and get the .hex file that the compiler produces.

Example setup:

[![Hex uploader][2]][2]

The hex uploader sketch also lets you change fuses.

The [AVR Fuse Calculator](http://www.engbedded.com/fusecalc) page will help you with getting the correct fuse settings.

  [1]: https://i.stack.imgur.com/5PcdO.png
  [2]: https://i.stack.imgur.com/u8gOG.jpg


message:
Problem with motor driver shield

I have recently bought a L293D shield and 2 BO motors. Whenever I connect the motors to the shield it makes a beeping noise. I searched online and found that I need to change PWM frequency but I know nothing about it and anyone please tell me about the PWM frequency and how to change it.

I have used almost every sketch found online but condition remains same. I am using 9V battery as External power supply and it is absolutely new. Please help me.

body:
Acting as a conduit for Google: `Arduino Change PWM Frequency` shows me:

https://playground.arduino.cc/Code/PwmFrequency

Which has the following example function:

    /**
     * Divides a given PWM pin frequency by a divisor.
     *
     * The resulting frequency is equal to the base frequency divided by
     * the given divisor:
     *   - Base frequencies:
     *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
     *      o The base frequency for pins 5 and 6 is 62500 Hz.
     *   - Divisors:
     *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
     *        256, and 1024.
     *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
     *        128, 256, and 1024.
     *
     * PWM frequencies are tied together in pairs of pins. If one in a
     * pair is changed, the other is also changed to match:
     *   - Pins 5 and 6 are paired on timer0
     *   - Pins 9 and 10 are paired on timer1
     *   - Pins 3 and 11 are paired on timer2
     *
     * Note that this function will have side effects on anything else
     * that uses timers:
     *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
     *     millis() functions to stop working. Other timing-related
     *     functions may also be affected.
     *   - Changes on pins 9 or 10 will cause the Servo library to function
     *     incorrectly.
     *
     * Thanks to macegr of the Arduino forums for his documentation of the
     * PWM frequency divisors. His post can be viewed at:
     *   http://forum.arduino.cc/index.php?topic=16612#msg121031
     */
    void setPwmFrequency(int pin, int divisor) {
      byte mode;
      if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
        switch(divisor) {
          case 1: mode = 0x01; break;
          case 8: mode = 0x02; break;
          case 64: mode = 0x03; break;
          case 256: mode = 0x04; break;
          case 1024: mode = 0x05; break;
          default: return;
        }
        if(pin == 5 || pin == 6) {
          TCCR0B = TCCR0B & 0b11111000 | mode;
        } else {
          TCCR1B = TCCR1B & 0b11111000 | mode;
        }
      } else if(pin == 3 || pin == 11) {
        switch(divisor) {
          case 1: mode = 0x01; break;
          case 8: mode = 0x02; break;
          case 32: mode = 0x03; break;
          case 64: mode = 0x04; break;
          case 128: mode = 0x05; break;
          case 256: mode = 0x06; break;
          case 1024: mode = 0x07; break;
          default: return;
        }
        TCCR2B = TCCR2B & 0b11111000 | mode;
      }
    }

And numerous results from this SE community also:

https://www.google.com/search?q=arduino+change+PWM+frequency+site:arduino.stackexchange.com

Which note methods for calculating/setting specific frequencies and pitfalls and side-effects of making such changes.


message:
Is there a way to disable modules like ADC without a sleep mode?

I'm working on a binary watch project. I want my circuit to live off of batteries for as long as possible, so I want to decrease the power consumption of my chip.

I'm using a barebones ATmega328P-PU with two 74HC595 shift registers. The ideal situation would be to keep the CPU, clock, flash, and I/O going so my program can continuously count the time on its own, but disable everything else that I'm not using, such as the ADC, BOD, TWI, timer1 and timer2, USART0, etc.

I took a look at the ATmega328P datasheet for the sleep modes, and it seems as though they all disable the CPU/Clock. Is this true? And if so, are there ways to disable the modules without enacting a sleep mode?

body:
Certainly there is.

      // disable ADC
      ADCSRA = 0;

You can disable lots of internal modules like this:

      power_all_disable();  // turn off all modules

See [my page about power saving](http://www.gammon.com.au/power).

---

Majenko commented that turning off the ADC, while leaving the processor running was pointless. The real way to save battery power is to sleep, and it is possible to do that and still keep track of the time.

On [my page about timers](http://www.gammon.com.au/forum/?id=11504&reply=10#reply10) there is code to use a 32.768 kHz clock crystal to sleep and wake every second, which you could then use to alter the display on your watch.

Code from that page:

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

    #include <avr/sleep.h>
    #include <avr/power.h>

    const byte tick = 3;

    // interrupt on Timer 2 compare "A" completion - does nothing
    EMPTY_INTERRUPT (TIMER2_COMPA_vect);

    void setup()
     {
      pinMode (tick, OUTPUT);

      // clock input to timer 2 from XTAL1/XTAL2
      ASSR = bit (AS2);

      // set up timer 2 to count up to 32 * 1024  (32768)
      TCCR2A = bit (WGM21);                             // CTC
      TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
      OCR2A =  31;              // count to 32 (zero-relative)

      // enable timer interrupts
      TIMSK2 |= bit (OCIE2A);

      // disable ADC
      ADCSRA = 0;

      // turn off everything we can
      power_adc_disable ();
      power_spi_disable();
      power_twi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_usart0_disable();

      // full power-down doesn't respond to Timer 2
      set_sleep_mode (SLEEP_MODE_PWR_SAVE);

      // get ready ...
      sleep_enable();

      }  // end of setup

    void loop()
      {

      // turn off brown-out enable in software
      MCUCR = bit (BODS) | bit (BODSE);
      MCUCR = bit (BODS);

      // sleep, finally!
      sleep_cpu ();

      // we awoke! pulse the clock hand
      digitalWrite (tick, ! digitalRead (tick));

      }  // end of loop

Whilst asleep, the processor uses very little power. In the example sketch I measured 1.46 µA current consumption, when the output was LOW, if running from 5V power supply, and 1.1 µA if running from 3.3V power supply.

---

Example setup:

[![Low-power clock board][1]][1]

I have two decoupling capacitors (the blue ones). A pull-up resistor on Reset.
A 32.768 kHz crystal between pins 9 and 10. A 22 pF capacitor between each leg of the crystal and ground.

A current-limiting resistor and a LED. It works, and toggles at 1 Hz. When asleep (LED not on) it draws 1.46 µA as mentioned above.

  [1]: https://i.stack.imgur.com/i9SL1.jpg


message:
How to speed application up (if possible)

I have an ARD 2560, which I communicate with through a special written Delphi 7 program (USB handling is done in the D-7 program).

I use the command syntax:

    <REG> <COMMAND) <:> <NUMBER> <CR>

where
REG is  A - K (the registers in the ARD 2650)
COMMAND can be a 2-chars command, but mostly 1-char commands.

    EG:  AR:255<cr>  // AR configures DDRA to out- or in-put , depending on the parameter - (here 255 / 0xff) .

    AI:0<cr>  Read port A input (actually return content of ARD2560 port A input register)

    AO:<number><CR>   Send Number to port A (and return result to D-7 ).

    ......

All those command are valid for Reg A to Reg K.

The response time from transmit (d7) to I ("D/7") get the answer is approx. 1 1/2 second. I have a feeling that my code is a big, big kludge (it actually works), but I would like any advice(s) to to improve code // speeding it up.

If I drop the line:

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

     if (char (pport[0] == '*' ))  // '*' can be 'A' to 'K'

The response time increases to appr. 2 seconds.

(sorry that there are no comments!)

Here's the code:

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

    #include <Esplora.h>

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

    void loop()
    {

      String chr;

      if (Serial.available() > 0)
      {
        String pport = Serial.readStringUntil(':');
        {
          String pos = Serial.readStringUntil('\n');

          if (char (pport[0] == 'A' ))        /* A */
          {
            if (pport == "AR")
            {
              DDRA = pos.toInt();
              DOCRLF("//AR+", pos.toInt());
            }
            else
            if (pport == "AI")
            {
              if (DDRA == B00000000)
              {
                Serial.print(PORTA);
                chr = "//AI";
              }
              else
              {
                chr ="//AI-";
              }
              DOCRLF(chr , pos.toInt());
            }
            else
            if (pport == "AO")
            {
              if (DDRA == B11111111)
              {
                PORTA = pos.toInt();
                chr = "//AO+";
              }
              else
              {
                chr = "//AO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "AU")
            {
              Serial.print(PORTA);
              DOCRLF("//AU+", pos.toInt());
            }
            else
            if (pport == "ABW")
            {
              PORTA = pos.toInt();
              DOCRLF("//ABW+", pos.toInt());
            }
            else
            if (pport == "ABR")
            {
              Serial.print(PORTA);
              DOCRLF("//ABR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'B' ))        /* B */
          {
            if (pport == "BR")
            {
              DDRB = pos.toInt();
              DOCRLF("//BR+", pos.toInt());
            }
            else
            if (pport == "BI")
            {
              if (DDRB == B00000000)
              {
                Serial.print(PORTB);
                chr = "//BI+";
              }
              else
              {
                chr = "//BI-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "BO")
            {
              if (DDRB == B11111111)
              {
                PORTB = pos.toInt();
                chr = "//BO+";
              }
              else
              {
                chr = "//BO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "BU")
            {
              Serial.print(PORTB);
              DOCRLF("//BU+", pos.toInt());
            }
            else
            if (pport == "BBW")
            {
              PORTB = pos.toInt();
              DOCRLF("//EBW+", pos.toInt());
            }
            else
            if (pport == "BBR")
            {
              Serial.print(PORTB);
              DOCRLF("//BBR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'C' ))        /* C */
          {
            if (pport == "CR")
            {
              DDRC = pos.toInt();
              DOCRLF("//CR+", pos.toInt());
            }
            else
            if (pport == "CI")
            {
              if (DDRC == B00000000)
              {
                Serial.print(PORTC);
                chr = "//CI+";
              }
              else
              {
                chr = "//CI-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "CO")
            {
              if (DDRC == B11111111)
              {
                PORTC = pos.toInt();
                chr = "//CO+";
              }
              else
              {
                chr = "//CO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "CU")
            {
              Serial.print(PORTC);
              DOCRLF("//CU+", pos.toInt());
            }
            else
            if (pport == "CBW")
            {
              PORTC = pos.toInt();
              DOCRLF("//CBW+", pos.toInt());
            }
            else
            if (pport == "CBR")
            {
              Serial.print(PORTC);
              DOCRLF("//CBR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'D' ))        /* D */
          {
            if (pport == "DR")
            {
              DDRD = pos.toInt();
              DOCRLF("//DR+", pos.toInt());
            }
            else
            if (pport == "DI")
            {
              if (DDRD == B00000000)
              {
                Serial.print(PORTD);
                chr = "//DI+";
              }
              else
              {
                chr = "//DI-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "DO")
            {
              if (DDRD == B11111111)
              {
                PORTD = pos.toInt();
                chr = "//DO+";
              }
              else
              {
                chr = "//DO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "DU")
            {
              Serial.print(PORTD);
              DOCRLF("//DU+", pos.toInt());
            }
            else
            if (pport == "DBW")
            {
              PORTD = pos.toInt();
              DOCRLF("//DBW+", pos.toInt());
            }
            else
            if (pport == "DBR")
            {
              Serial.print(PORTE);
              Serial.println("//DBR+");
            }
          }
          else
          if (char (pport[0] == 'E' ))        /* E */
          {
            if (pport == "ER")
            {
              DDRE = pos.toInt();
              DOCRLF("//ER+", pos.toInt());
            }
            else
            if (pport == "EI")
            {
              if (DDRE == B00000000)
              {
                Serial.print(PORTE);
                chr = "//ER+";
              }
              else
              {
                chr = "//ER-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "EO")
            {
              if (DDRE == B11111111)
              {
                PORTE = pos.toInt();
                chr = "//EO+";
              }
              else
              {
                chr = "//EO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "EU")
            {
              Serial.print(PORTE);
              DOCRLF("//EU+", pos.toInt());
            }
            else
            if (pport == "EBW")
            {
              PORTE = pos.toInt();
              DOCRLF("//EBW+", pos.toInt());
            }
            else
            if (pport == "EBR")
            {
              Serial.print(PORTE);
              DOCRLF("//EBR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'F' ))        /* F */
          {
            if (pport == "FR")
            {
              DDRF = pos.toInt();
              DOCRLF("//FR+", pos.toInt());
            }
            else
            if (pport == "FI")
            {
              if (DDRF == B00000000)
              {
                Serial.print(PORTF);
                chr = "//FI+";
              }
              else
              {
                chr = "//F1-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "FO")
            {
              if (DDRF == B11111111)
              {
                PORTF = pos.toInt();
                chr = "//FO+";
              }
              else
              {
                chr = "//FO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "FU")
            {
              Serial.print(PORTF);
              DOCRLF("//FU+", pos.toInt());
            }
            else
            if (pport == "FBW")
            {
              PORTF = pos.toInt();
              DOCRLF("//FBW+", pos.toInt());
            }
            else
            if (pport == "FBR")
            {
              Serial.print(PORTF);
              DOCRLF("//FBR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'G' ))        /* G */
          {
            if (pport == "GR")
            {
              DDRG = pos.toInt();
              DOCRLF("//GR+", pos.toInt());
            }
            else
            if (pport == "GI")
            {
              if (DDRG == B00000000)
              {
                Serial.print(PORTG);
                chr = "//GI+";
              }
              else
              {
                chr = "//GI-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "GO")
            {
              if (DDRG == B11111111)
              {
                PORTG = pos.toInt();
                chr = "//GO+";
              }
              else
              {
                chr = "//GO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "GU")
            {
              Serial.print(PORTG);
              DOCRLF("//GU+", pos.toInt());
            }
            else
            if (pport == "GBW")
            {
              PORTG = pos.toInt();
              DOCRLF("//GBW+", pos.toInt());
            }
            else
            if (pport == "GBR")
            {
              Serial.print(PORTG);
              DOCRLF("//GBR+", pos.toInt());
            }
          }
          else
          if (char (pport[0] == 'H' ))        /* H */
          {
            if (pport == "HR")
            {
              DDRH = pos.toInt();
              DOCRLF("//HR+", pos.toInt());
            }
            else
            if (pport == "HI")
            {
              if (DDRH == B00000000)
              {
                Serial.print(PORTH);
                chr = "//HI+";
              }
              else
              {
                chr = "//HI-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "HO")
            {
              if (DDRH == B11111111)
              {
                PORTH = pos.toInt();
                chr = "//HO+";
              }
              else
              {
                chr = "//HO-";
              }
              DOCRLF(chr, pos.toInt());
            }
            else
            if (pport == "HU")
            {
              Serial.print(PORTH);
              DOCRLF("//HU+", pos.toInt());
            }
            else
            if (pport == "HBW")
            {
              PORTH = pos.toInt();
              DOCRLF("//HBW+", pos.toInt());
            }
            else
            if (pport == "HBR")
            {
              Serial.print(PORTH);
              DOCRLF("//HBR+", pos.toInt());
            }
          }
          else
          if (pport == "RA")
          {
            int aport = (pos.toInt());

            if (aport > -1 && aport < 16)
            {
              Serial.println (" OK ");
            }
          }
          else
          if (pport == "KO")
          {
            Serial.print("//KO+");
            if (DDRA == B11111111)
            {
               Serial.print("A");
            }
            else
            {
               Serial.print("a");
            }
            if (DDRB == B11111111)
            {
               Serial.print("B");
            }
            else
            {
               Serial.print("b");
            }
            if (DDRC == B11111111)
            {
               Serial.print("C");
            }
            else
            {
               Serial.print("c");
            }
            if (DDRD == B11111111)
            {
               Serial.print("D");
            }
            else
            {
               Serial.print("d");
            }
            if (DDRE == B11111111)
            {
               Serial.print("E");
            }
            else
            {
               Serial.print("e");
            }
            if (DDRF == B11111111)
            {
               Serial.print("F");
            }
            else
            {
               Serial.print("f");
            }
            if (DDRG == B11111111)
            {
               Serial.print("G");
            }
            else
            {
               Serial.print("g");
            }
            if (DDRH == B11111111)
            {
               Serial.print("H");
            }
            else
            {
               Serial.print("h");
            }
            Serial.println();
          }
        }
      }
    }

    void DOCRLF (String txt, int vval)
    {
      Serial.print(txt);
      Serial.println(vval);
    }

body:
This is not really a proper answer to your question. As I mentioned in
a comment, I believe your actual problem is the Delphi program not
sending the LF character you sketch expects. Instead, I am giving here a
coding style suggestion: _do not repeat yourself_.

Whenever you find yourself coding with copy-paste, you should try to
simplify the program using arrays and/or loops. Below is a suggested
alternative version of your `loop()`, with most of its redundant
repetitive repetitions removed:

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

    struct port_t {
        volatile uint8_t *ddr;
        volatile uint8_t *port;
    };

    static const port_t ports[] = {
        { &DDRA, &PORTA },
        { &DDRB, &PORTB },
        { &DDRC, &PORTC },
        { &DDRD, &PORTD },
        { &DDRE, &PORTE },
        { &DDRF, &PORTF },
        { &DDRG, &PORTG },
        { &DDRH, &PORTH },
        { NULL,  NULL   },  // there is no port I
        { &DDRJ, &PORTJ },
        { &DDRK, &PORTK },
        { &DDRL, &PORTL }
    };

    void loop()
    {
        // Read the command line.
        if (Serial.available() == 0) return;
        String pport = Serial.readStringUntil(':');
        String pos = Serial.readStringUntil('\n');

        // The "KO" command reads all ports.
        if (pport == "KO") {
            Serial.print("//KO+");
            for (char port_id = 'A'; port_id <= 'H'; port_id++) {
                if (*ports[port_id - 'A'].ddr == 0xff)
                    Serial.print(port_id);
                else
                    Serial.print(tolower(port_id));
            }
            Serial.println();
            return;
        }

        // Identify the port to act on.
        char port_id = pport[0];
        if (port_id < 'A' || port_id > 'L' || port_id == 'I') {
            Serial.println(F("Error: unknown port."));
            return;
        }
        port_t port = ports[port_id - 'A'];

        // Perform the requested action.
        String command = pport.substring(1);
        String chr = String("//") + port_id + command;
        if (command == "R") {
            *port.ddr = pos.toInt();
            DOCRLF(chr + "+", pos.toInt());
        } else if (command == "I") {
            if (*port.ddr == 0)
                Serial.print(*port.port);
            else
                chr += "-";
            DOCRLF(chr , pos.toInt());
        } else if (command == "O") {
            if (*port.ddr == 0xff) {
                *port.port = pos.toInt();
                chr += "+";
            } else {
                chr += "-";
            }
            DOCRLF(chr, pos.toInt());
        } else if (command == "U" || command == "BR") {
            Serial.print(*port.port);
            DOCRLF(chr + "+", pos.toInt());
        } else if (command == "BW") {
            *port.port = pos.toInt();
            DOCRLF(chr + "+", pos.toInt());
        }
    }


message:
Is it possible to disable functions/methods?

I recently started using the TimeAction library (which allows for proto-threading) and I noticed it has a really useful function for enabling/disabling threads. I want to use the same idea but apply it to a general function, though I haven't been able to find a possible solution to doing such a task on the internet. Here is a potential way for how I would like to implement it:

    #include <TimedAction.h>

    boolean disableCheck = false;
    boolean checking = false;
    boolean state = false;
    const int motionPin = 5;
    void checkMotion();
    void motion();
    void DisableCheckMotion();

    TimedAction checkable = TimedAction(6000, DisableCheckMotion);

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

    void loop() {
      checkMotion(); //this will be the function I wish to enable and disable

      if(checking == true)
      {
        motion();
      }
      if(disableCheck == true)
      {
        checkable.check();
      }

    }
    void checkMotion()
    {
       checking = true;
    }
    void motion()
    {
       if(digitalRead(motionPin) == HIGH)
    {
       Serial.println("motion");
       checking = false;
       checkable.check();
    }
    }
    void DisableCheckMotion()
    {
      state ? state = true : state = false;
      if(state == false)
    {
      checkMotion.disable(); //this is where I would like to disable the function
      disableCheck = true;
    }

      if(state == true)
    {
      checkMotion.enable(); //this is where I would like to enable the function
      disableCheck = false;
    }
    }

The purpose of this task is to output one value for whenever a PIR scanner (set at pin 5) picks up motion. Without any form of delaying it will flood the output with values (which is undesirable). A thread is used to offer this delay, I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed.

The ideal setup would be for the Arduino board to receive the input and then delay the input from being received again for a period of time while not delaying the entire program. What would be the best way to implement this?

body:
If you don't want a function to run you can just return at the start of that function:

    void myFunction() {
        if (!myFunctionShouldRun) return;
        ... rest of function ...
    }

If `myFunctionShouldRun` is false the `if` will be true (due to the `!`) and the function will return.  If it's `true` the rest of the function will execute.


message:
Burn hex with optiLoader

Can [optiLoader][1] be used to burn custom hex?

For example, there's hex representation stored in optiLoader.ino in `image_328`, if that value is replaced with content of my pre-compiled hex, should that work right out of the box or some additional tweaking is needed?

**EDIT**

Discussion about the same topic on [arduino forum][2] as well.

  [1]: https://github.com/WestfW/OptiLoader
  [2]: https://forum.arduino.cc/index.php?topic=535153.0

body:
Yes, it should work provided that your desired target image is stored in the same form, with correct metadata, and that **it is small enough to fit in the programmer device**.

The storage format of the payload-to-program could be made more optimal by a factor of almost two; however, for the original purpose of injecting compact Arduino-style bootloaders that is scarcely needed, and would have made preparing payloads more complicated.


message:
Using SD shield for extra external memory?

I am an Arduino beginner and I am planning to make a musical instrument with it. I want to add record and playback functionalities into the instrument.

I figure I will have to store lots of data to meet this feature, but the Arduino I'm using (Uno/Nano) probably won't have enough memory to hold lots of songs.

My question is, is using an SD card with an SD shield a good way to expand memory? If not, what should I use to do so?

Thanks

body:
There are different options:

- SD shield: much memory (GB's), however keep in mind that it will take time to retrieve the data from the SD card. Also you can retrieve 512 bytes every time (which also means it costs 512 precious bytes of arduino SRAM).

- External SRAM: There are external SRAM ICs, like 23LC1024 or 24K256. These are much faster and offer 128 or 32 KB. There are many others too, these are most 'common'. These are much faster than SD cards, you can get 1, 2 or more bytes per time. But it's not the same as Arduino SRAM, e.g. you cannot really store variables, so you have to copy data to internal SRAM to be used.

So first, check how much you need, and more important: what is the latency you can live with.


body:
Since you are working just with instructions on how to play audio, not the audio itself, you effectively have very small amounts of data (comparatively).

You can store that data in a file on SD card and read it back simply enough (there's plenty of examples for reading from and writing to SD).

You don't need the whole song in memory all the time - you only care about the note you're playing (or recording) at any one instance in time, so you don't need lots of memory.

How you format the data is entirely up to you, but I would suggest following the MIDI standard which will allow you to work with other tools to create and edit the files as well as the Arduino. You can also then export your music simply to other applications, such as MuseScore, Finale, Sibelius, Ardour, etc.


message:
Genuino UNO 5V pin is reading 0.3V

So I was trying to set up the LCD screen that came with my Genuino starter kit when I noticed that the board screen did not power on at all, unlike a few days ago when it worked.

In order to verify that the UNO was delivering power I simply connected an LED in series with a 220Ω resistor, between the 5V and ground pins. The LED did not power on.

I then, with the UNO still connected over USB, measured the voltage between across the resistor and LED and found it to be around 0.2-0.3V. Going further, reading the voltage between the 5V and ground solder connections on the back of the board and the reading is about the same.

I can power the LED from a digital pin that I set to HIGH, the issue seems to just be with the 5V pin.

Is there anything simple that I am missing (I hope there is) or is there likely a problem with my board? If there is a problem, could I use a digital pin to power a larger circuit such as that with an LCD or would the current supplied be too low?

body:
There are a couple more places you can sample the 5V signal, see the photo here:

[![Arduino Uno][1]][1]

On the right, on the ICSP header, the pin marked VCC is also connected to the 5V signal. Try testing that.

(The other one is pin 2 of the ICSP interface for the USB chip, but the one on the right should be adequate for testing).

I don't know why you are mucking around with LEDs and resistors, just put your meter between Gnd and 5V.

I find sometimes that the hookup cable has failed, try testing that (or try with a different cable).

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


message:
"Bad request" error (HTTP) while posting to PHP server using Arduino and ESP8266

I'm doing an IoT project where the temperature and humidity values from a DHT11 sensor is sent to a PHP server using HTTP post. When I run the Arduino, the Serial Monitor says "Bad request". The sensor values are not appearing on the webpage. Please, help me figure out the problem. I am using an Arduino Uno with and an ESP-01.

    // Code to use SoftwareSerial
    //The final sketch
    #include "SoftwareSerial.h"
    #include <dht.h>

    #define dht_dpin 8

    String data;
    String ssid = "TRAK family";

    String password = "rukman12345";

    SoftwareSerial espSerial(6, 7); // RX, TX

    dht DHT;

    float t;
    float h;

    String server = "svce-ece-b.000webhostapp.com";

    String uri = "esp.php";

    boolean DEBUG = true;

    void showResponse(int waitTime)
    {
        long t = millis();
        char c;
        while (t + waitTime > millis()) {
            if (espSerial.available()) {
                c = espSerial.read();
                if (DEBUG)
                    Serial.print(c);
            }
        }
    }

    void setup()
    {
        DEBUG = true;

        Serial.begin(115200);
        delay(500);

        espSerial.begin(115200);

        espSerial.println("AT+RST");
        showResponse(1000);

        // espSerial.println("CIOBAUD=9600");
        // showResponse(1000);

        espSerial.println("AT+CWMODE=1");
        showResponse(1000);

        espSerial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
        showResponse(5000);

        if (DEBUG)
            Serial.println("Setup completed");
    }

    void httppost()
    {
        espSerial.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

        if (espSerial.find("OK")) {
            Serial.println("TCP connection ready");
        }
        delay(1000);

        String postRequest =
            "POST " + uri + " HTTP/1.0\r\n" +
            "Host: " + server + "\r\n" +
            "Accept: *" + "/" + "*\r\n" +
            "Content-Length: " + data.length() + "\r\n" +
            "Content-Type: application/x-www-form-urlencoded\r\n" +
            "\r\n" + data;

        String sendCmd = "AT+CIPSEND=";
        espSerial.print(sendCmd);
        espSerial.println(postRequest.length());

        delay(500);

        if (espSerial.find(">")) {
            Serial.println("Sending..");
            espSerial.print(postRequest);

            if (espSerial.find("SEND OK")) {
                Serial.println("Packet sent");
                while (espSerial.available()) {
                    String tmpResp = espSerial.readString();
                    Serial.println(tmpResp);
                }

                // close the connection
                espSerial.println("AT+CIPCLOSE");
            }
        }
    }

    void loop()
    {
        // Read sensor values
        DHT.read11(dht_dpin);
        float t = DHT.temperature;
        float h = DHT.humidity;
        if (isnan(t) || isnan(h)) {
            if (DEBUG)
                Serial.println("Failed to read from DHT");
        }
        else {
            if (DEBUG)
                Serial.println("Temp=" + String(t) + " *C");
            if (DEBUG)
                Serial.println("Humidity=" + String(h) + " %");

            data = "temperature=" + String(t) + "&humidity=" + String(h);

            httppost();
        }

        delay(1000);
    }

This is my PHP code:

    <?php
        global $Temp;
        global $Humidity;
        if(isset($_POST['temperature'])){
            $Temp=$_POST["temperature"];
        }
        if(isset($_POST['humidity'])){
            $Humidity=$_POST["humidity"];
        }

        $Write="
Temperature : " .$Temp . " Celcius
" . "
Humidity : " .       $Humidity . " %
";
        file_put_contents('sensor.html',$Write);
    ?>

body:
The URI path in the HTTP request must start with a `/`.

It should be:

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

    String uri = "/esp.php";


message:
RGB Not displaying Red when using LCD

I was testing my RGB (common anode) on its own playing with colours and got the red, green to work as desired.

However, when I connected my LCD board to my Arduino Uno as well as the RGB (using the same code prior and same output pins so I know the code isn't the issue) the RGB no longer displays red.

I assume it has something to do with the fluctuating voltage/current after I've put in the LCD but I cant work out how to resolve it. When its meant to be red it's just nothing, doesn't light up, green however still works.

    #include <LiquidCrystal.h>
    #define COMMON_ANODE
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    int SelectCounter = 0;
    int hours = 0; // start hours
    int minutes = 0; //start min
    int seconds = 5; //start seconds
    int redPin = A1;
    int greenPin = 2;
    int bluePin = 3;
    int digitposition = 0;
    int readkey;
    int speaker = A5;
    int buttonPin = A4;
    int buttonPushCounter = 0;   // counter for the number of button presses
    int buttonState = 0;         // current state of the button
    int lastButtonState = 0;

    void setup() {
    pinMode(speaker, OUTPUT);
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    pinMode(buttonPin, INPUT);
    Serial.begin(9600);
    }

    void loop() {
    noTone(speaker);
    setColor(0, 0, 255); // red

    ....... }

    void trigger() {
      lcd.clear(); // clears the screen and buffer
     lcd.setCursor(6,0);
     lcd.println("MUM:      ");
     lcd.setCursor(4, 1); // set timer position on lcd for end.
     lcd.println("WAKE UP!    ");
     tone(speaker, 10);
     setColor(0, 255, 0);  // green
     delay(500);
     digitalWrite(A1, HIGH);
     digitalWrite(2, HIGH);
     digitalWrite(3, HIGH);
     noTone(speaker);
     delay(500);
     lcd.display();
     }

    void setColor(int red, int green, int blue)
    {
      #ifdef COMMON_ANODE
       red = 255 - red;
       green = 255 - green;
       blue = 255 - blue;
     #endif
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);
    }

body: Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.


message:
Esp8266 and HttpClient not working properly

I am working on a project to send data to an API. Here is my code

    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>

    #include <ESP8266HTTPClient.h>

    #define USE_SERIAL Serial

    ESP8266WiFiMulti WiFiMulti;

    const char* key="***********";

    void setup() {

        USE_SERIAL.begin(115200);
        USE_SERIAL.println();
        USE_SERIAL.println();
        USE_SERIAL.println();

        for(uint8_t t = 4; t > 0; t--) {
            USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
            USE_SERIAL.flush();
            delay(1000);
        }

        WiFi.mode(WIFI_STA);
        WiFiMulti.addAP("******", "*********");

    }
    String data=" ";
    void loop() {
        data+="{";
        data+="\"";
        data+="light";
        data+="\"";
        data+=":";
        data+=830;
        data+=",";
        data+="\"";
        data+="temperature";
        data+="\"";
        data+=":";
        data+=23;
        data+=",";
        data+="\"";
        data+="humidity";
        data+="\"";
        data+=":";
        data+=202;
        data+="} ";

        // wait for WiFi connection
        if((WiFiMulti.run() == WL_CONNECTED)) {

            HTTPClient http;

            USE_SERIAL.print("[HTTP] begin...\n");
            // configure traged server and url
            http.begin("https://us-central1-sensorapp-d2a64.cloudfunctions.net/getData",key);      //Specify request destination
            http.addHeader("Content-Type", "application/json");  //Specify content-type header
            int httpCode = http.POST(data);   //Send the request
            String payload = http.getString();                  //Get the response payload
            USE_SERIAL.println(httpCode);   //Print HTTP return code
            USE_SERIAL.println(payload);    //Print request response payload

            USE_SERIAL.print("[HTTP] GET...\n");
            if(httpCode > 0) {
                // HTTP header has been send and Server response header has been handled
                USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

                // file found at server
                if(httpCode == HTTP_CODE_OK) {
                    //   String payload = http.getString();
                    USE_SERIAL.println(payload);
                }
            } else {
                USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
            }

            http.end();
        }

        delay(30000);
    }

After one successful request, it gives `error 400 (Bad Request)` until I reset the nodemcu. But then again it sends the data once successfully and continues with `400 (Bad Request)`.

Why are all the following requests bad? Is there something I haven't done?

body:
You declare and initialize `data` as a `String` in the global space. Then, in loop, you use a bunch of concatenations to build your request string.

You never clear the contents of `data`, but back at the top of `loop()` on the next round, you concatenate all the string data again, which duplicates it.

Side note, the `String` type is terrible for low-memory devices, and especially bad when you use a lot of concatenations. Because of the way the [`String`](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) type works internally, when you concatenate strings, you end up leaving "holes" in the RAM that aren't likely to be able to be re-used.

Even if you do fix the code by clearing `data` after you submit your HTTP request, your program will still run out of RAM pretty quickly.

Better would be to build the constant parts of the string as constant globals and just concatenate the variable parts when needed and clear it after use.

Best would be to stop using `String` and use instead a `char data[DATA_SIZE]` type of string buffer and use the standard C string utilities like `strncpy()`, `strnlen()`, `strncat()`, etc.


message:
How to measure the supply voltage of Arduino without using an analog pin

I'm using Arduino Nano to measure temperature with a 10 kohm thermistor and a voltage divider. My problem is I'm getting only 4.2V on the 5V pin. The power is supplied via a USB cable from a desktop PC.

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

I measured the output voltage of a USB port on the PC and it was around 4.5V. It doesn't look normal. So I suspect the power supply unit of the PC is not strong enough.

But it still makes sense to measure the voltage at the 5V pin since there is no guarantee it's exactly 5V. Its error will affect the calculated resistance of the thermistor. So I got it by connecting the pin directly to the A1 pin.

On the other hand, it seems to me Arduino internally and digitally knows the value of the supply voltage. So it would be faster and easier to get it rather than using the A1 pin. But I don't know how to do it.

After searching on the Internet, I could find only these things which didn't help me much.

- [voltage level - What are the 5V and VIN pins for? - Arduino Stack Exchange](https://arduino.stackexchange.com/questions/4458/what-are-the-5v-and-vin-pins-for)
- [voltage level - Getting 3.3v on 5v pin in Arduino Uno - Arduino Stack Exchange](https://arduino.stackexchange.com/questions/50591/getting-3-3v-on-5v-pin-in-arduino-uno)

I also considered using an external power supply, say 9V to the VIN pin but I don't feel like doing that much.

How can I measure the supply voltage of Arduino without using an analog pin?

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

body:
The Nano has an ATMega328P MCU, which has an internal 1.1V reference voltage.

You use [`analogReference()`](https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/) to change the reference voltage that analogRead() compares the analog inputs against.

You will need to use a voltage divider to ensure that your maximum possible supplied voltage ends up being no higher than the 1.1V reference.

You'll still need to use an analogInput pin.


body:
Yes, you can do it.

You can measure the voltage of the internal (approximately) 1.1V reference voltage using the ADC and use the results of that to calculate what the reference voltage you used (VCC) must have been to get the results you did.

This is a function I commonly use:

    long readVcc() {
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA,ADSC));
      result = ADCL;
      result |= ADCH<<8;
      result = 1125300L / result; // Back-calculate AVcc in mV
      return result;
    }

Depending on how close to 1.1V your internal reference voltage is, you may need to adjust the value `1125300L` in the code above.  Measure the actual VCC voltage and adjust that value until it results in the same voltage being returned (multiplied by 1000 since that function returns millivolts).

However, as Edgar Bonet mentions, you don't need to care about the supply voltage in your situation, since your thermistor readings are just a ratio that input voltage, whatever it is. Change the input voltage and you will get the same results, since the ADC returns a value between 0 and Vcc in 1024 steps. With different supply voltages you still get 1024 steps.


message:
Uploading sketch problem

I just plugged my arduino and click upload, it shows this error:

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

    Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"

    Sketch uses 948 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

[![][1]][1]

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

body:
In the Arduino IDE check for the available ports. Be sure that the COM Port on Windows or ACMO port on Linux based OS is selected.

If the problem continues then check if the port is allowed in Windows and Linux.


body:
either you are already using the serial port or you just didn't select the port from the arduino "Tools>port"
you can always check your device's communication port using the device manager.


message:
Problem with a seven segment display. The segments blink then turn off

I can't figure it out what is the problem with my circuit, the segments turning on for sec and then they are turning off for good.

I tried to connect to GND instead of the 5 V but then, nothing happened.

[![][1]][1]

My code:

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

    void setup() {
      for (int pin = 2 ; pin < 9 ; pin++){ // setup pins 2 – 8 to be output
        pinMode(pin, OUTPUT);
      }

      for (int pin = 2 ; pin < 9 ; pin++){ // turn on pins 2 - 8
        digitalWrite(pin, HIGH);
      }
    }

    void loop(){}

[Working simulation demo][2]

  [1]: https://i.stack.imgur.com/rCOCX.png
  [2]: https://www.tinkercad.com/things/bzFECN3pcfE-cool-tumelo

body:
With foregood you mean broken probably.

I don't see any resistor in your circuit, probably the LEDs are broken.

I'm afraid you have to use a new segment LED, and follow:

[Arduino Example][1]

Especially read this fragment:

Current-limiting Resistors

> Don't forget that the display uses LEDs, so you should use
> current-limiting resistors in series with the digit pins. 330 ohms is
> a safe value if you're unsure. If you use current-limiting resistors
> on the segment pins instead, then open up the SevSeg.h file and set
> RESISTORS_ON_SEGMENTS to 1 for optimal brightness.

  [1]: http://playground.arduino.cc/Main/SevenSegmentLibrary


body:
The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with).

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

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

To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments.

I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.


message:
How to measure CO2, Ammonia and Detect Smoke using MQ135?

----------
Setup Info:

MQ135 + Arduino+16x2LCD+ESP8266+ThinkSpeak.

Hi All, I have just bought a MQ135 . I started arduino basics with LED blinking , interfacing and then started with my real project.
e
I have seen in the data sheet of MQ135 that it can measure Ammonia, Sulfide,CO2 and Benze steam. It can also be used to detect smoke and alert.

But in the Arduino uno Serial monitor, I can see only one value 408.

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

Also, my friend suggested to calibrate this sensor for which I found really good material and started with 24 Hours on test after dumping a code to read data from it.
Now I read 1836 which was 1795 , about half an hour back.

Kindly reply and let me know what info or input is required from My side.
This is my first of my many uno projects to come.

Regards,
Sillicon
https://forum.arduino.cc/index.php?topic=535401.msg3649205#msg3649205

body:
> Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.


message:
How can i get rid of the error "cannot convert 'String' to 'const char*'"

I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:

    #define maxCommandLength 64

    String commands[] = {"/test", "/say", "/reset", "/sleep"};

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      Serial.println("Power on.");
    }
    char serial[maxCommandLength];
    boolean valid;
    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("Clearing command buffer(char 'serial'");
      for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
        serial[i] = ' ';
      }
      if (Serial.available()) {
        Serial.readBytesUntil(' ', serial, maxCommandLength);
      }
      if (serial[0] == '/') { //if it is a command
        Serial.print("Command recieved. \nCommand class:");
        Serial.println(serial);
        //test if command is valid
        for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
          valid = strcmp(serial,commands[i]);
          if(valid){
            break;
          }
        }
        //execution of command
        Serial.readBytesUntil(' ', serial, maxCommandLength);
        //.......
      }
    }

body:
there is no reason for command to be a String array. Instead make it a `const char**`:

    const char** commands = {"/test", "/say", "/reset", "/sleep"};


body:
You can call the `.c_str()` method of `String` class returning (temporary) `const char *` representation of underlying string, in your case:

    valid = strcmp(serial,commands[i].c_str());
    //                               ^^^^^^^^
should work. Just make sure you don't keep the returned `const char *` around longer than necessary because by spec it is no guaranteed to remain valid.


message:
Parse long CSV file with esp8266

I'm trying to write a code for nodeMCU (esp8266 based board) to continuously calculate distance between GPS location and geographical coordinates written in a CSV file in SD. Originally I thought the best way to do it was to parse the file, save the longitudes and latitudes in two arrays at startup and, then, calculate continuously distances between arrays and coordinates taken from GPS. If distance is less than a value, an output warns me. There is only a "little" problem: the file contains 5500 coordinates and, so, it is impossible to allocate two arrays containing 5500 floats inside ram memory. Now I have thought two alternatives:
1) save the two arrays in flash memory that is, I know, a lot slower but also bigger
2) parse and calculate distance line by line continuously: in a loop I'll take the first line from SD, parse it, calculate distance between it and GPS location and, then do the same thing for second, third,... line. It requires the continuous access to SD and parsing but I don't have to use flash memory.
What is the best option in your opinion? Have you got alternatives or suggestions?
Thank you!!

body:
Instead od the SD card you can use the esp8266 file system SPIFFS. It uses the flash of the esp8266, which is connected at 40MHz as Quad I/O on newer systems.

To [use SPIFFS][1] you create a folder named `data` in your esp8266 sketch folder. You put the files in that folder and then you use the SPIFFS upload plugin.

In runtime use the SPIFFS library. It is similar to SD library.

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/filesystem.rst


message:
Motor shield leaves no pins accessible

I just bought a motor shield for my UNO, in the pic below:

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

Plugging it into the uno leaves no pins accessible on the board. I’d like to use it to build a robot car, but there’s nowhere to plug in the ultrasonic sensors. Do I need to solder some pins to the row at the top of the pic, or to the through-board holes on the right labelled A0-5?

  [1]: https://i.stack.imgur.com/s1rbn.jpg

body:
yes. you can solder pin headers or contact wires directly to the shield. if use pinheaders it is easier to use the pins for other purposes.
In the case of using ultrasonic sensor you should have to use digital pins along with the 5v and ground pins of the shield.


body:
According to [tutorial][1], the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.

All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.

You can use analog pins as digital pins to connect the ultrasonic sensor.

Connection of I2C devices is possible on A4 and A5 pins.

The shield doesn't alow to stack a next shield, because it heats up.

  [1]: https://playground.arduino.cc/Main/AdafruitMotorShield