message:
How does WiFiServer.status() work?

What are the possible outcomes of calling ```status()``` on a ```WiFiServer``` from ```ESP8266WiFi.h```? The only documentation I could find only says it returns ```uint8_t```. Here's the [link](https://links2004.github.io/Arduino/da/de6/class_wi_fi_server.html#ad16f936581fd4d415910a52410291588).

body:
The basic set of functions of the esp8266 WiFi object follows the API of the Arduino's first WiFi library for Arduino WiFi Shield. It is [documented here][1].

The esp8266 implementation of status() focuses on state of the STA and maps SDK status to some of Arduino documented codes.

    wl_status_t ESP8266WiFiSTAClass::status() {
        station_status_t status = wifi_station_get_connect_status();

        switch(status) {
            case STATION_GOT_IP:
                return WL_CONNECTED;
            case STATION_NO_AP_FOUND:
                return WL_NO_SSID_AVAIL;
            case STATION_CONNECT_FAIL:
            case STATION_WRONG_PASSWORD:
                return WL_CONNECT_FAILED;
            case STATION_IDLE:
                return WL_IDLE_STATUS;
            default:
                return WL_DISCONNECTED;
        }
    }

  [1]: https://www.arduino.cc/en/Reference/WiFi
  [2]: https://www.arduino.cc/en/Reference/WiFiStatus


sender: user

message:
How to read distance of passing object?

Ok, guys this is my first post and I am new to Arduino but somewhat familiar with programming so I hope you guys can assist me. If any of this is confusing, I apologize in advance! :)

I want to be able to utilize a TOF sensor that will be stationary to capture the distance of a passing object at a certain moment after it is first detected, because it is round. So I wanted to use a photoelectric switch, so when the object would pass, it would send the signal to the TOF sensor to read the distance 17ms after that moment.(I've done the math, and the delay to be in the center(closest edge to the sensor of solid ball) of the object passing would take 17ms) Then I would like to have that distance be displayed onto a LCD screen, until the next object passes and the process repeats....Think of a conveyor belt with a basketball on it. The basketball would be moving and pass the sensor, but the distance to the center(closest edge to the sensor)of the ball would be measured at a certain moment and displayed until the next ball passes.

The next problem is that the distance needs to be converted to a "zone" So like between 10-12cm, it would = 2. 12.1-14 would be 3 etc... The last part is probably the easiest but, I have no idea where to start...I appreciate all who helps!

I was needing help with the code to make this work with the Arduino uno. The tof sensor is VL53L1X and E-931-S35RRQ photoelectric sensor. And the LCD will be a 7 segment display so as long as it’s programmed for that I can change out sizes later..

sender: assistant

body:
So break this into parts and solve each part separately. First, figure out how to interface the photoelectric sensor. First just write a loop() that waits for the state change when the sensor trips.

To get accurate timing you'll probably want to respond to the photoelectric sensor with an interrupt service routine that starts a timer. Get that working next.

Then figure out how to interface with your ToF sensor. When I googled it I found the bare sensor as well as versions on PC boards with an I2C interface. You may be able to find somebody's library that interfaces with the sensor. Get that working so you can take readings from the TOF sensor.

Then figure out how to drive the 7-segment display. Just write code that displays the values from 0-9 for 1 second each using a delay.

Once you've got all the pieces working separately, it's time to map out the logic if your program and make it work. Take a look at the "arduino blink without delay" example for how to write code that handles timed responses without using the `delay()` function.


body:
The sensor has a 50Hz ranging frequency; depending on the speed of the balls passing the measuring section, you may only need to wait for ranges of less than (whatever passes for inifinity in your setup) and then track the ranges until they hit a minimum, save that value, and there's your first answer. This saves a detector and has the additional virtue of being independent of the speed of the traveling ball (up to a resolution limited by the sensor's measuring frequency & your precision requirements).

The second part just needs a few `ifs`, such as:

    if( range < 10.0 ){
      zone = 1;   // or whatever else you need to do here
    }
    else if( range < 12.0 ){
      zone = 2;
    }
    else {
      zone = 3;   // anywhere else
    }


message:
Why does SoftwareSerial::read() return int?

The documentation on Arduino's website shows `SoftwareSerial::read()` as returning a `char`. ([link](https://www.arduino.cc/en/Reference/SoftwareSerialRead))

The header shows that the method returns an `int`. ([link](https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/libraries/SoftwareSerial/src/SoftwareSerial.h#L103))

The cpp definition shows `SoftwareSerial::read()` returning the value from a buffer array of `uint8_t` values. ([link](https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L402-L404))

Given all of this:

1. Why would the interface return an `int` instead of a `uint8_t`?
2. Why do the Arduino docs show it as returning a `char`?
3. Is it safe to send/receive 8-bits at a time using this library?

For (3) I'm using an HC-06 if that matters.

body:
1. You'll see in the code just above your third link that the function can return a value of `-1` if there is no data present. Thus a 16-bit value is used to cover the range of 8-bit `uint8_t`s, plus one extra value to show 'no valid data available'.

2. For simplicity, I guess.

3. Yes. This is what it's designed for.

In short, for all intents and purposes, only an 8-bit value is returned, but if you were to read into an `int`, you couldn't differentiate between a valid and invalid value.


body:
Stream declares `read` as returning `int` (look in `hardware/arduino/avr/cores/arduino/Stream.h`). `SofrtwareSerial` inherits from `Stream`, so they have to override that declaration, otherwise there would be two `read()` methods, one returning `int` and one returning `uint8_t`. Since `SoftwareSerial::read()` would onlyreturn an `int` between 0 and 255, which would fit in a `uint8_t`, there is no problem.

As for the Arduino docs, you get what you pay for :)


body:
> The documentation on Arduino's website shows SoftwareSerial::read() as returning a char.

No it doesn't. There is nothing in the documentation that tells you the return type. There is only an example where the returned value is assigned to a `char` variable. That doesn't mean that it returns a char - it just means that whatever data type it does return can be invisibly cast to a `char` by the compiler.

> The header shows that the method returns an int.

Indeed it does. That is because that is what it returns.

> The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values.

Yes, because the valid data that it deals with is 8 bits in size. Just because it handles 8 bit "valid" data doesn't mean that that's *all* it ever wants to return.  The "no data available" return value of -1 is obviously not something that is stored in the data. It's a status, not data.

----

> Why would the interface return an int instead of a uint8_t?

Because a `uint8_t` cannot encompass all the functionality stated in the "Returns" section:

> the character read, or -1 if none is available

You can't return -1 in a `uint8_t`.

> Why do the Arduino docs show it as returning a char?

It doesn't - as I mentioned above. It makes no claims at all about the returned data type.

> Is it safe to send/receive 8-bits at a time using this library?

Yes. It performs serial data transfers using 8-N-1 by default. That's 8 data bits, no parity, and one stop bit.

----

It's this kind of confusion with return types and bytes and integers and things that make people ask why they keep getting ÿÿÿÿÿÿ on the serial monitor. That's -1 cast as a char. I.e., "no data available" but they ignore that and treat everything returned as a `char` - most probably because the Arduino documentation shows an overly simplified example that ignores the possibility of a -1 being returned and treats everything as a `char`.

IMHO much of the Arduino documentation is somewhat sub-par and should not be taken literally - only as a rough guide for what is available. The same goes for much of their example code and projects.


message:
Is it possible to transmit radio signal with cheap 433Mhz transmitter as strings and receive it with an RTL-SDR

I have these Arduino transmitters and receivers.[![This is how they look like][1]][1]

They are very common. I am just trying to transmit a "Hello" Message using this code.

    #include <RH_ASK.h>
    #ifdef RH_HAVE_HARDWARE_SPI
    #include <SPI.h> // Not actually used but needed to compile
    #endif

    RH_ASK driver;
    // RH_ASK driver(2000, 4, 5, 0); // ESP8266 or ESP32: do not use pin 11 or 2
    // RH_ASK driver(2000, 3, 4, 0); // ATTiny, RX on D3 (pin 2 on attiny85) TX on D4 (pin 3 on attiny85),

    void setup()
    {
    #ifdef RH_HAVE_SERIAL
        Serial.begin(9600);   // Debugging only
    #endif
        if (!driver.init())
    #ifdef RH_HAVE_SERIAL
             Serial.println("init failed");
    #else
     ;
    #endif
    }

    void loop()
    {
        const char *msg = "hello";

        driver.send((uint8_t *)msg, strlen(msg));
        driver.waitPacketSent();
        delay(200);
    }

But they have to be received from the receiver module using another set of codes which I have done it.

But my question is, is it possible to receive the transmitted message with one of RTL-SDR's INSTEAD of using the receiver module? If so, How to do it?
[![My RTL-SDR:][2]][2]

  [1]: https://i.stack.imgur.com/wN5va.png
  [2]: https://i.stack.imgur.com/FmLt9.png

body:
In general you can use RTL-SDR to decode any AM and FM modulated signals (+some digital modulations) that lie within the frequency range form roughly 50MHz to about 1GHz. So 433MHz is confortably within that range.

There are many projects on GitHub that leverage the RTL-SDRs ability to decote 433MHz OOK modulated signals like:

[RTL_433][1]
Which comes with a ton of decoders for various appliances.

[OOK_Decoder][2]
Which will give you the demodulated raw output for you to decode the bits yourself.

I'm sure you will find more but those are in my opinion the most noteworthy for the 433MHz OOK space.

  [1]: https://github.com/merbanan/rtl_433
  [2]: https://github.com/jimstudt/ook-decoder


message:
Can arduino-cli verify sketches?

I'm trying to do some simple unit testing with [arduino-cli](https://github.com/arduino/arduino-cli#arduino-cli) in a .gitlab-ci file like so

```yaml
variables:
  DOCKER_HOST: tcp://docker:2375

image: "docker:latest"

services:
  - docker:dind

before_script:
  - docker pull "arduino/arduino-cli:latest"
  - arduinocli(){ docker run arduino/arduino-cli:latest "$@";}

search:
  script:
    - arduinocli lib search hi
```

but instead of `arduinocli lib search hi` at the end, I want to verify my sketch. Is there a way to do this with arduino-cli?

body:
In Arduino parlance the word "Verify" is used (erroneously) to mean "Compile the code into a binary or HEX file, but don't upload it to the board".

To compile (and thus "verify") the code just pass the `compile` command to `arduino-cli` with the board you want to compile for and the sketch you want to compile.


body:
@Majenko's is 100 % correct. Here's my updated `.gitlab-ci.yml` for [my arduino library][1].

```yml
image: ubuntu:latest

before_script:
  - apt-get update -yq
  - apt-get install -yq ca-certificates
  - apt-get update && apt-get install -y --no-install-recommends bzip2 curl unzip
  - apt-get upgrade -yq
  - curl -L -o arduino-cli.tar.bz2 https://github.com/arduino/arduino-cli/releases/download/0.3.3-alpha.preview/arduino-cli-0.3.3-alpha.preview-linux64.tar.bz2
  - tar xjf arduino-cli.tar.bz2
  - mv arduino-cli-0.3.3-alpha.preview-linux64 /usr/bin/ino
  - export APPDIR=$(ino config dump | grep --only-matching --regexp=/.*/Arduino)"/libraries/DC_motors"
  - mkdir --parents $APPDIR
  - mv ./* $APPDIR

test:
  script:
    - echo 'run a script'

compile:
  script:
    - ino core update-index
    - ino core install arduino:avr
    - ino core list
    - ino lib install "Adafruit Motor Shield V2 Library"
    - ino lib search Regexp
    - ino lib install Regexp
    - ino lib install AccelStepper
    - ino compile --fqbn arduino:avr:uno $APPDIR/examples/API
```

In case that library moves, here's the tree output of `DC_motors`

```.
├── examples
│   └── API
│       └── API.ino
├── extras
│   ├── test
│   │   └── Makefile
│   └── testPython.py
├── .gitignore
├── .gitlab-ci.yml
├── keywords.txt
├── library.properties
├── README.md
└── src
    ├── MSv2.cpp
    ├── MSv2.h
    ├── MSv2Motors.cpp
    ├── MSv2Motors.h
    ├── MSv2Steppers.cpp
    ├── MSv2Steppers.h
    └── utility
        ├── MSv2Common.cpp
        └── MSv2Common.h
```

  [1]: https://gitlab.com/robotics_fun/DC_motors


message:
How do I implement reverse enumeration?

Basically I'm trying to output a string based upon a value in an array, the following code is what I have come up with to achieve my desired result, but I have a feeling that there is a better way to do it.

    String day(int day) {
      if (day == 1) return "Sunday";
      if (day == 2) return "Monday";
      if (day == 3) return "Tuesday";
      if (day == 4) return "Wednesday";
      if (day == 5) return "Thursday";
      if (day == 6) return "Friday";
      if (day == 7) return "Saturday";
      else return "Undefined";
    }

    void setup() {
      Serial.begin(57600);
      while (!Serial);
      Serial.println(day(1));
    }

    void loop() {
    ;
    }

This prints "Sunday" in the Serial monitor

I would appreciate any input on how to optimize this code, thank you!

body:
My method makes use of the `__FlashStringHelper` class:

    // For convenience:
    typedef const __FlashStringHelper *FlashString;

    FlashString reverseEnum(int val) {
        switch (val) {
            case 0: return F("Option zero");
            case 1: return F("Option one");
            case 2: return F("Option two");
            default: return F("Invalid Enum");
        }
    }

Printing now is as simple as:

    Serial.println(reverseEnum(2));

Because it's a "flash string" the `print` function is overloaded properly and it performs the proper PROGMEM reading.

You can, of course, assign to a `FlashString`:

    FlashString myString = reverseEnum(2);
    Serial.println(myString);

Or if you don't want to use a typedef you can use the raw type:

    const __FlashStringHelper *myString = reverseEnum(2);
    Serial.println(myString);

It's just much cleaner to use a typedef.


body:
I'm no expert, but I imagine something along these lines would work:

    char* day(int day) {

      static char* dayName[7] = {"Sunday", "Monday", .... };

      if (day > 0 && day < 8) {
        return dayName[day-1];
      }
      else
        return "Undefined";
      }
    }

In any case, I'll be interested to hear why it's wrong (-:


message:
How to heat the air with arduino?

I have a plant growing box, fully controlled with arduino.

[Youtube: ESP8266 IOT Flora][1]

All things are under control, besides the air temperature.
I can cool it down running fans, but cannot find a way to heat it up.

Need to keep the temperature between **25-28 C** all the time.

I was thinking of:

 - 8x8 (64) Leds - maybe this can heat up the temperature, how much ?
 - Dedicated Module - is there any 5v heating module available ?

  [1]: https://www.youtube.com/watch?v=6N50UWrwcsE

body:
LEDs are not really efficient for heating up, you can better use a normal light bulb for that (they are less efficient, thus giving more heat).

The Arduino can only control some 100's of mA, that's not much for heating purposes.

Did you think about using a real heater (maybe small size), and use a relay to turn it on by your Arduino, and using a temperature sensor to switch it off above 28 and switch it on below 25 (or a lesser margin to keep up with the time it takes to change the environment temperature)?

If you do not want an external mains power, you could use probably a 12V heater and use a 12V->5V converter for your Arduino, or use a 5V heater pad, but according to what I have seen they are more for warming up cold hands, I doubt they can bring up the heat to 25-28 degrees Celcius. Besides, they are probably not very efficient.


body: One simple way I can think of would be to turn a 100 W lightbulb (**EDIT** or whatever size makes sense for your application) on / off using a relay.  You could use a heat lamp, but with a small box like you have, a lightbulb should give off plenty of heat.  You would want to make sure that the bulb didn't give off enough heat to damage any plastic too close to it.


body:
The total current of your power supply, 5V • 3A is only 15 watts. That's not enough power to create a meaningful amount of heat. (although looking at your video your grow box is really tiny...)

LEDs are a terrible choice for providing heat. They produce mostly light, and very little heat (which is good if you want light, but bad if your goal is to build a heater.)

You probably want 30-60 watts of heat. As others have said, you could use a light bulb with a relay to control it. You could use a digital thermometer like a DHT11 to measure the temp, and then have a "digital" relay to control the heat source. You'd write a sketch that would turn your heater on at slightly above your minimum temp and turn it off at slightly below your max temp. (How much above and below your thresholds should be would depend on how strong your heater is and how long it takes to heat up your grow space. You'd need to do some testing.)

I created a forced air "boot dryer" where I used a couple of 120V, 500 watt heating elements in series (which lowers the power to 250 watts) and a thermostat. That is likely way too much heat for your tiny grow-box. Here is a link to that heating element: https://www.amazon.com/gp/product/B005RG64LQ/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1

And for a relay I used a 5V "digital" relay like this one: https://vetco.net/products/single-relay-module-for-arduino?gclid=EAIaIQobChMIgfy8jtjJ4wIVA5-fCh2TXQH1EAQYBCABEgI3mfD_BwE


body:
You can use nickle chrome wire to easily heat that small box.

[From Wikipedia:][1]

> Almost any conductive wire can be used for heating, but most metals conduct electricity with great efficiency, requiring them to be formed into very thin and delicate wires in order to create enough resistance to generate heat. When heated in air, most metals then oxidize quickly, become brittle, and break. Nichrome wire, however, when heated to red-hot temperatures, develops an outer layer of chromium oxide, which is thermodynamically stable in air, is mostly impervious to oxygen, and protects the heating element from further oxidation.

5V nickle chrome wires are available online to order, it's usually used as car seat heater.

Just be careful do **not** use Nickle chrome wire with Arduino directly because it can draw up to 2A from the power source and burn your Arduino board, instead use a relay to control the heater.

Here's the schematic to control a heater using Arduino and a relay:

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

<!-- End schematic -->

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


message:
Restart variable every day

How can i restart a variable every day? I have an RTC 1307. The problem is that i cannot use an alarm event because the arduino will be shut down during that hour. So I need a more reliable solution.

This will work? A date could be an integer?

```
#include <EEPROM.h>
#include "RTClib.h"

int  lastDay;
int EE_ADDR = 0;
int totalLitres;

void setup() {
  EEPROM.get(EE_ADDR, lastDay);
}

void loop() {
DateTime now;
  if (now.day() != lastDay) // this happens exactly once a day.
    totalLitres = 0; // reset the accumulated volume

  lastDay = now.day();
}

body:
Here are a few suggestions:

* Since your RTC has some non-volatile RAM (NVRAM) onboard, you could
  use it instead of the EEPROM. This way you will not have to worry
  about the EEPROM endurance.
* If there is the possibility that the device gets power-cycled within a
  single day, you probably want it to preserve the liter count. This can
  be achieved by periodically saving this count to the NVRAM, and
  restoring it at startup. You can save often, as you don't have
  endurance limits.
* If the device is started after a full month of being off, if should
  notice some days have passed, even it the day number is the same as
  when it was turned off. Instead of saving just the day number, I would
  store the total number of days elapsed since 2000 Jan 1.

Untested implementation of the above suggestions:

```c++
#include <Wire.h>
#include <RTClib.h>

const uint32_t NVRAM_UPDATE_PERIOD = 10000;  // 10 seconds

/* Addresses for data items saved in the RTC's NVRAM. */
const uint8_t ADDRESS_LITERS    = 0x00;
const uint8_t ADDRESS_RESET_DAY = 0x02;

RTC_DS1307 rtc;
uint16_t liters;
uint16_t reset_day;

/*
 * If `liters' has not been reset today, reset it now and update both
 * the RAM and NVRAM copies of `reset_day'.
 */
void reset_liters_if_needed()
{
    uint16_t current_day = rtc.now().secondstime() / 86400;
    if (current_day > reset_day) {
        liters = 0;
        reset_day = current_day;
        rtc.writenvram(ADDRESS_RESET_DAY,
                (uint8_t *) &reset_day, sizeof reset_day);
    }
}

void setup()
{
    /* Pull the initial `liters' and `rest_day' from NVRAM. */
    rtc.begin();
    rtc.readnvram((uint8_t *) &liters, sizeof liters,
            ADDRESS_LITERS);
    rtc.readnvram((uint8_t *) &reset_day, sizeof reset_day,
            ADDRESS_RESET_DAY);
    reset_liters_if_needed();
}

void loop()
{
    /* Periodically update the NVRAM. */
    static uint32_t last_nvram_update;
    if (millis() - last_nvram_update >= NVRAM_UPDATE_PERIOD) {
        reset_liters_if_needed();
        rtc.writenvram(ADDRESS_LITERS,
                (uint8_t *) &liters, sizeof liters);
    }
}
```

For extra safety you may want to add a large capacitor in order to keep
the Arduino powered for a few milliseconds after being unplugged. And a
circuit that detects when it gets unplugged in order to immediately save
the data and stop accessing the NVRAM before it gets out of juice. This
kind of trick has already been discussed here, you should be able to
find the relevant questions and answers.


message:
Pro Micro with Atmega32U4 - reset - reprogramming

i am a new user on arduino card. i have a question about "Pro Micro with Atmega32U4".
- is this product programmable several times ? and the third pin (RST) - (Reset). so, does reset mean it erases memory?

Thank you in advance for your answers.

body:
Yes, the microcontroller on Arduinos (in this case the Atmega32U4) can be reprogrammed many times, only limited by the write limit of the flash memory (As I remember Microchip garantuees about 100,000 write cycles at minimum). You can program it over the USB port of the board or through an ISP programmer.

The Reset pin will do the same as a power cycle (turning off an on again) would do. If you program the Arduino, this program will start, when the Arduino get's power (after the Bootloader, which is used to program over USB without ISP programmer). This program will then run until the power is turned off, or until a reset is done by pulling the RST pin to ground. When the RST pin is released again, the Arduino will again start up. The flash memory and the EEPROM stay untouched and will not loose any data. But the data, that lies in SRAM (like any normal variable in the program) will be lost.


message:
'Delay command' and bluetooth communication problem

I have a project where I send data to Arduino via Bluetooth using an Android application. For example, when I press 1 from the 'bar led' part of the application, an animation needs to happen. When I press 2, a different animation will be displayed. However, because there is a 'delay command' in the animations, there is a delay in data exchange when I press the button. **How can I prevent this? Is there a command I can use instead of the 'Delay command'?**
<!-- language-all: lang-cpp -->

    void loop() {
      if (bluetooth.available()) {
      while (bluetooth.available())
        {
          bar_analog = bluetooth.parseInt();
          head_analog = bluetooth.parseInt();
          bar_anim = bluetooth.parseInt();
          strip_anim = bluetooth.parseInt();
          motor_speed = bluetooth.parseInt();
          direct = bluetooth.parseInt();
          level = bluetooth.parseInt();
          if (debug) {
            Serial.print("Bar Brightness: ");
            Serial.println(bar_analog);
            Serial.print("Bar Animation Type: ");
            Serial.println(bar_anim);
            Serial.print("Headlight Brightness: ");
            Serial.println(head_analog);
            Serial.print("Strip Animation Type: ");
            Serial.println(strip_anim);
            Serial.print("Motor Speed Level: ");
            Serial.println(motor_speed);
            Serial.print("Direction: ");
            Serial.println(direct);
            Serial.print("Mast Goes: ");
            Serial.println(level);
            Serial.println("--------------------------------");
          }
          if (bluetooth.read() == '\n') {

          }
      }}
      if(bar_anim==1) {
      digitalWrite(8,HIGH);
      delay(50);
      digitalWrite(8,LOW);
      delay(250);
      }
      else if(bar_anim==2) {
      digitalWrite(8,HIGH);
      delay(250);
      digitalWrite(8,LOW);
      delay(50);
    }
    }

[![app][1]][1]

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

body:
I see 2 problems with your code:

1. You use the `delay()` function, which is not good coding style, since it is basically busy waiting. The Arduino will do nothing in this time, also not reacting to any input. Instead you should use a non-blocking coding style, which only does something, when it is time to do so, and will not block until something happens. You can see this style in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It uses `millis()` as a time measure. Think of how you would bake a pizza. You would not sit on front of the oven doing nothing, until the pizza is ready. You would do other things while looking at your watch regularily, checking, if it is time to take out the pizza.

2. In the Serial communication part you use `parseInt()`. That can be a problem, since it has a timeout of 1s (standard value). Until the timeout the function will block. This is mitigated, if you consecently send a non-digit character at the end of every value. But it is better to first read a full message (until the newline character `\n`) and then process the message as a whole.

Also the line `if (bluetooth.available())` is not necessary here, since the `while` loop will do the same.


message:
Why the global variables info is not shown for Arduino Due in IDE?

If I compile a sketch for the Arduino Mega:

    Sketch uses 1804 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 188 bytes (2%) of dynamic memory,
    leaving 8004 bytes for local variables. Maximum is 8192 bytes.

If I compile the same sketch for the Arduino Due:

    Sketch uses 26304 bytes (5%) of program storage space. Maximum is 524288 bytes.

Why is the global variables part not supported for the Due, it seems to me it's quite important (even more than the sketch size).

Or can I enable this option somehow? (and if yes, how)

body:
There is a difference in how the build system calculates the memory size for AVR and SAM. The platform.txt file contains the rule for calculating the size. There is a difference how this is done for SAM (Arduino Due).

The AVR size rules (https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L79) are:

    ## Compute size
    recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
    recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*
    recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*
    recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*

And the rules for SAM (https://github.com/arduino/ArduinoCore-sam/blob/master/platform.txt#L91) are:

    recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
    recipe.size.regex=\.text\s+([0-9]+).*

They may be updated to give more information about the memory size. A good reference on the subject is http://www.support.code-red-tech.com/CodeRedWiki/FlashRamSize which shows that the output from size command for SAM contains much more information.

I assume that from the above information you see how this could be updated.

Cheers!


message:
Sending code for error detection facing problem with error not able to compile code

**MY PROJECT CODE:**
<!-- language-all: lang-cpp -->

    #include ESP8266WiFi.h
    #include LiquidCrystal.h
    #include FirebaseArduino.h>
    #include HX711.h>
    #define FIREBASE_HOST "iot-based-smart-dustbin.firebaseio.com"
    #define FIREBASE_AUTH "ljIbV03K07rLwoHRKSaAxWzJNCb3Lh6buc76dkvb"
    #define WIFI_SSID "AndroidAP"
    #define WIFI_PASSWORD "ashu1234"
    char c; //ESP
    String data   = "";  //ESP
    #define DOUT  15
    #define CLK  13
    #define IR1 14
    #define IR2 12
    HX711 scale(DOUT, CLK); // Init of library
    float calibration_factor = -96650; //-106600 worked for 3-40Kg max scale setup
    const int rs = 16, en = 5, d4 = 4, d5 = 0, d6 = 2, d7 = 10;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    void setup()
    {
       Serial.begin(9600);
       pinMode(IR1,INPUT);
      pinMode(IR2, INPUT);
      pinMode(DOUT, INPUT);
      pinMode(CLK, OUTPUT);
      lcd.begin(16, 2);     // Print a message to the LCD.
      lcd.print("WELCOME");
      delay(2000);
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    //  Serial.print("connecting");
      while (WiFi.status() != WL_CONNECTED)
        {
      //    Serial.print(".");
          delay(500);
        }
    //  Serial.println();
    //  Serial.print("connected: ");
    //  Serial.println(WiFi.localIP());
      scale.set_scale();
      scale.tare(); //Reset the scale to
    }
    void loop()
    {
      scale.set_scale(calibration_factor); //Adjust to this calibration factor
      float a=scale.get_units();   // a Variable to take weight values at input
      lcd.clear();
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      Firebase.setFloat("Weight", a);  //to set value in firebase // value on a sent to weight variable
      if (digitalRead(IR1)==HIGH)
      {
        Firebase.setFloat("IR1", HIGH);
        lcd.setCursor(0, 0);
        lcd.print("Location 1:High");
      }
       if (digitalRead(IR1)==LOW)
      {
        Firebase.setFloat("IR1", LOW);
        lcd.setCursor(0, 0);   //column, Row
        lcd.print("Location 1: Low");
      }
       if (digitalRead(IR2)==HIGH)
      {
        Firebase.setFloat("IR2", HIGH);
        lcd.setCursor(0, 1);
        lcd.print("Location 2:High");
      }
       if (digitalRead(IR2)==LOW)
      {
        Firebase.setFloat("IR2", LOW);
        lcd.setCursor(0, 1);
        lcd.print("Location 2: Low");
      }
      delay(2000);
      lcd.clear();
      if (a>=4)
      {
        lcd.setCursor(0, 0);
        lcd.print("Weight: High");
      }
       if (a<4)
      {
        lcd.setCursor(0, 0);
        lcd.print("Weight: Low");
      }
     delay(2000);
    }
    void send_msg_1()
    {
      Serial.println("AT+CMGF=1");// for GSM module in TEXT mode
      delay(1000);
      Serial.println("AT+CMGS=\"+9921526975\"\r");// Phone number (change)
      delay(1000);
      Serial.println("Dustbin at Location 1 is full");// Message body (change as per requirement)
      delay(1000);
      Serial.println((char)26);// send message
      delay(1000);
    }

**ERRORS I am Getting while compiling as follows:**

    sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'
     HX711 scale(DOUT, CLK); // Init of library
                          ^
    C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:
    In file included from C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:23:0:
    C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
       HX711();
       ^
    C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
    C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
     class HX711
           ^
    C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
    exit status 1
    no matching function for call to 'HX711::HX711(int, int)'

Please help me to solve this problem. Too much struggling...

body:
Probably the main problem is already in the first lines:

    #include ESP8266WiFi.h
    #include LiquidCrystal.h
    #include FirebaseArduino.h>
    #include HX711.h>

You should use the correct formatting:

    #include "ESP8266WiFi.h"
    #include "LiquidCrystal.h"
    #include "FirebaseArduino.h"
    #include "HX711.h"

Also, HX711 does not have a constructor with arguments, so instead of

    HX711 scale(DOUT, CLK);

uese

    HX711 scale;

and in Setup:

    scale.begin(DOUT, CLK);

You probably have the code meant for a different library.

See [HX711_full_example][1]. Or use the code belonging to your used HX711 library.

  [1]: https://github.com/bogde/HX711/blob/master/examples/HX711_full_example/HX711_full_example.ino


message:
How Should I Send Data to My Laptop from Multiple Arduinos?

I'm working a project which involves reading multiple RFID tags, from multiple directions, at the same time. Because of the multiple directions, I need to use multiple antennae. Because of the multiple tags, I need to use a simultaneous RFID reader.

Unfortunately, the wiring of the simultaneous RFID reader doesn't support multiple antennae, so each antenna will need its own simultaneous RFID reader. It seems likely - although I'm waiting for confirmation on this - that each RFID reader will have to have its own Arduino as well. What's the least horrible way of sending the data those antenna-reader-Arduino combinations are gathering to a laptop?

If this makes a difference, the laptop I'm going to be sending the data to will be running Ubuntu, and I'd like to collect the data using Python's pyserial package. Once I've got the data in a Python program, we're home and dry.

body: There are multiple solutions but the simplest one is probably to use Software serial, I2C, or SPI. The idea is basically the same for any of the protocols. You select one Arduino which is gonna be the master and be connected to the laptop. Than using any of those interfaces you connect the Arduino boards in to a chain. Than you can ask the slave Arduino boards if they have new data one by one. If they do they send it and the master forwards it to the laptop. In this way all the slave boards will wait until they are asked for data and thus avoid collisions of data streams.


body:
If you have not purchased the Arduinos yet, you could consider using the ESP8266 ("Arduino-like" with embedded wifi module, and not much more expensive, depending on the project size). Then you use your laptop as a server, and each ESP8266 sends the data via wifi to the laptop.

Arduino as a client (via wifi): https://www.arduino.cc/en/Reference/WiFiClient


message:
Reading consecutive two pulse periods continuously

I'm controlling the DC motor/fan speed by PWM through varying analog input. Using Uno or Nano.

The loop is as follows:

    void loop()
    {
      val = analogRead(analogPin0);  // read the analog input pin
      analogWrite(pwmPin9, map(val, 0, 1024, 0 , 255));
    }

Above analogPin0 value is varied by a poti.

But I also want to output the rpm on an LCD. To do that I need to measure the period between two consecutive pulses as shown below:

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

How could I measure continuously "period between two consecutive pulses"? Should I use interrupt? Does anybody have any experience with that?

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

body:
An interrupt off of one of the timers sounds like the easiest way to go. To get a measurement precision of, say 3% at 4ms means sampling every (4000us * .03) = 120us (8.333 KHz). If your code has little else to do, you might get away with clock-watching - `micros()` ticks every 4us - but you'll need to keep anything else you do between reads of `micros()` to under 120us, and half of that might be a good target figure.

In [this answer][1] I described a general non-blocking procedure for managing several tasks in a timely way. If you chose such a design, one task might manage the potentiometer and analog output, another one the RPM measurement, and another the LCD. The ISR would do nothing but set a flag.

The RPM & LCD tasks can run at a relatively low rate as they're intended for human consumption only. They may have to work piece-wise, though, to meet their time restrictions.

  [1]: https://arduino.stackexchange.com/questions/60759/how-to-rotate-two-or-more-steppers-simultaneously-by-giving-array-of-angles/66380#66380


body:
I see 2 ways to go here:

1. You could attach a simple interrupt for rising edge to the pin with `attachInterrupt()` and count the rising edges with a variable. If the third rising edge is sensed, you have 1 period. To measure the time you can save the starting time of the first rising edge to a variable with `micros()` (which gives you the time since startup in microseconds). At the third rising edge save the time difference between start and end to another variable (declared volatile): `micros()-start_time`. This variable can then be displayed in your `loop()` function. Be sure to only copy the variable to a local variable in this part and deactivate interrupts during this operation with `noInterrupts()` (reactivate interrupts after that with `interrupts()`. Also you should use an atomic flag variable (atomic meaning, that writing or reading this variable cannot be interrupted. For example if you use `byte` or any other 1byte variable) to show the `loop()` function, that there is new data to display. Only if that's the case, the code in the `loop()` function would process the data.

2. If you want to go fancy or if you want to measure higher speeds (lower periods), You can use the hardware of Timer1 as counter. You give the Timer1 your signal as clock input. On every edge the timer value get's incremented by 1. So when the timer value is 5, one period has passed. You can use the timer in compare match mode, so that it will generate an interrupt, if a special value (here 5) is in the timers value register. In that ISR (Interrupt Service Routine) you would record the current time with `micros()`. On compare match the timer will generate the interrupt, set the value to zero again (if configured right) and again start to count. So the period would be the time between 2 consecutive time measurements. Displaying in the `loop()` function can be handled similar to the principle above.

It might also be good to directly take a mean of the period (to filter out noise in the period) by counting, until multiple periods have gone by. In the first case you could count to 11 to get 5 periods. Then divide the time difference by 5 to get 1 period. For the second case you can set the Timer1 match register to 21 to get 5 periods. Here also divide the time by 5 to get 1 period.

Since you seem to be a beginner, I would suggest the first way: Using `attachInterrupt()`. The second way is more if you want to dig into the microcontrollers registers and the descriptions in the datasheet.

The first way could look something like this:

    const int pin = 2;

    volatile byte counter = 0;
    volatile unsigned long start_time;
    volatile unsigned long period;
    volatile byte data_flag = 0;

    void speed_ISR(){
        counter++;
        if(counter==3){
            unsigned long now = micros();
            period = now - start_time;
            data_flag = 1;
            start_time = now;
            counter = 1;
        }
    }

    void setup(){
        pinMode(pin, INPUT);
        attachInterrupt(digitalPinToInterrupt(pin), speed_ISR, RISING);
    }

    void loop(){
        if(data_flag){
            noInterrupts();
            unsigned long local_period = period;
            data_flag = 0;
            interrupts();
            // Now display the period on the LCD her
        } else {
            // Print zero to the LCD
        }
    }

The code gives you the opportunity to write zero to the LCD, when there is no pulse input (hence no data --> data_flag has to be zero). This may be uncomfortable to read on low pulse frequencies, if the LCD doesn't need longer to display the results as the next pulse will be measured, as it might display zero and the next measurement in fast succession. You could either use `millis()` to set `data_flag` to zero after a specified time (instead of resetting it near the LCD code), or you can limit the display rate like the blinking is done in the `BlinkWithoutDelay` example, that comes with the Arduino IDE.

Note that this code is not tested.


message:
Controlling a servo motor with two arduinos?

I have two Arduinos, two buttons and one servo motor.

I want to control a servo motor with two Arduino's when I pressed the buttons. I linked Arduino PWM pins (first Arduino PWM pin is 9, and second one is 3) to the servo motor signal input.

When I pressed button 1 servo motor moving a few, or pressed button 2. but the signal isn't clear, and servo motor doesn't move correctly that I assigned degree.

What can I do for the solution?

My first Arduino code is here:
<!-- language-all: lang-cpp -->

    #include<Servo.h>

    #define Buton 8

    Servo myServo;

    void setup() {
      pinMode(Buton, INPUT);
      myServo.attach(3);
    }

    void loop()
    {
      if (digitalRead(Buton) == 1)
      {
        myServo.write(90);
      }
      else
      {
        myServo.write(180);
      }

    }

and second arduino code is:

    #include<Servo.h>

    #define Buton 8

    Servo myServo;

    void setup() {
      pinMode(Buton, INPUT);
      myServo.attach(9);
    }

    void loop()
    {
      if (digitalRead(Buton) == 1)
      {
        myServo.write(90);
      }
      else
      {
        myServo.write(180);
      }

    }

body:
You can't just connect random pins together like that. Connecting two output pins together is a recipe for disaster. Best case scenario: nothing works. Worst case scenario: you break one or both Arduinos.

Only one Arduino can control a servo. If you want a second Arduino to make something happen to the servo you have to make it tell the Arduino that is controlling the servo that something should happen.

That could be a simple output of the second Arduino connected to an input of the first Arduino, in which case it kind of acts like a button. Or you could create some kind of communication channel between them - maybe using a Serial connection, or a Wire (I2C) connection. There's many ways, and which is best depends on how much control one Arduino needs to exert over the other.


message:
Arduino Bluetooth communication is slowing down because of the 'for' loop!

I'm sending data to Arduino through the mobile app. So far, all the code has been running consistently.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    #define FASTLED_INTERNAL
    #include <FastLED.h>
    #define NUM_LEDS_PER_STRIP 48
    SoftwareSerial bluetooth(53,52);    // TX,RX
    int bar_analog=0;
    int head_analog=0;
    int bar_anim=0;
    int anim=0;
    int motor_speed=1;
    int direct=0;
    int level=0;
    CRGB strip1[NUM_LEDS_PER_STRIP];
    CRGB strip2[NUM_LEDS_PER_STRIP];
    CRGB strip3[NUM_LEDS_PER_STRIP];
    CRGB strip4[NUM_LEDS_PER_STRIP];
    boolean debug = true;
    int IN1a=49;
    int IN2a=48;
    int PWM1=3;
    int IN1b=22;
    int IN2b=23;
    int PWM2=4;
    int hiz=100;
    int PWM_kare=2;
    int INA_kare = 51;
    int INB_kare = 50; //LED '+'sı OUTPUT B'de olduğu için INB'yi  HIGH yapıyoruz.
    void m1_cw() {
    digitalWrite(IN1a,HIGH);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,hiz);
    }
    void m1_ccw() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,HIGH);
    analogWrite(PWM1,hiz);
    }
    void m2_cw() {
    digitalWrite(IN1b,HIGH);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,hiz);
    }
    void m2_ccw() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,HIGH);
    analogWrite(PWM2,hiz);
    }
    void m1_stop() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,0);
    }
    void m2_stop() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,0);
    }
    void mast_up() {
    digitalWrite(24,HIGH);
    digitalWrite(25,LOW);
    }
    void mast_down() {
    digitalWrite(24,LOW);
    digitalWrite(25,HIGH);
    }
    void mast_stop() {
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
    }
    void kare() {
    analogWrite(PWM_kare,head_analog);
    digitalWrite(INB_kare, HIGH);
    digitalWrite(INA_kare, LOW);
    }
    void strip_dim() {
    for(int i=0;i<256;i=i+10) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }}
    for(int i=255;i>=0;i=i-10) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }}
    }
    void strip_stop() {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(0); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }
    }
    void setup() {
      Serial.begin(9600);
      bluetooth.begin(9600);
      Serial.println("Program is starting...");
      Serial.println("by Berke Ogulcan Parlak");
    pinMode(IN1a,OUTPUT);
    pinMode(IN2a,OUTPUT);
    pinMode(IN1b,OUTPUT);
    pinMode(IN2b,OUTPUT);
    pinMode(PWM1,OUTPUT);
    pinMode(PWM2,OUTPUT);
    pinMode(24,OUTPUT);
    pinMode(25,OUTPUT);
    pinMode(INA_kare, OUTPUT);
    pinMode(INB_kare, OUTPUT);
    pinMode(PWM_kare, OUTPUT);
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    digitalWrite(PWM1,LOW);
    digitalWrite(PWM2,LOW);
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
    digitalWrite(INA_kare, LOW);
    digitalWrite(INB_kare, LOW);
    digitalWrite(PWM_kare, LOW);
    FastLED.addLeds<NEOPIXEL, 26>(strip1, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<NEOPIXEL, 28>(strip2, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<NEOPIXEL, 30>(strip3, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<NEOPIXEL, 32>(strip4, NUM_LEDS_PER_STRIP);
    FastLED.setBrightness(0);
    }

    void loop() {
      while (bluetooth.available())
        {
          bar_analog = bluetooth.parseInt();
          head_analog = bluetooth.parseInt();
          bar_anim = bluetooth.parseInt();
          anim = bluetooth.parseInt();
          motor_speed = bluetooth.parseInt();
          direct = bluetooth.parseInt();
          level = bluetooth.parseInt();
          if (debug) {
            Serial.print("Bar Brightness: ");
            Serial.println(bar_analog);
            Serial.print("Bar Animation Type: ");
            Serial.println(bar_anim);
            Serial.print("Headlight Brightness: ");
            Serial.println(head_analog);
            Serial.print("Strip Animation Type: ");
            Serial.println(anim);
            Serial.print("Motor Speed Level: ");
            Serial.println(motor_speed);
            Serial.print("Direction: ");
            Serial.println(direct);
            Serial.print("Mast Goes: ");
            Serial.println(level);
            Serial.println("--------------------------------");
          }
          if (bluetooth.read() == '\n') {

      }}
            kare();
           if(direct==1) { //ileri
      m1_ccw();
      m2_ccw();
      }
    else if(direct==2) { //geri
      m1_cw();
      m2_cw();
      }
    else if(direct==3) { //sol
      m1_ccw();
      m2_cw();
      }
    else if(direct==4) { //sağ
      m1_cw();
      m2_ccw();
      }
    else if(direct==0) { //durur
      m1_stop();
      m2_stop();
      }
    if(level==1) { //mast yukarı
      mast_up();
      }
    else if(level==2) { //mast aşağı
      mast_down();
      }
    else if(level==0) { //mast durur
      mast_stop();
      }
    if(anim==2) {
      strip_dim();
      }
    else if(anim==0) {
      strip_stop();
      }
      }
But when I added the for loop to the code, all the data started to shift. (When I press the button from the application 'lag' occurs and the data is mixed.)I mentioned that part of the code below. **Why does the data shift?**

    void strip_dim() {
    for(int i=0;i<256;i=i+10) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }}
    for(int i=255;i>=0;i=i-10) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }}
    }
    void strip_stop() {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(0); //Parlaklık
    strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
    strip2[j] = CRGB( 100, 172, 45);
    strip3[j] = CRGB( 100, 172, 45);
    strip4[j] = CRGB( 100, 172, 45);
    FastLED.show();
    }
    }

body:
You are creating an instance of a class a lot of times (25 * 48 * 8 + 255 * 48 * 4 = 58,560 times), and that is a costly operation.

Instead, make one instance (before the for loops), and use that to assign everywhere you need it.

Something like;

    CRGB crgb( 100, 172, 45);

    for(int i=0;i<256;i=i+10) {
        for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
            FastLED.setBrightness(i);
            strip1[j] = crgb;
            ...


body:
Your chief problem is that FastLED turns off interrupts when sending the data. It does that because timing is critical, and with interrupts turned on that timing will get completely messed up.

So with FastLED running repeatedly in a loop there is very little time when interrupts are enabled for reception to occur over SoftwareSerial.

Unlike a real UART, which can receive and store a byte before triggering an interrupt, SoftwareSerial triggers an interrupt to at the start of receiving a byte and that interrupt routine is used to do the actual reception. So if interrupts aren't enabled at the moment a byte starts arriving on the GPIO pin it can't start receiving, so it misses the byte and it ends up a mess.

Since you are using an Arduino Mega there is absolutely no reason for you to use SoftwareSerial. You have plenty of real hardware UARTs available to connect your Bluetooth device to which will be able to receive a byte while FastLED is sending out data (as long as it's not sending out data for too long...).


message:
Does DmxSerial stops interrupts?

I am trying to build a setup with an Arduino Mega, having a DMX output (using DMXSimple library), and a MIDI library (to be done).

I was wondering, if I get into problems. According to [This question][1], where Majenko's answer mentions that FastLED holds interrupts, I wonder if I can get into problems if I try to read MIDI data from 3 serial ports while sending DMX.

Probably FastLED (for led strips) and DMX (250 kbps) have some similarity. DMXSimple works with just one data line (no UART), but MIDI is using UART (31.25 kbps), 3 UARTS.

My fear is that everything works separately (I tried it before, long time ago with MIDI), but when I try to combine it, I get timing problems.

  [1]: https://arduino.stackexchange.com/questions/67377/arduino-bluetooth-communication-is-slowing-down-because-of-the-for-loop/67378?noredirect=1#comment144972_67378

body:
Yes, it does disable interrupts when sending a byte:

    #if defined(__AVR__)
    void dmxSendByte(volatile uint8_t value)
    {
      uint8_t bitCount, delCount;
      __asm__ volatile (
        "cli\n"                            <<==== DISABLE INTERRUPTS
        "ld __tmp_reg__,%a[dmxPort]\n"
        "and __tmp_reg__,%[outMask]\n"
        "st %a[dmxPort],__tmp_reg__\n"
        "ldi %[bitCount],11\n" // 11 bit intervals per transmitted byte
        "rjmp bitLoop%=\n"     // Delay 2 clock cycles.
      "bitLoop%=:\n"\
        "ldi %[delCount],%[delCountVal]\n"
      "delLoop%=:\n"
        "nop\n"
        "dec %[delCount]\n"
        "brne delLoop%=\n"
        "ld __tmp_reg__,%a[dmxPort]\n"
        "and __tmp_reg__,%[outMask]\n"
        "sec\n"
        "ror %[value]\n"
        "brcc sendzero%=\n"
        "or __tmp_reg__,%[outBit]\n"
      "sendzero%=:\n"
        "st %a[dmxPort],__tmp_reg__\n"
        "dec %[bitCount]\n"
        "brne bitLoop%=\n"
        "sei\n"                             <<==== ENABLE INTERRUPTS
        :
          [bitCount] "=&d" (bitCount),
          [delCount] "=&d" (delCount)
        :
          [dmxPort] "e" (dmxPort),
          [outMask] "r" (~dmxBit),
          [outBit] "r" (dmxBit),
          [delCountVal] "M" (F_CPU/1000000-3),
          [value] "r" (value)
      );
    }

Also that routine is run from within a timer interrupt routine. On AVR with no interrupt priorities even without disabling interrupts it would still be blocking all other software from running.


message:
Two flow sensors, one ESP32, LCD and/or Arduino

I want to build a flow meter but the Gal/Min rating of something like this [flow meter][2] is too low. I am thinking of strapping two side by side with suitable plenums for In and Out.

I have found some [sketches][1] like this but wondering how to use the two inputs to aggregate the results to GPM and Gallons total for display on an LCD screen. I am unsure what happens if two Hall-results arrive at or about the same time but on different Data Pins.

I have priced some single sensors with a higher flow rate for the pipe size but they run to several hundred dollars. Gallons are not critical as long as I can be within about 5% error over ten minutes, our average tank fill time.

Can someone please point me at some code to get me started for an ESP32 and LCD. I'd even consider adding a Nano if that makes things easier. I imagine that would certainly prevent collision issues. Basically I need to be able to handle the flow rate to a single LCD.

Thanks

  [1]: https://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/
  [2]: https://www.amazon.com/GRODIA-Sensor-Food-Grade-Flowmeter-Counter/dp/B07MY5ZN3Z

body:
A Hall Effect Sensor like that just gives you a pulse every rotation (or two pulses per rotation, etc) of the internal vanes.

If you use interrupts to count the pulses then two pulses arriving at the same time will be handled sequentially. The interrupt flag indicating a pulse has arrived is set in hardware the moment the pulse arrives, and the CPU checks all the interrupt flags between instructions. Each flag is handled sequentially, the order determined by interrupt priority settings and a "natural" order determined by the internal wiring of the CPU.

However there is a better way on the ESP32, and that is the [Pulse Counter](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/pcnt.html) peripheral.  This is designed to count pulses like the signals from Hall Effect sensors.

You can just leave the Pulse Counter counting your pulses, then periodically read and reset the pulse count to see how much water has flowed in that period. It looks from the documentation that you can have two inputs both making the same counter increment, so it will do the aggregating for you.


message:
Sketchy Wemos D1 mini Pro

Recently, I bought a ["ThingPulse ESP2866 Wifi Color Display Kit"][1]. I bought the kit before reading the reviews and finally read them the other day. Some of the reviews seem fake but a couple of them say that the Wemos D1 mini pro is being used to "steal credit cards" and other information. The bad reviews claimed that when they plugged the wemos into a power source, a wifi network named "ESP_xxxxxx" appears and thats how their data is stolen. I plugged the Wemos that came in my kit to a power source and a wifi network starting with "ESP..." appeard. I was wondering if this is a valid concern or if its just conspiracy. I am not very informed on cybersecurity and data security so I thought this would be the best place to ask. Please let me know if you'd like anymore information.  Thank you!

  [1]: https://www.amazon.com/dp/B06XZJQ7LV/ref=cm_sw_r_cp_apa_i_b73nDb9Y0K1Y8

body:
It's pure conspiracy, paranoia, or people just generally not having the slightest clue what they have bought. By default the ESP8266 is in Access Point mode, and named ESP_[last 6 chars of MAC address]. It will have an IP address in the range 192.168.4.x. And that is all.

It can't do anything else until you actually program it to do something.

Part of the "problem" is probably that the ESP8266 remembers WiFi settings independently of the sketch that is running on it. It's only the WiFi settings it remembers, though - not what to do with any data that travels over WiFi. That is purely down to whatever sketch you install.

**Unless you manually program it so it connects to your WiFi, or add extra hardware for other communications, the device can not, and will never be able to, send any data to anyone, anywhere, ever. Full stop.**


body: Before you’ve programmed the WEMOS, it will appear like an access point. It’s one if it’s great qualities of this versatile little chip. I wouldn’t worry about it. Don’t you have a secure vault for your personal info? It’s very easy to encrypt. Just search the internet on how to protect your data. You can really go it the safe way and implement a VPN. You might have to pay a 1-2$ a month for the service, which is actually a cloud based service.


message:
No Data Received on Serial Port & Unable to DFU Reset. Advice?

Having a problem running my original code that I tested last week, which worked on multiple days last week.

I tried to do a DFU reset and update the BootLoader, but it didn't work. I checked the baudrate and board selections in the Tools tab, but those were fine.

 I didn't change anything in the code, I checked the wires on the hardware setup (nothing looks loose).

Thought it could be an error with the USB cable, changed the USB cable to a different one, still same error.

Also - using a Mac. But the same issue arose on the Windows PC. Did not try to reset using the Windows computer, but reset issue has more to do with the other hardware?

Checked the serial port - and it's selected to right one.
[![enter image description here][1]][1]

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

[![Error Posting - no data from the serial port][3]][3]

  [1]: https://i.stack.imgur.com/LU7gA.png
  [2]: https://i.stack.imgur.com/pvbqb.png
  [3]: https://i.stack.imgur.com/EPP1W.png

body:
Step Zero - check that the port selected works.

Step Next -  if you still get the error, try the DFU reset options and follow the steps outlined in the link below.

https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/using-the-bootloader


message:
MOSFET dimmer IR controlled

I am trying to make a group of LED dim with PWM to a MOSFET. The code seems to work for this, but the trouble is that the IR receiver will only receive the signal to turn on the lights and then IR receivers onboard LED goes to a permanent dim state (which is suppose to be off completely).  It then refuses to take input until a Arduino reset is preformed.  I purchased another IR receiver and placed it in the same configuration and it work exactly as intended I could brighten the LEDS and I saw the PWM stretch on my oscilloscope with every click of my remote.  The trouble is that the receiver quickly quit working at this point I think there is a problem with my circuit.  I am attaching the circuit diagram in hopes that someone can help.

Thanks,
Billa

    #include <IRremote.h>

    int led = 9;
    int led2 = 10;
    int brightness = 0;    // how bright the LED is
    const int RECV_PIN = 7; //IR Receiver Pin
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup() {
      // declare pin 9 to be an output:
      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);
      Serial.begin(9600);
      irrecv.enableIRIn();

    }

    void loop() {

      analogWrite(led, brightness);
      analogWrite(led2, brightness);

      if(irrecv.decode(&results)) //this checks to see if a code has been received
    {
        if(results.value == 0xFF906F) //if the button press equals the hex value 0xC284
        {
            Serial.println("Triggered U");
            brightness = brightness + 5;
        }

        if(results.value == 0xFFE01F) //if the button press equals the hex value 0xC284
        {
            Serial.println("Triggered D");
            brightness = brightness + 5;
        }

        irrecv.resume(); //receive the next value
    }

      delay(100);
    }

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

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

body:
The first error I see with the sketch is right under this line of code `Serial.println("Triggered D");`. You are incrementing the variable `brightness` when you probably meant to decrement it.

The second error is with your call to `analogWrite()`. This function accepts an `integer` between 0 and 255. You do not [constrain][1] the value to that range, and can see what I mean by adding this line of code `Serial.println(brightness);` right above this one `irrecv.resume();` in your sketch. Going from 0 to -5 turns the LED from off to maximum brightness. Is this what you want it to do?

The errors with your MOSFET circuit is a "General Electronics" question, and should be asked on electronics.stackexchange.com. As I mentioned in one of my comments to your question, there is a [recommended format for drawing schematics][2].

My other comment was regarding [this Q+A at EE][3]. You won't find a consensus on exactly how to use a MOSFET there either, but the [image in this answer][4] may be helpful to you.

  [1]: https://www.arduino.cc/reference/en/language/functions/math/constrain/
  [2]: https://electronics.stackexchange.com/questions/28251/rules-and-guidelines-for-drawing-good-schematics
  [3]: https://electronics.stackexchange.com/questions/68748/question-about-mosfet-gate-resistor
  [4]: https://electronics.stackexchange.com/a/68754/165322


message:
Arduino as Slave on I2C bus to read data from other I2C devices

Good afternoon;
I am a bit new to the world of I2C bus. I'm trying to implement a project that have  Arduino MEGA as a master and Arduino nano as slave. I have some I2C sensors that i want the slave (Arduino nano) to read. Please how can i implement this.

body:
An Arduino can be both a master and a slave.  Nick Gammon's page on I2C describes how to do it.   http://www.gammon.com.au/i2c

>Communicating with other devices

>So all this I2C stuff is great, you can use just two wires (plus ground) to talk to up to 119 devices. But what if you have a device (like a keypad) that doesn't support I2C? Well, the simple answer is that you can use something that does as an interface. For example, a second Arduino. My examples above do just that, using one as the master and second one to display text on LEDs.

>In fact, the "master" can also act as a slave, since you can have multiple masters on one wire. The example below shows how you can send data from one Arduino to another, whilst waiting for information to be sent from the second back to the first.

See the link for code examples.


message:
Getting issues while using SoftwareSerial

I am trying to read string send from esp8266 esp01 to Arduino mega. When I use normal Rx and Tx ports, it works properly but when i am initializing new serial port using SoftwareSerial then nothing is being shown on the serial monitor.

Please help me as i have been stuck and trying to solve this for weeks now.
Below are the code for esp8266 and Arduino mega

>>Code for ARDUINO MEGA

    #include<SoftwareSerial.h>

    SoftwareSerial myS(4,5);

    String data="true";

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    myS.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(myS.available()){
      data=myS.readString();
      }
      Serial.println(data);
      //Serial.write(data);
      delay(2000);
    }

>> Code for ESP8266

    void setup() {
      Serial.begin(9600);     // Initialize the Serial interface with baud rate of 9600
    }

    // the loop function runs over and over again forever
    void loop() {
      if(Serial.available()>0)    //Checks is there any data in buffer
      {
        Serial.print("We got:");
        Serial.print(char(Serial.read()));  //Read serial data byte and send back to serial monitor
      }
      else
      {
        Serial.println("Hello World..."); //Print Hello word every one second
        delay(1000);                      // Wait for a second
      }
    }

------------------------------------------------------

Moreover, i have tried read() as well instead of readString(), but it does not work either. I have also tried switching Rx and TX pins meaning connecting Rx->Tx, Tx->Rx and vice versa i.e. Rx->Rx and Tx->Tx, but it does not work in any of the case.
Any help or suggestion will be appreciated.
Thanks

body:
SoftwareSerial only works on a few select GPIO pins on the Mega. Specifically those pins that have PCINT on them.

But that is irrelevant. There is no reason to use `SoftwareSerial` on a Mega except in exceptional circumstances.  You have four hardware UARTs on the Mega, so there is no call to use `SoftwareSerial`.  Use the real UART pins and objects:

    Serial -> RX(0) / TX(1)
    Serial1 -> RX1(19) / TX1(18)
    Serial2 -> RX2(17) / TX2(16)
    Serial3 -> RX3(15) / TX3(14)

Just replace all references in your code to the `SoftwareSerial` instance with `Serial1` (delete the `#include` and the object instance constructor) and use TX1 and RX1 to connect your module:

    String data="true";

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(9600);
        Serial1.begin(9600);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        if(Serial1.available()){
            data=Serial1.readString();
        }
        Serial.println(data);
        //Serial.write(data);
        delay(2000);
    }


message:
Breadboard arduino uno not working properly

[![enter image description here][1]][1]Is there any mistake in the circuit of arduino uno on breadboard... I am using arduino uno board to program this 328p mcu and after that i remove 328p from arduino uno board and placing on breadboard as shown in circuit diagram. But mcu is not working(i.e the motors are not and other devices connected to mcu are not working) But when i connect reset,vcc,gnd pins of 328p on breadboard to arduino uno board without 328p on it then its working fine and all devices are working according to my program.. even when  i connect those reset,vcc and gnd pins to reset,vcc,gnd of  any usb asp programmer then also its working fine(*even programmer is not plugged in to pc). Its very strange behavior even if i disconnect any of these reset,vcc,gnd cables then also its not working... Is there any errors in circuit...please help me out[![, breadboard][2]][2]

  [1]: https://i.stack.imgur.com/oLn2T.png
  [2]: https://i.stack.imgur.com/zGnkq.png

body:
Problem solved by adding 100nf capacitor between reset and ground.... Which enables a auto reset function after every time powering on..
[from this arduino forum i got this solution][1]

Thank you everyone

  [1]: https://forum.arduino.cc/index.php?topic=107140.0#msg804230


message:
Serial communication PC to Arduino using C and send via NRF

I'm trying to communicate my PC with an Arduino Mega via serial and after send the message via NRF to another Arduino.

But I don't know if the message is send correctly or if it even send the message. Because I can't debug using `Serial Monitor`. If it is opened the serial port appear as busy.

When I execute the code the TX led on the Arduino blinks, but nothing is send via NRF.

I made some tests using only the NRF between the Arduinos and it's working, but when I try using the PC - Arduino serial communication, nothing happens.

**C Code**

    #include <stdio.h>
    #include <string.h>

    char arduinoPort[] = "/dev/ttyACM0";

    int main() {

      char buffer[] = {'1'};
      int error = 10;
      FILE *usb_port;

      usb_port = fopen(arduinoPort, "rwb");

      if(!usb_port) {
        perror(arduinoPort);
        return 1;
      }

      //memcpy(buffer, &error, sizeof(error));
      fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

      fclose(usb_port);

      return 0;
    }

**Arduino Code**

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <printf.h>
    #include <RF24_config.h>

    RF24 radio(7, 8); // CE, CSN

    uint64_t address = 0xF0F0F0F0E1LL;

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

      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
      radio.printDetails();

    }

    void loop() {

      if(Serial.available() > 0) {

        char byteLido = Serial.read();

        radio.write(&byteLido, sizeof(byteLido));
        delay(1000);
      }
    }

body:
Working with serial in C on Linux is not as simple as opening a file and reading from it (though in *some* circumstances that can work).

You should open the file using `open()` not `fopen()`, then use `tcgetattr()` and `tcsetattr()` etc to configure the port.

For example:

    #include <stdio.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <unistd.h>
    #include <errno.h>
    #include <string.h>
    #include <signal.h>
    #include <stdlib.h>

    struct termios oldsettings, newsettings;
    int fd;

    // This signal handler will close the port cleanly leaving
    // it in the same state it started in
    void sighandler(int sig) {
        if (sig == SIGINT) {
            if (fd >= 0) {
                // Restore the settings to original
                tcsetattr(fd, TCSANOW, &oldsettings);

                // Close the port
                close(fd);

                printf("Program teminated. Thank you for playing.\n");
                // Exit the program
                exit(0);
            }
        }
    }

    int main(int argc, char *argv) {

        // Trap CTRL-C to close the port properly
        signal(SIGINT, &sighandler);

        fd = open("/dev/ttyACM0", O_RDWR);
        if (fd < 0) {
            fprintf(stderr, "Error opening serial port: %s\n", strerror(errno));
            return 10;
        }

        // Save the settings
        tcgetattr(fd, &oldsettings);
        // Grab the current settings again to modify
        tcgetattr(fd, &newsettings);

        // Set the baud rate
        cfsetispeed(&newsettings, B9600);
        cfsetospeed(&newsettings, B9600);

        // Make it a raw port
        cfmakeraw(&newsettings);

        // Apply the settings
        tcsetattr(fd, TCSANOW, &newsettings);

        char c;
        printf("Press CTRL-C to terminate\n");

        while (read(fd, &c, 1) == 1) {
            printf("Got character 0xx\n", c);
        }

        fprintf(stderr, "Reception terminated: %s\n", strerror(errno));

        return 0;
    }

No one ever said programming C was easy. It makes you appreciate just how much work the Arduino API does behind the scenes for you...

Also you need to be aware that the Arduino resets (if you use an Uno, Mega, or other board with a separate USB interface chip) when you open the serial port. You need to wait about 2 seconds after opening the port before you ever send anything, or whatever you send will be completely ignored.  You can do that with:

    sleep(2);

after you have opened and configured the port.


message:
How do I join two RGB ledPanel 32x64 in order to get one 64x64?

I'm making a project to make a pixelArt of 64x64 using two 64x32 RGB ledMatrix and Arduino MEGA.

[This is the RGB Panel][1] I am using.

I use ADAFruit and RGBMatrixPanel libraries in my Arduino Code and if I connect the Arduino pins to the RGB panel it works, but the problem is when I try to connect the output of the first panel to the input of the second, I saw the "same image duplicated" but with different brightness, and if I change the length of the panel seems to print random LEDs.

I know that Adafruit is thought to get a screen with max of height of 32, but I don't care, because for my purpose you can assign each pixel programmatically in order to print the proper image.

I followed [this guide][2] in order to make the connection with a panel of 64x32.

I think that I have to change my code and also my physical connections, but I don't know how, can anyone help me?

Other option that I thought was create another matrix2 instance at the same code using different PINS, but this is very weird.

This is the current connections: (I have a power supply of 5v - 10A)
[![enter image description here][3]][3]

This is the result that I have: (duplicated in both screens with a brighness/weird shadow in the second)
[![enter image description here][4]][4]

And this is the final result that I'm looking for: (this is made with two Arduino Megas)
[![enter image description here][5]][5]

Thanks in advance!

  [1]: https://es.aliexpress.com/item/32904852724.html?spm=a2g0s.9042311.0.0.685963c0LrWjF8
  [2]: https://learn.sparkfun.com/tutorials/rgb-panel-hookup-guide/all
  [3]: https://i.stack.imgur.com/K9Baj.jpg
  [4]: https://i.stack.imgur.com/wfRjO.jpg
  [5]: https://i.stack.imgur.com/zQpC1.jpg

body:
First off, connecting the 2nd panel to the same output pins as the first one, you are simply sending same data to the 2nd panel, which is why you get the duplicate visuals. I'm guessing you are sending power that same way, which is why you are seeing the brightness dim.

Secondly, it's hard to read on the pics in the AliExpress listing, but the Sparkfun site had a better image, which shows an "Output" connection on the back of the panels.  You need to daisy chain the 2nd panel to the first panel through this "Output" connection. This should prevent you from having to create a 2nd matrix2 and use a 2nd set of pins.

Third, having a 2nd set of pins and controlling the 2nd LED matrix can make updating the image faster. It depends on your library as well as how the LED matrix is made, so it really depends on those factors, but some LED systems are designed so there is a maximum amount of pixels that can be displayed before there's a noticeable delay in LED updated. With this amount of LED pixels, you're probably fine, but if you want fast updates and expect to expand your matrix in the future, you might want to consider driving the panels separately. I'm not saying you have to now, but if you're seeing lag, this might be a good option.


message:
NodeMCU 1.0 - Exception 9 `Fatal exception 9(LoadStoreAlignmentCause):`

I am getting this error in my code.
`Fatal exception 9(LoadStoreAlignmentCause):`

Using core version `2.4.2`

Stack trace

 Decoding stack results
 0x40213e9c: dns_gethostbyname at core/dns.c line 1472
 0x40204c21: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
 0x40205038: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
 0x4020306b: setPostString(int, int, Array8Int, char*) at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 516
 0x40203f8a: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 335
 0x40209080: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
 0x402048e0: loop() at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 243

struct declaration

    struct Array8Int {
        int array[8];
    };

loop

    char post[300] = "";
    int pulseChange05m = rainCheck(slaveData);
    int now10 = floor(unixtimeServer/10)*10;
    Array8Int slaveData = slaveCheck(now()); // update slaveData array
    setPostString(now10, pulseChange05m, slaveData, post);

functions

 void setPostString(int unixtimeEvent, int pulseChange, Array8Int postData, char* postStr) {
   bool flag = true;
   float rainHour = pulseChange*0.25;
   if (hour() == 10) { // 7 AM palmital
     rainCount = 0;
     rainCount05m = 0;
   }
   rainCountHour = rainCount;
   int humidityBme280HourAvg = 0;
   int pressureBme280HourAvg = 0;
   int temperatureBme280HourAvg = 0;
   int lightSensorHourAvg = 0;
   int pressureBme280HourMin = 100000;
   int temperatureBme280HourMin = 1000;
   int temperatureBme280HourMax = -1000;
   int counterLoop = counterHour;
   for(int i=0;i<counterLoop;i++) {
     lightSensorHourAvg += lightSensorHour[i];
     pressureBme280HourAvg += pressureBme280Hour[i];
     temperatureBme280HourAvg += temperatureBme280Hour[i];
     temperatureBme280HourMax= max(temperatureBme280HourMax,temperatureBme280Hour[i]);
     pressureBme280HourMin = min(pressureBme280HourMin,pressureBme280Hour[i]);
     temperatureBme280HourMin = min(temperatureBme280HourMin,temperatureBme280Hour[i]);
     humidityBme280HourAvg += humidityBme280Hour[i];
   }
   pressureBme280HourAvg = pressureBme280HourAvg/counterLoop;
   temperatureBme280HourAvg = temperatureBme280HourAvg/counterLoop;
   lightSensorHourAvg = (int)lightSensorHourAvg/counterLoop;

   strcat(postStr, stationId);
   strcat(postStr,"&3="); // chuva hora
   strcat(postStr, dtostrf(rainHour,6,2,charDummy));
   strcat(postStr,"&8=");
   strcat(postStr, dtostrf(temperatureBme280HourAvg,6,2,charDummy));
   strcat(postStr,"&9="); //temperature avg
   strcat(postStr, dtostrf(temperatureBme280HourAvg,6,2,charDummy));
   strcat(postStr,"&10="); //temperature avg
   strcat(postStr, dtostrf(temperatureBme280HourMax,6,2,charDummy));
   strcat(postStr,"&11="); //temperature avg
   strcat(postStr, dtostrf(temperatureBme280HourMin,6,2,charDummy));
   strcat(postStr,"&20=");
   strcat(postStr, dtostrf(pressureBme280HourAvg,10,0,charDummy));
   strcat(postStr,"&22=");
   strcat(postStr, dtostrf(pressureBme280HourMin,10,0,charDummy));
   strcat(postStr,"&101=");
   strcat(postStr, dtostrf(lightSensorHourAvg,6,0,charDummy));
   strcat(postStr,"&time=");
   strcat(postStr, dtostrf(unixtimeEvent,16,0,charDummy));
   strcat(postStr,"&endline=1");
   strcat(postStr, "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
 }
 int rainCheck(Array8Int slaveData) {
   int pulseChange = slaveData.array[0];
   return pulseChange;
 }

body:
> Fatal exception 9(LoadStoreAlignmentCause):

This is caused by you (or some code you are running) attempting to read or write a 32 bit value from memory that is not "aligned" to 32 bits.  It is most often the result of trying to cast portions of a byte array (for instance a buffer received over UDP) to a 32-bit integer.  The compiler is not clever enough to know that the byte array portion you are casting isn't at a 32-bit boundary and thus doesn't know to use the 8-bit load/store instructions to access the memory.

Mapping a `struct` over a buffer can also have similar issues where the buffer is 8-bit aligned and the `struct` contains 32-bit words.

You can combat it by forcing the alignment of any buffers which you treat in such a way with the `__attribute__((aligned(4))` tag:

    uint8_t __attribute__((aligned(4))) buffer[128];

You can also "pack" structures to tell the compiler "These variables are mis-aligned and should not be padded to 32-bits":

    struct foo {
        uint8_t bar1;
        uint32_t bar2;
    } __attribute__((packed));

If in doubt, though, just pull individual bytes out of buffers (or wherever) and build up your larger integers manually with bit shifting and OR operators (`<<` and `|`), and do the reverse for filling byte buffers.


body:
I had this error including on new cards
it worked on one card and not on another
the reason is that my eeprom was not initialized
the nodemcu 8266 that was working properly, was the one I used for development. Because i was using test to write on my eeprom so the value was put in it.
I did not understand what append After, I try flashing reload original setup etc...
I read your answer and I pass this program (which is a stupid manual writing of my eeprom)
I make it running once
and after that
I could load my other programs without problems
~~~~

    #include <EEPROM.h>
struct credential {
  char WIFI_SSID [39] = " ";
  char WIFI_PASSWORD [39] = " ";
  char SMTP_HOST[44] = " ";
  uint16_t SMTP_PORT = 465;
  char AUTHOR_EMAIL[39] = " ";
  char AUTHOR_PASSWORD[39] = " ";
  char RECIPIENT_EMAIL[39] = " ";
  uint16_t  NbOfProbe = 1; //number of probe 1-to 16
  char TypeOfDevice[16] = "f";// F or f fridge R freezer O hot  exemple fRoFRr
  char AlertMin [54] = "30";//with always a sign like-10+0+2 the sign act like a separator
  char AlertMax [54] = "38";//with always a sign like-10+0+2 the sign act like a separator
  uint16_t  NbOfMinNormMail = 60 ;//time to wait in sec between 2 normal messages eg 14400 sec(4 hours)
  uint16_t  PowerOffMinWait = 1 ;
  uint16_t  TempOffLimitWait = 1;
  char AlertPowerMsg[41] = "alerte coupure de courant "; //Message alerte coupure de courant
  char AlertTempMsg[41] = "alerte temperature hors limite";
  char NormalTempMsg[41] = "Tout est ok ";
  char DateMsg[16] = "vide";
};
typedef struct credential settingcredent;
settingcredent parametersEeprom;
uint addr = 0;
void setup()
{
  Serial.begin(115200);
delay (100);
/*
  // fake data
  struct {
    uint val = 0;
    char str[20] = "";
  } data;
*/
  // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
  // this step actually loads the content (512 bytes) of flash into
  // a 512-byte-array cache in RAM
 //                                                                          EEPROM.begin(512);

  // read bytes (i.e. sizeof(data) from "EEPROM"),
  // in reality, reads from byte-array cache
  // cast bytes into structure called data
 //
 showeprom ();

  strncpy(parametersEeprom.WIFI_SSID,"myssid",39);
  strncpy(parametersEeprom.WIFI_PASSWORD,"passmyssid",39);
  strncpy(parametersEeprom.SMTP_HOST,"smtp.gmail.com",44);
  parametersEeprom.SMTP_PORT=465;
  strncpy(parametersEeprom.AUTHOR_EMAIL,"iottest@gmail.com",39);
  strncpy(parametersEeprom.AUTHOR_PASSWORD,"iottest01",39);
  strncpy(parametersEeprom.RECIPIENT_EMAIL,"johndoe@hotmail.fr",39);
  parametersEeprom.NbOfProbe = 4; //number of probe 1-to 16
  strncpy(parametersEeprom.TypeOfDevice,"rffo",16);// F or f fridge R freezer O hot  exemple fRoFRr
  strncpy(parametersEeprom.AlertMin,"-20+0+2+23",54);//with always a sign like-10+0+2 the sign act like a separator
  strncpy(parametersEeprom.AlertMax,"-15+5+7+28",54);//with always a sign like-10+0+2 the sign act like a separator
  parametersEeprom.NbOfMinNormMail = 60 ;//time to wait in sec between 2 normal messages eg 14400 sec(4 hours)
  parametersEeprom.PowerOffMinWait = 10 ;
  parametersEeprom.TempOffLimitWait = 20;
  strncpy(parametersEeprom.AlertPowerMsg,"alerte coupure de courant ",41); //Message alerte coupure de courant
  strncpy(parametersEeprom.AlertTempMsg, "alerte temperature hors limite",41);
  strncpy(parametersEeprom.NormalTempMsg, "Tout est ok ",41);
  strncpy(parametersEeprom.DateMsg,"vide",16);
  EEPROM.put(addr, parametersEeprom);
  EEPROM.commit();

  EEPROM.get(addr,parametersEeprom);
  Serial.println("New values are: "+String(parametersEeprom.WIFI_PASSWORD)+","+String(parametersEeprom.WIFI_SSID)+","+String(parametersEeprom.SMTP_HOST));
}
void showeprom ()
{
  EEPROM.begin(sizeof(parametersEeprom));
  EEPROM.get(addr, parametersEeprom); //read data from array in ram and cast it into struct called parametersEeprom

  Serial.println("-------------------------"); //Showing the details
  Serial.print("your SSID ="); Serial.println( parametersEeprom.WIFI_SSID);
  Serial.print("your password for SSID ="); Serial.println( parametersEeprom.WIFI_PASSWORD);
  Serial.print("your SMTP_HOST ="); Serial.println( parametersEeprom.SMTP_HOST);
  Serial.print("your SMTP_PORT ="); Serial.println( parametersEeprom.SMTP_PORT);
  Serial.print("Your less secure email="); Serial.println( parametersEeprom.AUTHOR_EMAIL);
  Serial.print("Your password for not secure email="); Serial.println( parametersEeprom.AUTHOR_PASSWORD);
  Serial.print("Your email that must receive msg like MeTheBoss@MyCompany.com="); Serial.println( parametersEeprom.RECIPIENT_EMAIL);
  Serial.print("The number of thermometers probe you have is ="); Serial.println( parametersEeprom.NbOfProbe);
  Serial.print("Enter in order type of device (F)ridge f(R)ezzer (O)ven like RFFO="); Serial.println( parametersEeprom.TypeOfDevice);
  Serial.print("Enter mintemp in order per device like(suppose RFFO) -22-1+5+180="); Serial.println( parametersEeprom.AlertMin);
  Serial.print("Enter maxtemp in order per device like(suppose RFFO) -16+4+10+220="); Serial.println( parametersEeprom.AlertMax);
  Serial.print("Number of sec between 2 normal mails like(4hours) 240 ="); Serial.println( parametersEeprom.NbOfMinNormMail);
  Serial.print("Number of sec to wait before sending message Power off like 5 ="); Serial.println( parametersEeprom.PowerOffMinWait);
  Serial.print("Number of sec to wait before sending message warning temp like 5 ="); Serial.println( parametersEeprom.TempOffLimitWait);
  Serial.print("Message power down(30 char) like WARNING POWER OFF GRID="); Serial.println( parametersEeprom.AlertPowerMsg);
  Serial.print("Message temperature off min/max(30 char) like WARNING TEMPERATURE ABNORMAL="); Serial.println( parametersEeprom.AlertTempMsg);
  Serial.print("Message report state of all fridges freezer Oven like Everything is OK in the kitchen ="); Serial.println( parametersEeprom.NormalTempMsg);
  Serial.print("Enter date of the modif parameters like 08/23/21-18:25="); Serial.println( parametersEeprom.DateMsg);

}
void loop()
{
  delay(10000);
  showeprom ();

}

~
~

I hope that this experiment can be usefull
I cannot explain why it work


message:
Why is Arduino I2C so sensitive to RFI/EMI?

I have a 2-motor robot project that uses a MP6050 for relative heading (yaw) measurements, and I'm having problems with the I2C bus when the motors are running.  I have done most of the things suggested here and elsewhere; 2.2K pullups vs default, shortest possible (3cm) I2C wires, MPU6050 as far away from the motor drivers as possible, reduced I2C clock speed to 100KHz, etc, etc (for additional details, see my [blog post][1] on the subject).

So, my question is, why is the I2C bus so sensitive to RFI/EMI, especially with 2.2K pullups to +5V?  Looking at the levels with my O'scope shows a 0-4.6V swing, so it's hard to believe that EMI-induced currents could be high enough across 2.2K to pull the 'high' level low enough to be considered a '0', so something else must be going on.  Maybe the EMI is getting into the MPU6050 output driver circuit, causing it to turn off?  If so, maybe capacitive bypasses on the I2C lines would help.  Any ideas?  Are other IMU modules less susceptible to motor driver EMI?

TIA,

Frank

  [1]: https://www.fpaynter.com/2019/07/mpu6050-imu-motor-noise-troubleshooting/

body:
Put a ground plate between your data lines and the power+signal lines used to drive the motor. A GPS ground plate is fine, see link below. You can just cut a piece of metal sheet to fit, or even use folded metal foil connected to ground. Motors are just noisy, and I2C is sensitive. Even updating a I2C LCD can cause noise. I like to use shielded wire (like for headphone- or HDMI cable) if my data lines are more than an inch long. You can shield lines with metal foil and heatshrink, but that’s a mess.

Use an opto-isolator to turn on your motors if a ground plate is not enough. If they only drive in one direction, add a catch diode and a 330pF cap to trim the noise. But they are probably most noisy when running. Good luck with that.

https://www.imnasa.com/en/ground-plate-200x64x12mm-for-gps-etc.html


message:
Convert Arduino MEGA Code to Arduino DUE Code?

I've been working with MEGA before. This code works completely with MEGA. I'm still at beginner level in Arduino.

**Q:** How do I adapt this code to DUE?

**Note:** I'm asking this question because I think the only problem in adaptation seems to be `SoftwareSerial`.
<!-- language-all: lang-cpp -->
```
#include <SoftwareSerial.h>
SoftwareSerial bluetooth(52,53);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;
int IN1a=49;
int IN2a=48;
int PWM1=3;
int IN1b=22;
int IN2b=23;
int PWM2=4;
int hiz=100;
int PWM_kare=2;
int INA_kare = 51;
int INB_kare = 50; //LED '+'sı OUTPUT B'de olduğu için INB'yi  HIGH yapıyoruz.
void m1_cw() {
    digitalWrite(IN1a,HIGH);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,hiz);
}
void m1_ccw() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,HIGH);
    analogWrite(PWM1,hiz);
}
void m2_cw() {
    digitalWrite(IN1b,HIGH);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,hiz);
}
void m2_ccw() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,HIGH);
    analogWrite(PWM2,hiz);
}
void m1_stop() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,0);
}
void m2_stop() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,0);
}
void mast_up() {
    digitalWrite(24,HIGH);
    digitalWrite(25,LOW);
}
void mast_down() {
    digitalWrite(24,LOW);
    digitalWrite(25,HIGH);
}
void mast_stop() {
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
}
void kare() {
    analogWrite(PWM_kare,head_analog);
    digitalWrite(INB_kare, HIGH);
    digitalWrite(INA_kare, LOW);
}
void setup() {
    Serial.begin(9600);
    bluetooth.begin(9600);
    Serial.println("Program is starting...");
    Serial.println("by Berke Ogulcan Parlak");
    pinMode(IN1a,OUTPUT);
    pinMode(IN2a,OUTPUT);
    pinMode(IN1b,OUTPUT);
    pinMode(IN2b,OUTPUT);
    pinMode(PWM1,OUTPUT);
    pinMode(PWM2,OUTPUT);
    pinMode(24,OUTPUT);
    pinMode(25,OUTPUT);
    pinMode(INA_kare, OUTPUT);
    pinMode(INB_kare, OUTPUT);
    pinMode(PWM_kare, OUTPUT);
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    digitalWrite(PWM1,LOW);
    digitalWrite(PWM2,LOW);
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
    digitalWrite(INA_kare, LOW);
    digitalWrite(INB_kare, LOW);
    digitalWrite(PWM_kare, LOW);
}

void loop() {
    if (bluetooth.available()) {
        while (bluetooth.available())
        {                                                //AppInventor'dan çektiğimiz verileri,değişkenlere atıyoruz.
            bar_analog = bluetooth.parseInt();
            head_analog = bluetooth.parseInt();
            bar_anim = bluetooth.parseInt();
            strip_anim = bluetooth.parseInt();
            motor_speed = bluetooth.parseInt();
            direct = bluetooth.parseInt();
            level = bluetooth.parseInt();
            if (debug) {                                   // Arduin seri ekranından değerleri okumak için gereklidir.
                Serial.print("Bar Brightness: ");
                Serial.println(bar_analog);
                Serial.print("Bar Animation Type: ");
                Serial.println(bar_anim);
                Serial.print("Headlight Brightness: ");
                Serial.println(head_analog);
                Serial.print("Strip Animation Type: ");
                Serial.println(strip_anim);
                Serial.print("Motor Speed Level: ");
                Serial.println(motor_speed);
                Serial.print("Direction: ");
                Serial.println(direct);
                Serial.print("Mast Goes: ");
                Serial.println(level);
                Serial.println("--------------------------------");
            }
            if (bluetooth.read() == '\n') {               //Yazdırma işlemleri bu satırda yapılacak..

            }
        }}
    if(direct==1) { //ileri
        m1_ccw();
        m2_ccw();
    }
    else if(direct==2) { //geri
        m1_cw();
        m2_cw();
    }
    else if(direct==3) { //sol
        m1_ccw();
        m2_cw();
    }
    else if(direct==4) { //sağ
        m1_cw();
        m2_ccw();
    }
    else if(direct==0) { //durur
        m1_stop();
        m2_stop();
    }
    if(level==1) { //mast yukarı
        mast_up();
    }
    else if(level==2) { //mast aşağı
        mast_down();
    }
    else if(level==0) { //mast durur
        mast_stop();
    }
    kare();            //kare LED aktif.
}
```

body:
SoftwareSerial is a workaround for Arduino versions without enough Hardware Serial ports, which is not the case of Arduino Mega or Arduino Uno which have 4.

Delete `SoftwareSerial`, replace all occurrences of `bluetooth` by `Serial1`, and rewire the Serial communication from pins `52`|`53` into pins `18`|`19` instead of (TX|RX)

Besides, the Arduino Due tends to be more "strict" than Arduino Mega compiler.

Besides that, your code will compile with no issues.

Also, remember Arduino Due is 3.3V and not 5V.


message:
how to set buzzer on and off

I have a project that require me to use magnetic contact sensor. I will put the sensor at the door. So the idea is i want every time someone open the door, the buzzer will make a sound, but it will only stay for 3 seconds. When the door is close, buzzer will do nothing and when someone open the door again, the buzzer will make a sound for 3 seconds again. That is the loop. Here is my code. Sorry it's messy. I changed it few times and it still not working like what I want.

    const int buzzer = 13;
    const int sensor = 4;

    int state; // 0 close - 1 open switch

    void setup()
    {
      pinMode(sensor, INPUT_PULLUP);
    }

    void loop()
    {
      state = digitalRead(sensor);

      if (state == HIGH){
        tone(buzzer,1000);
        delay(3000);
        noTone(buzzer);
      }

      else{
        noTone(buzzer);
      }

    }

body:
When I have a state-machine problem such as this, I diagram it first - here's mine, based on how I understand your requirements:

[![State Diagram][1]][1]

Most state machines are only activated when an external event happens, so not much happens inside the state-boxes. But since your application only does this one thing, you can actually do your testing inside the states. This is the difference between between blocking- and non-blocking programming - we can afford to block (delay until something happens) because there is nothing else we have to do in the meanwhile.

And my code for the state-machine (which I haven't tested, but it compiles without error):

    const int buzzer = 13;
    const int sensor = 4;

    int state; // 0 close - 1 open switch

    void setup()
    {
       pinMode(sensor, INPUT_PULLUP);
    }

    void loop()
    {
       // Wait for sensor HIGH
       while( digitalRead(sensor) == LOW )
          ;

       // Sensor HIGH - Alarming
       tone(buzzer, 0.52);
       delay(3000);

       // Wait for sensor LOW
       noTone(buzzer);
       while( digitalRead(sensor) == HIGH )
          ;

       // (goes to Wait for sensor HIGH)
    }

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


message:
NodeMCU what is my esp3286 core version

How do I find out what my esp3286 core version using Arduino IDE?

body: Tools Menu -> Board -> Boards Manager - scroll down to the core and see what version it is.