body:
I have 2 sets of RGB Leds, each set is driven by 3 OUTPUT analog pins of the arduino, as illustrated below:
[![enter image description here][1]][1]

The code is supposed to put on HIGH the 6 analog pins at the same time so that the Leds light up all at the same time, but when I run it, there's a latency between the 2 groups of Leds.
Here's the code:

    const int r[2] = {3, 9};
    const int g[2] = {5, 10};
    const int b[2] = {6, 11};

    const int red[3] = {255, 0, 0};
    const int green[3] = {0, 255, 0};
    const int blue[3] = {0, 0, 255};

    int* colors[3] = {red, blue, green};

    void setup() {
        for(int i=0;  i<2; i++){
            pinMode(r[i], OUTPUT);
            pinMode(g[i], OUTPUT);
            pinMode(b[i], OUTPUT);
      }
    }

    void setColor(int r, int g, int b, int color[]){
        int R = 255 - color[0];
        int G = 255 - color[1];
        int B = 255 - color[2];
        analogWrite(r, R);
        analogWrite(g, G);
        analogWrite(b, B);
    }

    void loop() {
        for(int c=0; c<3; c++){
          setColor(r[0], g[0], b[0], colors[c]);
          setColor(r[1], g[1], b[1], colors[3-c-1]);
          delay(1000);
        }
    }

I should point out that the values of the resistors are in my circuit are different than in the diagram.

Is there something wrong in the wiring or in the code that prevents the Leds from wiring all at the same time?

EDIT: I tried the code one more time on the arduino and all Leds lit up at the same time. That happened in the past, but sometimes there's just a latency that I can neither explain nor fix...

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

title: How to light up RGB Leds at the exact same time?

Answers: 0


body:
I want to connect two CCS811 sensors with ESP32 dev board. Since the sensors have fixed address, I am unable to use them simultaneously. I have read that on ESP32 multiple I2C buses can be created. While trying to follow that route I tried to modify the library but I am stuck. I can't simply pass different pins for SDA and SCL when calling ccs.begin() function. It only takes one argument and that is the sensor address (code chunk from library below):

    bool Adafruit_CCS811::begin(uint8_t addr) {
      _i2caddr = addr;

      _i2c_init();

      SWReset();
      delay(100);

      // check that the HW id is correct
      if (this->read8(CCS811_HW_ID) != CCS811_HW_ID_CODE)
        return false;

      // try to start the app
      this->write(CCS811_BOOTLOADER_APP_START, NULL, 0);
      delay(100);

 and the actual wire.begin() function is called in the _i2c_init() function which is defined in the lib as:

    void Adafruit_CCS811::_i2c_init() {
      Wire.begin();
    #ifdef ESP8266
      Wire.setClockStretchLimit(500);
    #endif
    }

With my very basic knowledge of classes and object, I am unable to modify the library to make it work with 2 I2C buses. Could you please help me with this?

Link to Adafruit CCS811 library:(https://github.com/adafruit/Adafruit_CCS811/blob/master/Adafruit_CCS811.cpp)

My Code so far:

    #include <Arduino.h>
    #include <Wire.h>
    #include "Adafruit_CCS811.h"

    Adafruit_CCS811 ccs1;
    Adafruit_CCS811 ccs2;

    TwoWire sen1 = TwoWire(0);
    TwoWire sen2 = TwoWire(1);

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

      Serial.println(F("CCS811 test"));

      if (!ccs1.begin(25, 26, 100000))
      {
        Serial.println("CCS 1 Failed.");
        //while (1);
      } else {
        Serial.println("CCS 1 OK!");
      }

      // Wait for the sensor to be ready
      //while (!ccs.available());
    }

    void loop()
    {
      if (ccs1.available())
      {
        if (!ccs1.readData())
        {
          Serial.println(" This is CSS");
          Serial.print("CO2: ");
          Serial.print(ccs1.geteCO2());
          Serial.print("ppm, TVOC: ");
          Serial.println(ccs1.getTVOC());
        }
        else
        {
          Serial.println("ERROR!");
          //while (1);
        }
      }
      delay(500);
    }

title: Initiating 2nd I2C bus on ESP32 with CCS811 sensor

Answers: 0


body:
I am currently doing a robotic arm project. I used load cell with HX711 amplifier to detect and monitor of the objects. If the objects is less than 3kg, then the servomotor in gripper can rotate and the gripper can hold the objects. But there is an error in my coding.

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

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

title: 'scale' was not declared in this scope

Answers: 1

body:
You forgot 'at least' to declare the global variable:

    HX711 scale;

See documentation: https://github.com/bogde/HX711/blob/master/src/HX711.h

See GitHub example: https://github.com/bogde/HX711/blob/master/examples/HX711_basic_example/HX711_basic_example.ino


body:
I am using the Protothread Library from Adam Dunkels.
It is supposed to wait 1 second and then continue. But instead it gets stuck there and everything after that line is not executed.

    lastTimeBlink = millis();
    PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);

Why does it get stuck there?
The entire code is uploaded here: https://pastebin.com/jRsuvn54

(The comments are on german)

title: Arduino stuck in PT_WAIT_UNTIL

Answers: 1

body:
By best attempt to provide something of an answer.

You have said:

> PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);

That is not literally represented in your code, so I take your question to refer
to:

```c++
int dist2 = dist1.toInt();
...
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > (dist2 * 1710));
```

or a similar section.

When you execute this `PT_WAIT_UNTIL`, `dist2` contains whatever value you initialized it with in `int dist2 = dist1.toInt();`   Assuming the condition isn't met, you are exiting `runCommand()` by way of `PT_WAIT_UNTIL`'s `return PT_WAITING;`

```c
#define PT_WAIT_UNTIL(pt, condition) \
  do {               \
    LC_SET((pt)->lc);     \
    if(!(condition)) {     \
      return PT_WAITING;    \
    }               \
  } while(0)
```

The `LC_SET` here in `PT_WAIT_UNTIL` is being used to generate a label that can be jumped-to later:

```
#define LC_SET(s)                                \
   do {                                          \
     LC_CONCAT(LC_LABEL, __LINE__):              \
     (s) = &&LC_CONCAT(LC_LABEL, __LINE__);      \
   } while(0)
```

Later when you later call runCommand to resume the thread, you execute `LC_RESUME` by way of `PT_BEGIN(pt);`

```c
#define PT_BEGIN(pt) { char PT_YIELD_FLAG = 1; LC_RESUME((pt)->lc)
...
#define LC_RESUME(s)  \
  do {      \
    if(s != NULL) {   \
      goto *s;    \
    }      \
  } while(0)
```

`goto *s` here is ultimately jumping to the label created by your use of `PT_WAIT_UNTIL`.

You are now back in `PT_WAIT_UNTIL` checking the condition with the line `if(!(condition))`.  That is, you are checking `millis() - lastTimeBlink > (dist2 * 1710)`  However, what you are *probably* (more on that below) doing here is reading junk off the stack.  `dist2` **was** initialized on a *previous* execution of `runCommand` and its effective lifetime ended when you returned in `PT_WAIT_UNTIL` on that prior execution.  On this new execution `dist2` is **un**initialized because you have jumped over its initialization.  If you turn the warning level up in File/Preferences you should see something for this.

A number of things can happen at this point, most of them not good.  I can't say what the compiler's optimizer will do to this code for certain, but not much would surprised me.  It seems likely, just on familiarity with optimizing compilers and what your code looks like, that it is generating code to read `dist2`.  That may  sound like a given, but it isn't when you're doing something undefined.  It's possible `dist2` has the value from a previous run where you're executing this function in a loop.  But it could also have value that makes `dist2 * 1710` evaluate to a duration of up to nearly 50 days, causes `PT_WAIT_UNTIL` to return from runCommand for so long as you're testing.

Generally, if you're going to use these proto-threads you're going to have to be very careful in thinking about what's actually initialized and what just *looks* like it is.  If you have a `PT_whatever` between a non-static local variable initialization or assignment and code where it's used, that's something to examine.


body:
So the task is to control 12v DC motor.

With first button, you can add up motor speed by certain speed step.

With second button, you can slow down motors speed by certain speed step.

With third button you cant speed up motor to its max, but problem is there that i must be done smoothly. For example i press third button and in motor starts to spin faster and faster till it reaches max speed. But now when i press this button motor jumps to it max, and i don't know why. There is no smoothness.

I cant use delay, must be done by millis

```
[code]
int speed = 0;
int motor = 5,
    fasterbutton = 7, slowerrbutton = 4, tillmaxbutton = 2;
unsigned long previousMillis = 0;
const long interval = 100;
const long smoothinterval = 5000;
boolean faster, slower, tillend;
int begginingspeed;
const int step = 3;
const int maxspeed = 255;

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, OUTPUT);
  pinMode(7, INPUT_PULLUP);
  Serial.begin(9600);
}
void loop() {
  tillend = digitalRead(2);
  slower = digitalRead(4);
  faster = digitalRead(7);

  //button Nr 7 start DC motor and festens up
  if (faster == !HIGH && begginingspeed < maxspeed) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed += step;
      if (faster == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR ON" );
      }
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      previousMillis = currentMillis;
    }
  }

  //button Nr 4 slows down  DC motor
  else if (slower == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed -= step;
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      if (slower == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR OFF" );
      }
      previousMillis = currentMillis;
    }
  }

  //button Nr 2 for smooth fastens up DC motor till max
  if (tillend == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis <= interval) {
      for (begginingspeed = begginingspeed; begginingspeed <= 255; begginingspeed += step)
        analogWrite(motor, begginingspeed);
    }
    previousMillis = currentMillis;
  }

}
[/code]
```
[![Shematic][1]][1]

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

title: smooth DC motor control with millis

Answers: 2

body:
If not delay then you'll probably have to use something like an H-Bridge. L298N is a good place to start. You can use PWM to control its speed and its gradual too.

https://www.browncountylibrary.org/wp-content/uploads/2018/03/arduino_dc_motors.pdf

Here's the relevant documentation

body:
I suggest using a different logic in your program. I would first divide up the different parts of the project:

- A code part, which reads the 3 buttons and sets/increments/decrements a variable based on the button clicks, and
- a code part, which takes a variable as set point and ramps the PWM (`analogWrite()`) output up or down, until the set point is reached. (So the setpoint is the target speed/PWM value)

This division between "input code" and "output code" is rather common, since it often makes your code better structured and makes it possible to easily add new inputs for one single output.

---

Let us first look at the second part (ramping the PWM signal up and down). We need a variable, that holds the current PWM value, and one, that holds the current set point (for both we are starting with zero, thus the motor stands still here:

    int current_speed = 0;
    int speed_setpoint = 0;

We also need a timestamp variable for using `millis()` to regularly setting the PWM output according to the set point and the corresponding interval (here as a define). Additionally we also define the increment, with which the PWM value should be incremented on each sample:

    unsigned long motor_timestamp;
    #define MOTOR_SAMPLE_INTERVAL  100
    #define MOTOR_SAMPLE_INCREMENT 3

We are doing all this in the global scope. Now in the loop function we first check for `millis()` and the timestamp (which gives us a regular sample interval for the motor speed) and then check, if the current speed is higher or lower than the setpoint and change the `current_speed` accordingly. At the end we write the value of `current_speed` to the output:

    if(millis() - motor_timestamp > MOTOR_SAMPLE_INTERVAL){
        if(current_speed < speed_setpoint){
            current_speed += MOTOR_SAMPLE_INCREMENT;
        } else if(current_speed > speed_setpoint){
            current_speed -= MOTOR_SAMPLE_INCREMENT;
        }
        analogWrite(motor, current_speed);
        motor_timestamp += MOTOR_SAMPLE_INTERVAL;
     }

So now we `current_speed` of the motor will follow the `speed_setpoint`, but will only increment or decrement with the speed you set with the `MOTOR_SAMPLE_INTERVAL` and the `MOTOR_SAMPLE_INCREMENT`. The new target speed is simply set by giving the variable `speed_setpoint` a new value. The above code will take care of reaching it.

---

Now lets look at the first part (reading the buttons for changing a variable). At your current code, you need to hold the button down for the value to change. From your text is guess, that you want a click behavior (1 step in speed for 1 button click, meaning button press and release). For that I suggest using the [Bounce2][1] library, which will handle the buttons - especially the debouncing - for you:

    #include <Bounce2.h>
    Bounce bounce = Bounce();

    void setup(){
        bounce.attach( BOUNCE_PIN, INPUT_PULLUP );
        // DEBOUNCE INTERVAL IN MILLISECONDS
        bounce.interval(5); // interval in ms
    }

    void loop(){
        bounce.update();
        if(bounce.fell()){
            // Handle the button click here
        }
    }

Inside the `if(bounce.fell())` statement, you would handle the action for the button click, in this case: updating the `speed_setpoint` variable. Define an increment value for the buttons and do the increment/decrement in the if statements. In global scope:

    #define BUTTON_SPEED_INCREMENT 4

In the `loop()` function:

    if(slower_bounce.fell()){
        speed_setpoint -= BUTTON_SPEED_INCREMENT;
    }
    if(faster_bounce.fell()){
        speed_setpoint += BUTTON_SPEED_INCREMENT;
    }
    if(tillend_bounce.fell()){
        speed_setpoint = maxspeed;
    }

---

Now you need to put all this together. I will leave that to you. You can then tune the behavior to your liking by changing the defines.

---

Note the following points:

- The motor will accelerate linear. That should be fitting for you.

- The code will restart the PWM wave at every `MOTOR_SAMPLE_INTERVAL`. That is ok for a motor when the interval is significantly higher than the PWM interval. When you choose the interval too low (like single digit milliseconds), you need to put the `analogWrite()` call into the if statements with the increment of `speed_setpoint`. That will take 1 more statement, but will solve the problem.

- If you choose the `MOTOR_SAMPLE_INTERVAL` too low, the speed change will get stuttery

  [1]: https://github.com/thomasfredericks/Bounce2


body:
I have made a drone/car quadruped robot thing and I need help with the code. I have found two codes to use to control each aspect of it but I need help to connect them. I have made a radio controller with a Xbee 3 Pro that has a spdt (two position switch) and I want to use it to switch the modes. I want the car to be LOW and the drone to be HIGH (If it helps the switch is on pin digital pin 9 of a Arduino Nano). I am a beginner at the coding aspect of the project and I would appreciate all the help I can get.

[![https://www.youtube.com/watch?v=enT-O4NwCzc][1]][1]

  [1]: https://i.stack.imgur.com/Rfz02.jpg
https://www.youtube.com/watch?v=enT-O4NwCzc

title: Switch loops with SPDT switch

Answers: 1

body:
There is no need for a SPDT switch. A SPST works just as well.

If you have a SPDT switch with 3 positions (pole 1 closed, open, pole 2 closed) you can use it to activate one pin or the other, or neither.

Let's pretend your switch is an SPST. Ignore one of the poles (pole 2, say.)

Connect a digital pin to pole 1. connect the common (center) pin to ground.

Set your digital pin to `INPUT_PULLUP`. Now, when the pin is LOW, the switch is closed (mode A). When the pin is HIGH, the switch is open (mode B).


body:
I have a ```main.ino``` file that contains

    struct EulerAngles {
      double roll, pitch, yaw;
    };

    void setup() {
      EulerAngles angles;
      angles = anglesCalc();
      Serial.print(angles.yaw);
    }

    void loop() {
      Serial.println("In loop");
      delay(1000);
    }

and an ```angles.ino``` file that contains

    EulerAngles anglesCalc(){
       EulerAngles a;
       // calculate a
       return a;
    }

When I compile the program, I get a compile error in the ```main.ino``` file:

       code/so_examples/main.ino:5:1: error: 'EulerAngles' does not name a type
     void setup() {
     ^~~~~~~~~~~
    code/so_examples/main.ino: In function 'void setup()':
    code/so_examples/main.ino:7:12: error: 'anglesCalc' was not declared in this scope
       angles = anglesCalc();
                ^~~~~~~~~~
    code/so_examples/main.ino:7:12: note: suggested alternative: 'angles'
       angles = anglesCalc();
                ^~~~~~~~~~
                angles
    [Build] Error occurred.

How do I fix this? Note that struct is declared before all else, so this [answer][1] does not seem to apply.  I am using the Stino plugin for Sublime Text as the IDE.

  [1]: https://arduino.stackexchange.com/questions/66530/class-enum-was-not-declared-in-this-scope

title: Returning struct from function generates 'does not name a type' compilation error

Answers: 3

body:
Try to add `struct` at the first of function, such as:
```
struct EulerAngles anglesCalc(){
   EulerAngles a;
   // calculate a
   return a;
}
```

body:
I would avoid having multiple .ino files, because of the issues raised
in the other answers. If you want to split your code into multiple
files, the scheme that works reliably is to have:

- a single .ino file, named like the containing folder, holding the
  “main” program (this is Arduino-specific)
- a pair of .h/.cpp files for each “module” implementing a sub-feature
  of the program (this is common C++ practice).

Within the .h/.cpp pair, the .h file _declares_ everything the compiler
needs for understanding code that _uses_ the feature: type definitions
(including classes) and function prototypes. The .cpp file holds the
actual implementation.

Applying this scheme to your case would give:

`my-sketch.ino` (actually, with the name of the containing folder):

```c++
#include "angles.h"

void setup() {
  EulerAngles angles;
  angles = anglesCalc();
  Serial.print(angles.yaw);
}

void loop() {
  Serial.println("In loop");
  delay(1000);
}
```

`angles.h`:

```c++
struct EulerAngles {
  double roll, pitch, yaw;
};

EulerAngles anglesCalc();
```

`angles.cpp`:

```c++
#include <Arduino.h>
#include "angles.h"

EulerAngles anglesCalc() {
   EulerAngles a;
   // calculate a
   return a;
}
```

Note that including `<Arduino.h>` is only useful if the code uses the
Arduino core API. Otherwise you can omit it. The main sketch does not
need to include `<Arduino.h>` because it is implicitly included in the
.ino file by the Arduino IDE. There is no such implicit inclusion when
the IDE processes .cpp files.

body:
There is an open [issue][1] with the Stino Arduino plugin for Sublime Text which means that structs are not handled properly.

Thank you to [Jura][2] and [Edgar Bonet][3] for helping me to answer this question.

  [1]: https://github.com/Robot-Will/Stino/issues/507
  [2]: https://arduino.stackexchange.com/users/37622/juraj
  [3]: https://arduino.stackexchange.com/users/7508/edgar-bonet


body:
Apologies if this has been discussed before but I couldn't find anything.

I have written a simple LED class. For illustration (it is actually a bit more complex) but it goes something like;

    class LED {
        LED(byte pin);
      private:
        int _pin;
    };

And the constructor is simply;

    LED::LED(byte pin) {
        _pin = pin;
    };

and I create a global instance of this class at the top of my code thus;

    LED redLED(5);

It is necessary to create this as a global object because (a) I can't create the object in the setup() function because it would go out of scope and (b) I can't create in the loop() function because I don't want to create an infinite number of these objects.

This all seems to work OK but it just leaves me wondering exactly when this constructor gets executed? I suppose that it must be before setup()?

Answered!

Many thanks to all the respondents. So when using the Arduino IDE the build process must silently insert the main() procedure. I was not aware that it did this. I guess that *most* of the time you can get away with not knowing when the global constructors are called.

It is good practice (I think) to create a "wrapper" class for all/any external (or perhaps internal) hardware devices that are connected to your arduino. And it is thus perhaps tempting (but risky) to do initialisation work in the constructor.

So given what I now know, it is better to create an "init()" method for such classes that can be called from setup(). Even if just to do the the pinmode() call.

Thanks again.

title: When are global constuctors executed?

Answers: 3

body:
It is executed before the `main()` is called (in the `main()` there is `setup()` called and then `loop()` is called in infinite loop).

It has its own sections for the constructors and destructors:
http://beefchunk.com/documentation/sys-programming/binary_formats/elf/elf_from_the_programmers_perspective/node4.html

body:
    class LED {
    private:
      const byte _pin;
    public:
      LED(const byte pin);
    };
With an even simpler c'tor:

    LED::LED(const byte pin) : _pin(pin) {};

To be a bit on-topic: The initializer list is even executed before the constructor body, and is thus the way to initialize constants.

Question remains whether it's guaranteed that this works:

    class LED {
    private:
      const byte _pin;
    public;
      LED(const byte pin) : _pin(pin) {pinMode(_pin,OUTPUT);}
      set(bool state) {digitalWrite(_pin, state); }
    };

( Can pinMode be called that early, or should one invent an init() method? )

My experience says : works well ...

body:
The global constructors run right after the initializations performed by
the C runtime startup code, and right before `main()` gets called.

In a nutshell, the C runtime initialization code:

- does some low-level initializations (e.g., setup the memory)
- calls the global constructors
- calls `main()`, which in turn
  - calls `init()` to do the Arduino-specific initializations
  - calls `setup()`
  - repeatedly calls `loop()`

The fine details are probably platform-specific. For AVR-based boards,
they are documented in the [avr-libc manual][libc].

[libc]: https://www.nongnu.org/avr-libc/user-manual/mem_sections.html#sec_dot_init


body:
I want to fetch specific data from firebase using Node Mcu ESP 8266. I can fetch the num value, but I failed to fetch the id value. The serial monitor kept displaying 0 when I try to fetch the id value. Any method to fetch the newest insert id value( Id value automatically update every time I submit the form at my web application). Thank you.

below is my coding
```
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

// Set these to run example.
#define FIREBASE_HOST "inserted"
#define FIREBASE_AUTH "inserted"
#define WIFI_SSID "Pro_4258"
#define WIFI_PASSWORD "1234567890"

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

  // connect to wifi.
  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());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
int a;

void loop() {

  a=Firebase.getInt("id");

  if (Firebase.failed())
  {
    Serial.println(Firebase.error());
    }else
    {
      Serial.println(a);
      }
delay(500);
}
```
[![Firebase realtime database][1]][1]

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

title: using esp8266 to fetch specific data from firebase

Answers: 0


body:
I bought some individually addressable LED strips (a large reel). To keep the cost down they are WS2811 and it's one chip per 6 leds. I don't know the cheapness or LED styl makes any difference to the problem but I'm just putting it out there.

They support 24V so to be safe I'm running them at 23V. I have the data line hooked up to pin 13 of the ESP, and a ground connection to the power supply to create a common ground. I am using Alexa to control the colours. This is the code:
```
#include <WiFi.h>
#include <Espalexa.h>
#include <FastLED.h>
#include <Adafruit_NeoPixel.h>

FASTLED_USING_NAMESPACE

#define NUM_LEDS 120
#define LED_TYPE WS2811
#define LED_PIN 13
CRGB leds[NUM_LEDS];

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_RGB + NEO_KHZ400);

#define ESPALEXA_ASYNC
Espalexa espalexa;

#define RELAY_PIN 12

boolean connectWifi();

void colorLightChanged(uint8_t brightness, uint32_t rgb);

const char* ssid = "****";
const char* password = "****";
boolean wifiConnected = false;

void setup()
{
  Serial.begin(115200);
  delay(2000);

//  FastLED.addLeds<LED_TYPE, LED_PIN>(leds, NUM_LEDS);
//
  pinMode(LED_PIN, OUTPUT);
  pinMode(RELAY_PIN, OUTPUT);

  digitalWrite(RELAY_PIN, HIGH);
//
//  for (int i = 0; i < NUM_LEDS ; i++) {
//    leds[i] = CRGB(0, 0, 0);
//  }
//  FastLED.show();

  strip.begin();
  strip.show();

  wifiConnected = connectWifi();

  if(wifiConnected){
    espalexa.addDevice("Lights", colorLightChanged);

    espalexa.begin();

  } else
  {
    while (1) {
      Serial.println("Cannot connect to WiFi. Please check data and reset the ESP.");
      delay(2500);
    }
  }
}

void loop()
{
   espalexa.loop();
   delay(1);
}

void colorLightChanged(uint8_t brightness, uint32_t rgb) {
  for (int i = 0; i < NUM_LEDS; i++) {
//    leds[i] = CRGB((rgb >> 16) & 0xFF, (rgb >>  8) & 0xFF, rgb & 0xFF);
//    FastLED.setBrightness(brightness);
      strip.setPixelColor(i, (rgb >> 16) & 0xFF, (rgb >>  8) & 0xFF, rgb & 0xFF);
  }
//  FastLED.show();
    strip.show();

  if(brightness == 0) { //lights off
    digitalWrite(RELAY_PIN, LOW);
  }
  else { //lights on
    digitalWrite(RELAY_PIN, HIGH);
  }

//  Serial.print("Brightness: ");
//  Serial.print(brightness);
//  Serial.print(", Red: ");
//  Serial.print((rgb >> 16) & 0xFF); //get red component
//  Serial.print(", Green: ");
//  Serial.print((rgb >>  8) & 0xFF); //get green
//  Serial.print(", Blue: ");
//  Serial.println(rgb & 0xFF); //get blue
}

boolean connectWifi(){
  boolean state = true;
  int i = 0;

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  Serial.println("Connecting to WiFi");

  Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    if (i > 40){
      state = false; break;
    }
    i++;
  }
  Serial.println("");
  if (state){
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.println("Connection failed.");
  }
  return state;
}
```
I've tried both Neopixel and FastLED with the same outcomes. Those outcomes are totally wrong colours:
This is supposed to be `cyan` except it's mostly yellow with a bit of blue.
[![][1]][1]
This is supposed to be `purple`
[![][2]][2]
And I think you get the idea. The lights strips light up with wrong colours (I've had whats supposed to be `gold`, be `purple`), blotches of colours or just make some look really similar (on Alexa, warm white to cool white look almost identical apart from a change in brightness).

I don't know what could be causing this though. I've made sure theres a common ground, I've made sure the pin on the ESP is right (i.e. just a plain output pin with no other fancy stuff), I've tried 2 different libraries and still no luck.

Could anyone help me out?

EDIT: These are these the strips I bought if it helps: https://www.superlightingled.com/65ft20m-roll-ws2811-dc24v-36ledsm-addressable-led-light-strips-digital-full-dream-color-chasing-flexible-led-strips-p-3163.html

  [1]: https://i.stack.imgur.com/xiLOi.jpg
  [2]: https://i.stack.imgur.com/AoXsf.jpg

title: ESP32 light strips showing incorrect colours

Answers: 1

body:
That strip seems to be BGR instead or RGB.

Use `NEO_GRB` instead in your initializer. So:

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_BGR + NEO_KHZ400);


body:
I currently use a Pololu USB AVR Programmer v2.1 for programming 328p chips and I really like it. The ability to have ISP and Serial in one physical device, enumerating as two separate COM ports on the PC, the programmer powering the circuit at 3.3v, with the programmers windows GUI interface to set voltages, programming frequency and give feedback on the programming when things go wrong, is all brilliant.

However, many of my circuits either have a power requirement higher than that on the Pololu (80mA), or to much capacitance (33uF) so that the power surge on connection is too much for the Pololu and it resets.  The reset disconnects my serial debugger, disconnects the Pololu GUI, and sometimes does not come back on at all due to the startup current draw.

I am looking for suggestions for an alternative device, or way of stopping the brown out on power up?

Thanks very much
Kevin

title: ISP Programmer with Serial and 5v/3.3v power

Answers: 1

body:
How about, connecting a tiny battery across the 3.3v output of the Pololu.  Lets assume a 3.7v LiPo, charged to 3.3v.

When the battery is connected at 3.3v, no current will flow.

When my device to be programmed is connected it will draw a spike of current, which will start to take the Pololu below 3.3v, but then the LiPo will start supplying current and stop the Pololu voltage getting dragged down and browning out.

The LiPo will then be slightly below 3.3v, so will get a Constant Voltage charge back to 3.3v.

Two potential issues I can see:

1) When the Pololu is disconnected from the USB will it be being 'back powered' by the LiPo?

2) When in CV charge mode, the only current limiting will be internal resistance of the Pololu output / LiPo cell, probably not an issue in practice due to the voltage drop being very small.

I know it is a hack, but thoughts welcomed.

Cheers
Kev


body:
I just bought an Esp8266(not the node MCU) and tried connecting it with Arduino without a USB to serial converter but in vain. I am a beginner and don't know what to do. It is not responding to AT commands. Can anyone give me a detailed step by step process to connect it?[![enter image description here][1]][1]

I am using Arduino UNO R3.

This is my connection diagram:-

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

I uploaded an empty code(Bare minimum example code), just to see if the AT commands are working, but it failed to respond. I reflashed it, then also it is not working.
when I type AT it shows nothing. But if I shake it, sometimes it shows gibberish.

  [1]: https://i.stack.imgur.com/b5FTz.png
  [2]: https://i.stack.imgur.com/SVz7W.jpg

title: Not Able to communicate with ESP8266

Answers: 0


body:
I am using MightyCore and platformio. My config file looks like [this](https://github.com/zoonman/nanodds/blob/master/platformio.ini)

My fuses are set as:
```
E:FD
H:D6
L:8F
```
I have controller running at 16 MHz and SCK frequency is 8 MHz.
My display is showing white color and that is it. I know to make it function properly I have to use 1 MHz SPI clocking.
If I program CKDIV8 fuse my controller doesn't start. I dunno why, kind of black magic going on there for me. My lack of knowledge is not helpful there.

I tried to use the following tricks:

Setting SPI speed using TFT library
```cpp
// earlier in main.cpp
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
// later in setup()
tft.setSPISpeed(1000000); // has no effect on SCK
```

Trying to set it directly via SPI class instance:
```cpp
// in setup()
SPI.setClockDivider(SPI_CLOCK_DIV128); // no effect
```

Or statically:
```cpp
// in setup()
SPIClass::setClockDivider(SPI_CLOCK_DIV128); // still no effect
```
Also I tried to pass `DEFAULT_SPI_FREQ` build flag with frequency preset.

I ran out of ideas.

Schematic is here:
[![Schematic][1]][1]

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

title: How to set SPI speed for ATmega1284P?

Answers: 1

body:
Per [this issue](https://github.com/adafruit/Adafruit-ST7735-Library/issues/107) setSPISpeed has to be made after initR like this:

```cpp
tft.initR(INITR_BLACKTAB);
tft.setSPISpeed(1000000);
```


body:
What is the maximum speed for external ADC I can expect to get with ESP32? I'm planning to have 16-bit ADC connected to I2C or SPI whichever gives more speed.

How that information is calculated from information in ESP data sheet?

title: Max. external ADC speed with ESP32 (SPI or I2C)?

Answers: 0


body:
I would like to replace utf8 characters to byte values for easier character display handling.
The actual replacement table comes from the lcd datasheet therefore it is not utf8 to ascii conversion. Hence I would like to define some macros, where I put the utf8 character, and it returns some matching hex code.

Here is the bare minimum code:
```
#define IV('┌') 0xC9
#define IV('°') 0xB2

char line0[4] = {0xC9, '4', 0xB2, 0}; // works
char line1[4] = {IV('┌'), '4', IV('°'), 0}; // do not work

void setup() {}
void loop() {}
```

It does not compile and I must be missing something obvious or rather basic.
Any help is much appreciated.

title: utf8 to hex macro

Answers: 2

body:
```c++
#define IV('┌') 0xC9
```

That *really* isn't how macros work. What goes in the brackets is a named parameter that is then used in the body of the macro. You can't have multiple macros named the same like that.

The simplest thing to do is just make a set of macros named after what the character is.  For example:

```c++
#define CHR_DEGREE 0xc9
#define CHR_BOX_TL 0xB2

char line1[4] = {CHR_BOX_TL, '4', CHR_DEGREE, 0};
```

body:
After some googling I came up with this solution.
I really hope someone finds a more elegant way to express it.
These embedded ternary operators are really error prone.

```
#define IV(i) ( \
(i)=='┌' ? 0xc9 : \
(i)=='⎩' ? 0x15 : \
(i)=='⎭' ? 0x17 : \
(i)=='⎰' ? 0x18 : \
(i)=='°' ? 0xb2 : \
(i)=='™' ? 0xd0 : \
(i)=='Ξ' ? 0xd8 : \
(i) )

char line2[21] = {0x15, '_', 0xd8, '_', 0x17, 0xd0, '1', 0xc9, '5', 0x18, '5', '0', '0', 0xb2, ' ', ' ', ' ', ' ', ' ', 0}; //original
char line4[21] = {IV('⎩'), '_', IV('Ξ'), '_', IV('⎭'), IV('™'), '1', IV('┌'), '5', IV('⎰'), '5', '0', '0', IV('°'), ' ', ' ', ' ', ' ', ' ', 0}; //wanted

void setup() {}
void loop() {}
```


body:
I defined myself a struct:

    typedef struct {
      unsigned char current;
      unsigned char start;
      unsigned char target;
      unsigned long startTime;
      unsigned int duration;
    } led;

I was able to initialize an instance of that like this:

    led h_red = {0,0,255,0,300};

However, when I try to have them in an array:

    led leds[LEDS];
    leds[0] = {0,0,0,0,0};
    leds[1] = {0,0,0,0,0};
    leds[2] = {0,0,255,0,300};

I get this error

    signal:28:1: error: 'leds' does not name a type
     leds[0] = {0,0,0,0,0};
     ^~~~
    signal:29:1: error: 'leds' does not name a type
     leds[1] = {0,0,0,0,0};
     ^~~~
    signal:30:1: error: 'leds' does not name a type
     leds[2] = {0,0,255,0,300};
     ^~~~

And I have no idea what I'm doing wrong here. You can see the full change [here on GitHub](https://github.com/iGEL/c-signal/commit/f27b9fa8ee9325455efe2c99100cbf0b04785257#diff-2cf64226463199d393dbbb66a4d404277bbe98a068de58e26005121d8368ea24R28-R30)

title: Initializing Array of structs

Answers: 2

body:
> ```c++
> led h_red = {0,0,255,0,300};
> ```

Here, you are defining a variable, and at the same time giving it an
initial value. This is called an _initialization_.

> ```c++
> led leds[LEDS];
> ```

Here you are defining an array. Since it is in global scope, and not
explicitly initialized, it is implicitly initialized to all bytes zero.

> ```c++
> leds[0] = {0,0,0,0,0};
> ```

Here, you are trying to give a value to an element of the array that has
already been defined previously. This is thus _not_ an initialization,
but an _assignment_. Unlike initializations, assignments cannot exist
outside a function. If you want to assign initial values, you can do it
in `setup()`.

Alternatively, you can initialize the array while you define it:

```c++
led leds[LEDS] = {
    {0, 0,   0, 0,   0},
    {0, 0,   0, 0,   0},
    {0, 0, 255, 0, 300}
};
```

body:
<!-- language-all: lang-cpp -->

I've upvoted [@Edgar Bonet's answer](https://arduino.stackexchange.com/a/80237/7727), because it is correct.

I want to add some more examples and explanations though.

## Key summary:

In C and C++, you can NOT have code _logic_ outside of functions. The global context outside of functions is intended for _declarations_, _definitions_, and some _initializations_/_constructors_ only. All code _logic_ must be _inside of a function_. Code _logic_ includes post-construction variable assignments, `if` statements, etc.

## Examples:

### 1. NOT allowed:

**Therefore, you can NOT do the following, since it attempts to do non-initializing _assignments_ outside of all function scopes.**

Notice also that in C++ (which Arduino is), you don't need to use `typedef` for structs either, so I've removed that from the `struct` definition. I'm also using the [stdint.h types](http://www.cplusplus.com/reference/cstdint/), which are considered safer and "best practice" for data types, as they specify the exact type size in bits. Use `uint8_t` in place of `unsigned char`, `uint32_t` instead of the Arduino Uno's `unsigned long`, and `uint16_t` instead of the Arduino Uno's `unsigned int`. Also, in C++ in particular, [`constexpr`](https://en.cppreference.com/w/cpp/language/constexpr) or enums are preferred over `#define` to set variable constants.

    constexpr uint8_t NUM_LEDS = 3;

    struct Led {
      uint8_t current;
      uint8_t start;
      uint8_t target;
      uint32_t startTime;
      uint16_t duration;
    };

    Led leds[NUM_LEDS];
    // NOT OK: Variable (re)assignments are NOT allowed outside of functions in
    // C and C++.
    leds[0] = {0, 0,   0, 0,   0};
    leds[1] = {0, 0,   0, 0,   0};
    leds[2] = {0, 0, 255, 0, 300};

    void setup()
    {
    }

    void loop()
    {
    }

### 2. IS allowed:

**You CAN, however, have variable _initializations_ outside of functions, so long as they occur at the same time as _construction_, so this is perfectly valid:**

    Led leds[NUM_LEDS];
    // This form of aggregate initialization during construction is just fine in the
    // global scope outside of all functions.
    Led leds[NUM_LEDS] = {
        {0, 0,   0, 0,   0},
        {0, 0,   0, 0,   0},
        {0, 0, 255, 0, 300},
    };

    void setup()
    {
    }

    void loop()
    {
    }

### 3. Also IS allowed:

**Or, you can just move your reassignments into a function, such as `setup()`:**

    Led leds[NUM_LEDS];

    void setup()
    {
        // This variable (re)assignment is just fine since it's inside
        // of a function.
        leds[0] = {0, 0,   0, 0,   0};
        leds[1] = {0, 0,   0, 0,   0};
        leds[2] = {0, 0, 255, 0, 300};
    }

    void loop()
    {
    }

### 4. Full, runnable example on a PC:

**Here's a full, runnable example on a PC, with printing to verify the contents of the struct were changed:**

Run it online yourself [on OnlineGDB here](https://onlinegdb.com/MnEOQgCQT), or from my [eRCaGuy_hello_world](https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world) repo here: [struct_array_initialization.cpp](https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/struct_array_initialization.cpp):

    #include <stdint.h>
    #include <stdio.h>

    // Get the number of elements in a C-style array
    #define ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))

    constexpr uint8_t NUM_LEDS = 3;

    struct Led {
      uint8_t current;
      uint8_t start;
      uint8_t target;
      uint32_t startTime;
      uint16_t duration;
    };

    // To initialize once at construction. This form of aggregate initialization
    // can be used anywhere: both inside and outside functions.
    Led leds[NUM_LEDS] = {
        { 1,  2,  3,  4,  5},
        { 6,  7,  8,  9, 10},
        {11, 12, 13, 14, 15},
    };

    // Print the full contents of an array of `Led` structs
    void printLeds(const Led ledArrayIn[], size_t ledArrayLen)
    {
        for (size_t i = 0; i < ledArrayLen; i++)
        {
            printf("ledArrayIn[%lu]\n"
                   "current   = %u\n"
                   "start     = %u\n"
                   "target    = %u\n"
                   "startTime = %u\n"
                   "duration  = %u\n\n",
                   i,
                   ledArrayIn[i].current,
                   ledArrayIn[i].start,
                   ledArrayIn[i].target,
                   ledArrayIn[i].startTime,
                   ledArrayIn[i].duration);
        }
    }

    int main()
    {
        printf("Hello World\n\n");

        printLeds(leds, ARRAY_LEN(leds));

        printf("==============\n\n");

        // Do this to set or change the structs at any time AFTER construction!
        // This variable (re)assignment is only allowed inside of a function, NOT
        // in the global scope outside of all functions!
        leds[0] = {10, 20,  30,  40,  50};
        leds[1] = {60, 70,  80,  90, 100};
        leds[2] = { 0,  0, 255,   0, 300};

        printLeds(leds, ARRAY_LEN(leds));

        return 0;
    }

Sample output:

    Hello World

    ledArrayIn[0]
    current   = 1
    start     = 2
    target    = 3
    startTime = 4
    duration  = 5

    ledArrayIn[1]
    current   = 6
    start     = 7
    target    = 8
    startTime = 9
    duration  = 10

    ledArrayIn[2]
    current   = 11
    start     = 12
    target    = 13
    startTime = 14
    duration  = 15

    ==============

    ledArrayIn[0]
    current   = 10
    start     = 20
    target    = 30
    startTime = 40
    duration  = 50

    ledArrayIn[1]
    current   = 60
    start     = 70
    target    = 80
    startTime = 90
    duration  = 100

    ledArrayIn[2]
    current   = 0
    start     = 0
    target    = 255
    startTime = 0
    duration  = 300

## Other references:
1. https://en.cppreference.com/w/cpp/language/aggregate_initialization
1. [my answer] https://stackoverflow.com/questions/61240589/how-to-initialize-a-struct-to-0-in-c/61240590#61240590


body:
So I have a Wemos D1 mini which I want to connect to my WiFI in order to let is push sensor data to my server. But I cannot connect it with my WiFi as I get a code 6.

```c++
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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

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

The `Serial.print(WiFi.status());` prints 6 which is WL_CONNECT_FAILED if I'm right.

I checked the router and it uses WPA/WPA2, the ssid and password are correct. The router is using 2.4 GHz with WiFi 802.11b and 802.11g.

I used the board to scan, with the example code provided by the esp8266 board manager library thing, and it found my SSID with the ones of my neighbors.

Can somebody tell me what is going wrong?

I already checked solutions like: [This one][1] , github answers, etc.

Edit: It can connect to a mobile phone hotspot. It gives code 6 1 time and then it connects. Any one an idea how I connect to the WiFi the router is providing ?

  [1]: https://arduino.stackexchange.com/questions/65637/wifi-stopped-connecting-wemos-d1-mini

title: Wemos D1 mini won't connect to WiFi: status code 6

Answers: 2

body:
Apparently, something went wrong with connecting to the router. The router was casting 802.11 g + n, which for some reason, made the esp8266 give a code 6. I have tried 802.11 b, 802.11 b+g+n, 802.11 n, which work all fine.

So I updated the settings that the router now uses 802.11n and the esp8266 can now connect to the internet!

body:
For me, the solution was manually setting the mode to 802.11g as explained here: https://github.com/esp8266/Arduino/issues/8412

Add the following code before connecting the WiFi:

```
WiFi.setPhyMode(WIFI_PHY_MODE_11G);
```


body:
I have a very rudimentary setup with an arduino nano, an LED strip, a pushbutton and a resistor.

I was trying to use the pushbutton as a toggle, using this code

```c++
#include <stdio.h>
#include <stdlib.h>
#include<FastLED.h> // header file

#define NUM_LEDS 14 // number of led present in your strip
#define DATA_PIN 12 // digital pin of your arduino

CRGB leds[NUM_LEDS];

const int button = 2;            // GPIO 8 for the button
int status = false;

void setup() {
  //Serial.begin(9600);
  pinMode(button, INPUT);         // define button as an input
  pinMode(DATA_PIN, OUTPUT);           // define LED as an output
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  if (digitalRead(button)==true) { // if button is pressed
    // flip status
    //Serial.println("Changing status");
    status = !status;
    //Serial.println(status);
    toggle(status);
  }

  while (digitalRead(button) == true) {
    //Serial.println("while loop");
    delay(50);
    //Serial.println(status);
  }//

  delay(50);
} // begin again

void toggle(bool status) {
  if (status == true) {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::White;  //set the all leds to white
    }
    FastLED.show();
  } else {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::Black;  //set the all leds off
    }
    FastLED.show();
  }
}
```

This is my circuit
[![enter image description here][1]][1]

I am powering this from a battery (PNY model 12200, 2200 mAh, Output 5 V=1A) via USB into the arduino board. I am having some issues. Mainly, the lights would go on by themselvs after a while, maybe not full power but still would be on. Not sure where the problem is, any hints appreciated.

I also sometimes get the lights turned off, maybe I'm feeding current into the wrong place and a safety mechanism either on the arduino or the battery stick turns everything off to protect itself?

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

title: Troubleshooting WS2812b LED strip with toggle on/off button

Answers: 1

body:
The [manual for the T2200][1], which I think is what you're referring to, says:
> Note: If the PowerPack does not automatically power on when a device
> is connected press the power button. The PowerPack will turn off after
> 90 seconds when there are no devices connected.

This is a common feature for USB battery banks meant for charging phones and similar devices.  It *probably* shuts off when the current drops below some set limit, say 50mA for more than 90s.  But it could also be looking every 90s for the average current over the course of 10ms.  They just don't say.  Given their description it sounds likely that it regularly turns on for some short time to probe for a load.  All in all, not knowing the specifics of this may drive you nuts.  Part of the thing to keep in mind is that someone using this thing to charge a cellphone wouldn't necessarily notice or care if it cut in and out every few seconds.  If you want to use this to power an Arduino it's worth getting a good handle on how it behaves through some experimentation.  Some of these power banks do have a way to disable their load detection and auto-shutoff feature; I did not see anything about that for this model.

The Nano, the official one anyway, has a 500mA PTC polyfuse on the USB VBUS ("5V").  Your code says `#define NUM_LEDS 14`.  The WS2812b LEDs use [something on the order of 50mA][2] each at max output.  You should probably measure what you're actually drawing, with the intensity you are commanding them to be, to be sure you're a good margin below 500mA.  If you are in fact using 14 of them, and if it's possible that all can go full brightness, then you are perhaps trying to use something like 735mA, quite a bit above 500mA.  You way find that it's necessary to route 5V around your Arduino to your LED strip, ideally through its own over-current protection.

Each time you power on or reset your project there's going to be some time before the sketch sets the pin connected to WS2812 data signal to output and some defined level.  It may be a good idea to add an external pull resistor on the LED data signal, probably to GND, so that during power-up and reset the LED strip data signal is not picking up noise and trying to interpret it as color data and changing your load on your power source in the process.  Having the powerbank potentially turning your project on and off gives extra opportunities for this to happen.  If you trip the polyfuse, either by commanding the LEDs to draw too much or having the floating data pin do likewise, the voltage on the Nano side of it will drop.  When the voltage drops it may trip the AVR microcontroller's brownout detector, which in turn will reset it the AVR, again bringing about a floating data pin on your LED strip.

  [1]: https://www.pny.com/File Library/Support/PNY Products/User Guides and Tutorials/PowerPacks/PowerPack-T2200-T2600-T4400-T5200-Series-User-Guides.pdf
  [2]: https://www.pjrc.com/how-much-current-do-ws2812-neopixel-leds-really-use/


body:
I have a toy car and I want to measure the coordinates/location of that car in my house.

It need to bee high precision equipment so GPS won't work here.

My precision requriments is 5+- cm and the distance is like 10-20 meters as maximum raduis.

What module should I use then?

title: What module should I use for high precision localization?

Answers: 0


body:
I have a setup of 2 Arduino Leonardo boards. Let's refer to them as Board A and Board B.

Board A is a master SPI board that is constantly communicating via SPI to an array of sensors. At some point, board A will need to be flashed with a new sketch.  That's where Board B comes in.

I want to use Board B go use an Arduino as ISP sketch to go and flash a new sketch onto board A. Problem is that Arduino as ISP uses SPI, which conflicts with the code on board B since board B is a master device communicating to other sensors via SPI.

Is it possible for board B to flash board A via ISP?

title: Is it possible for Arduino as ISP board to flash an ISP master board?

Answers: 1

body:
Yes, you can flash an MCU using ISP even if the MCU acts as an SPI device (be it master or slave). The programmer puts the MCU into reset mode, so at the time the sketch is uploaded, SPI will be disabled anyway.
Another thing you need to think of are the other SPI devices (the sensors or what ever the MCU controls). They can pick up the SPI signals sent by the programmer and occasionally write on the bus themselves, therefore disturb communication on the MISO line, which would be critical. There are two options to handle this:

 1. Simply disconnect any SPI slaves during code upload
 2. Make sure there are pullups on the CS lines so they have a defined state (they might be floating while the MCU is in reset). Some slaves might require pulldowns to be deactivated, but that's uncommon.


body:
I'm planning to use an ESP8266 (Wemos D1 Mini) to use as a software SPI monitor to send over WiFi.

As a test, I've done a cut-down sketch that just counts the interrupts, a simple frequency counter. I've made it as simple as possible but it won't stay connected to WiFi and crashes after about 10 seconds.

The input signal to CLKPin is 6667 Hz.

Here's the sketch:

```c++
#include <ESP8266WiFi.h>

const char* ssid     = "SSID";
const char* password = "PASSWORD";

long nextPrint = 1000; // when to print the next message to serial

const int CLKPin = 5; // Pin connected to CLK
volatile long ClkCount = 0; // number of times clock interrupt has fired

void CLK_ISR() {
  ClkCount++;
}

void setup() {
  Serial.begin(115200);
  long startTime = millis();

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to wifi");

  attachInterrupt(CLKPin, CLK_ISR, RISING);

  //Set the CLK-pin to input
  pinMode(CLKPin, INPUT);
}

void loop() {
  if (millis() > nextPrint) {
    Serial.print("Freq is: ");
    Serial.println(ClkCount);
    ClkCount = 0;
    nextPrint += 1000;
  }
  yield();
}
```

It always gets in a reboot/crash loop (no idea why the first few counts are wrong - I guess the ESP isn't ready yet):

    Connecting to SSID ...
    .Connected to wifi
    Freq is: 1
    Freq is: 1
    Freq is: 0
    Freq is: 0
    Freq is: 1
    Freq is: 0
    Freq is: 2313
    Freq is: 6667
    Freq is: 6666
    Freq is: 6667
    Freq is: 6667
    Freq is: 6667
    Freq is: 6667
    Freq is: 6667
    Freq is: 6667
    Freq is: 6667

    Exception (0):
    epc1=0x40202034 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

    ctx: sys
    sp: 3ffffc40 end: 3fffffb0 offset: 01a0

    >>>stack>>>
    3ffffde0:  401067da 00000026 00000000 00000001
    3ffffdf0:  c0017025 3ffe8d04 3ffee188 00000001
    3ffffe00:  00000003 00000008 3ffee99c 00000022
    3ffffe10:  3fffc200 401067a0 3fffc258 4000050c
    3ffffe20:  40004384 00000030 00000012 ffffffff
    3ffffe30:  60000200 00000006 30043003 80000000
    3ffffe40:  20000000 3fff0c38 80000000 203fc120
    3ffffe50:  00000000 3fffc6fc 00000001 3fff0c3c
    3ffffe60:  00000154 003fc120 60000600 00000030
    3ffffe70:  40106845 00000080 00000022 3fffc200
    3ffffe80:  c0017025 3fffc258 4000050c 00000022
    3ffffe90:  3fffc200 401067a0 3fffc258 00000022
    3ffffea0:  3fffc200 401067a0 3fffc258 4000050c
    3ffffeb0:  40202b20 00000030 00000012 ffffffff
    3ffffec0:  40000f49 3ffee9e8 00000000 3fffd9d0
    3ffffed0:  00000000 00000000 00000000 fffffffe
    3ffffee0:  ffffffff 3fffc6fc 00000001 3fffdab0
    3ffffef0:  00000000 3fffdad0 3ffee9e8 00000030
    3fffff00:  3ffee99c 0000000a 3ffe8bc8 402094cc
    3fffff10:  00000000 400042db 3ffeff84 40104580
    3fffff20:  40004b31 3fff0b84 000001f4 003fc080
    3fffff30:  40105aac 000001f4 3ffed190 401004f4
    3fffff40:  40106e4d 3fff0b84 00000000 00f8676f
    3fffff50:  3ffe8bc8 3ffe8d04 3ffed190 40224d02
    3fffff60:  40223d49 40223d52 3ffed004 3ffee1b0
    3fffff70:  40228445 3ffed004 3ffee1b0 00f857fe
    3fffff80:  4022848a 3fffdab0 00000000 3fffdcb0
    3fffff90:  3ffee1c8 3fffdad0 3ffee9e8 40202b43
    3fffffa0:  40000f49 40000f49 3fffdab0 40000f49
    <<<stack<<<

     ets Jan  8 2013,rst cause:2, boot mode:(1,6)

     ets Jan  8 2013,rst cause:4, boot mode:(1,6)

    wdt reset

What am I doing wrong, or is it just not possible to stay connected to WiFi while using interrupts on an ESP8266?

title: ESP8266 and interrupts - not possible?

Answers: 2

body:
Yes possible, but the ESP8266 only has one core and one set of peripherals. WiFi uses time, interrupts, and even the ADC peripheral, and maybe more.

This is why anything timing-critical, or time-intensive, is a pain to get to work properly on an ESP8266. It depends one what you are trying to do, of course, and also on if you can unload what you want to a peripheral the WiFi doesn't use, or if switching off WiFi is an option during parts of your code.

Generally, for applications such as yours, I would get an ESP32 or an Arduino Nano 33 IoT or any other solution that has a core for handling WiFi, and a core for you to use without restrictions. It makes development a more pleasant experience.

If, for some reason, you are bound to using an ESP8266, you would have to be more specific about what your eventual goal is; maybe a workaround can be found.

body:
I found the solution on another forum.

You need to add the `ICACHE_RAM_ATTR` attribute to the interrupt so it stays in cache.

    void ICACHE_RAM_ATTR CLK_ISR() {
      ClkCount++;
    }

Now:

    Freq is: 332596 - connected for 680s, operating at 160MHz

That's all I tested to, but 330kHz is a *bit* better than crashing at 7kHz, lol!

**edit:** I've discovered that it now crashes after exactly 1200s (20mins), repetitively.

I'm still investigating why, but I believe that it's some kind of watchdog timer.


body:
Consider if the lifespan of atmega328 has been wear out.

It said on datasheet of atmega how many times we can upload sketch about 10.000times (cmiiw), should i change the arduino or only the microcontroller after 10.000 times have been arrive? what if that times has been arrive? What happened with that IC? If it will starting problem, can we change only the microcontroller (atmega328PU)?? Or any there's thing or stuff we must change too?

Should i burn the bootloader to that IC after replace it?

title: Replacing the IC (atmega328) if lifespan has been arrive

Answers: 1

body:
You only need to change the IC, not the entire board. The microcontroller IS the IC.

Also, you will not see any degradation, it will just 'suddenly' fail, or starting to fail sometimes, without any warning or counter that counts up/down to 10,000.

Also keep in mind that this number is the MINIMUM guaranteed value, most ICs will go much further.

The best way to prevent getting into problems related with this issue is:

- When you have a finished project and it works, just keep that IC for that project.
- In case you fear getting into this problem during development, only change it if you are sure you have problems (i.e. you cannot upload your sketch anymore).
- Think before uploading 100 times per day a sketch for debugging purposes (add `Serial.print` lines, or even better, use a PC to debug all non Arduino related code.


body:
I just have a complex program that runs on a NANO. Now when I use my printlns for debugging I am running out of memory.

I read about using a programmer to get rid of the bootloader that uses 2K space on a NANO. I bought an USBTinyIsp and got it to work successfully... almost I can program the nano as I wanted, but I do not get any additional space.

When programming with debug printlns I run into the same message as before which states the same maximum space within (I guess it was 30700).

Why is this the case? I thought the bootloader gets overridden when using a programmer and so frees 2K of programmable space.

Please note: I am not asking how to optimize my program code! Thank you for taking notice ;)

Thank you very much.

title: Extend program space by getting rid of bootloader on NANO

Answers: 1

body:
It's enforcing [this line][1] from the arduino:avr boards.txt
```#
nano.menu.cpu.atmega328.upload.maximum_size=30720
```

To be clear, the board is assumed to have a bootloader, even if you're not using it to get the code onto the board, that is upload via programmer.

You could edit that and change some fuses yourself.  But you could also probably just use [MCUdude MiniCore][2], choosing an option that does not use a bootloader, e.g. `ATmega328P` with `No bootloader`, which gives you maximum upload of [32768][3]:

```#
328.menu.bootloader.no_bootloader.upload.maximum_size=32768
```

Keep in mind that in either case you'll have needed to set the fuses for not having a bootloader.  As weird as this sounds, choosing the `No Bootloader` option in MCUdude MiniCore for the `ATmega328P`, and then doing `Burn Bootloader` sets these fuses for you, despite the name not actually burning a bootloader in this case.  If you were to edit the maximum upload size for the Nano board, you would need to manually set the fuses similarly to what Burn "Bootloader" does for the MiniCore ATMega328P with No-bootlader option.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/boards.txt#L145
  [2]: https://github.com/MCUdude/MiniCore
  [3]: https://github.com/MCUdude/MiniCore/blob/v2.0.9/avr/boards.txt#L75


body:
I am trying to build a system, that plays specific audios (.wav files) from a SD-Card, according to the key combination that has been pressed.

I am using:

 - 4x4 Membrane
 - 4 Ohm Speaker
 - MicroSD Card Adapter Module
 - TIP120 Transistor (for amplification)
 - Arduino NANO clone (https://www.amazon.de/gp/product/B0755XYBG4)

So I broke the project down in various steps:

 1. playing .wav file from the SD Card (works fine)
 2. using keypad (works fine)
 3. combinig both (as you may have guessed: does not work)

Here are the codes I used for every step:

1)
```c++
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup() {
  tmrpcm.speakerPin = 9;
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD fail");
    return;
  }

  tmrpcm.setVolume(5);
  tmrpcm.play("test.wav");
}

void loop() {}
```
This plays test.wav one time after uploading or resetting.

2)
```c++
#include <Keypad.h>

// Definition für das Keypad von Elegoo
const byte ROWS = 4; // vier Zeilen
const byte COLS = 4; // vier Spalten
// Symbole auf den Tasten
const byte rows[ROWS] = {2, 3, 12, 5};//connect to the row pinouts of the keypad
const byte cols[COLS] = {6, 7, 8, 11};//connect to the column pinouts of the keypad

char keys[ROWS][COLS] = { //create 2D arry for keys
  {'D', 'C', 'B', 'A'},
  {'#', '9', '6', '3'},
  {'0', '8', '5', '2'},
  {'*', '7', '4', '1'},
};

// Instanz von Keypad erzeugen, Keymap und Pins übergeben
Keypad customKeypad = Keypad(makeKeymap(keys), rows, cols, ROWS, COLS);

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

void loop() {
  // Gedrückte Taste abfragen
  char customKey = customKeypad.waitForKey();
  Serial.println(customKey);
}
```
This code prints out every pressed key.

3)
```c++
#include <Keypad.h>
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

// Definition für das Keypad von Elegoo
const byte ROWS = 4; // vier Zeilen
const byte COLS = 4; // vier Spalten
// Symbole auf den Tasten
const byte rows[ROWS] = {2, 3, 12, 5};//connect to the row pinouts of the keypad
const byte cols[COLS] = {6, 7, 8, 11};//connect to the column pinouts of the keypad

char keys[ROWS][COLS] = { //create 2D arry for keys
  {'D', 'C', 'B', 'A'},
  {'#', '9', '6', '3'},
  {'0', '8', '5', '2'},
  {'*', '7', '4', '1'},
};

// Instanz von Keypad erzeugen, Keymap und Pins übergeben
Keypad customKeypad = Keypad(makeKeymap(keys), rows, cols, ROWS, COLS);

void setup() {
    tmrpcm.speakerPin = 9;
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD fail");
    return;
  }
}

void loop() {
  // Gedrückte Taste abfragen
  char customKey = customKeypad.waitForKey();
  Serial.println(customKey);

  if (customKey == 8) {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
  }
}
```
This code **should** play test.wav if key 8 is pressed.

**THE PROBLEM**

So the problem is not that there is no sound at all, but its just completely distorted. The sound quality never was great but sufficient. Now it sounds like "too much signal" is coming onto the speaker and interferes with the audio. Even if there shouldn't be any audio playing, machine-like sounds are produced by the speaker. By slowly working through the code I managed to find the line that probably causes the problem:

```c++
char customKey = customKeypad.waitForKey();
Serial.println(customKey);
```
If put it in a comment and put
```c++
tmrpcm.setVolume(5);
tmrpcm.play("test.wav");
```
in the setup function the audio is played.

I tried a lot and it doesn't matter where you put the `getKey` line (or change it to `waitForKey()`), as long as this line is somewhere in a function the sound is distorted.

Why does this happen? How can i work around it?

Can anybody please help me with this? :)

**wiring diagram**

[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][7]][7]

  [1]: https://i.stack.imgur.com/hivJH.jpg
  [2]: https://i.stack.imgur.com/3WS2a.jpg
  [3]: https://i.stack.imgur.com/ypXIt.jpg
  [4]: https://i.stack.imgur.com/8LATA.jpg
  [5]: https://i.stack.imgur.com/KYrna.jpg
  [6]: https://i.stack.imgur.com/IKrL1.jpg
  [7]: https://i.stack.imgur.com/QWHBC.jpg
  [8]: https://i.stack.imgur.com/WGcKz.jpg

title: Keypad - Speaker - Interference

Answers: 0


body:
I'm currently making a line following robot using PID control. My robot uses an Arduino Uno board, a L298N motor, 1 9V battery, 2 motors, 5 TCRT 5000 infrared light sensors to detect a black line on a white surface. I uploaded the code successfully but my robot didn't do anything:

 - Both of my motors didn't run at all
 - the sensors couldn't detect the line. The sensors somehow could only detect the distance between it and the ground when i lift the robot above the ground.
 - The wire connections are fine.
When i used a multimeter to measure the voltage, I found out that there was no voltage from the L298N to both motors. The circuit diagram that i'm using:
[![enter image description here][6]][6]

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

And this is my code:
```
float Kp = 1;
float Ki = 1;
float Kd = 1;

//setup speed of the motors
#define ENAspeed 200
#define ENBspeed 200

#define ENB 5 // Enable pin PWM of the Left motor
#define IN4 6 // pin of left motor
#define IN3 7 // pin of left motor
#define IN2 8 // pin of right motor
#define IN1 9 // pin of right motor
#define ENA 10 // Enable pin PWM of the Right motor

int Sensor[] = {A1, A2, A3, A4, A5};
float P = 0;
float I = 0;
float D = 0;
int Error = 0;

int Previous_Error, Previous_I;
int PID_value;
int Left_Speed, Right_Speed;

void setup(){

     pinMode(9, OUTPUT);
     pinMode(8, OUTPUT);
     pinMode(7, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(10, OUTPUT);

     pinMode(A1, INPUT);
     pinMode(A2, INPUT);
     pinMode(A3, INPUT);
     pinMode(A4, INPUT);
     pinMode(A5, INPUT);

     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);

     analogWrite(ENB, Left_Speed);
     analogWrite(ENA, Right_Speed);

     for (int i = 1; i <= 5; i++)
      {Sensor[i];}
     // reading the sensor if HIGH (Black line) or LOW (White line) line
     Sensor[1] = digitalRead(A1);
     Sensor[2] = digitalRead(A2);
     Sensor[3] = digitalRead(A3);
     Sensor[4] = digitalRead(A4);
     Sensor[5] = digitalRead(A5);
}

    void loop() {
    //use analogwrite to run motor at adjusted speed
     CalculateError();
     Calculate_PID();
     motor_control();
}

  void CalculateError(){
  if ((Sensor[1] == 1) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 4;}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 0;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = -3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 1))
  {Error = -4;}
  //Special case
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {if (Previous_Error = -4) {Error = -5;}
  else if (Previous_Error = 4) {Error = 5;}}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = 0;}
}

  void Calculate_PID() {
    P = Error;
    I += Error;
    //I = I + Previous_I;
    D = Error - Previous_Error;

    PID_value = (Kp * P) + (Ki * I) + (Kd * D);

    I += Error;
    Previous_I = I;
    Previous_Error = Error;
}

  void motor_control() {

     //define new speed limitation for the engine
     Left_Speed  = constrain (Left_Speed, 0, 255);
     Right_Speed = constrain(Right_Speed, 0, 255);

     //calculating the effective motor speed:
          if ((-5 < Error) and (Error < 0)){
              Left_Speed  = ENBspeed - PID_value;
              Right_Speed = ENAspeed + PID_value;
          }

          if ((0 < Error) and (Error < 5)){
              Left_Speed  = ENBspeed + PID_value;
              Right_Speed = ENAspeed - PID_value;
          }

          if (Error == 0){
              Left_Speed  = ENBspeed;
              Right_Speed = ENAspeed;
          }
     }
```

Sorry for my bad English if there is any mistake. I'm quite new to Arduino and thanks in advance for your help.

title: Line Following Robot using PID control not working

Answers: 0


body:
I'm grappling with types between two different libraries.

The gist is that I'm using the [ArduinoWebsockets](https://github.com/gilmaimon/ArduinoWebsockets) library to receive information coming from my API that I then want to render out to an LED matrix. An example message would look like this:

```
1
2
4
8
16
32
64
128
```

It's important to point out that the data here is a list of **string** version of numbers, not integers.

I.e. if you look at the binary version of `1` from the list, it's actually `110001` which is the ASCII code for the character `1`.

This is because the message coming back from the websocket server is pulled out as a `const char *`.

The LED matrix function I'm calling has a signature of:

```
void Write_Max7219(unsigned char address, unsigned char dat)
```

So I need to send in the values as `unsigned char`s.

I want to:
- parse this information line by line
- convert the ASCII character for the number into its integer equivalent
- pass the value to a different function to write the data to an LED matrix

I'm not sure how exactly to do this. I've been grappling with the type const char pointer vs regular char pointer and how to properly parse the return delimited string.

Any help would be greatly appreciated!!

# Clarification

Based on some of the comments I don't think I explained the reason I'm trying to do this conversion very well. Here's (hopefully) a better explanation:

The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix.

The number 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix.

The idea is that I could send over rows of numbers where each row corresponds to the row on the LED matrix.

e.g.
```
1   -> 0b00000001
2   -> 0b00000010
4   -> 0b00000100
8   -> 0b00001000
16  -> 0b00010000
32  -> 0b00100000
64  -> 0b01000000
128 -> 0b10000000
```

But the messages I get from the websocket server are coming through as the string representations of the numbers (ASCII or UTF) vs the numbers themselves, so I can't just pass the numbers into the function for the LED matrix because the underlying binary is different.

The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001).

# UPDATE AND RESOLUTION

So I've been on a big troubleshooting journey. When @ocrdu said:

> BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

I thought "yeah, that's the real way of fixing it and understanding what's going on", so I started tracing the issue back. Without going into all of the detail it turns out that the problem I was having was actually starting at the test client.

I use [firecamp](http://firecamp.io/) and [websocat](https://github.com/vi/websocat) as websocket client testing tools. I was trying to send the binary data via both tools, but when I dug in via Wireshark I found that the data in flight coming from the client itself was made up of the hex values for the encoded characters of the `1`s and `0`s.

[![wireshark][1]][1]

After researching and [asking a separate stackoverflow question](https://stackoverflow.com/questions/65449143/sending-data-as-binary-via-websockets-encodes-numbers-as-text/65453539#65453539) I figured out a way of sending the actual binary data from the client, specifically `printf`.

e.g.:

```
 printf "\x01\x02\x03\x04\x05\x06\x07\x08" | websocat -b ws://localhost:3002
```

[![printf solution][2]][2]

Now that this works I can start going back through the rest of my Arduino code and have it parse the binary data directly instead of converting the encoded values to their binary counterpoints.

All of that said, I do appreciate all of the help. I may not have needed to do the conversions for this particular instance, but I want to get better with my C types, conversions, and general understanding so the knowledge gained here is still beneficial. Thanks everyone :bows:

  [1]: https://i.stack.imgur.com/gOt33.jpg
  [2]: https://i.stack.imgur.com/MP41n.jpg

title: Converting c string to integer to unsigned char

Answers: 1

body:
Not sure if or why you want to convert `char*` to `int`, but if you need to, there are [`atoi()`][1], [`atol()`][2], [`strtol()`][3], [`strtoul()`][4] to consider, or rolling your own function.

Pros and cons are discussed [here][5]. Main thing to note is that `atoi()` and `atol()` have no error handling, but if the `char*` you feed them is completely under control and predictable, that need not be a problem.

BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

  [1]: https://www.cplusplus.com/reference/cstdlib/atoi/
  [2]: https://www.cplusplus.com/reference/cstdlib/atol/
  [3]: https://www.cplusplus.com/reference/cstdlib/strtol/
  [4]: https://www.cplusplus.com/reference/cstdlib/strtoul/
  [5]: https://stackoverflow.com/a/22866001/12570891


body:
I wanted to d a simple circuit using Arduino to control the lights in my house. But i do not know which relay module to use my house runs on standard 220v ac.
Can anyone tell me weather this relay board will be enough

https://www.roboelements.com/wp-content/uploads/2018/10/1-Channel-5V-Relay-Module-for-Arduino-with-Optocoupler.jpg

Or should I buy a 2 channel one?
And another thing what is the difference between 1 channel and 2 channel relay board.

I'm a complete beginner, so please help me out.

title: Which relay module to buy and what is the difference between 1 channel and 2 channel relay boards

Answers: 1

body:
Yes, you can use those. You have to watch a few things:

- Input voltage: 5V, perfect for Arduino
- Output voltage: 220 V, perfect for 220V AC
- Output amperage: 10A, what you control should use max 10 A, and I would use max 5A, and also consider switching on current into account. However, 10A is a lot of current.

The difference between 1 and 2 channels relay boards, is just that there are either 1 or 2 of them, meaning you can control 1 or 2 motors independently from each other.


body:
Just starting to learn about Arduino and IoT. I'd like to know what the Arduino hardware options are to try the following:

 1. Use FreeRTOS as SO
 2. WiFi and BLE connectivity
 3. Solderless board
 4. Test OTA features
 5. Experiment integration with different IoT Cloud platforms e.g. Azure IoT Hub
 6. Build custom IoT devices

title: What are the Arduino hardware options for experimenting with IoT?

Answers: 1

body:
There are many options; which one is "best" for you I leave up to your own research, that could start here:

There's a list of Arduino's based on the SAMD21 that are supported by the [FreeRTOS_SAMD21][1] library [here][2]; pick any one with WiFi and BLE.

There are probably a zillion clones out there that could also do what you want, and there is also a FreeRTOS port for the ESP32 (ESP-IDF FreeRTOS, and maybe other ones as well).

  [1]: https://github.com/BriscoeTech/Arduino-FreeRTOS-SAMD21
  [2]: https://www.arduino.cc/reference/en/libraries/freertos_samd21/


body:
My two arduino communicating serially with XBee. The receiver arduino also controls the servo motor. Servo works stably when there is no xBee connection. But when Arduino's serial communication, there is a problem in the operation of the servo motor. Servo motor stuttering while rotate, so stuttering occurs.

Can you help me?

My Coordinator Code:

    #include <SoftwareSerial.h>
    #define xBeeRxPin 10
    #define xBeeTxPin 9
    int deger3;
    int deger4;
    String d1,d2,d3;
    SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

    void setup() {
      Serial.begin(38400);
      xBeeSerial.begin(38400);
    }void loop() {

      deger3 = analogRead(A0);
      deger4 = analogRead(A2);

      String deger5 =  (String)deger3 + ";" + (String)deger4 ;

      xBeeSerial.println(deger5);

      delay(50);
    }

My Receiver Code:

    #include <SoftwareSerial.h>
    #include <Servo.h>
    #define xBeeRxPin 10
    #define xBeeTxPin 9
    SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
    String d1,d2,d3;

    const int trigPin = 4;
    const int echoPin = 3;
    long duration;
    int distance;
    Servo myServo;

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      xBeeSerial.begin(38400);
      Serial.begin(38400);
      myServo.attach(11);
    }
    void loop() {
      for(int i=15;i<=165;i++){
        myServo.write(i);
         delay(10);
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, 11200);
        distance= duration*0.034/2;

        if(xBeeSerial.available()>0){
          d1=xBeeSerial.readString();
        }
      }

      for(int i=165;i>15;i--){
        myServo.write(i);
         delay(10);
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, 11200);
        distance= duration*0.034/2;

        if(xBeeSerial.available()>0){
          d1=xBeeSerial.readString();
      }
     }
    }

title: Arduino - ServoMotor Control and SoftwareSerial

Answers: 1

body:
When SoftwareSerial enters an interrupt each time it receives a character and [busy-waits (delays)][1] to time in each data sample as the bits in the character come in.  No other interrupt service routines can run while this is happening.  It also turns off interrupts [when it sends][2].

The servo library for the AVR [uses timer interrupts][3] to generate the servo position signals.

When characters are being received, SoftwareSerial will interfere with the generation of the servo position signal because only one interrupt service routine can run at a time.

You may be able to mitigate the problem adding significant delay between characters sent, reducing the total number of characters sent.  This would limit the interference and give servo time to get back to its correct position from however far it managed to deviate over the course of an inbound serial character.

There are also alternative libraries that use the AVR's Input Capture feature on an ICP pin to do some of the work of serial in hardware, and that may work for you.  Here's [one example][4] library.

[@ocrdu][5] has rightly prompted me to add that there are servo libraries that [will do the servo signal generation in hardware][6].

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L154
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L436
  [3]: https://github.com/arduino-libraries/Servo/blob/1.1.7/src/avr/Servo.cpp#L80
  [4]: https://github.com/SlashDevin/NeoICSerial
  [5]: https://arduino.stackexchange.com/users/61722/ocrdu
  [6]: https://www.arduino.cc/reference/en/libraries/servo-hardware-pwm/


body:
I am wondering if it is possible to attach a microphone to an Arduino board and make the Arduino recognize a volume peak in a specific range of frequencies.

I want it to detect a specific peak (for example 0,1 dB) in the range of 1000 hz to 5000 hz.

title: Recognize peak in specific frequency area

Answers: 3

body:
You could sample the sound from the microphone and then apply a Fast Fourier Transformation ([FFT][1]).

An FFT lets you decompose a sequence of samples into components of different frequencies, usually into "buckets" that each have a small frequency band. You can then have a look at these buckets to see if there is a peak in a specific frequency range.

There are several examples and libraries for this on Arduinos, like [EasyFFT][2] and [arduinoFFT][3].

*PS. Edgar Bonet's [answer][4] is better; I may have become a bit lazy at coming up with computationally efficient ways of doing things because of my using "beefy" Arduinos exclusively.*

  [1]: https://en.wikipedia.org/wiki/Fast_Fourier_transform
  [2]: https://create.arduino.cc/projecthub/abhilashpatel121/easyfft-fast-fourier-transform-fft-for-arduino-9d2677
  [3]: https://www.arduino.cc/reference/en/libraries/arduinofft/
  [4]: https://arduino.stackexchange.com/a/80286/61722

body:
You can filter the signal and look at the power that lies within the
frequency range you are interested about. You could use an FFT for that,
but it is quite computationally expensive. If you go for the FFT, you
would probably end up sampling the mic in small bursts (a few
milliseconds sampled every few tens of milliseconds), as the Arduino
would spend most of its time processing the data.

A better option is probably to work in the time domain, rather than the
frequency domain. If you do not need to know exactly how much power lies
in each frequency bin, and are only interested in the total power within
the window of interest, then the FFT is computing too much stuff you do
not need. A less computationally expensive option would be to run the
samples through a digital band pass filter tailored to the band you
want. You can then compute the power from the output of the filter and
low-pass it:

    raw_sample = sample_the_microphone_somehow();
    filtered_signal = bandpass_filter(raw_sample);
    instantaneous_power = filtered_signal * filtered_signal:
    smoothed_power = low_pass_filter(instantaneous_power);

But you would still need a beefy Arduino if you want to be able to
acquire and process the samples at a reasonable rate: at least twice the
highest frequency that comes out of the microphone.

A still better option could be to do the filtering in the analog domain,
before the signal reaches the Arduino. If you can at least remove the
frequency components above 5 kHz, then the Arduino would only need
to sample at 10 kS/s, and run a digital high pass filter to remove
the part of the signal below 1 kHz. This should be easy enough even
for an AVR-based Arduino.

For the implementation of the filters, you may want to try this [online
filter builder][filtuino]

[filtuino]: http://www.schwietering.com/jayduino/filtuino/

body:
An alternative to the FFT is the [Goertzel algorithm][1]. It is intended to only detect a single frequency, so may not suit your purpose of working with a range.

But it may be more practical and require less intensive processing. Although intended to only detect a single frequency, it will of course give results near a given frequency, depending on the sampling rates and detection thresholds.

I have previously used an Arduino Goertzel algorithm library, but there doesn't appear to be anything available through the Library Manager at the moment; a web search shows [some hits][2] though.

The beauty of the Goertzel algorithm is that it only needs to keep a small amount of data in memory, so may have some benefit on smaller processors over more data intensive techniques like FFT.

I would try implementing one or more Goertzel detectors across your range (eg one at 3kHz or two at 2kHz and 4kHz) to see if they are sensitive enough.

  [1]: https://en.wikipedia.org/wiki/Goertzel_algorithm
  [2]: https://github.com/jacobrosenthal/Goertzel


body:
My 16x2 LCD shows one line cut and the 7th column also cut:

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

Applying pressure:

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

  [1]: https://i.stack.imgur.com/dtdPb.jpg
  [2]: https://i.stack.imgur.com/JzQti.jpg

title: LCD 16x2 shows one line cut and the 7th column also cut

Answers: 1

body:
My LCD module looks so similar to yours I decided risk to taking it apart for the purposes of taking pictures for to go along with the description.  It went back to together fine.

The black part I suggested pushing down on I'm going to call a "bezel", even though I'm not sure that's technically the correct term for it.

The pink color showing between the PCB and bezel is probably a "zebra strip" or [elastomeric connector][1].  They conduct signals from LCD controller mounted on the PCB up to the LCD glass itself.  Sometimes they don't make good contact and so some segments of the LCD don't respond or respond poorly.  They may make better contact when you apply pressure to them.  If some or all of the segments start responding when you do that, it's a fairly good indication that this is a problem, though not an Arduino problem as such, it's a problem encountered with some frequency by Arduino users.

If you may need to replace the strips, or clean them, or adjust the bezel to apply more pressure to them.  Or just get another LCD module.

Back of one of my LCD modules that looks a lot like yours:
[![Back of LCD Module Showing Clips][2]][2]

If you look at the back side of the board you *may* find that you can unclip the bezel; though it could also be soldered or glued etc.  If/when you do unclip it, the zebra strips and LCD glass will probably come free, perhaps with polarization filters as well.  You'll want to pay attention to the orientation of the *everything* so you know what you're doing when you put it back together.

I unclipped my the bezel on mine and the zebra strips (pink; they're not always pink) stayed with it. It is no *so* easy to see the "zebra" pattern on these particular strips.  Often they more alternating gray/white pattern.
[![Bezel part separated from PCB still containing zebra strips and glass][3]][3]

Here's the PCB showing the contacts that the zebra strips mate to an the LED backlight spreader. Apologies for the dust.
[![PCB with bezel, zebra strips, and LCD glass removed.][4]][4]

The strip pattern is a little easier to see in this image.  You can also see the pattern of the conductors on the LCD glass.
[![LCD glass with glass contacts showing and close-up of zebra strip][5]][5]

You can try cleaning the strips and the glass and PCB where the make contact.  I would be careful *what* you clean with; look for trustworthy recommendations. In any case, keep your finger grease off of everything, either by using gloves or just washing and drying your hands before working on it.

  [1]: https://en.wikipedia.org/wiki/Elastomeric_connector
  [2]: https://i.stack.imgur.com/Vdvvq.jpg
  [3]: https://i.stack.imgur.com/0VeLh.jpg
  [4]: https://i.stack.imgur.com/OgYV1.jpg
  [5]: https://i.stack.imgur.com/Ej1Wd.jpg


body:
I've got the same code running on 2 different boards:

 1. MKR1010
 2. Adafruit Feather M0

I'm using WiFiNINA on the former, and WiFi101 on the latter.

Other than that, the code that's exactly the same: every 10 seconds connects to WiFi, sends an HTTPS Request, and then sends a response back to the server (response is a bunch of metrics: memory, counter, time & day).

I am also using a WDT to reset the board if it hangs.

After a lot of refinement and experiments, the Adafruit board is able to run for *days* with no hangs (indicated by no WDT triggers), and no visible degradation (e.g. memory stays stable over time).

The MKR1010 board, on the other hand, resets several times per day.

### What I've done?

I've been able to narrow down issues to the network stack (I think). I've randomly injected a bogus hostname to the `WiFikSSLClient::connect` method (e.g every `n` calls, where `n` is random,  I will switch the real hostname with something that will not resolve, simulating a longer latency).

In reviewing the WiFi101 codebase I've found a long, hardcoded, non-customizable timeout [here][1].

```
...
while (_info[sock].state == SOCKET_STATE_CONNECTING && millis() - start < 20000) {
  m2m_wifi_handle_events(NULL);
 }
...
```

20 seconds is greater than the max WDT timeout (16 seconds). You can argue that for network operations, 20 seconds would be reasonable, but I'm expecting connections in _my_ network to happen much faster, so I tweaked the library (WiFi101) to 10 seconds and the reliability increased significantly. Every once in a while I get a connection error, but that is fine. The system recovers nicely on the next attempt.

I have not been able to find similar timeouts in WiFiNINA (looks like a much more complex codebase too, but that is my first impression. I'm not an expert)

If I disable the WDT around the `connect` method, then the MKR1010 will hang after some time. If I leave it, it will recover through a WDT reset.

I'm making sure the firmware on both boards is up to date.

While the WDT solves the issue of ensuring the board recovers, I'd love to fix it properly.

### Questions

* Is this consistent with anyone's experience?
* Are there alternatives to *WiFiNINA* for the MKR1010?
* Is there something obvious I'm missing when configuring the WiFI stack (e.g. a timeout someplace else)?

  [1]: https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp#L145

title: WiFi101 vs WiFININA - reliability issues

Answers: 0


body:
When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.

How can I do what I want using the `read_counter()` function?

The problem here is that I am already in the timer function with the `read_counter()` function.

```c++
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}
```

Note: The read_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:

`if (read_counter() % 1000) PORTB^=(1<<LED);`

**Update: My new code :**

    while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                     //makes 32 seconds.
             {
        if(TCNT1624==0) //per 15624=1 second,
        PORTA^=(1<<0);
               //led_blink_1s
       }
But,it doesn't work.Should I use util delay function?

title: How can I control blinking of LED while in timer function?

Answers: 3

body:
Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.

```c++
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}
```

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.

**EDIT:**

If you have your (pseudo) code like this:

```c++
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}
```

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

1. The timer starts at 1000, for example, and has just incremented.
1. The loop runs for 50 times until the timer increments to 1001.
1. This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
1. Now the loop will run for 50 times, while the timer is still at 20000.
1. The condition is `true` on each repetition, so `do_something()` will be executed 50 times in a row.
1. Next, the timer increments to 20001, and the condition becomes `false`.

This is exactly what you observe: If the condition of the `if` becomes `true`, its statement will be executed repeatedly.

Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.

body:
If read-counter is already incremented once a millisecond, use that to time your LED flashes:

```
void wait_function() {
  timer_init();
  bool LED_State = LOW
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
    if (read_counter % 1000 == 0) { //Switch 1000 to 500 here if it flashes too slowly
       LED_State = !LED_State;
       digitalWrite(LEDPin, LED_State ? HIGH : LOW);
    }
  }
}
```

That code will turn the LED on for one second, then off for one second, etc. (For a total cycle time of 2 seconds.) If you want the full on-off cycle to last 1 second, lower the if statement's value from 1000 to 500.

body:
My solution:

    uint16_t st_led=0;
      uint16_t et_led=0;

        while((TIFR1 & (1 << OCF1A))==0) //30 second
        {

          st_led=TCNT1;
          et_led=st_led;
          while((et_led-st_led)<=15624) //1 second
          {
            et_led=TCNT1;
          }
          PORTA ^= (1<<ledno);
        }
        TIFR1=(1<<OCF1A);
        TCCR1B=0;


body:
I have tried many combinations and I can get the Attiny85 to display on the TM1637 just fine, but I cannot get ant readings from the DTH11, tried different pins, libraries. I upload code via UNO as isp and that works fine. Tried same code on UNO and it works.

This is my first question on here, I usually figure things, but also first ATtiny85 adventure.

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

```c++
#include <TM1637Display.h>
#include "DHT.h"
#define CLK 4
#define DIO 3
#define DHTPIN 2  //
#define DHTTYPE DHT11
int MTD (2000);
TM1637Display display = TM1637Display(CLK, DIO);
DHT dht(DHTPIN, DHTTYPE);

const uint8_t celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_D | SEG_E | SEG_F
}; // oC
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_E | SEG_F | SEG_G
}; // oF
const uint8_t Humidityh[] = {
  SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, SEG_C | SEG_D | SEG_E | SEG_F | SEG_B
}; // HU

void setup() {
  dht.begin();
  display.setBrightness(7);
}

void loop() {
  delay(1000);
  float Humidity = dht.readHumidity();
  float TemperatureC = dht.readTemperature();
  float TemperatureF = dht.readTemperature(true);

  display.showNumberDecEx(TemperatureF, 0b10000000, false, 2, 0);
  display.setSegments(Fahrenheit, 2, 2); delay(MTD);
  display.showNumberDecEx(Humidity, 0b10000000, false, 2, 0);
  display.setSegments(Humidityh, 2, 2); delay(MTD);
  display.showNumberDecEx(TemperatureC, 0b10000000, false, 2, 0);
  display.setSegments(celsius, 2, 2); delay(MTD-1000);
}
```

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

title: ATtiny85-DHT11-TM1637

Answers: 1

body: Found <TinyDHT.h> and all works ok, just what I wanted.