body:
Thanks for all the investigative work.

Throwing in my 2 cents :

I was also experiencing random cutoffs and wierd noises.
I was using the Servo class in combination with the DFPlayer on an Arduino UNO board.
It turns our that the Servo class uses the timers that are related to pin 9 and 10. When attaching a servo, signals will be outputted on those ports.
So don't hook up your DFPlayer or anything else on those ports.
Probably because the Servo class was sending all kinds of data over the serial connection to the DFPlayer, the module would stop playing and start making a lot of random noise for the remaining duration of the mp3.

Other things that I came across and might help other people :
The DFPlayer needs MP3's of a certain length. MP3's of just 1~2 seconds don't play. +5 seconds seems to be fine.
Any fancy MP3 encoding also prevents the MP3s from playing.
The led will light up but no sound will be outputted.

Depending on the library used for the DFPlayer, the filenames and folder names do matter. The mp3's have to be in the MP3 folder and be named like 0001.mp3, 0002.mp3

According to 1 of the many datasheets out there, the DFPlayer requires 3.3v levels for the RX and TX port, regardless of the operating voltage.
So do put those 1K resistors there. It won't hurt the module.

Motors and servo's do cause a lot of noise on the power source if you run the board off the 5v USB port.
Even small motors can generate spikes of +2A when turned on.

Signals from other cables and devices can also interfere with the serial connection so ideally use shielded wires for the TX/RX cables.

According to the SD card specs of some manufacturers, power usage for an SD card can go up to 100mA.
The module itself can produce 3W output so that would also add up to 600mA @ 5V. And add something like 150mA for the microcontroller onboard.
So even a standard 5v@500mA USB port won't have enough power to drive just the Arduino and DFPlayer in some cases.

Someone took a look at the clicks and plops on pause or power on/off :
http://work-now-dammit.blogspot.com/2016/08/dfplayer-mp3-module-power-onoff-clicks.html
Remove the 0-ohm resistor next to the 8002 amp. Connect pin 1 of the 8002 amp to the BUSY pin (16) of the module.


sender: user

message:
DFPlayer Noise: Researched, Tried, and Bep Bep Bep Bep Bep

Spent an entire day researching and attempting to fix the DFPlayer noise problem. The amp works as expected, so it is not the problem. I have made a video to help you better understand the sound produced: [https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be][1]

This is the amp/speaker used: [https://sites.google.com/site/wayneholder/chiptunes][2]

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

The amp with speaker works as expected using another similar mp3 player like from a computer or possibly a phone.

[![enter image description here][4]][4]

Here we get the bep bep bep bep bep... as the amp/speaker has its own battery power.

[![enter image description here][5]][5]
Here I made everything as one power source. Bep bep bep bep bep...

I think I exhausted my research and made the following attempts:

    > -Electrolytic Capacitor at the power terminals
    > -Electrolytic Capacitor parallel with ceramic capacitor from negative terminal to VCC in DFPlayer
    > -Diode from positive terminal to VCC in DFPlayer
    > -Battery Power source; USB power source; Power Supply power source; 5V USB plug regulator power source
    > -1k Resistor from TX RX; Rx Tx
    > -1-10k resistor from Rx Tx
    > -1k between channel to GND
    > -Separate power source for each the Arduino, amp, and DFPlayer
    > -Tried multiple DFPlayers

Keep note that the amp/speaker works well. The files are the same both on the computer and in the SD card.

Here is my code:
<!-- language-all: lang-cpp -->

    #include <DFRobotDFPlayerMini.h>

    /***************************************************
    DFPlayer - A Mini MP3 Player For Arduino
     <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

     ***************************************************
     This example shows the basic function of library for DFPlayer.

     Created 2016-12-07
     By [Angelo qiao](Angelo.qiao@dfrobot.com)

     GNU Lesser General Public License.
     See <http://www.gnu.org/licenses/> for details.
     All above must be included in any redistribution
     ****************************************************/

    /***********Notice and Trouble shooting***************
     1.Connection and Diagram can be found here
     <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
     2.This code is tested on Arduino Uno, Leonardo, Mega boards.
     ****************************************************/

    #include <Arduino.h>
    #include <SoftwareSerial.h>
    #include <DFRobotDFPlayerMini.h>
    int counter = 0;
    SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);

    void setup()
    {
      mySoftwareSerial.begin(9600);
      Serial.begin(115200);

      Serial.println();
      Serial.println(F("DFRobot DFPlayer Mini Demo"));
      Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

      if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
        Serial.println(F("Unable to begin:"));
        Serial.println(F("1.Please recheck the connection!"));
        Serial.println(F("2.Please insert the SD card!"));
        while(true);
      }
      Serial.println(F("DFPlayer Mini online."));

      myDFPlayer.volume(15);  //Set volume value. From 0 to 30
      delay(1000);
    myDFPlayer.enableDAC();  //Enable On-chip DAC
    }

    void loop()
    {
      static unsigned long timer = millis();
      if(millis() - timer > 1000 && counter == 0)
      {
       myDFPlayer.play(1);
       Serial.println(F("Music Started"));
       delay(1000);
       Serial.println(F("1 second later..."));
       delay(6000);
       Serial.println(F("7 seconds later..."));
       delay(1000);
       counter =1;
      }

    delay(7000);

      if (myDFPlayer.available()) {
        printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      }
    }

    void printDetail(uint8_t type, int value){
      switch (type) {
        case TimeOut:
          Serial.println(F("Time Out!"));
          break;
        case WrongStack:
          Serial.println(F("Stack Wrong!"));
          break;
        case DFPlayerCardInserted:
          Serial.println(F("Card Inserted!"));
          break;
        case DFPlayerCardRemoved:
          Serial.println(F("Card Removed!"));
          break;
        case DFPlayerCardOnline:
          Serial.println(F("Card Online!"));
          break;
        case DFPlayerPlayFinished:
          Serial.print(F("Number:"));
          Serial.print(value);
          Serial.println(F(" Play Finished!"));
          break;
        case DFPlayerError:
          Serial.print(F("DFPlayerError:"));
          switch (value) {
            case Busy:
              Serial.println(F("Card not found"));
              break;
            case Sleeping:
              Serial.println(F("Sleeping"));
              break;
            case SerialWrongStack:
              Serial.println(F("Get Wrong Stack"));
              break;
            case CheckSumNotMatch:
              Serial.println(F("Check Sum Not Match"));
              break;
            case FileIndexOut:
              Serial.println(F("File Index Out of Bound"));
              break;
            case FileMismatch:
              Serial.println(F("Cannot Find File"));
              break;
            case Advertise:
              Serial.println(F("In Advertise"));
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }
    }

  [1]: https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be
  [2]: https://sites.google.com/site/wayneholder/chiptunes
  [3]: https://i.stack.imgur.com/6rIO7.jpg
  [4]: https://i.stack.imgur.com/3iVtY.jpg
  [5]: https://i.stack.imgur.com/GuY9s.jpg

sender: assistant

body:
I found that noise was due to three issues,

 - Forgetting to ground BOTH GND pins on the DFPlayer chip
 - Forgetting to put 1k resistors in the Tx and Rx lines
 - Power fluctuations

**Power is the big issue**. When I powered my Arduino with a 9v 2A supply all the noise went away. Switching to USB power (5v) caused the noise to return.


body: I had the same problem. It was solved with a separate power supply to the DFPlayer. I also grounded both sides of the player but that alone was insufficient.


body:
**My Problem & Solution:**  I recently attempted to control the DFPlayer with an Arduino Pro Mini and also experienced loud pulsing noises during playback (along with the music file). The pulsing could be seen on a scope on one of the speaker leads. Unloading the speaker did not help, using different power supplies did not help. Also, with regard to tying the two DFPlayer GND pins together, that's not necessary on my board since they are already connected together via the metal shell of the micro SD connector.

However, I noticed that when I attempted to re-program the Mini (or even when I pressed the reset button), there was a short period of time when the pulsing stopped and the music file played as it should. In my case the problem was the data line from the Mini to the Rx pin on the DFPlayer (there was no connection to the Tx pin). I verified this by starting playback (with the pulsing noise) and then disconnecting the Rx connection. That stopped the pulsing and the music file played as expected.

The software solution was to force the transmit pin on the Mini (I'm using soft serial) to a LOW state immediately after sending the Play command. Works fine now.

Update: I had previously connected the Mini serial output directly to the DFPlayer Rx pin without a 1K limiting resistor. Now, with the resistor in place I no longer get the pulsing noise during playback and there is no longer a need to pull the control line low.


body: I've had loads of crazy little issues like this with the dfplayer and tried lots of solutions with very inconsistent results. Sometimes a technique like extra grounding or a resistor to the tx/rx pins will work the magic and then on making another copy of the circuit, the problem is inexplicably back! Here's a important clue that I haven't seen anywhere on forums yet, so I wanted to add it into the mix. Though the dfplayer is claimed to work from 3.3V to 5V, I've found it is *much* better behaved at 3.3V! Running it at 5V gives me odd noise and stability problems that vanish at 3.3V. You can get very cheap and efficient 3.3V regulators that are no bother to use. Try running it at the lower voltage and see if those issues clear up!


message:
How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor

I would like to make an alarm system using ultrasonic sensor.

My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.

But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.

I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.

    int echoPin = 10; // pin 10 for the echo

    int trigPin = 9; // pin 9 for trigger
    int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
    #include <NewPing.h> // Library for improved ultrasonic sensor readings

    #include <SoftwareSerial.h>

    NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

    int ledpin=7;
    // Variables will change:
    int ledState = LOW;             // ledState used to set the LED

    // Generally, you should use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0;        // will store last time LED was updated

    // constants won't change:
    const long interval = 250;           // interval at which to blink (milliseconds

    void setup() {
        pinMode(ledpin,OUTPUT);
        Serial.begin(9600); //sets up serial monitor
    }

    void loop() {

        delay(50);

        Serial.print("Ping: ");
        Serial.print(sonar.ping_cm());
        Serial.println("cm");

        //warning
        Serial.println("cm");

        //warning
        if(sonar.ping_cm()>=30)
        {
          unsigned long currentMillis = millis();

          if (currentMillis - previousMillis >= interval) {
            // save the last time you blinked the LED
            previousMillis = currentMillis;

            // if the LED is off turn it on and vice-versa:
            if (ledState == LOW) {
              ledState = HIGH;
            } else {
              ledState = LOW;
            }

            // set the LED with the ledState of the variable:
            digitalWrite(ledpin, ledState);
          }

        }
    }

body:
You are initiating the `NewPing` library with `NewPing sonar(trigPin, echoPin,30);`. The last parameter is the maximum distance in cm, that will be measured. On the [Arduino Playground site][1] of the library it says

> sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from

<!-- language: c -->

    if(sonar.ping_cm()>=30)

to

<!-- language: c -->

    if(sonar.ping_cm()==0)

  [1]: https://playground.arduino.cc/Code/NewPing#Methods


message:
Adafruit IO example won't compile, library required is correct version

I have Arduino IDE 1.8.5 installed, and also Adafruit IO Arduino 2.6.0 and Adafruit MQTT Library 0.20.0.

With the Adafruit IO lib comes a set of examples, and I wanted to use example adafruitio_07_digital_out as a starting point for a project on an Adafruit HUZZAH ESP8266.

It won't compile. I get

    #error "This sketch requires Adafruit MQTT Library v0.17.0 or higher. Please install or upgrade using the Library Manager."

which I find strange. I've tried installing 0.17.0 instead of 0.20.0, but that doesn't help.

Is there anything I can do to get this to work? The suggested solution of using the Library Manager to install the required package is obviously not working.

body: It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.


message:
Arduino tone frequency isn't always precise

I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.

It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.

The code itself is good, because I use a constant in the tone() function call for specifying the frequency.

Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

body:
As far as I know, `tone()` implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.

Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.


message:
Does a delay in a loop save energy?

I've noticed most example snippets always have a delay in the loop even if it's not needed for proper execution of the program.

I can only assume this is added because people copy and paste without understanding what's going on but it got me thinking if adding a delay could possible save power too.

If I have a loop that checks some inputs for changes could it be possible that adding a `delay(10)` saves some cycles and thus power?

body:
No, it burns energy by doing nothing.

You definitively should send your MCU to sleep and wake up on events or use the watchdog timer to wake up after a predefined period of time.


body:
The [`delay` function](https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/wiring.c#L106-L117) doesn't do anything special. It basically just counts down milliseconds inside a while loop and times it with `micros()`.

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

    void delay(unsigned long ms)
    {
     uint32_t start = micros();

     while (ms > 0) {
      yield();
      while ( ms > 0 && (micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }


body:
No, a short delay (up to 100 millis) is usually inserted in a void loop() when you are attached to an external sensor, in order to stabilize the readings. But it has nothing to do with power consumption. As an example, here are lines 49-52 from the example sketch "AnalogInSerialOut":

          // wait 2 milliseconds before the next loop
          // for the analog-to-digital converter to settle
          // after the last reading:
          delay(2);


body:
> could it be possible that adding a delay(10) saves some cycles and thus power?

No, the `delay()` function just pauses the code for the time specified. It's stil running and consuming energy for counting the time and waiting it to finish.

If you need to conserve power, you could adjust your circuit components in a fashion that will save energy, or if you want to save energy on your Arduino, you could use a breadboard setup(Instructions [here][1] and [here][2]) or make use of the internal watchdog timer to sleep and wake at certain time intervals. [More tutorial about watchdog timer is explained here][3].

Cheers!

  [1]: https://www.youtube.com/watch?v=npc3uzEVvc0
  [2]: http://www.instructables.com/id/Standalone-Arduino-ATMega-chip-on-breadboard/
  [3]: https://www.youtube.com/watch?v=AzZBgH67mgE


body:
The answers above are wrong, at least for NodeMCU 0.9 (ESP-12 board) ESP8266 and I also tested with Firebeetle ESP8266 board. Since I have a USB tester I can check that if the loop method is empty, the boards consume about **70mA-80mA** but during delay(ms) they consume about **20mA-30mA**.

This is the delay function for the boards commented:

    void __delay(unsigned long ms) {
        if(ms) {
            os_timer_setfn(&delay_timer, (os_timer_func_t*) &delay_end, 0);
            os_timer_arm(&delay_timer, ms, ONCE);
        } else {
            esp_schedule();
        }
        esp_yield();
        if(ms) {
            os_timer_disarm(&delay_timer);
        }
    }

I have not investigate further why delay function saves so much power consumption.


body:
I suspect the answer depends on the kind of Arduino you're using.

The ESP8266 is ARM based, and I believe ARM chips include power management circuits, where subsystems are automatically put in low power state when they are not being used. An ARM-based Arduino will likely use a lot less power while executing a delay than while doing other things.

I don't think AVR chips have any sort of power management, so they have all their silicon "lit up" at all times. That said, CMOS logic circuits do use more power when switching states than when idle, so even an AVR-based Arduino will probably use slightly less power while in a delay() function that it will when it's running instructions that use the arithmetic unit, UARTs, and other subsystems of the chip.

You'll get much better power savings by putting your Arduino into sleep mode.


body:
As stated in previous answers, at least on the AVR version of the
Arduino core, `delay()` is a busy wait that keeps the CPU running. In
his answer, Duncan C correctly states that “CMOS logic circuits do use
more power when switching states than when idle”. It is then expected
that instructions that switch a large number of gates or flip-flops
consume more power than instructions that only switch a few ones.

Out of curiosity, I disassembled a call to `delay()` to see what kind of
instructions it executes. I found that the “hot path” is a loop that
executes 44 instructions per iteration:

* 23 of them do arithmetic or logic (add, subtract, compare, XOR)
* 13 move data around (register load, register copy, I/O, read RAM)
* 7 alter the program flow (function call, return, jump, conditional
  branches, conditional skip)
* 1 alters a bit in a status register

I do not know how this compares with “typical” code, but the large
proportion of instructions that do arithmetic and logic computations
suggests that `delay()` should be way more energy hungry than, say, a
long sequence of [`nop`][nop] instructions. In the end, the only way to
know for sure whether `delay()` changes anything to the power
consumption of a specific program would be to measure it.

As a side note, an easy way to save some power on AVR boards is to
`#include <avr/sleep.h>` and insert a call to `sleep_mode()` at the end
of `loop()`. The sleep with not last for long though, as the Arduino
core sets Timer 0 to interrupt the CPU every 1024 µs.

[nop]: https://en.wikipedia.org/wiki/NOP_(code)


message:
Send SMS Arduino Uno + SIM900A shield

I am working on a module to send messages. I write the message on the serial monitor + phone number and I have to send the message to the line.

***Question:***

How to send messages through the SIM900A shield?

***Problem:***
What am I doing wrong in my code? Because I do not get an error but it does not send the SMS using the shield.

Try:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(6, 7);
    char msg;

    void setup() {
      mySerial.begin(9600); // Setting the baud rate of GSM Module
      Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);
    }

    void loop() {
      if (Serial.available()>0)
        switch(Serial.read()) {
          mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
          delay(1000); // Delay of 1000 milli seconds or 1 second
          mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
          delay(1000);
          mySerial.println("sim900a sms");// The SMS text you want to send
          delay(100);
          mySerial.println((char)26);// ASCII code of CTRL+Z
          delay(1000);
        }
      if (mySerial.available()>0) Serial.write(mySerial.read());
    }

***This is my shield***
[![This is my shield][1]][1]

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

Other try:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(6, 7);
    char msg;

    void setup() {
      mySerial.begin(9600);  // Setting the baud rate of GSM Module
      Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);
    }

    void loop() {
      mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
      delay(1000);
      mySerial.println("sim900a sms");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
    }

body:
There was not really a question, but I do notice there is no case's in your switch statement..

example from [here][1]

    // do something different depending on the range value:
      switch (range) {
        case 0:    // your hand is on the sensor
          Serial.println("dark");
          break;
        case 1:    // your hand is close to the sensor
          Serial.println("dim");
          break;
        case 2:    // your hand is a few inches from the sensor
          Serial.println("medium");
          break;
        case 3:    // your hand is nowhere near the sensor
          Serial.println("bright");
          break;
      }
      delay(1);        // delay in between reads for stability

  [1]: https://www.arduino.cc/en/Tutorial/SwitchCase


message:
Why is there a third connection to the host in this 3 wire current output sensor diagram?

I've got a 3 wire 4-20mA current output sensor, externally powered by 12V, which I want to read from an Arduino Uno (5V). The sensor connection diagram is below, but I don't understand why it says to connect the sensor power out (12V) to the host as well?

Below that is how I think I should connect it (i.e. with the power out from the sensor simply connected back to itself). Will this work? Could I damage my board or, far worse, the sensor itself this way?

Thanks alot!

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

  [1]: https://i.stack.imgur.com/wPNhO.png
  [2]: https://i.stack.imgur.com/eQ4Nj.png

body:
The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.

All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

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

<!-- End schematic -->

In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good.  RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does).  D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.


message:
Use Wii Remote and Arduino to emulate a keyboard for Windows 10?

Is it possible to use an Arduino to communicate with a Wii Remote, connect the Arduino to a Windows 10 computer, and have the Wii Remote inputs be translated into keyboard keys for Windows 10?

I've used several Wii Remote Windows 10 apps, such as WiiUSoft, but I find such programs very unreliable.

Thanks for any help.

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

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

body:
The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard.  There are examples in the IDE that show how to do this.

It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible.  So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.

There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including [a library](https://hardwarefun.com/projects/wiiremote)), so couple that with the examples in the IDE and a suitable board and you are good to go.  From then on it's just a Simple Matter of Programming...


message:
Hold all "millis()" values in an array?

I'm working on a project where I could have up to six devices connected to an arduino, it might be the case that not all of them will be attached at the same time, and all of them need to be able to receive PWM signals but without using delay().

There are a number of different PWM patterns already programmed into the code, what I'd like to do is be able to assign more than one device to a single pattern, and start/stop the patterns at different times to different devices.

I have a python script (and soon an Android app) that sends a message in the following format to the device:

`<int(pin_number), string(pattern_name), int(highest_pwm_value 0 - 255), int(delay_between_pulses_in_seconds)>`

Is there some way of coding something like the following, and if so, how would I go about it?

    array timings[];

    void fade(unsigned long thisMillis, int fadeInterval, int maxPWM, int motor_pin) {
      if (thisMillis - timings[motor_pin] >= fadeInterval) {
        // yup, it's time!
        if (fadeDirection == 1) {
          fadeValue = fadeValue + fadeIncrement;
          if (fadeValue >= maxPWM) {
            // At max, limit and change direction
            fadeValue = maxPWM;
            fadeDirection = 0;
          }
        } else {
          //if we aren't going up, we're going down
          fadeValue = fadeValue - fadeIncrement;
          if (fadeValue <= minPWM) {
            // At min, limit and change direction
            fadeValue = minPWM;
            fadeDirection = 1;
          }
        }
        // Only need to update when it changes
        analogWrite(motor_pin, fadeValue);

        // reset millis for the next iteration (fade timer only)
        timings[motor_pin] = thisMillis;
      }
    }

The bit that I'm unsure about is how the array should be defined etc, as I'm primarily a python developer so it's rare I have to explicitly set the type of an item in an array!

body:
This is a classic example where you want to create a class.  A class will contain all the control logic for dealing with one pin - all the functions, all the variables, etc.

Then you just create as many instances of the class as you need for your different pins. Each one is completely separate from the other, and each one can be controlled at will.

For instance, you might make something like this (untested):

    class FaderPin {

        private:
            uint32_t timestamp;
            int motor_pin;
            int fadeInterval;
            int minPWM;
            int maxPWM;
            int fadeDirection;
            int fadeValue;

        public:
            FaderPin(int pin, int minp, int maxp, int interval) {
                motor_pin = pin;
                minPWM = minp;
                maxPWM = maxp;
                fadeInterval = interval;
                fadeDirection = 1;
                fadeValue = minp;
                timestamp = millis();
            }

            void fade() {
                uint32_t thisMillis = millis();
                if (thisMillis - timestamp >= fadeInterval) {
                    // yup, it's time!
                    if (fadeDirection == 1) {
                        fadeValue = fadeValue + fadeIncrement;
                        if (fadeValue >= maxPWM) {
                            // At max, limit and change direction
                            fadeValue = maxPWM;
                            fadeDirection = 0;
                        }
                    } else {
                        //if we aren't going up, we're going down
                        fadeValue = fadeValue - fadeIncrement;
                        if (fadeValue <= minPWM) {
                            // At min, limit and change direction
                            fadeValue = minPWM;
                            fadeDirection = 1;
                        }
                   }
                   // Only need to update when it changes
                   analogWrite(motor_pin, fadeValue);
                   // reset millis for the next iteration (fade timer only)
                   timestamp = thisMillis;
               }
           }

    };

Then you can:

    FadePin motorOne(5, 0, 255, 10);
    FadePin motorTwo(6, 0, 255, 10);

And regularly call:

    motorOne.fade();
    motorTwo.fade();


body:
The answer given at https://forum.arduino.cc/index.php?topic=529364.msg3608306#msg3608306 is as follows:

    struct motor_data {
       int id;
       unsigned long start_time;   //store time stamp here
       unsigned long duration;      //time ends    ...
    };

    motor_data motors[6] //declaration
    motors[0].start_time = millis(); //accessing

Thoughts on this approach?


message:
Why am I getting only around 40% the range of my ADS1115 using an Arduino Uno?

I've connected my ADS1115 to an Arduino Uno as in the diagram (Vdd - 5V, Gnd - Gnd, SDA/SCL - SDA/SCL), all powered from the USB on a PC, with A0-3 unconnected, and am getting readings of around 3000 (i.e. 3000/65535 on 5V supply = 0.23V) from all four analog pins. Then if I connect them to 3.3V output on the arduino they give me only 17625 (i.e. 1.34V) i.e. about 40% of the full range I expected. If I try with a seperate 5V supply, it's still the same problem. Why is this?

P.S. sorry the code format below isn't very good, but basically it reads the four pins by
`int16_t V1 = ads.readADC_SingleEnded(PIN) `.

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

    #define THERMISTORPIN1 0
    #define THERMISTORPIN2 1
    #define SHELLPTPIN 2
    #define SPAREPIN 3
    #include < Wire.h >
    #include < Adafruit_ADS1015.h >

    Adafruit_ADS1115 ads(0x48);  //16 bit ADC add-on for arduino for better temperature resolution
    float Voltage = 0.0;

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

    void loop(void)
    {
     int16_t V1;
     int16_t V2;
     int16_t V3;
     int16_t V4;
     long cumV1;
     long cumV2;
     long cumV3;
     long cumV4;
     float avgV1;
     float avgV2;
     float avgV3;
     float avgV4;

     //take readings of voltages between resistor and thermsitor
     int i=0;

     while(i<6) {
      V1 = ads.readADC_SingleEnded(THERMISTORPIN1); //5 readings to allow the arduino capacitors to equalize with the pin voltage, to increase accuracy
      V2 = ads.readADC_SingleEnded(THERMISTORPIN2);
      V3 = ads.readADC_SingleEnded(SHELLPTPIN);
      V4 = ads.readADC_SingleEnded(SPAREPIN);
      i++;
      delay(10);
     }

     while(6<=i && i<16) {
      cumV1+= ads.readADC_SingleEnded(THERMISTORPIN1);  //multiple measurements from which to take an average, to increase precision
      cumV2+= ads.readADC_SingleEnded(THERMISTORPIN2);
      cumV3+= ads.readADC_SingleEnded(SHELLPTPIN);
      cumV4+= ads.readADC_SingleEnded(SPAREPIN);
      i++;
      delay(10);
     }

     avgV1=cumV1/10;
     avgV2=cumV2/10;
     avgV3=cumV3/10;
     avgV4=cumV4/10;

     //print out information to serial monitor on laptop
     Serial.print(V1);
     Serial.print(" ");
     Serial.print(V2);
     Serial.print(" ");
     Serial.print(V3);
     Serial.print(" ");
     Serial.println(V4);
     Serial.print(" ");
     Serial.print(avgV1);
     Serial.print(" ");
     Serial.print(avgV2);
     Serial.print(" ");
     Serial.print(avgV3);
     Serial.print(" ");
     Serial.println(avgV4);
     //Serial.println();
     delay(1000);
    }

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

body:
Your readings are correct because you have the default gain set. You have incorrectly assumed that you can convert the ADC reading from your 16-bit ADC to Volts by dividing by `2^16 - 1`. Your ADC has gain settings to have more accurate readings for certain voltage intervals. If we look at the [example sketch][1], we see

     void setup(void)
    {
      Serial.begin(9600);
      Serial.println("Hello!");

      Serial.println("Getting single-ended readings from AIN0..3");
      Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

      // The ADC input range (or gain) can be changed via the following
      // functions, but be careful never to exceed VDD +0.3V max, or to
      // exceed the upper and lower limits if you adjust the input range!
      // Setting these values incorrectly may destroy your ADC!
      //                                                                ADS1015  ADS1115
      //                                                                -------  -------
      // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
      // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
      // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
      // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
      // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
      // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

      ads.begin();
    }

Your ADC has a default gain of 2/3, or 0.1875mV per count. You say when you connect 3.3V to the pin, you get a reading of 17625. Thus we have

    17625 * 0.1875 / 1000.0 [V]
    = 3.3046875 [V]

Which is a correct reading. A reading on a floating pin (nothing attached) is irrelevant. Use the correct factors from above to convert your read ADC value to voltage.

Side note: In line

    avgV1=cumV1/10;

You have the `float avgV1` on the left and `cumV1` (a `long`) divided by 10 on the right; this will do a integer division. Make sure to divide by `10.0f` if you want a floating point average.

Side note 2:

These factors do make sense. If you apply positive 6.144V on the 2/3rd gain setting, you will read the maximum positive value of a `int16_t`, i.e. 2^15-1 = 32767 (solve above formula for the count). If you apply -6.144V, you get -32768; thus the full 16-bit number space is used. On differnt gain settings it analogous.

  [1]: https://github.com/adafruit/Adafruit_ADS1X15/blob/master/examples/singleended/singleended.pde


message:
writing very long function

I'm writing an Arduino program, and I need to write a function to input some numbers trough a computer connected to it trough the serial interface.

This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.

---
What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:

    class GetNumbers {
        public:
            //using the constructor as what I called "main" function
            GetNumbers(int arg1, char arg2) {
                performFirstAction();
                performSecondAction();
                ...
            }
        private:
            performFirstAction() {...};
            performSecondAction() {...};
            ...

            bool aSharedVariable;
            int anotherVariable;
            ...
    };
And where I actually need to input those numbers from the computer:

    GetNumbers uselessName (x,y);

Making the "main" function a normal class method (and not the constructor) seems to be even worse:

    GetNumbers myClass;
    myClass.getNumbers(x,y);
    ...
    //somewhere else in the same scope
    myClass.getNumbers(r,s);

body:
Maybe it's my background of old C programmer but... I would just write
plain functions, no classes, like in C. And I would keep all this stuff
in a single file, to provide some form of encapsulation:

my\_parser.h:

    some_type get_numbers(int arg1, char arg2);

my\_parser.cpp:

    static int performFirstAction(float arg1, int arg2, char arg3)
    {...}

    static bool performSecondAction(long arg1, void *arg2, int arg3)
    {...}

    some_type get_numbers(int arg1, char arg2)
    {...}

Note that there is only one function declared in the .h: this is the
“interface” to your module. Note also that all the other functions are
defined as `static`. This tells the compiler to keep them hidden from
the linking phase, so they do not pollute the global namespace. And
finally, note that there is no global shared variable: everything is
passed as arguments to the functions.

The rationale for the last point is that this helps the compiler
optimize things. A static function that is called only once is almost
guaranteed to be inlined by the compiler. Which means there is no
overhead in passing the arguments. On the other hand, if you use global
variables and the compiler doesn't manage to optimize them away, you
will incur the cost of RAM access.


message:
Initialization of function pointer array

I have an array of function pointers:

    unsigned int dimension = 8;
    void (* myFunctions [dimension])();

This array is a member of a class:

    class myClass {

        static const unsigned int dimension;

        void (* myFunctions [dimension])();
    }

and in a cpp file:

    const unsigned int dimension = 8;

It's size is known at compile time, but it's values will be added through a public method in unknown parts of the code. I need to be able to find out at any time whether there is a valid pointer at some index in that array at any time, and my idea was to do that by comparing the pointer against `nullptr`: if it doesn't equals it then I'll assume that it holds a valid function pointer.

I was wondering if I need to initialize the array before making that kind of speculation. How is this array initialized if I only write the above two lines of code? Can I assume something like `myFunctions[x] ==  nullptr` is true in that case? Or do I need to do an explicit initialization like the following one?

    for(int i = 0; i < dimension; i++)
        myFunctions[i] = nullptr;

body:
You should actively zero-initialize your pointers in the constructor of your class.

The "zero-initialization" of the C++ language only applies in certain cases defined [here][1]. In certain configurations, e.g., when the object of the class has an explicit constructor which does not initialize the array, or when the class has no constructor and an object is function-locally created by typing `myClass myObject;`, the pointers are not initialized to `nullptr`.

They do get automatically zero-initialized via the C++ standard without you doing anything if an object of this class is declared and defined as a global variable, though. Then you have a "static storage location", and your object is zero-init'ed by zero-init'ing every data member. Your array of function pointers gets then member-wise zero-init'ed to the zero-value of a pointer, i.e., `nullptr`.

But you should write robust code which is always correct regardless of which kind of method is used to instantiate the object. Thus, the `for` loop in the constructor as you have it is correct.

See the analogous question I asked [here][2] (which I asked because I gave an initially wrong answer and felt responsible).

  [1]: http://en.cppreference.com/w/cpp/language/zero_initialization
  [2]: https://stackoverflow.com/questions/48809894/c-zero-initialization


body:
It's seem like the array is initialized with nullptr. I got to read the 1,600 pages C++17 specification to be sure. Meanwhile, I test.

You can always initialize explicitly the array, in the constructor.

Here a brief proof of concept for you to try. (I made public the class member to keep things short).

    //  An empty function, do nothing
    void someFunction()
    {

    }

    class MyClass
    {
    public:
     MyClass()
     {
      for(int i = 0; i < dimension; i++) {
       myFunctions[i] = someFunction; // Replace with nullptr to test.
      }
     }

    static const unsigned int dimension = 5;
    void (*myFunctions[dimension])();
    };

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

     while(!Serial);

     MyClass test;

     for(auto x : test.myFunctions) {
      if(x == nullptr) {
       Serial.println("null");
      } else {
       if(x == someFunction) {
        Serial.println("some function");
       } else {
        Serial.println("????");
       }
      }
     }
    }

    void loop()
    {

    }


message:
ILI9341 backlight flickers when using USB power from Laptop

I've developed a project using am ILI9341, ESP12F and Arduino. Everything works fine except a very annoying issue. The LCD flickers when I use the laptop's USB. But when I use a USB charger it's much better.

I use https://github.com/Bodmer/TFT_eSPI library for SPI driver and AMS1117 as regulator (with 1uf in the input, and 10uf in output).

I don't think the software has a problem because I don't refresh anything on the display (just draw something in the setup function, not in loop) and also it changes with different power sources. The problem is the backlight.

When I move the USB cable it goes crazier sometimes. I've checked it with many different cables and computers. Is this because of noise or something from the USB port? How can I fix this?

It's very important for me to be able to use the USB port as the power source.

# Update
When I'm uploading the code to the ESP8266 (using TXD & RXI), the LCD doesn't flicker event a little bit! And immediately after finishing the upload, the LCD brightness decreases and starts flickering!

The circuit is pretty simple and LCD pins are connected directly as listed [here](https://raw.githubusercontent.com/Bodmer/TFT_eSPI/master/User_Setup.h)

body:
That happens because not all USB ports can supply more than 500mA of current.
When you use a charger's USB port, it is designed to provide more than 500mA of current(ex. 1-2amps in most chargers). Try using a USB port that can provide more than 500mA of current. Most PCs and Laptops will only supply 500mA at maximum unless specified so.

More information regarding USB power can be read [here on Wikipedia][1].

Cheers!

  [1]: https://en.wikipedia.org/wiki/USB#Power


body: I fixed this issue finally. The USB could supply both ESP and ILI9341, but the regulator could not. AMS1117 is not able to handle both EPS and ILI9341, we could connect ILI9341 directly to v5 (which it's not good and it would be hot!) or we can use another cheap regulator like XC6206P332MR just for the LCD.


body: I solve the problem controlling the frecuency of refresh with the led pin. With a timer of 10ms disappears flickering


message:
Grove A12-200 current sensor

I am trying to measure current from an LFG with Arduino Uno and Grove current sensor (A12-200). I found a code at this link [you can see Arduino code here][1].

  [1]: http://wiki.seeed.cc/Grove-Electricity_Sensor/

The code works, but there are some operations that I don't understand. Let me copy and paste the code here (for further information, please follow the link above).

    /****************************************************************************/
    //  Function: Measure the amplitude current of the alternating current and
    //            the effective current of the sinusoidal alternating current.
    //  Hardware: Grove - Electricity Sensor
    //  Date:    Jan 19,2013
    //  by www.seeedstudio.com
    #define ELECTRICITY_SENSOR A0 // Analog input pin that sensor is attached to

    float amplitude_current;               //amplitude current
    float effective_value;       //effective current

    void setup()
    {
        Serial.begin(9600);
        pins_init();
    }
    void loop()
    {
        int sensor_max;
        sensor_max = getMaxValue();
        Serial.print("sensor_max = ");
        Serial.println(sensor_max);
        //the VCC on the Grove interface of the sensor is 5v
        amplitude_current=(float)sensor_max/1024*5/800*2000000;
        effective_value=amplitude_current/1.414;//minimum_current=1/1024*5/800*2000000/1.414=8.6(mA)
                            //Only for sinusoidal alternating current
        Serial.println("The amplitude of the current is(in mA)");
        Serial.println(amplitude_current,1);//Only one number after the decimal point
        Serial.println("The effective value of the current is(in mA)");
        Serial.println(effective_value,1);
    }
    void pins_init()
    {
        pinMode(ELECTRICITY_SENSOR, INPUT);
    }
    /*Function: Sample for 1000ms and get the maximum value from the SIG pin*/
    int getMaxValue()
    {
        int sensorValue;             //value read from the sensor
        int sensorMax = 0;
        uint32_t start_time = millis();
        while((millis()-start_time) < 1000)//sample for 1000ms
        {
            sensorValue = analogRead(ELECTRICITY_SENSOR);
            if (sensorValue > sensorMax)
            {
                /*record the maximum sensor value*/
                sensorMax = sensorValue;
            }
        }
        return sensorMax;
    }

<!-- -->

    effective_value=amplitude_current/1.414

I don't understand why dividing `amplitude_current` by 1.414 we'll get `effective_current`.

And in the function `getMaxValue()`, I know what it does, but I don't understand why we just need `maxvalue`.

body:
You are measuring a sinusoidal "signal" that is alternating in polarity. What the code notes as "effective" current the equivalent DC current for purposes of measuring power consumption. In EE, it's called "RMS" or Root Mean Square, and it's the mathematical derivation to calculate consumed power or current in a situation where the current flows symmetrically back and forth, and thus a time average would give zero.

It's dividing the peak current by the square-root of 2 (1.414).


message:
My outputs are not outputting any current at only two of my pinmodes but work fine on the others

My pinMode output 5 and 6 don't works with this code but will work when they are stand alone.

What is causing the Arduino to not output anything from these outputs within my code?

    #include <SoftwareSerial.h>                    // use the software serial library
    SoftwareSerial mySerial(3,4); // receive data at pin 3; transmit data at pin 2
    int setpoint;
    float val;
    int roomtemp;
    int UCL;
    int LCL;

    float salinity;
    void setup()
    {
     // put your setup code here, to run once:
     Serial.begin(9600);
     pinMode(5,OUTPUT);
     pinMode(6,OUTPUT);
     pinMode(3,OUTPUT);
     pinMode(2, OUTPUT);
     roomtemp=25;
     setpoint=7.0291*roomtemp+334.73;
     UCL=setpoint+6.12;
     LCL=setpoint-6.12;
     Serial.print("Setpoint =");
     Serial.print(setpoint);
     Serial.print("Degrees Celsius");
     Serial.print("UCL =");
     Serial.print(UCL);
     Serial.print("Degrees Celsius");
     Serial.print("LCL =");
     Serial.print(LCL);
     Serial.print("Degrees Celsius");
     mySerial.begin(9600);
     delay(500);           // set data rate to 9600 baud; wait for bootup
     mySerial.write(254);
     mySerial.write(128);
     mySerial.write(254);
     mySerial.write(1);    // clear screen & move to top left position
     mySerial.write(254);
     mySerial.write(132);
     mySerial.print("LCL");
     mySerial.write(254);
     mySerial.write(139);
     mySerial.print("SP");
     mySerial.write(254);
     mySerial.write(144);
     mySerial.print("UCL");
     mySerial.write(254);
     mySerial.write(192);
     mySerial.print("S:");
     mySerial.write(254);
     mySerial.write(195);
     mySerial.print(0.072,3);
     mySerial.write(254);
     mySerial.write(201);
     mySerial.print(0.100,3);
     mySerial.write(254);
     mySerial.write(207);
     mySerial.print(0.108,3);
     mySerial.write(254);
     mySerial.write(148);
     mySerial.print("T:");
     mySerial.write(254);
     mySerial.write(152);
     mySerial.print("24.1");
     mySerial.write(254);
     mySerial.write(158);
     mySerial.print("25.0");
     mySerial.write(254);
     mySerial.write(164);
     mySerial.print("25.9");
     mySerial.write(254);
     mySerial.write(212);
     mySerial.write(254);
     mySerial.write(212);
     mySerial.print("S=");
     mySerial.write(254);
     mySerial.write(220);
     mySerial.print("T=");
    }

    void loop()
    {
     Serial.println();
     int val=analogRead(5);
     Serial.print("Analog Value =");
     Serial.print(val);
     Serial.print("Temperature =");
     Serial.println((0.14227*val)-47.621);

     if(val<LCL) { digitalWrite(3,HIGH); }
     else if(val>UCL) { digitalWrite(3,LOW); }

     mySerial.write(254);
     mySerial.write(227);

     if(val<LCL) { mySerial.write("H= ON"); }

     mySerial.write(254);
     mySerial.write(227);

     if(val>UCL) { mySerial.write("H=OFF"); }

     digitalWrite(2, HIGH);
     delay(100);
     int analogS=analogRead(4);
     digitalWrite(2, LOW);
     Serial.println(analogS);
     delay(1000);
     salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
     Serial.print("Salinity =");
     Serial.println(salinity);
     mySerial.write(254);
     mySerial.write(214);
     mySerial.print(salinity);
     mySerial.write(254);
     mySerial.write(222);
     mySerial.print((0.14227*val)-47.621,1);
     Serial.println("analog value");
     Serial.print(analogRead(4));
     float target= (salinity-(salinity-.1)*.60);
     float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
     float denom= ((.1));
     float valve= ((numer/denom)/10.00);

     if(.096<salinity>.104) {
      delay(5000);
     }

     if(salinity>.104) {
      Serial.print("Entering DIon Function");
      digitalWrite(6,HIGH);
      delay(valve);
      digitalWrite(6,LOW);
      delay(5000);
     }

     if(salinity<.096) {
      Serial.print("Entering Saltyon Function");
      digitalWrite(5,HIGH);
      delay(valve);
      digitalWrite(5,LOW);
      delay(5000);
     }

     Serial.print("time");
     Serial.println(valve);
    }

body:
I think the problem is not in the output pin (which you say works elsewhere) but in your calculations. I made a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) of the part of the code that does the calculations, testing every possible reading you might have got from `analogRead(4)` (mainly because I found the calculations code rather obscure). Here it is:

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

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

    void loop()
      {
      for (int analogS=0; analogS < 1024; analogS++)
        {
        Serial.print ("analogS = ");
        Serial.print (analogS);
        salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
        Serial.print (", Salinity = ");
        Serial.print (salinity);
        float target= (salinity-(salinity-.1)*.60);
        float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
        float denom= ((.1));
        float valve= ((numer/denom)/10.00);
        Serial.print(",  valve = ");
        Serial.println(valve);
        }
       Serial.flush ();
       exit (1);
      }

Testing that reveals:

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

    analogS = 0, Salinity = 0.00,  valve = 3.64
    analogS = 1, Salinity = 0.00,  valve = 3.64
    analogS = 2, Salinity = 0.00,  valve = 3.64
    analogS = 3, Salinity = 0.00,  valve = 3.64
    ... some lines omitted ...
    analogS = 1016, Salinity = 6.21,  valve = 3.64
    analogS = 1017, Salinity = 6.25,  valve = 3.64
    analogS = 1018, Salinity = 6.28,  valve = 3.64
    analogS = 1019, Salinity = 6.32,  valve = 3.64
    analogS = 1020, Salinity = 6.35,  valve = 3.64
    analogS = 1021, Salinity = 6.39,  valve = 3.64
    analogS = 1022, Salinity = 6.43,  valve = 3.64
    analogS = 1023, Salinity = 6.46,  valve = 3.64

As you can see, `valve` is always 3.64, so you will be doing this:

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

        digitalWrite(6,HIGH);
        delay(3);
        digitalWrite(6,LOW);

In other words, port 6 will be HIGH for 3 milliseconds, probably too short a time for you to notice. Ditto for port 5.

---

Also this doesn't do what I suspect you think it does:

    if(.096<salinity>.104) {
        delay(5000);
    }

That will evaluate `.096 < salinity` to be 0 or 1. Then it will evaluate:

    0 > 0.104
    1 > 0.104

This is not what you are intending, I think. Try:

    if(salinity < .096 || salinity > .104) {
        delay(5000);
    }

If that is what you mean, I can't be sure - maybe you mean the opposite:

    if(salinity > .096 && salinity < .104) {
        delay(5000);
    }

If you write things out clearly, without trying to do shortcuts, it will be much more obvious what the test really is.


message:
My shield does not have further female headers? How do I stack more shields?

I purchased a motor shield (L293D) and it doesn't have the female header which I can connect to another shield. What can I do to stack up more shields?
For being more specific I ordered my shield from here:
https://www.amazon.in/Simple-Labs-SLAEX039-Shield-Arduino/dp/B00K2Z3GAE/ref=sr_1_1?ie=UTF8&qid=1518767182&sr=8-1&keywords=motor+shield+for+arduino+uno&dpID=41h0ag2SCgL&preST=_SX342_QL70_&dpSrc=srch

And please tell me how to do it because it is new for me. A guide or something?

body:
Many shields cannot be stacked, even if you replace the headers. The biggest reason is that the shield uses most of, if not all, the available pins. Motor shield often fall into this category, so they don't add the pointless expense of stackable headers.

Before you consider stacking any shields, whether they have stackable headers or not, you first need to learn how the shields work and what pins they require to ensure there are no conflicts.


message:
Determine an earthquake intensity/magnitude level using ADXL345 and Arduino

I want to create a project using Arduino that monitor the Earthquake. I used an ADXL345 Accelerometer to detect if there is an earthquake. I used the Adafruit ADXL345 example to determine a acceleration of x-axis, y-axis and z-axis in terms of m/s^2. I want to used the Japan Meteorological Agency seismic intensity scale to determine the intensity level of the earthquake because it gives the Peak Ground Acceleration. If there is a way to determine the earthquake intensity level using ADXL345?

body:
[Copied from https://stackoverflow.com/questions/48365221/accelerometer-using-adxl345-for-earthquake-detection]

That sensor is not suitable. It has 13 bit resolution at +-16g full range. That gives you a sensitivity of 0.002g for the lsb. In order to detect an earthquake directly below you, you need approx. a few milli-g ([e.g. see here][1]), even less for earthquakes with an epicentre elsewhere.

You want a sensor which is much more sensitive by a factor of 100 and probably with more resolution (better ADC), too.

(And you should have been able to do this quick google-search analysis yourself ;) )

  [1]: https://en.wikipedia.org/wiki/Peak_ground_acceleration


message:
Using the physical serial port on a BSFrance LoRa32u4?

I can use the serial-over-USB channel by simply using `Serial` in my code.

The LoRa32u4 has an RXD1 and TXD1 pair on pins 20/21 (Arduino 0/1).

[![enter image description here][1]][1]
https://docs.bsfrance.fr/documentation/11296_LORA32U4/LoRa32u4_pinout_diagram.pdf

How do I configure and use this serial port (for receiving NMEA GPS)?

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

body: >[ATmega32U4-based boards use] Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started page and hardware page.


message:
How to measure electrical conductivity using Arduino?

I want to measure TSS (Total soluble salt) in the soil. I have found in some literature that, through measuring of electrical conductivity, it is much easier to measure TSS. So, I thought, If I can measure electrical conductivity, it might be possible to find out TSS.

Logic behind the TSS is that, pure water is poor conductor of electric, increasing of soluble salt in water proportionately lift up the conductivity. So are there any sensors that readily measure conductivity? A point I also want to mention, can a voltmeter be useful for that?

body:
That should be possible  ... connect +5V to one end, an analog input pin on the other, don't forget a resistor which is high enough not to get more current than allowed. Than measure on the analog input pin the conductivity (value) and act on it.

Afaik the max amperage for an analog pin is 20 mA if I remember correctly. Thus a resistor of V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250 ohm should be ok. This will only occur if the conductivity is 100%. If you get a very low conductivity than you will get very low numbers when reading the analog pin. When you get too less values, you have to lower the resistor value, but you risk of burning a pin when too much current gets across.


body:
The answer is [Three Dollar EC - PPM Meter \[Arduino\]][1]. I tried it against a consumer level EC meter and got the same results after calibration. It's cheap and simple.

[![Arduino EC Meter pinout][2]][2]

The only warning is that there is several scales in use to measure EC, so results may not be comparable between diferentes devices **and** you have to read carefully the EC recomendations for your water solution.

**EC units**

Electrical conductivity can be expressed using a number of different units, but the typical unit is siemens per meter2 per mole (S/m2/mole) or millisiemens per centimetre (mS/cm). The mS/cm unit is generally used in Europe as a guide to the concentration of nutrients in water. In North America, conductivity is converted into a count of the ions in the water using parts per million (which can also be converted into units including mg/l etc.). This is done by converting the EC into a value based on the ions contained in the solution. Fortunately, there is a fixed calculation for the relationship between all these units, which is given in the table below.

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

**Code for the EC meter**

    /*
      ElCheapo Arduino EC-PPM measurments

      This scrip uses a common USA two prong plug and a 47Kohm Resistor to measure the EC/PPM of a Aquaponics/Hydroponics Sytem.
      You could modift this code to Measure other liquids if you change the resitor and values at the top of the code.

      This Program will give you a temperature based feed controller. See Read me in download file for more info.

      28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

              This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see .

        Parts:
        -Arduino - Uno/Mega
        -Standard American two prong plug
        -1 kohm resistor
        -DS18B20 Waterproof Temperature Sensor

        Limitations:
        -
        -

        See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

    */

    #include <OneWire.h>
    #include <DallasTemperature.h>

    //************************* User Defined Variables ********************************************************//

    int R1= 1000;
    int Ra=25;          //Resistance of powering Pins
    int ECPin= A0;
    int ECGround=A1;
    int ECPower =A4;

    //*********** Converting to ppm [Learn to use EC it is much better**************//
    // Hana      [USA]        PPMconverion:   0.5
    // Eutech    [EU]         PPMconversion:  0.64
    // Tranchen  [Australia]  PPMconversion:  0.7
    // Why didnt anyone standardise this?

    float PPMconversion=0.5;

    //*************Compensating for temperature ************************************//
    // The value below will change depending on what chemical solution we are measuring
    // 0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
    float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

    //********************** Cell Constant For Ec Measurements *********************//
    // Mine was around 2.9 with plugs being a standard size they should all be around the same
    // But If you get bad readings you can use the calibration script and fluid to get a better estimate for K
    float K=2.34;

    //************ Temp Probe Related *********************************************//
    #define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
    const int TempProbePossitive =8;  //Temp Probe power connected to pin 9
    const int TempProbeNegative=9;    //Temp Probe Negative connected to pin 8

    //***************************** END Of Recomended User Inputs *****************************************************************//

    OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
    DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

    float Temperature=10;
    float EC=0;
    float EC25 =0;
    int   ppm =0;

    float raw= 0;
    float Vin= 5;
    float Vdrop= 0;
    float Rc= 0;
    float buffer=0;

    //*********************************Setup - runs Once and sets pins etc ******************************************************//
    void setup()
    {
     Serial.begin(9600);
     pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
     digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
     pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
     digitalWrite(TempProbePossitive , HIGH);
     pinMode(ECPin,INPUT);
     pinMode(ECPower,OUTPUT);//Setting pin for sourcing current
     pinMode(ECGround,OUTPUT);//setting pin for sinking current
     digitalWrite(ECGround,LOW);//We can leave the ground connected permanantly

     delay(100);// gives sensor time to settle
     sensors.begin();
     delay(100);
     //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
     // Consule Read-Me for Why, or just accept it as true
     R1=(R1+Ra);// Taking into acount Powering Pin Resitance

     Serial.println("ElCheapo Arduino EC-PPM measurments");
     Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
     Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
     Serial.println("");
     Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
     Serial.println("");
     Serial.println("Measurements at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:");
    }

    void loop()
    {
     GetEC();          //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water
     PrintReadings();  // Cals Print routine [below main loop]
     delay(5000);
    }

    void GetEC()
    {
     sensors.requestTemperatures();          // Send the command to get temperatures
     Temperature=sensors.getTempCByIndex(0); //Stores Value in Variable
     //************Estimates Resistance of Liquid ****************//
     digitalWrite(ECPower,HIGH);
     raw= analogRead(ECPin);
     raw= analogRead(ECPin);// This is not a mistake, First reading will be low beause if charged a capacitor
     digitalWrite(ECPower,LOW);

     //***************** Converts to EC **************************//
     Vdrop= (Vin*raw) / 1024.0;
     Rc = (Vdrop*R1) / (Vin-Vdrop);
     Rc = Rc-Ra; //acounting for Digital Pin Resitance
     EC = 1000/ (Rc*K);

     //*************Compensating For Temperaure********************//
     EC25  =  EC / (1+ TemperatureCoef*(Temperature-25.0));
     ppm=(EC25)*(PPMconversion*1000);
    }

    //***This Loop Is called From Main Loop- Prints to serial usefull info ***//
    void PrintReadings()
    {
     Serial.print("Rc: ");
     Serial.print(Rc);
     Serial.print(" EC: ");
     Serial.print(EC25);
     Serial.print(" Simens  ");
     Serial.print(ppm);
     Serial.print(" ppm  ");
     Serial.print(Temperature);
     Serial.println(" *C ");
    };

**Code for calibration**

    /*
      ElCheapo Arduino EC-PPM measurments Calibration

      This Script is used for calibration of the sensor and fine tuning of the Cell Constant K
      Submerge the sensor and temperature probe in the calibration solution and leave for a while so the temperature probe can settle
      Change the value of the calibration solution to suit the solutiton strength
      Stir the probe to make sure the solution is well mixed and upload the code to the arduino
      Open the terminal for an update of the estimated Cell Constant K [should be around 3] and use this new value in the main EC code.

      28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

              This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see .

        Parts:
        -Arduino - Uno/Mega
        -Standard American two prong plug
        -1 kohm resistor
        -DS18B20 Waterproof Temperature Sensor

        See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

    */

    //************************** Libraries Needed To Compile The Script [See Read me In Download] ***************//
    // Both below Library are custom ones [ SEE READ ME In Downloaded Zip If You Dont Know how To install Use them or add a pull up resistor to the temp probe

    #include <OneWire.h>
    #include <DallasTemperature.h>

    //************************* User Defined Variables ********************************************************//

    float CalibrationEC = 0.762; //EC value of Calibration solution is s/cm

    //##################################################################################
    //-----------  Do not Replace R1 with a resistor lower than 300 ohms    ------------
    //##################################################################################
    int R1 = 1000;
    int Ra = 25; //Resistance of powering Pins
    int ECPin = A0;
    int ECGround = A1;
    int ECPower = A4;

    //*************Compensating for temperature ************************************//
    //The value below will change depending on what chemical solution we are measuring
    //0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
    float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

    //************ Temp Probe Related *********************************************//
    #define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
    const int TempProbePossitive = 8; //Temp Probe power connected to pin 9
    const int TempProbeNegative = 9;  //Temp Probe Negative connected to pin 8

    //***************************** END Of Recomended User Inputs *****************************************************************//

    OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
    DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

    float TemperatureFinish = 0;
    float TemperatureStart = 0;
    float EC = 0;
    int ppm = 0;

    float raw = 0;
    float Vin = 5;
    float Vdrop = 0;
    float Rc = 0;
    float K = 0;
    int i = 0;
    float buffer = 0;

    //*********************************Setup - runs Once and sets pins etc ******************************************************//
    void setup()
    {
     Serial.begin(9600);
     pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
     digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
     pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
     digitalWrite(TempProbePossitive , HIGH);
     pinMode(ECPin, INPUT);
     pinMode(ECPower, OUTPUT); //Setting pin for sourcing current
     pinMode(ECGround, OUTPUT); //setting pin for sinking current
     digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly

     delay(100);// gives sensor time to settle
     sensors.begin();
     delay(100);
     //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
     // Consule Read-Me for Why, or just accept it as true
     R1 = (R1 + Ra);

     Serial.println("ElCheapo Arduino EC-PPM measurments Calibration");
     Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
     Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
     Serial.println("");
     Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
     Serial.println("");
     Serial.println("Starting Calibration: Estimated Time 60 Seconds:");
    };
    //******************************************* End of Setup
    //************************************* Main Loop - Runs Forever ***************************************************************//
    //Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop
    void loop()
    {
     i = 1;
     buffer = 0;
     sensors.requestTemperatures();// Send the command to get temperatures
     TemperatureStart = sensors.getTempCByIndex(0); //Stores Value in Variable

     //************Estimates Resistance of Liquid ****************//
     while(i <= 10) {
      digitalWrite(ECPower, HIGH);
      raw = analogRead(ECPin);
      raw = analogRead(ECPin); // This is not a mistake, First reading will be low
      digitalWrite(ECPower, LOW);
      buffer = buffer + raw;
      i++;
      delay(5000);
     };

     raw = (buffer / 10);

     sensors.requestTemperatures();// Send the command to get temperatures

     TemperatureFinish = sensors.getTempCByIndex(0); //Stores Value in Variable

     //*************Compensating For Temperaure********************//
     EC = CalibrationEC * (1 + (TemperatureCoef * (TemperatureFinish - 25.0))) ;

     //***************** Calculates R relating to Calibration fluid **************************//
     Vdrop = (((Vin) * (raw)) / 1024.0);

     Rc = (Vdrop * R1) / (Vin - Vdrop);

     Rc = Rc - Ra;

     K = 1000 / (Rc * EC);

     Serial.print("Calibration Fluid EC: ");

     Serial.print(CalibrationEC);

     Serial.print(" S  ");  //add units here

     Serial.print("Cell Constant K");

     Serial.print(K);

     if(TemperatureStart == TemperatureFinish) {
      Serial.println("  Results are Trustworthy");
      Serial.println("  Safe To Use Above Cell Constant in Main EC code");

     } else {
      Serial.println("  Error -Wait For Temperature To settle");
      Serial.print("Temp start=");
      Serial.print(TemperatureStart);
      Serial.print(" Temp end=");
      Serial.println(TemperatureFinish);
     }
    }
    //*************************** End Of Main Loop *******************************************************************//
EDIT:

Make sure to use a factory sealed male plug. If water get inside the plug, the voltage reading will be inaccurate.

  [1]: https://hackaday.io/project/7008-fly-wars-a-hackers-solution-to-world-hunger/log/24646-three-dollar-ec-ppm-meter-arduino
  [2]: https://i.stack.imgur.com/W4YHF.png
  [3]: https://i.stack.imgur.com/VpcM3.png


message:
Is there a sensor to measure a distance between 2 point as in range [0-2 meter]?

I'm looking for a way of detecting if 2 pieces of hardware are within 2 meters of eachother or not. The idea is to build a prototype to lock computers automatically. I just need a recommendation on the sensor if it exists. Geofencing, bluetooth etc are not reliable enough.

body:
You can use a lot of different methods with advantages/disadvantages:

- Use an IR LED/receiver and calculate the distance of travelling of the lights. Disadvantage: you need a very precise timing mechanism (light is fast), also take latency into account for non-light parts, and hardware needs to be in visible range and pointing to each other with LEDs)
- Use an ultrasonic sensor like SR-HC04. Disadvantage: devices must point to each other in a small precise angle.
- Using an RF method and sending/receiving e.g. via nRF24L01+ 2.4 GHz trasnceivers, to check the difference in time between sending and receiving when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.


message:
Why my loop stop working

i have an arduino, an RTC (time), a DHT (humidity and temp sensor), oled screen (128x32 ; microoled 1306) and 4 relais ;

all seems to work perfectly for hours, but sometime (1 or 2 per day..) everything stop working ;

- screen i frozen on last info displayed
- relais stay stuck in a random position (somtimes turning everythings ON (on=LOW with thoses relay.))

i obviously made a mistake, but don t know what...
what can cause a loop to stay stuck randomly ???
plz save me :)

**EDIT => A REWORK OF THAT TERRIBLE CODE AVAILABLE IN ANSWER, THE PROBLEM IS STILL THERE**

    // GND GND
    // A4 SCL
    // A5 SDA
    // VCC  5V

    // for DHT11,
    //      VCC: 5V or 3V
    //      GND: GND
    //      DATA: A7+

    // YL-39 + YL-69 humidity sensor
    const byte humidity_sensor_pin = A1;
    const byte humidity_sensor_vcc = 6;

    // ecran SDA / SDL
    // RELAIS Pin D8
    // RELAIS2 Pin D9
    // RELAIS3 Pin D10
    // RELAIS4 Pin D11

    // Relais reboot D5 ?

    #include <SimpleDHT.h>
    #include <Wire.h>
    #include "U8glib.h"
    #include "RTClib.h"

    const int pinDHT11 = 7;
     SimpleDHT11 dht11;

    RTC_DS1307 RTC;
    U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);

    const int relay = 8; // Light
    const int relay2 = 9; // Wind
    const int relay3 = 10; // Heat
    const int relay4 = 11; // Humidity

    // Time Variable
    DateTime InitTime ;
    int InitHour;

    const int startHour = 20;
    const int startMin = 01;
    const int startTime = startHour *100 + startMin;
    const int endHour = 8;
    const int endMin = 01;
    const int endTime= endHour *100 + endMin;
    const int maxWind = 5;
    const int startWind = 05;
    int lastWind ;

    const int dayMinTemp = 18;
    const int dayMaxTemp = 20;
    const int nightMinTemp = 16;
    const int nightMaxTemp = 19;

    const int minhum = 50;

    void drawInit(DateTime InitD){
    String text = String(InitD.day());
      text += " ";
    text += String(InitD.month());

    String text2 = String(InitD.hour());
      text2 += ":";
    text2 += String(InitD.minute());
    text2 += ":";
    text2 += String(InitD.second());

     u8g.setFont(u8g_font_unifont);
      u8g.setPrintPos(0,16);
      u8g.print(text);
      u8g.setPrintPos(0,32);
      u8g.print(text2);

    }
    void drawTemp(float temp, int hum, int nowT){
    String text = "Temp: ";
      text += temp;
        text += "*C";
    String text2 = "Hum: ";
      text2 += hum;
        text2 += "% :";
        text2 += nowT;

     u8g.setFont(u8g_font_unifont);
      u8g.setPrintPos(0,16);
      u8g.print(text);
      u8g.setPrintPos(0,32);
      u8g.print(text2);
    }

    void draw(String staT, String endT, String nowT){
    String iotxt;
    if (digitalRead(relay) == LOW){iotxt="On";}else{iotxt="Off";}

    String text = "S: ";
      text += staT;
      text += " E: ";
      text += endT;
    String text2 = "H: ";
      text2 += nowT;
    //  text2 += " L: ";
    //  text2 += iotxt;

      u8g.setFont(u8g_font_unifont);
      u8g.setPrintPos(0,16);
      u8g.print(text);
      u8g.setPrintPos(0,32);
      u8g.print(text2);
    }

    void drawerror(String error){
      String text = "err mod: ";
      text += error;

      u8g.setFont(u8g_font_unifont);
      u8g.setPrintPos(0,16);
      u8g.print(text);

    }

    void draw2(int nowTime){
      String iotxt;
      String hottxt;
      String lumtxt;
        String humtxt;

    if (digitalRead(relay) == LOW){lumtxt="On";}else{lumtxt="Off";}
    if (digitalRead(relay2) == LOW){iotxt="On";}else{iotxt="Off";}
    if (digitalRead(relay3) == LOW){hottxt="On";}else{hottxt="Off";}
    if (digitalRead(relay4) == LOW){humtxt="On";}else{humtxt="Off";}

    String text = "Hot: ";
      text += hottxt;
      text += " Lum: ";
      text += lumtxt;

    String text2 = "Hum: ";
      text2 += humtxt;
      text2 += " Win: ";
      text2 += iotxt;

      u8g.setFont(u8g_font_unifont);
      u8g.setPrintPos(0,16);
      u8g.print(text);
      u8g.setPrintPos(0,32);
      u8g.print(text2);
    }

    void setup () {

     pinMode(relay, OUTPUT);
     pinMode(relay2, OUTPUT);
     pinMode(relay3, OUTPUT);
     pinMode(relay4, OUTPUT);
     digitalWrite(relay, HIGH);
     digitalWrite(relay2,HIGH);
     digitalWrite(relay3,HIGH);
     digitalWrite(relay4,HIGH);

        Serial.begin(9600);
        Wire.begin();

        if (! RTC.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }
      RTC.begin();

       DateTime now = RTC.now();
     InitTime = now ;
    InitHour =  now.hour()*100 + now.minute();
    }

    void loop () {

     byte temperature = 0;
      byte humidity = 0;

    int err = SimpleDHTErrSuccess;
      if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    //    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);

        u8g.firstPage();
      do {
        drawerror("DHT");
      } while( u8g.nextPage() );
    delay(3000);

        return;
      }else{

      // Serial.print("Sample OK: ");
     // Serial.print((int)temperature); Serial.print(" *, ");
     // Serial.print((int)humidity); Serial.println(" H");

    // Relay Chaleur
    if (digitalRead(relay)==LOW){
    if((int)temperature < dayMinTemp){
       digitalWrite(relay3,LOW);
       //  Serial.print("HEAT : On");

      }else{digitalWrite(relay3,HIGH);
         //  Serial.print("HEAT : Off");
    }
      }else{
        if((int)temperature < nightMinTemp){
       digitalWrite(relay3,LOW);
         //   Serial.print("HEAT : On");

    }else{
          digitalWrite(relay3,HIGH);
       //  Serial.print("HEAT : Off");

          }
        }
    // fin relay chaleur

      if (! RTC.isrunning()) {
        drawerror("RTC");}else{

       DateTime now = RTC.now();

    int nowTime= now.hour()*100 + now.minute();

    // § WIND
    if(now.minute() >= startWind && now.minute() <= startWind+maxWind ){
          digitalWrite(relay2,LOW);
         // Serial.println("Wind ON");
          lastWind = nowTime;

      }else if(now.minute()>startWind+5 || now.minute()<startWind){
              digitalWrite(relay2,HIGH);
        //  Serial.println("Wind OFF");
          }

    // § END WIND

    // START humidity
    if(int(humidity)<minhum){
          digitalWrite(relay4,LOW);

      }else{    digitalWrite(relay4,HIGH);
      }
    //
    // § LIGHT START

    if(startTime<endTime){
      if(startTime <= nowTime && endTime >= nowTime){
          digitalWrite(relay,LOW);
        //  Serial.println("Light ON");
      }else{
          digitalWrite(relay,HIGH);
    //      Serial.println("Light OFF");
    }}else{
      if(endTime <= nowTime && startTime >= nowTime){

          digitalWrite(relay,HIGH);
      //    Serial.println("Light OFF");
      }else{
              digitalWrite(relay,LOW);
        //  Serial.println("Light ON");
        }}

    //  if(nowTime >= startTime && nowTime <= 2359){
    //            digitalWrite(relay, LOW);
    //            Serial.println("Light ON");
    //            }
    //       else if(nowTime  < endTime ){
    //            digitalWrite(relay, LOW);
    //            Serial.println("LIGHT ON");}
    //       else if(nowTime  >= endTime && nowTime  < startTime){
    //            digitalWrite(relay, HIGH);
    //            Serial.println("Light OFF");}
    //      }
          // § LIGHT END

    u8g.firstPage();
      do {
        draw(String(startTime),String(endTime),String(nowTime));
      } while( u8g.nextPage() );
    delay(3000);

    u8g.firstPage();
      do {
        drawInit(InitTime);
      } while( u8g.nextPage() );
     delay(3000);

    u8g.firstPage();
      do {
        draw2(nowTime);
      } while( u8g.nextPage() );
     delay(3000);
    u8g.firstPage();
      do {
        drawTemp(float(temperature), int(humidity),int(NowT));
      } while( u8g.nextPage() );
     delay(3000);
        }}}

body:
While it makes logical sense to use the `String` type to hold strings of text, it's really a very poor choice for a low-RAM device like an Arduino.

You are using the string concatenation operator (`+`) a lot. The `String` type handles this by grabbing a new block of RAM that is equal to the sum of the 2 strings you are concatenating, puts the new string in that RAM, and marks the previous block of RAM that held one of the strings as empty and available for re-use.

The problem is that when you keep concatenating bits to the same string variable, it has to keep finding longer and longer continuous blocks of RAM into which to put the new string. All the previous blocks that are "available" for use, are also too short, as they are all the length of previous strings prior to your new, longer string requirement.

As @Majenko noted, this means your RAM is "swiss cheese" -- full of holes that can't be used by the program for more strings.

One solution is to avoid the `String` variable type and instead use what are called *C-Style Strings* - arrays of `char` type. It's a whole new, old world of doing things, and can be more challenging than the `String` type, but it has a distinct advantage of not shredding the device's RAM.

The *C-style string* world is ruled by monsters like `strnlen()` and `strncpy()`, and making sure you have remembered to allocate enough RAM at the start of your program, and making sure you null-terminate your array.

Of the myriad tutorials and descriptions on using C-style strings, one is at https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body:
after rewrite all code, rewire all relay, bypass the relay card (using another relay), the problem is still there, but i finally found other people with the same problem, and the solution seem to be adding a "snubber" on each relay, i m waiting for it and will give u a return if it work :
[link to arduino forum for a common problem][1]

  [1]: https://forum.arduino.cc/index.php?topic=200393.0


message:
Strange discrete errors when reading HC-SR04 sonar sensor

I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:

    unsigned long sonarMeasure() {
        digitalWrite(TRIGGER, HIGH);
        delayMicroseconds(10);
        digitalWrite(TRIGGER, LOW);
        return pulseIn(ECHO, HIGH);
    }

    double distance = duration * 0.03455;

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather **discrete jumps of about 4 mm**? And when looking closer, there is **another frequent jump of <1mm**:

[![measured distances][1]][1]

(As far as I can tell, the jumps increase at larger distances.)

**Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?**

I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.

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

body:
I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.

What you should do is either remove the bad readings, or take the average/most common value of the last x readings.

Or throw away values too far off some default (like the last average) and average the rest.


message:
RPM measurement using quadrature encoder

I am trying to build a RPM controller for my project. I am using a quadrature encoder (ppr=400) and Arduino Uno for this purpose. I am using the code given below inorder to caluculate the RPM of the DC motor. I get a reading on my serial Monitor. However, this RPM doesn't match with my manual calculation (i.e when I calculate the RPM Manually using a stop watch- for lower speeds).

EDIT-> Eg- Manually I get around 10 RPM, but my program shows 60 and more.

I have used one interrupt pin on my Arduino UNO.

    #define encoder0PinA  2
    #define encoder0PinB  3
    int power=6; // to power up the encoder
    int gnd=4;  // to provide ground to the encoder
    int motor=11; //motor PWM pin
    int dir=10;
    volatile unsigned int encoder0Pos = 0;

    void setup() {
      pinMode(encoder0PinA, INPUT);
      digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
      pinMode(encoder0PinB, INPUT);
      digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor
      pinMode(power,OUTPUT);
      pinMode(gnd,OUTPUT);
      digitalWrite(power,HIGH);
      digitalWrite(gnd,LOW);
      pinMode(motor,OUTPUT);
      pinMode(dir,OUTPUT);
      digitalWrite(dir,LOW);

      attachInterrupt(0, doEncoder, RISING);  // encoder pin on interrupt 0 - pin 2
      Serial.begin (9600);
      Serial.println("start");    // a personal quirk
      analogWrite(motor,120); // to set a particular test RPM to the motor.
    }

    void loop() {
      encoder0Pos=0;
      delay(1000);
      float rpm=encoder0Pos/(400);
      Serial.println(rpm);
    }

    void doEncoder() {

      encoder0Pos++;
      }

Also I tried the very first code on the following link "https://playground.arduino.cc/Main/RotaryEncoders".. In this case my Arduino stops transmitting completely. I tried the same code on one of my friend's setup.. surprisingly it works there.
Can't understand where I am going wrong... Is my coding approach correct?? Please enlighten me...
Thank you.

body:
Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation

Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.

You are calculating revolutions per second with your code, not per min
number of pulses/400(if this is correct number)=Revolutions     which you are clearing ever 1000ms

Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.

Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection,   ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.


message:
avr/io.h No such file or directory error when compiling using avr-gcc

I am trying to use the atmega328p as standalone microchip and program it. I ama using an Arduino Uno as ISP. I have written a simple program to test it however when I try to compile it using

    avr-gcc -mmcu=atmega328p -o main.out main.c

I get the error:

    main.c:1:20: fatal error: avr/io.h: No such file or directory
    compilation terminated.

I am running OpenSUSE Leap 42.3 and i have installed **avr-gcc**, **avr-libc**.

My code:

    #include <avr/io.h>

    int main() {
        DDRB = 1;
        PORTB = 1;
    }

Thank you in advance!

body:
I’m guessing you started with the toolchain Arduino put on your machine.

Try explicitly including the header files on the include path with the `-I` switch.

    avr-gcc -mmcu=atmega328p -I /path/to/avr/include -o main.out main.c

Just search for the `io.h` file. It should be somewhere close by to where you found the compiler.


message:
Error while uploading the sketch for Arduino Mini

I'm having a problem while uploading the program.

    Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

    Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
    Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
    Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
    D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

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

             System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

    avrdude done.  Thank you.

    An error occurred while uploading the sketch

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

What should I do?

body:
On Uno and other boards with USB on board, for flashing the [IDE resets the Atmega to bootloader][1], sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?

If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.

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


body:
"If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button."

In the IDE, if you select File:Preferences and turn on Verbose outputs, you can see when the IDE is about to download, there will appear "compiled xxx of 32xxx bytes), then3 attempts to download. If you press Reset when you see that message, or press & hold reset then release when you see that message, it is much easier to get the bootloader started at the right time (assuming one is actually loaded and there is nothing interfering with the signals on the D0/D1 pins).