message:
Instances of a class inside another class - is there a way to control the amount?

I have a class with 12 instances of a button, to create a keypad( meaning that this is the only case I use 12 instances). But this class can be just a button array of any other number between 1-12. I'm looking for a way to minimize class overhead of 12 instances, when I most of the time use much less.

'.h' file:

    class buttonArrayTFT
    {
    public:
      buttonArrayTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
      void create_array(uint8_t R, uint8_t C, char *but_txt[]);
      uint8_t checkPress(TS_Point &p);

    public:

    protected:
      ButtonTFT _button0;
      ButtonTFT *_buttons[12] = {&_button0, &_button1, &_button2, &_button3,
                                 &_button4, &_button5, &_button6, &_button7,
                                 &_button8, &_button9, &_button10, &_button11};
    private:
      ButtonTFT _button1;
      ButtonTFT _button2;
      ButtonTFT _button3;
      ButtonTFT _button4;
      ButtonTFT _button5;
      ButtonTFT _button6;
      ButtonTFT _button7;
      ButtonTFT _button8;
      ButtonTFT _button9;
      ButtonTFT _button10;
      ButtonTFT _button11;

    private:
      uint8_t _num_items = 0;
    };

body:
You can use a *template* class to provide compile time parameters to your class to tune it. This is most often used in the context of providing a *type* for the class to operate on. However it's not limited to that. It's also often used to provide a storage size or other similar constant to the class.

They kind of work like preprocessor macros. You specify a token in the class and then give that token a value when you instantiate an object. That token can then be used all over the place in your class.

In your case you can provide the number of elements in your array of buttons as a template variable, for example (note: untested):

```c++
template <int N> class buttonArrayTFT {
    protected:
        ButtonTFT _buttons[N];
    public:
        void doSomething();
};

template <int N> void buttonArrayTFT::doSomething() {
    for (int i = 0; i < N; i++) {
        _buttons[i].doSomethingOnAButton();
    }
}
```

Of course you have to treat your objects a little differently since you can't make an array of pointers to predefined objects any more. Instead just a simple array of objects should be enough.

You then instantiate your class passing the number of elements you want:

```c++
// Array of 12 buttons
buttonArrayTFT<12> myButtons;
// and do something
myButtons.doSomething();
```


sender: user

sender: assistant

body:
As pointed out in a comment on your original question, a **template** is likely the best solution.

Templates allow you to write highly flexible code. I won't explain why; that's something that goes a little beyond the actual question. However, the following will show that you can create a template that means you can create a `buttonArrayTFT` class with *N* number of `buttonTFT` elements, so long as *N* is known at compile time. The [link given as  a comment][1] talks describes various aspects of templates but does not necessarily explain how to string it all together.

From the section **Non-type parameters for templates**, you will see that you can specify an integer as a parameter for creating *N* elements of an array member variable.

But what about the *type parameter, T*? You can simply omit it. You don't actually have to create a template for a *type*.

In your *.h* file:
```c++
template <uint8_t ARRAY_SIZE>
class buttonArrayTFT
{
public:
// One thing to remember about templates: you have to pack the definition
// into the header file with the declaration to avoid all manner of headaches.

    buttonArrayTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft)
    {
    // Perhaps this is a good opportunity to check that the specified
    // size of the array is sensible, i.e. not zero and no more than 12.
        if ((ARRAY_SIZE == 0) || (ARRAY_SIZE > 12))
        {
            // decide how you want to handle this problem
        }
            // Add the rest of your constructor here
    }

    void create_array(uint8_t R, uint8_t C, char *but_txt[]);
    uint8_t checkPress(TS_Point &p);

    // This little piece of magic allows you to access buttonTFT 'x' of the
    // private _buttonArray as if a buttonArrayTFT class was an array
    buttonTFT &operator[](uint8_t index)
    {
    // Check that 'index' is a valid element in the array
        if (index > _num_items)
        {
            // decide how you want to handle this problem
        }
        return _buttonArray[index];
    }
private:
    buttonTFT _buttonArray [ARRAY_SIZE];
    // I recommend making this constant
    const uint8_t _num_items = ARRAY_SIZE;
};
```
I shall leave it up to you to sort out your privates, publics and protecteds, and I have left out `ButtonTFT _button0;` to keep you on your toes.

You'll also notice that the array is private, as before, but there is now no array-of-pointers-to-buttons. This is because there is no need; the magic `buttonTFT &operator[](int index)` allows you to access array elements directly.

In your *.ino* file, or as appropriate, you use the following code to create and then wield the class:
```c++
buttonArrayTFT<4> myFourButtonArray(/* constructor arguments as required*/);
buttonArrayTFT<12> myTwelveButtonArray(/* constructor arguments as required*/);
```
This gives you two instances of the class, with the respective number of `buttonTFT` elements! You can now access specific buttons using the following code:
```c++
myFourButtonArray[0];    // Returns a reference to the first buttonTFT
myTwelveButtonArray[10]; // Returns a reference to the eleventh buttonTFT
myFourButtonArray[n]     // Returns a reference to the 'n+1'th buttonTFT
```
On the assumption that the `buttonTFT` class has some kind of 'read' function that returns a TRUE or FALSE for the status of the button, you can write:
```c++
if (myFourButtonArray[0].read())
{
    // executed if the button is ON
}
else
{
    // executed if the button is OFF
}
```

**A NOTE ON CONST-NESS:**

The overloading of `operator[]`, while wonderfully magic, is open to abuse. However, this is no different from your original code. The array of `buttonTFT` elements is private but there is public access to all the buttons almost as if the array was not private. In the case of your original code, one could write:
```c++
myButtonArray._buttons[0] = myButtonArray._buttons[1];
```
Now `_buttons[0]` *points to the same buttonTFT* as `_buttons[1]`.

Ouch. Now `myButtonArray._buttons[0]->read()` is literally the same thing as `myButtonArray._buttons[1]->read()`.

That said, my code does not make it a great deal better; the equivalent code:
```c++
myFourButtonArray[0] = myFourButtonArray[1];
```
Simply *copies* the right hand side over to the left hand side. You still have two distinct `buttonTFT` instances, with probably no memory leaks, but I am guessing that `buttonTFT` class may contain a reference to an Input pin, so the `_button[0]` pin will now be whatever `_button[1]` pin is because the member variable that stores the pin reference will be overwritten.

To solve this weakness, simply add the `const` qualifier to the beginning of the `operator[]` overload:
```c++
const buttonTFT &operator[](uint8_t index)
{ // };
```
Now the `buttonTFT` element cannot be altered. This of course brings in a new headache that all functions that rely on `myArray[n]` also need to be constant. It is up to you to determine how constant correctness should be interpreted and whether it is worth the hassle.

  [1]: http://www.cplusplus.com/doc/oldtutorial/templates/


body:
I want to share my final updated library (thanks to answers by Majenko&Charlie), perhaps it'll help others.

`.h` file

    template <uint8_t N>
    class buttonArray_TFT
    {
    public:
      int8_t dx = 5;         /* define spacing between buttons */
      int8_t dy = 5;         /* define spacing between buttons */
      uint8_t scale_f = 100; /* change the cale of array. 100% take entire screen */
      uint8_t shift_y = 255; /* Shifts in y director*/
      uint8_t shift_x = 255; /* Shifts in x director*/
      int shrink_shift = 0;  /* shrink array in pixels, and shifts up/ down (+/-) */

      uint8_t &a = butarray[0].a;
      uint8_t &b = butarray[0].b;
      uint8_t &txt_size = butarray[0].txt_size;
      uint16_t &txt_color = butarray[0].txt_color;
      uint16_t &border_color = butarray[0].border_color;
      uint16_t &face_color = butarray[0].face_color;
      bool &roundRect = butarray[0].roundRect;

    protected:
      ButtonTFT butarray[N];

    public:
      buttonArray_TFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
      void create_array(uint8_t R, uint8_t C, char *but_txt[]);
      uint8_t checkPress(TS_Point &p);
    };

and more in :
`.h` file :

    template <uint8_t N>
    buttonArray_TFT<N>::buttonArray_TFT(XPT2046_Touchscreen &_ts, Adafruit_ILI9341 &_tft)
    {
      for (int i = 0; i < N; i++)
      {
        butarray[i].TS[0] = &ts;
        butarray[i].TFT[0] = &tft;
      }
    }

    template <uint8_t N>
    void buttonArray_TFT<N>::create_array(uint8_t R, uint8_t C, char *but_txt[])
    {
    \\ Code
    }

    template <uint8_t N>
    uint8_t buttonArray_TFT<N>::checkPress(TS_Point &p)
    {
      for (uint8_t i = 0; i < N; i++)
      {
        if (butarray[i].checkPress(p))
        {
          return i;
        }
      }
      return 99;
    }


body:
There are more options to solve your question.

----------

To use a template as recommended in the other answers is a fancy option, but if you use a template multiple times, it creates a real class for every template value and you will see it on used flash size.

----------

The best option in my opinion is to provide the array to the class over a constructor. Create a global array of buttons and hand it over to buttonArrayTFT object over a constructor.
```
const uint8_t BUTTON_COUNT = 12;
ButtonTFT buttons[BUTTON_COUNT];
ButtonArrayTFT buttonArrayTFT(buttons, BUTTON_COUNT);
```
The ButtonArrayTFT class (simplified) would be like:
```
class ButtonArrayTFT {
private:
  ButtonTFT *buttons;
  uint8_t count;
public:
  ButtonArrayTFT(ButtonTFT *_buttons, uint8_t _count) {
    buttons = _buttons;
    count = _count;
  }
```
----------

Other option is to use dynamic allocation on heap. If you would create a ButtonArrayTFT object only once at start and never delete it it would not cause heap fragmentation.
```
class ButtonArrayTFT {
private:
  ButtonTFT *buttons;
  uint8_t count;
public:
  ButtonArrayTFT(uint8_t _count) {
    count = _count;
    buttons = new ButtonTFT[count];
  }
```


message:
motor driver only works on one side:

I have 3 motor drivers and all 3 other them only seem to only work on one of the 2 sides. I have used a voltmeter to check the voltages across the each of the 2 sections on each motor driver. For all 3 of the motor drivers, 2 of them had one side which had a voltage of 5V (which should be 7.2 volts as thats the power supply) and the other sides of the 2 motor drivers was 0-0.05V (so effectively no voltage). The other motor driver had no voltage from either of the 2 sides. Are all 3 of the motor drivers faulty or have I broke them? The schematic for the motor drivers was as follows:
[![enter image description here][1]][1]

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

(Apart from instead of a 12V source, a 7.2V source is used buts thats the amount of Volts I need for the motors. The arduino I used was an Arduino mega rather than an UNO shown in this diagram as I got this diagram off the internet)
Heres a link for the place where I ordered the motor drivers from:
https://thepihut.com/products/l298n-motor-stepper-driver

Here is my code:
```cpp
    #include <PS2X_lib.h> //for v1.6
    int enA = 3;
    int in1 = 8;
    int in2 = 7;
    int enB = 9;
    int in3 = 5;
    int in4 = 4;
    int error = 0;
    byte type = 0;
    byte vibrate = 0;
    int light_one_pin = 36;
    int light_two_pin = 38;
    bool lights_on = false;
    PS2X ps2x;
    void setup(){
     Serial.begin(9600);
     pinMode(enA, OUTPUT);
     pinMode(in1, OUTPUT);
     pinMode(in2, OUTPUT);
     pinMode(in3, OUTPUT);
     pinMode(in4, OUTPUT);
     pinMode(light_one_pin, OUTPUT);
     pinMode(light_two_pin, OUTPUT);

     //CHANGES for v1.6 HERE!!! **************PAY ATTENTION*************
     for(int x = 0; x < 100; x++)
     {
      error = ps2x.config_gamepad(13,11,10,12, true, true);   //setup pins and settings:  GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
     }
     error = 0;

    }

    void loop() {
      ps2x.read_gamepad(false, vibrate);

      if(ps2x.ButtonPressed(PSB_GREEN) && lights_on == false)
      {
         digitalWrite(light_one_pin, HIGH);
         digitalWrite(light_two_pin, HIGH);
         lights_on = true;
         Serial.println("on");
      }
      else if(ps2x.ButtonPressed(PSB_GREEN) && lights_on == true)
      {
          digitalWrite(light_one_pin, LOW);
          digitalWrite(light_two_pin, LOW);
          lights_on = false;
          Serial.println("off");
      }

      if(ps2x.Analog(PSS_LY) < 128)
        {
          digitalWrite(in1, LOW);//all fowards wheel
          digitalWrite(in2, HIGH);
          digitalWrite(in3, HIGH);
          digitalWrite(in4, LOW);
          analogWrite(enA, 255);
          analogWrite(enB, 255);
          Serial.println("forwards");

        }

        else if(ps2x.Analog(PSS_LY) > 128)
        {
          digitalWrite(in1, HIGH);//all backwards wheels
          digitalWrite(in2, LOW);
          digitalWrite(in3, LOW);
          digitalWrite(in4, HIGH);
          analogWrite(enA, 255);
          analogWrite(enB, 255);
          Serial.println("backwards");

        }

        else if(ps2x.Analog(PSS_LY) == 128)
        {
          analogWrite(enA, 0);
          analogWrite(enB, 0);
          Serial.println("stationary");

        }

        else if(ps2x.Analog(PSS_LX) == 128)
        {
            //Serial.println("still");
            //wheel_steering_servo.write(wheel_steering_servo_angle);
        }

        Serial.println(ps2x.Analog(PSS_LX));

    }
```

body:
There are a couple of things that you can check-

**Your code**-

Chances are that all of the motor drivers are functional (as manufacturing defects are very rare) and that there is something wrong with the code.

**1-** **The motor driver that you are using has 2 pins that should be labeled "ENA", "ENB" (or some variant of these), in order for the motor driver to work on both sides, both these pins must be high, if any one of these are low, then that side will not work. I highly recommend that you directly connect these 2 pins to 5V, and use the 4 inputs for the control.**

**2-** The 4 input pins labeled "IN1", "IN2", "IN3", "IN4" are the pins that instructs the driver to move each side forward or back, check your code to make sure that these pins are high or low as per your requirement.

Another thing is that both the forward and back inputs of one side must not be high at the same time otherwise it won't work

**Your hardware**-

If you find that something is getting abnormally hot on the boards or worse if something is burnt, then you should check your circuit and make sure there are no problems.

--
A problem in your code, is that "ENB" is not set as an output and hence is not high, you should also modify the setup to set the "ENA", "ENB" to high to make sure that it is on.

So your setup should go something like this-

```c++
     Serial.begin(9600);
     pinMode(enA, OUTPUT);
     pinMode(enB, OUTPUT);
     digitalWrite(enA, HIGH);
     digitalWrite(enB, HIGH);
     pinMode(in1, OUTPUT);
     pinMode(in2, OUTPUT);
     pinMode(in3, OUTPUT);
     pinMode(in4, OUTPUT);
     pinMode(light_one_pin, OUTPUT);
     pinMode(light_two_pin, OUTPUT);
```


body:
Just a correction to something Coder9390 wrote:

The ENA and ENB pins on this motor drive are not supposed to be used as digital pins and receive HIGH or LOW, but as analog pins and receive a value in range 0-255 using a PWM pin (PWM pins are marked on the board with a ~). This enables you to control the speed of the motor, by simulating low voltage.

In your code you actually seem to do this correctly, so I don't think this is the problem. Setting the pinMode of ENA and ENB to OUTPUT on the other hand is correct, so it might actually be the problem. I couldn't reproduce your bug this way though, so it might be something else.

In case you don't need to control the speed of the motor and want it to always go full speed, you can use jumpers to short each EN pin with it's orthogonal-adjacent pin (which are marked in your image as 5v) to achieve the same effect of connecting them to 5v "manually" as Coder9390 suggested (basically by placing the jumpers there you are doing exactly that - connecting the EN pins to 5v).

Coder9390, if you implicitly meant to suggest using jumpers like this, then sorry for misrepresenting your answer. I thought it wasn't clear to beginners who might get here, and that it requires an elaboration.

See this motor driver usage explained here: [https://create.arduino.cc/projecthub/ryanchan/how-to-use-the-l298n-motor-driver-b124c5][1]

  [1]: https://create.arduino.cc/projecthub/ryanchan/how-to-use-the-l298n-motor-driver-b124c5


message:
Is it possible to use a slide switch without a resistor?

I understand [how pullup and pulldown resistors work][1] with push buttons and I also understand that an analogous idea can be applied to slide switches. Furthermore, I know that some versions of [Arduino have an internal pullup resistor][2] that can be used, if you adjust the code properly.

I was wondering, if I can, without using the internal pullup resistor, wire a slide switch without any kind of resistor like so:

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

As I understand, this should behave exactly the same as using a pull-down resistor. If the switch is on the left side, pin 7 would read `LOW` and if the switch is on the right side, it would read `HIGH`.

Is that a problem with wiring the switch like this? Is there a reason why using a resistor would be better?

In my final project I intend to use a Digispark board and I would not like to rely on its internal resistor and I also would like to avoid using an external resistor if I can.

  [1]: https://www.youtube.com/watch?v=uWrN1RCQrgA&list=PLsCUTjzpUHK8X3pCU6nS0AFADk0Fw7MhM
  [2]: https://www.arduino.cc/en/Tutorial/Foundations/DigitalPins
  [3]: https://i.stack.imgur.com/DtaX1.png

body:
You *may* be able to do it, or you may not. It depends on the switch.

There are two classes of slide switch:

* Make-before-break
* Break-before-make

In the former the contact you are sliding to is connected *before* the one you are sliding away from is disconnected. This can cause untold problems as you will basically create a short circuit between 5V and GND. Everything will die.

In the latter the contact you are sliding away from is disconnected first, and then the new contact you are sliding towards is connected. That is safer, but it does mean that there is a short period while you're sliding the switch where neither contact is connected. At this time the input pin is floating - just as if you had nothing connected at all (which is in fact the case).

That is of course not a desirable scenario as it's probably the most amount of bounce you will ever see in a switch - bounce you need to eliminate in software to give you a clean signal.

That period of uncertainty is eliminated if you have a pullup or pulldown resistor, since there is never a period where there is no connection, and there's never a period where you risk shorting out power and ground. All you have to content with then is the natural bounce of the contacts as they close.


message:
can differential drive work together with ultrasonic sensor?

I've written a sketch to drive a differential drive system, specifically - to be able to drive strait. This does work.

So I am trying to add the ability to stop when the path is blocked using US sensor directed towards the front of the "car". I manage to get correct readings, but my "car" cannot move strait anymore.

I tried using the ping_timer() functionality of NewPing library, but it did not solve the problem. When the ultrasonic code is commented out, my "car" can go strait.

My algorithm for strait driving is essentially to compare the pulses from two rotary encoders fitted to the wheels, and if one exceeds the other by more than one pulse, shut down the relevant motor and turn on the other motor (if it wasn't on already) so the slower motor has a chance to keep-up.

I wonder if there is a problem in my code that I cannot find, I will be very thankful for anyone who can review my sketch:

    #include <Arduino.h>
    // #include <Servo.h>
    #include <TimedAction.h>
    #include <NewPing.h>

    #define RIGHT_MOTOR_ON (0 - int(pulseCountRight <= pulseCountLeft + 1))
    #define LEFT_MOTOR_ON (0 - int(pulseCountLeft <= pulseCountRight + 1))

    const int EN_RIGHT = 6;
    const int IN1_RIGHT = 7;
    const int IN2_RIGHT = 8;
    const int ENCODER_RIGHT = 2;

    const int EN_LEFT = 5;
    const int IN1_LEFT = 10;
    const int IN2_LEFT = 11;
    const int ENCODER_LEFT = 3;

    const int SPEED = 100;

    const int BW_TRUE = -1;
    const int BW_FALSE = 0;

    // const int SERVO_PIN = 9;
    // const int SERVO_MAX_RIGHT = 0;
    // const int SERVO_MAX_LEFT = 125;
    const int SERVO_SWEEP_DELAY = 150;
    // const int SERVO_TURN_RIGHT = -25;
    // const int SERVO_TURN_LEFT = 25;

    const int ULTRASONIC_TOO_CLOSE = 20;
    // Timeout is the maximum time it would take sound to do a roundtrip with length of "ULTRASONIC_TOO_CLOSE".
    // Formula is: DIST(cm) x TIME(us per cm).
    const int ULTRASONIC_TIMEOUT = ULTRASONIC_TOO_CLOSE * US_ROUNDTRIP_CM;
    const int ULTRASONIC_TRIG_PIN = 13;
    const int ULTRASONIC_ECHO_PIN = 12;

    unsigned int pulseCountRight = 0;
    unsigned int pulseCountLeft = 0;

    int movingStrait = BW_TRUE;
    int stopping = BW_TRUE;

    double distance = 0.0;

    void pingTimer();
    void checkTimer();

    NewPing sonar(ULTRASONIC_TRIG_PIN, ULTRASONIC_ECHO_PIN, 400);

    TimedAction pingTimerAction(SERVO_SWEEP_DELAY, pingTimer);

    // Servo myServo;

    void countPulse(unsigned int &counter) {
      ++counter;

      char c[1000];
      sprintf(c, "Pulses (right,left): %d,%d, Motor on (right,left): %d,%d", pulseCountRight, pulseCountLeft, RIGHT_MOTOR_ON, LEFT_MOTOR_ON);
      Serial.println(c);

      analogWrite(EN_RIGHT, SPEED & (RIGHT_MOTOR_ON | ~movingStrait) & ~stopping);
      analogWrite(EN_LEFT, SPEED & (LEFT_MOTOR_ON | ~movingStrait) & ~stopping);
    }

    void forward() {
      movingStrait = BW_TRUE;
      stopping = BW_FALSE;
      pulseCountRight = 0;
      pulseCountLeft = 0;

      digitalWrite(IN1_RIGHT, LOW);
      digitalWrite(IN2_RIGHT, HIGH);

      digitalWrite(IN1_LEFT, LOW);
      digitalWrite(IN2_LEFT, HIGH);

      analogWrite(EN_RIGHT, SPEED);
      analogWrite(EN_LEFT, SPEED);
    }

    void backwards() {
      movingStrait = BW_TRUE;
      stopping = BW_FALSE;
      pulseCountRight = 0;
      pulseCountLeft = 0;

      digitalWrite(IN1_RIGHT, HIGH);
      digitalWrite(IN2_RIGHT, LOW);

      digitalWrite(IN1_LEFT, HIGH);
      digitalWrite(IN2_LEFT, LOW);

      analogWrite(EN_RIGHT, SPEED);
      analogWrite(EN_LEFT, SPEED);
    }

    void right() {
      movingStrait = BW_FALSE;
      stopping = BW_FALSE;

      digitalWrite(IN1_RIGHT, LOW);
      digitalWrite(IN2_RIGHT, HIGH);

      digitalWrite(IN1_LEFT, HIGH);
      digitalWrite(IN2_LEFT, LOW);

      analogWrite(EN_RIGHT, SPEED);
      analogWrite(EN_LEFT, SPEED);
    }

    void left() {
      movingStrait = BW_FALSE;
      stopping = BW_FALSE;

      digitalWrite(IN1_RIGHT, HIGH);
      digitalWrite(IN2_RIGHT, LOW);

      digitalWrite(IN1_LEFT, LOW);
      digitalWrite(IN2_LEFT, HIGH);

      analogWrite(EN_RIGHT, SPEED);
      analogWrite(EN_LEFT, SPEED);
    }

    void stop() {
      movingStrait = BW_FALSE;
      stopping = BW_TRUE;

      digitalWrite(IN1_RIGHT, LOW);
      digitalWrite(IN2_RIGHT, LOW);

      digitalWrite(IN1_LEFT, LOW);
      digitalWrite(IN2_LEFT, LOW);
    }

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

      pinMode(EN_RIGHT, OUTPUT);
      pinMode(EN_LEFT, OUTPUT);
      pinMode(IN1_RIGHT, OUTPUT);
      pinMode(IN2_RIGHT, OUTPUT);
      pinMode(IN1_LEFT, OUTPUT);
      pinMode(IN2_LEFT, OUTPUT);

      pinMode(ENCODER_RIGHT, INPUT_PULLUP);
      pinMode(ENCODER_LEFT, INPUT_PULLUP);

      // pinMode(SERVO_PIN, OUTPUT);

      pinMode(ULTRASONIC_TRIG_PIN, OUTPUT);
      pinMode(ULTRASONIC_ECHO_PIN, INPUT);

      attachInterrupt(digitalPinToInterrupt(ENCODER_RIGHT), [] { countPulse(pulseCountRight); }, CHANGE);
      attachInterrupt(digitalPinToInterrupt(ENCODER_LEFT), [] { countPulse(pulseCountLeft); }, CHANGE);

      digitalWrite(IN1_RIGHT, LOW);
      digitalWrite(IN2_RIGHT, HIGH);

      digitalWrite(IN1_LEFT, LOW);
      digitalWrite(IN2_LEFT, HIGH);

      analogWrite(EN_RIGHT, SPEED);
      analogWrite(EN_LEFT, SPEED);

      // myServo.attach(SERVO_PIN);
      // myServo.write((SERVO_MAX_RIGHT + SERVO_MAX_LEFT) / 2);

      forward();
    }

    unsigned long start_time = 0;

    void pingTimer() {
      sonar.timer_stop();
      start_time = micros();
      sonar.ping_timer(checkTimer);
      // NewPing::timer_us(ULTRASONIC_TIMEOUT * 4, checkTimer);
    }

    void checkTimer() {
      // static int angle = SERVO_MAX_RIGHT;
      // static int direction = SERVO_TURN_LEFT;
      if (micros() - ULTRASONIC_TIMEOUT >= start_time && sonar.check_timer()) {
        distance = ((float) sonar.ping_result / (float) US_ROUNDTRIP_CM) / 2.0;
        if (distance < ULTRASONIC_TOO_CLOSE) {
          stop();
          Serial.println("stoppeing");
        }
      }
      // sonar.timer_stop();
    }

    void loop() {
      pingTimerAction.check();
      if (distance == 0 || distance > ULTRASONIC_TOO_CLOSE) {
        // forward();
      }
    }

Here is a printout of the pulse counts and the status of the motors for a run:

    DifferentialDrive2
    Pulses (right,left): 1,0, Motor on (right,left): -1,-1
    Pulses (right,left): 1,1, Motor on (right,left): -1,-1
    Pulses (right,left): 2,1, Motor on (right,left): -1,-1
    Pulses (right,left): 3,1, Motor on (right,left): 0,-1
    Pulses (right,left): 4,1, Motor on (right,left): 0,-1
    Pulses (right,left): 5,1, Motor on (right,left): 0,-1
    Pulses (right,left): 6,1, Motor on (right,left): 0,-1
    Pulses (right,left): 7,1, Motor on (right,left): 0,-1
    Pulses (right,left): 8,1, Motor on (right,left): 0,-1
    Pulses (right,left): 9,1, Motor on (right,left): 0,-1
    Pulses (right,left): 9,2, Motor on (right,left): 0,-1
    Pulses (right,left): 9,3, Motor on (right,left): 0,-1
    Pulses (right,left): 9,4, Motor on (right,left): 0,-1
    Pulses (right,left): 9,5, Motor on (right,left): 0,-1

    Pulses (right,left): 9,6, Motor on (right,left): 0,-1
    Pulses (right,left): 9,7, Motor on (right,left): 0,-1
    Pulses (right,left): 9,8, Motor on (right,left): -1,-1
    Pulses (right,left): 9,9, Motor on (right,left): -1,-1
    Pulses (right,left): 10,9, Motor on (right,left): -1,-1
    Pulses (right,left): 11,9, Motor on (right,left): 0,-1
    Pulses (right,left): 12,9, Motor on (right,left): 0,-1
    Pulses (right,left): 13,9, Motor on (right,left): 0,-1
    Pulses (right,left): 14,9, Motor on (right,left): 0,-1
    Pulses (right,left): 15,9, Motor on (right,left): 0,-1
    Pulses (right,left): 16,9, Motor on (right,left): 0,-1
    Pulses (right,left): 17,9, Motor on (right,left): 0,-1
    Pulses (right,left): 17,10, Motor on (right,left): 0,-1
    Pulses (right,left): 17,11, Motor on (right,left): 0,-1
    Pulses (right,left): 17,12, Motor on (right,left): 0,-1
    Pulses (right,left): 17,13, Motor on (right,left): 0,-1
    Pulses (right,left): 17,14, Motor on (right,left): 0,-1
    Pulses (right,left): 17,15, Motor on (right,left): 0,-1
    Pulses (right,left): 17,16, Motor on (right,left): -1,-1
    Pulses (right,left): 17,17, Motor on (right,left): -1,-1
    Pulses (right,left): 18,17, Motor on (right,left): -1,-1
    Pulses (right,left): 19,17, Motor on (right,left): 0,-1
    Pulses (right,left): 20,17, Motor on (right,left): 0,-1
    Pulses (right,left): 21,17, Motor on (right,left): 0,-1
    Pulses (right,left): 22,17, Motor on (right,left): 0,-1
    Pulses (right,left): 23,17, Motor on (right,left): 0,-1
    Pulses (right,left): 24,17, Motor on (right,left): 0,-1
    Pulses (right,left): 24,18, Motor on (right,left): 0,-1
    Pulses (right,left): 24,19, Motor on (right,left): 0,-1
    Pulses (right,left): 24,20, Motor on (right,left): 0,-1

What bugs me about this output is that I am expecting the slower motor not to open such large gaps, and I also know that in reality it did not open such large gaps. I suspect some pulses don't get counted for some reason, perhaps I am putting too much work on the micro-controller.

If the problem is not in my code, I wonder if this problem can be solved on a single Arduino device and I just have a weak algorithm, or perhaps it requires a separate device for the ultrasonic and a separate device for the differential drive.

Thanks in advance for any helpers.

PS. I am using this motor shield: [https://osoyoo.com/2020/08/06/osoyoo-motor-shield/][1]

  [1]: https://osoyoo.com/2020/08/06/osoyoo-motor-shield/

body:
Thanks to @chrisl, here is the answer:

The NewPing library uses Timer2 on UNO, which means pin 3 (and 11) is not available for use. I have been using pin 3 for interrupts from a rotary encoder, which is probably the reason for the sluggish performance.

The bad news are there are only two interrupt pins on UNO - 2 and 3, so if I want to attach two rotary encoders to my two drive wheels, I cannot use interrupts to count the pulses. There may be a workaround, I couldn't think of one, but I think IR proximity sensors may be a better choice than my ultrasonic sensor because judging from code examples they are neither blocking nor do they need timers, but I didn't really dive deep into them yet so I may be wrong on this.


message:
Arduino Nano I2C OLED display 0.96 inches 128x64 pixels

I have a strange issue while trying to run the hello world code on an arduino nano connected to an OLED display.

This is the code I used:

        #include <Adafruit_SSD1306.h>
    Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

    void setup() {

      // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x32

      display.display();
      delay(2000);

      display.clearDisplay();      //this line to clear previous logo
      display.setTextColor(WHITE); //without this no display
      display.print("Hello World!");//your TEXT here
      display.display();            //to shows or update your TEXT
    }

    void loop() {

     }

But I get this on the display.
[![OLED][1]][1]

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

Any idea what I could be missing?

Thanks !

  [1]: https://i.stack.imgur.com/gAuRF.jpg
  [2]: https://i.stack.imgur.com/fUgRa.jpg

body:
Mystery solved :)

After some more reading it appears that the display driver is actually SH1106, so after using the [right][1] library I got the display working.[![enter image description here][2]][2]

  [1]: https://github.com/adafruit/Adafruit_SH110x
  [2]: https://i.stack.imgur.com/UTS74.jpg


message:
Updating ESP32 firmware from another ESP32 over USB, similar to how esptool.py works

Is there a way to update the firmware on one ESP32 from another ESP32 over USB, similar to how firmware can be updated using esptool.py?

This would essentially be like a port of whatever magic esptool.py uses over USB to update an ESP32, but instead of running through Python it would be an Arduino C++ sketch and would read the firmware to write to the other ESP32 from SPIFFS.

body:
The esp32 can update itself. To store and apply the updated sketch's binary it uses the Update library bundled with the ESP32 Arduino boards support package.

Then there are libraries for different ways of transporting the binary over network:
* ArduinoOTA for upload from the Arduino IDE
* HTTPUpdate to download the binary from a web server
* HTTPUpdateServer to upload the binary to ESP32 over a web page

The keyword is "OTA update" as "over the air update" even it is possible to transport the update over cable too.


body:
You can use the SD card to update the firmware.
Here is the example [code][1]

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/Update/examples/SD_Update/SD_Update.ino


message:
Is there something that I need to do to make the code from this answer compile?

I tried to compile the following code (using Arduino 1.8.16 with an esp8266-12)

    extern volatile unsigned long timer0_millis;
    unsigned long new_value = 0;

    void setup(){
      //Setup stuff
    }

    void loop(){
      //Do stuff
      //--------

      //Change Millis
      setMillis(new_value);
    }

    void setMillis(unsigned long new_millis){
      uint8_t oldSREG = SREG;
      cli();
      timer0_millis = new_millis;
      SREG = oldSREG;
    }

from an answer to [this question][1], but I get the following error

     error: 'SREG' was not declared in this scope
       uint8_t oldSREG = SREG;
                     ^
    exit status 1
    'SREG' was not declared in this scope

I wouldn't necessarily want to use this code for any real purpose, other than as an exercise in learning.  What am I missing?  What is **SREG** ?

  [1]: https://arduino.stackexchange.com/questions/22994/resetting-millis-and-micros?newreg=6b314918a8154c95aaf850ca92883946

body:
`SREG` is the processor status register. One of the bits in there is the interrupt flag, which is cleared with the `cli()` command and reset at the end of the function. Why the original poster used the register instead of just using cli/sei is unclear. (Note: Instead of `cli()` and `sei()` the arduino documentation uses the much clearer equivalents `noInterrupts()` and `interrupts()`.)

This SREG register is, in this form, hardware specific and therefore not available if you're using the esp8266 toolchain. The above code builds fine with an Arduino Uno or similar board. To build for the esp8266, change the code to:

```cpp
void setMillis(unsigned long new_millis){
  noInterrupts();
  timer0_millis = new_millis;
  interrupts();
}
```

I don't have such a board, so I can't verify it really works on this board. You might get a linker error about a non-existing `timer0_millis` variable.


message:
Serial.write - sedd ascii characters with hex value in the same line

Working on making a controller for a haunted house prop. Trying to get it to interface with a device.

Was able to use a serial analyzer to see what commands and values are being sent.

the hex codes being sent over serial for manual control is " 40 4d 01" which translates to "@M[?]"

the third byte 01 is the configuration state you want to have it change to. I'm using a byte to store the value between 0-255.

I'm stumped at how to send 2 ASCII characters but in the same Serial.write() command send a raw value, or at how to send them all as hex. I'm sure this is straight forward and I'm just unaware of some simple function.

body:
You can use a `byte` array for this:

```c++
    // at the appropriate place in your code:
    byte message[] = { '@', 'M', 0x01 };
    Serial.write(message, sizeof message);
```

If you need, you can prepare the array and just assign the value:

```c++
byte message[] = { '@', 'M', 0 };

// ...

    byte value = 0x01; // or any other assignment

    // at the appropriate place in your code:
    message[2] = value;
    Serial.write(message, sizeof message);
```


body:
First of all, I will challenge your assumption that you have to send the
three bytes in the same call to `Serial.write()`. There is no real
advantage in doing so. Serial output is handled through a memory buffer
that is consumed by the serial port within an interrupt service routine.
`Serial.write()` only writes to that memory buffer. Thus, you can
simply:

```c++
Serial.write("@M");
Serial.write(1);
```

and the receiver will not see the difference. There will be no gap
between the `'M'` and the `1`. There is no notion of “messages” or
“frames” on a serial link, unless an upper layer protocol adds its own
framing, which is not the case here.

Next, if you really want to issue a single call (futile as this is), you
could

```c++
Serial.write("@M\1");
```

This, however, will not work if the last byte is zero. The method shown
by the busybee is more general ans is able to send a zero-valued byte.


message:
Why does Arduino Due appear to halt after single call to ADC_Handler?

In the simple example below I just software trigger an ADC acquisition and then set the builtin LED's digital out in the interrupt handler. I don't know why the program appears to halt however.

```c

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

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  adc_enable_channel(ADC, ADC_CHANNEL_6);
  adc_enable_interrupt(ADC, ADC_IER_EOC6);
  pmc_enable_periph_clk(ID_ADC);
  NVIC_EnableIRQ(ADC_IRQn);

  Serial.println("GO");
}

void loop()
{
  Serial.println("RUNNING");
  adc_start(ADC);
}

void ADC_Handler(void)
{
  digitalWrite(13,HIGH);
  adc_get_status(ADC);
}
```

I know the handler gets called because the LED lights.  The main loops appears to stop running after this as it lo longer prints out anything.  If I don't trigger an acquision in the main loop it runs forever. Likewise if I don't enable the interrupt or the NVIC.

I can't explain this behavior.

body:
The freeze will occur unless unless `ADC_ISR` bits 0-15 are 0 at the end of the interrupt handler.  In this case, ISR returns bit 6 set for the enabled channel (6).  For many interrupts, the bit can be reset to 0 by simply reading `ADC_ISR`. However for end-of-conversion interrupts the converted data register for that channel *must* be read for the ISR bit to be set to 0.

Therefore this code will not halt. (I included some extra printouts to make clear the register values at each point in time.)

```c
volatile uint32_t LAST = 0;
volatile uint32_t CHAN6 = 0;
volatile uint32_t ISR1 = 0;
volatile uint32_t ISR2 = 0;

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

  adc_enable_channel(ADC, ADC_CHANNEL_6);

  adc_enable_interrupt(ADC, ADC_IER_EOC6);

  pmc_enable_periph_clk(ID_ADC);

  NVIC_ClearPendingIRQ(ADC_IRQn);
  NVIC_EnableIRQ(ADC_IRQn);

  Serial.println("GO");
  adc_configure_trigger(ADC, ADC_TRIG_SW,0);
}

void loop()
{
  Serial.println(ISR1,BIN);
  Serial.println(ISR2,BIN);

  adc_start(ADC);
  delay(1000);
}

void ADC_Handler(void)
{
  ISR1 = adc_get_status(ADC); // chan 6 bit =1
  LAST = adc_get_latest_value(ADC);
  ISR1 = adc_get_status(ADC); // chan 6 bit =1 (still)

  CHAN6 = adc_get_channel_value(ADC, ADC_CHANNEL_6);
  ISR2 = adc_get_status(ADC); // chan 6 bit = 0
}

```

However, I will note that the datasheet for the chip says on page 1322 `Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.`

**This appears to be false**. Reading ADC_LCDR *does not* clear the status bit and will cause a hang.  `ADC_CDR6`  **must** be read specifically to avoid a hang.


message:
How to send multiple data over serial in one byte?

I'm currently reading 3 limit switches and sending those data over Serial.write using the following code.

    #include <SPI.h>
    #include <Wire.h>
    #include <arduino-timer.h>

    //Define limit switch pins
    #define LEFT_SWITCH_PIN 5
    #define RIGHT_SWITCH_PIN 6
    #define REAR_SWITCH_PIN 7

    bool left_switch_state;
    bool right_switch_state;
    bool rear_switch_state;
    bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};
    int switch_pin_array[3] = {LEFT_SWITCH_PIN,RIGHT_SWITCH_PIN,REAR_SWITCH_PIN};

    int send_status_state = 0;

    void setup() {
        Wire.begin();
        Serial.begin(115200);
        status_timer.every(200, sendStatus);
    }

    void sendStatus() {
      if (send_status_state == 0) {
        getLimitSwitch();

        unsigned char buf[5];
        buf[0] = 'S';
        buf[1] = switch_state_array[0];
        buf[2] = switch_state_array[1];
        buf[3] = switch_state_array[2];
        buf[4] = '|';
        Serial.write(buf,5);
        send_status_state = 1;

      }
    }

    void loop() {
        status_timer.tick();
      }

    void getLimitSwitch()
    {
      for (int i=0; i<3; i++)
      {
        switch_state_array[i] = digitalRead(switch_pin_array[i]);
      }
    }
    /*********************************************************************************************************
        END FILE
    *********************************************************************************************************/

as you can see I'm currently using 3 bytes to send the states of each limit switch separately.

        buf[1] = switch_state_array[0];
        buf[2] = switch_state_array[1];
        buf[3] = switch_state_array[2];

How can I send all limit switch data in one byte?

body:
You should learn how to use bitwise operators. These are needed to do what you want.

We can save the state of each switch in one bit each. For this we first define our global variable that will hold the switch states:

    byte switch_states = 0;

Then in `getLimitSwitch()` we loop through our pins. The result of `digitalRead()` is always one of `0` and `1`. So we can take this value and bit shift it to the left. Then we do bitwise OR operations to put the value into our `switch_states` variable:

    void getLimitSwitch()
    {
      for (int i=0; i<3; i++)
      {
        switch_states |= ( digitalRead(switch_pin_array[i]) << i );
      }
    }

Then you can send that byte over Serial. It can hold up to 8 states.

    Serial.write(switch_states);

---

The most interesting line here is

    switch_states |= ( digitalRead(switch_pin_array[i]) << i );

Lets follow here with an example: Lets assume we look at the pin with index 2 and it is HIGH. So we have `switch_states |= ( 1 << 2 )`. This equates to the following representation in binary `switch_states |= ( 0b00000001 << 2 )`. `<<` shifts the bit pattern to the left; by 2 digits in this case. So we get `switch_states |= 0b00000100;`. That is equal to `switch_states = switch_states | 0b00000100;`. The bitwise OR operator `|` return a value where each bit is set to 1, if the corresponding bit in at least one of the two operants is 1. Here we use this to put the bits together.

If the pins have the states HIGH,LOW,HIGH the resulting value will be `0b00000101`, aka. `5` in decimal.

---

On the other side you might want to decode this value. How it is done depends on the architecture (using a PC, a microcontroller, ...). But on an Arduino you can test for a pin to be HIGH with this:

    if(received_states_variable & (1 << pin_index))

---

Note: Doing this

    bool left_switch_state;
    bool right_switch_state;
    bool rear_switch_state;
    bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};

doesn't make much sense. You initialize the array elements just with the implicitly to `false` initialized variables. You just don't need the normal bool variables. You can just simply define your `bool` array. If you want to initialize it explicitly, just use `true` or `false` directly:

    bool switch_state_array[3] = {false, false, false};

or even

    bool switch_state_array[3] = {false};


message:
Peculiar behaviour of arduino pro micro

I am working with an arduino pro micro and I am facing a peculiar problem. The project I am working with includes arduino MKR NB 1500 as well. I am transferring data from MKR NB 1500 to arduino pro micro through Serial1(Rx/Tx pins). I have added the sample code that i am using on both boards

program in arduino MKR NB 1500
```
void setup() {
  Serial1.begin(9600);
}
void loop() {
  Serial1.print("printing");
  delay(2000);
}
```

program in pro micro
```
#include "Keyboard.h"

void setup() {
  Serial1.begin(9600);
  Keyboard.begin();
}

void loop() {
  Keyboard.write(Serial1.read());
}
```
I would like to transfer some data from MKR NB 1500 to pro micro which emulates a keyboard and prints the data in a editor. I am powering the arduino MKR NB 1500 via USB using its native USB port. The pro micro works as expected when I connect both these boards to USB ports in the same laptop. (Output: printingprintingprintingprinting)

However, the pro micro prints garbage values when I connect the MKR NB 1500 to a USB port belonging to a different laptop. (Output: a10joh<qqj<zstjo)

Is there any reason for such a behavior. Please let me know if you need more information from my side or if i have not made myself clear.

body:
You have to connect ground between the modules. Without common ground the logic level of signal can't be measured. While both boards were powered over USB from the same laptop the boards had common ground.

----------

`read` returns -1 if nothing is available so check if some character was received:
```
void loop() {
  if (Serial1.available()) {
    Keyboard.write(Serial1.read());
  }
}
```

btw: The MKR can emulate a keyboard too with the Keyboard library.


message:
got a compiling error while programming node mcu

i was programming my node mcu i modified the code and got a complination error but when i compiled the original code i got no error
modified code

    #include "arduino_secrets.h"
    #include "thingProperties.h"

    // define the GPIO connected with Relays and switches
    #define RelayPin1 5  //D1
    #define RelayPin2 4  //D2
    #define RelayPin3 14 //D5
    #define RelayPin4 12 //D6

    #define RelayPin5 2  //d4
    #define RelayPin6 0   //D3
    #define RelayPin7 13  //D7
    #define RelayPin8 15   //d8

    #define wifiLed   16   //D0

    int toggleState_1 = 0; //Define integer to remember the toggle state for relay 1
    int toggleState_2 = 0; //Define integer to remember the toggle state for relay 2
    int toggleState_3 = 0; //Define integer to remember the toggle state for relay 3
    int toggleState_4 = 0; //Define integer to remember the toggle state for relay 4
    int toggleState_5 = 0; //Define integer to remember the toggle state for relay 5
    int toggleState_6 = 0; //Define integer to remember the toggle state for relay 6
    int toggleState_7 = 0; //Define integer to remember the toggle state for relay 7
    int toggleState_8 = 0; //Define integer to remember the toggle state for relay 8

    void relayOnOff(int relay) {

      switch (relay) {
        case 1:
          if (toggleState_1 == 0) {
            digitalWrite(RelayPin1, HIGH); // turn on relay 1
            toggleState_1 = 1;
            Serial.println("Device1 ON");
          }
          else {
            digitalWrite(RelayPin1, LOW); // turn off relay 1
            toggleState_1 = 0;
            Serial.println("Device1 OFF");
          }
          delay(100);
          break;
        case 2:
          if (toggleState_2 == 0) {
            digitalWrite(RelayPin2, HIGH); // turn on relay 2
            toggleState_2 = 1;
            Serial.println("Device2 ON");
          }
          else {
            digitalWrite(RelayPin2, LOW); // turn off relay 2
            toggleState_2 = 0;
            Serial.println("Device2 OFF");
          }
          delay(100);
          break;
        case 3:
          if (toggleState_3 == 0) {
            digitalWrite(RelayPin3, HIGH); // turn on relay 3
            toggleState_3 = 1;
            Serial.println("Device3 ON");
          } else {
            digitalWrite(RelayPin3, LOW); // turn off relay 3
            toggleState_3 = 0;
            Serial.println("Device3 OFF");
          }
          delay(100);
          break;
         case 4:
          if (toggleState_4 == 0) {
            digitalWrite(RelayPin4, HIGH); // turn on relay 3
            toggleState_4 = 1;
            Serial.println("Device4 ON");
          } else {
            digitalWrite(RelayPin4, LOW); // turn off relay 3
            toggleState_4 = 0;
            Serial.println("Device4 OFF");
          }
          delay(100);
          break;
         case 5:
          if (toggleState_5 == 0) {
            digitalWrite(RelayPin5, HIGH); // turn on relay 3
            toggleState_5 = 1;
            Serial.println("Device5 ON");
          } else {
            digitalWrite(RelayPin5, LOW); // turn off relay 3
            toggleState_5 = 0;
            Serial.println("Device5 OFF");
          }
          delay(100);
          break;
         case 6:
          if (toggleState_6 == 0) {
            digitalWrite(RelayPin6, HIGH); // turn on relay 3
            toggleState_6 = 1;
            Serial.println("Device6 ON");
          } else {
            digitalWrite(RelayPin6, LOW); // turn off relay 3
            toggleState_6 = 0;
            Serial.println("Device6 OFF");
          }
          delay(100);
          break;
         case 7:
          if (toggleState_7 == 0) {
            digitalWrite(RelayPin7, HIGH); // turn on relay 3
            toggleState_7 = 1;
            Serial.println("Device7 ON");
          } else {
            digitalWrite(RelayPin7, LOW); // turn off relay 3
            toggleState_7 = 0;
            Serial.println("Device7 OFF");
          }
          delay(100);
          break;
        case 8:
          if (toggleState_8 == 0) {
            digitalWrite(RelayPin8, HIGH); // turn on relay 4
            toggleState_8 = 1;
            Serial.println("Device8 ON");
          }
          else {
            digitalWrite(RelayPin8, LOW); // turn off relay 4
            toggleState_8 = 0;
            Serial.println("Device8 OFF");
          }
          delay(100);
          break;
        default : break;
      }
    }

    void setup() {
      // Initialize serial and wait for port to open:
      Serial.begin(9600);
      // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
      delay(1500);

      // Defined in thingProperties.h
      initProperties();

      // Connect to Arduino IoT Cloud
      ArduinoCloud.begin(ArduinoIoTPreferredConnection);

      setDebugMessageLevel(2);
      ArduinoCloud.printDebugInfo();

      pinMode(RelayPin1, OUTPUT);
      pinMode(RelayPin2, OUTPUT);
      pinMode(RelayPin3, OUTPUT);
      pinMode(RelayPin4, OUTPUT);
      pinMode(RelayPin5, OUTPUT);
      pinMode(RelayPin6, OUTPUT);
      pinMode(RelayPin7, OUTPUT);
      pinMode(RelayPin8, OUTPUT);

      pinMode(wifiLed, OUTPUT);

      digitalWrite(RelayPin1, LOW);
      digitalWrite(RelayPin2, LOW);
      digitalWrite(RelayPin3, LOW);
      digitalWrite(RelayPin4, LOW);
      digitalWrite(RelayPin5, LOW);
      digitalWrite(RelayPin6, LOW);
      digitalWrite(RelayPin7, LOW);
      digitalWrite(RelayPin8, LOW);

      digitalWrite(wifiLed, HIGH);  //Turn ON WiFi LED
    }

    void loop() {
      ArduinoCloud.update();

      if (WiFi.status() != WL_CONNECTED)
      {
        digitalWrite(wifiLed, HIGH); //Turn ON WiFi LED
      }
      else{
        digitalWrite(wifiLed, LOW); //Turn OFF WiFi LED
      }
    }

the original code

    #include "arduino_secrets.h"
    #include "thingProperties.h"

    // define the GPIO connected with Relays and switches
    #define RelayPin1 5  //D1
    #define RelayPin2 4  //D2
    #define RelayPin3 14 //D5
    #define RelayPin4 12 //D6

    #define SwitchPin1 10  //SD3
    #define SwitchPin2 0   //D3
    #define SwitchPin3 13  //D7
    #define SwitchPin4 3   //RX

    #define wifiLed   16   //D0

    int toggleState_1 = 0; //Define integer to remember the toggle state for relay 1
    int toggleState_2 = 0; //Define integer to remember the toggle state for relay 2
    int toggleState_3 = 0; //Define integer to remember the toggle state for relay 3
    int toggleState_4 = 0; //Define integer to remember the toggle state for relay 4

    void relayOnOff(int relay) {

      switch (relay) {
        case 1:
          if (toggleState_1 == 0) {
            digitalWrite(RelayPin1, HIGH); // turn on relay 1
            toggleState_1 = 1;
            Serial.println("Device1 ON");
          }
          else {
            digitalWrite(RelayPin1, LOW); // turn off relay 1
            toggleState_1 = 0;
            Serial.println("Device1 OFF");
          }
          delay(100);
          break;
        case 2:
          if (toggleState_2 == 0) {
            digitalWrite(RelayPin2, HIGH); // turn on relay 2
            toggleState_2 = 1;
            Serial.println("Device2 ON");
          }
          else {
            digitalWrite(RelayPin2, LOW); // turn off relay 2
            toggleState_2 = 0;
            Serial.println("Device2 OFF");
          }
          delay(100);
          break;
        case 3:
          if (toggleState_3 == 0) {
            digitalWrite(RelayPin3, HIGH); // turn on relay 3
            toggleState_3 = 1;
            Serial.println("Device3 ON");
          } else {
            digitalWrite(RelayPin3, LOW); // turn off relay 3
            toggleState_3 = 0;
            Serial.println("Device3 OFF");
          }
          delay(100);
          break;
        case 4:
          if (toggleState_4 == 0) {
            digitalWrite(RelayPin4, HIGH); // turn on relay 4
            toggleState_4 = 1;
            Serial.println("Device4 ON");
          }
          else {
            digitalWrite(RelayPin4, LOW); // turn off relay 4
            toggleState_4 = 0;
            Serial.println("Device4 OFF");
          }
          delay(100);
          break;
        default : break;
      }
    }

    void manual_control() {
      //Manual Switch Control
      if (digitalRead(SwitchPin1) == LOW) {
        delay(200);
        relayOnOff(1);
      }
      else if (digitalRead(SwitchPin2) == LOW) {
        delay(200);
        relayOnOff(2);
      }
      else if (digitalRead(SwitchPin3) == LOW) {
        delay(200);
        relayOnOff(3);
      }
      else if (digitalRead(SwitchPin4) == LOW) {
        delay(200);
        relayOnOff(4);
      }
    }

    void setup() {
      // Initialize serial and wait for port to open:
      Serial.begin(9600);
      // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
      delay(1500);

      // Defined in thingProperties.h
      initProperties();

      // Connect to Arduino IoT Cloud
      ArduinoCloud.begin(ArduinoIoTPreferredConnection);

      setDebugMessageLevel(2);
      ArduinoCloud.printDebugInfo();

      pinMode(RelayPin1, OUTPUT);
      pinMode(RelayPin2, OUTPUT);
      pinMode(RelayPin3, OUTPUT);
      pinMode(RelayPin4, OUTPUT);

      pinMode(wifiLed, OUTPUT);

      pinMode(SwitchPin1, INPUT_PULLUP);
      pinMode(SwitchPin2, INPUT_PULLUP);
      pinMode(SwitchPin3, INPUT_PULLUP);
      pinMode(SwitchPin4, INPUT_PULLUP);

      //During Starting all Relays should TURN OFF
      digitalWrite(RelayPin1, HIGH);
      digitalWrite(RelayPin2, HIGH);
      digitalWrite(RelayPin3, HIGH);
      digitalWrite(RelayPin4, HIGH);

      digitalWrite(wifiLed, HIGH);  //Turn OFF WiFi LED
    }

    void loop() {
      ArduinoCloud.update();

      manual_control(); //Control relays manually

      if (WiFi.status() != WL_CONNECTED)
      {
        digitalWrite(wifiLed, HIGH); //Turn OFF WiFi LED
      }
      else{
        digitalWrite(wifiLed, LOW); //Turn ON WiFi LED
      }
    }

    void onSwitch1Change() {
      if (switch1 == 1)
      {
        digitalWrite(RelayPin1, HIGH);
        Serial.println("Device1 ON");
        toggleState_1 = 1;
      }
      else
      {
        digitalWrite(RelayPin1, LOW);
        Serial.println("Device1 OFF");
        toggleState_1 = 0;
      }
    }

    void onSwitch2Change() {
      if (switch2 == 1)
      {
        digitalWrite(RelayPin2, HIGH);
        Serial.println("Device2 ON");
        toggleState_2 = 1;
      }
      else
      {
        digitalWrite(RelayPin2, LOW);
        Serial.println("Device2 OFF");
        toggleState_2 = 0;
      }
    }

    void onSwitch3Change() {
      if (switch3 == 1)
      {
        digitalWrite(RelayPin3, HIGH);
        Serial.println("Device2 ON");
        toggleState_3 = 1;
      }
      else
      {
        digitalWrite(RelayPin3, LOW);
        Serial.println("Device3 OFF");
        toggleState_3 = 0;
      }
    }

    void onSwitch4Change() {
      if (switch4 == 1)
      {
        digitalWrite(RelayPin4, HIGH);
        Serial.println("Device4 ON");
        toggleState_4 = 1;
      }
      else
      {
        digitalWrite(RelayPin4, LOW);
        Serial.println("Device4 OFF");
        toggleState_4 = 0;
      }
    }

i have included the arduino_secrets and thingproperties in my both pieces of code the difference is that i wanted 8 relay pins to be configured instead of 4 pins
please ask if any thing is needed from me

this was the exact error

    C:\Users\akki kisu\Documents\Arduino\libraries\ArduinoIoTCloud\src\property\Property.cpp:25:19: note: '#pragma message: No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps .'
       25 |   #pragma message "No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps ."
          |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x1c): undefined reference to `_Z15onSwitch1Changev'
    c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x34): undefined reference to `_Z15onSwitch2Changev'
    c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x40): undefined reference to `_Z15onSwitch3Changev'
    c:/users/akki kisu/appdata/local/arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld.exe: sketch\Code_NodeMCU_Alexa_ArduinoIotCloud_4Relays.ino.cpp.o:(.text._Z14initPropertiesv+0x4c): undefined reference to `_Z15onSwitch4Changev'
    collect2.exe: error: ld returned 1 exit status
    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

body:
In Arduino IoT cloud the *variables* synced between the Cloud and the sketch are defined in the definition of the (IoT) *thing*. The *variables* are reflected into the thingProperties.h file which is maintained by the Cloud editor. The on<variable_name> functions in the sketch handle the synchronization of these *variables*. They are declared in the thingProperties.h

You removed the `onSwitchChange` functions, but you didn't remove the switchChange *variables* in the definition of the Thing. The thingProperties.h still contains declarations of `onSwitchChange` functions, but the linker can't find the definition of the function because you removed it from the sketch.

The errors are like this one:
```
undefined reference to `_Z15onSwitch1Changev'
```

To solve this, remove the switchChange *variables* from the *thing* in the Cloud UI.


message:
Adding L293D motor shield to Breadboard

Anyone knows how to attach the l293D motor driver shield on a breadboard?

I need to put the shield on top of a breadboard and then use an Atmega328P as the main way of controlling it.
Than you :)

body:
Acknowledging that it is not exactly the answer to your question, the folks at Adafruit have written an excellent [tutorial][1] on breadboarding the raw [L293D *chip*][2]. Which may be a more compact option for you?

Your question asks how to attach an L293D shield to a breadboard, and as @Juraj said in the comments, you can't do this easily directly. As @Jsotola mentioned, a UNO format shield is designed to connect directly to a uno, not to breadboard.

On a UNO format shield the pin alignment on the 18 pin (10+8) header sider of the shield (the digital pins) is not a comfortable fit into breadboard hole spacing (the shorter 14 pin side does align OK with breadboard). To make matters worse a UNO shield is wider than the available rows on a single standard breadboard. However, if you're willing to use more force and bend a few pins on the shield (**not recommended**) you can make this work using two breadboards side by side. The photo shows one possibility.
[![Fitting a UNO shield onto breadboard][3]][3]

A **better solution** as mentioned by @ChrisL in the comments might be to use [dupont connectors][4] to connect the shield pins as needed (e.g. to a non-UNO format arduino).
[![Dupont connector][5]][5]

There are different versions and clones of the L293D shield in circulation. I think most of these are based on the (now obsolete) Adafruit open source [version 1][6]. In any case you'll need to refer to the datasheet for the version you're using and be sure to connect every pin required from the shield to the arduino using the dupont connectors.

There are plenty of tutorials available regarding using the L293D shield, one example is at [Last Minute Engineers][7]

  [1]: https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/overview
  [2]: https://www.ti.com/lit/ds/symlink/l293.pdf
  [3]: https://i.stack.imgur.com/mAj0c.jpg
  [4]: https://electronics.stackexchange.com/questions/179179/what-is-the-official-name-for-these-jumper-wires
  [5]: https://i.stack.imgur.com/lC3Z0.jpg
  [6]: https://learn.adafruit.com/adafruit-motor-shield
  [7]: https://lastminuteengineers.com/l293d-motor-driver-shield-arduino-tutorial/


message:
Reverse engineering an i2c signal

I have an i2c device that i would like to rreverse engineer. Using the oringal master of the device here is a snapshot from the logical analyzer

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

 I would like to replace the orginal master of the device with an arduino, the device has an interrupt pin that when detected it will do the trasaction above.

So far what i have figuerd out is the address is 0x53 (the first byte). I have also figured out by interactive with the device that the second,third, and last byte are data from the slave device.

How do i write an arduino code to simulate this transaction? Here is the code i have written and the response i got is not quite the same

    #include <Wire.h>

    void setup() {
      Wire.begin();        // join i2c bus (address optional for master)
      Wire. setClock(100000)
      Serial.begin(9600);  // start serial for output
    }

    void loop() {
      Wire.requestFrom(0x53, 6);    // request 6 bytes from slave device #8

      while (Wire.available()) { // slave may send less than requested
        char c = Wire.read(); // receive a byte as character
        Serial.print(c);         // print the character
      }

      delay(500);
    }

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

  [1]: https://i.stack.imgur.com/fsPhd.png
  [2]: https://i.stack.imgur.com/n4IiS.png

body:
# Customised Protocol

As has been mentioned in the comments, it may be that the controller and target are communicating using a customised protocol for which you will need to modify the `Wire` library and/or the `TWI` library.

Modifying the `TWI` library is not easy because it uses a very convoluted mixture of ISR code and non-ISR polling code.

I've [re-written the TWI library][1] so that you can use standard burst-read and burst-write protocols in either ISR mode or polling mode, or **build your own protocol using building-block functions**. It uses the watchdog timer to detect timeouts when the bus freezes due to an error.

# Terminology

The terminology of my TWI library conforms to NXP Semiconductors recently released [v7 of the I2C-bus specification][2] which has:

> Updated the terms "master/slave" to "controller/target" throughout to align with MIPI I3C specification and NXP's Inclusive Language Project

[![UM10204, I2C-bus specification and user manual, v7, 2021-10-01, Table 1, Revision history][3]][3]

  [1]: https://wokwi.com/arduino/projects/306825661000974912
  [2]: https://www.nxp.com/webapp/Download?colCode=UM10204
  [3]: https://i.stack.imgur.com/MWeQh.png


message:
UNO's Internal EEPROM "read" returns incorrect values when it precedes "write"

I am an Arduino instructor and I was preparing some material on the utilization of the Arduino UNO's internal EEPROM when I encountered a problem.
The problem is, I am trying to show the original value on a specific EEPROM location using the EEPROM.read function, then I do write a new value to that location using the EEPROM.write function and try reading it again, please take a look at its code, I use the Serial Monitor to print those values.

    #include <EEPROM.h>

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

      // Print to the Serial Monitor the value read from address 20. "Which should be 255"
      Serial.println(EEPROM.read(20));
      // Write to the EEPROM the value 143 in address 20.
      EEPROM.write(20, 143);
      // Print to the Serial Monitor the value read from address 20. "Which should be 143"
      Serial.println(EEPROM.read(20));
    }

    void loop() {

    }

Now I have verified already that this location has a value of 255 using another sketch which basically does nothing but print the contents of the EEPROM on the Serial Monitor.

    #include <EEPROM.h>

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

      for(int i = 0; i < 1024;i++)
      {
        Serial.print("Address: ");
        Serial.print(i);
        Serial.print(", Value: ");
        Serial.println(EEPROM.read(i));
      }

    }

    void loop() {

    }

Now what is my problem?
My problem is in my first sketch, the EEPROM.read function does not return 255, instead it returns the value 143 which is not even supposed to be there until the next instruction.
I know the EEPROM.write takes around 3.3ms and the writing is what wears down the EEPROM cell, but I also do know that reading takes approximately 0ms and does not wear down the EEPROM cell.
Even though that in mind, I have deliberately placed a "delay(100);" after reading, still no result.

    #include <EEPROM.h>

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

      // Print to the Serial Monitor the value read from address 20. "Which should be 255"
      Serial.println(EEPROM.read(20));
      delay(100);
      // Write to the EEPROM the value 143 in address 20.
      EEPROM.write(20, 143);
      // Print to the Serial Monitor the value read from address 20. "Which should be 143"
      Serial.println(EEPROM.read(20));
    }

    void loop() {

    }

Further more, when I remove the EEPROM.write completely from the code and utilize the EEPROM.read only, I do read correct results, but of-course I do change the address as well to test it.

My setup is:
Windows 10 Pro 64-bit.
Arduino IDE 1.8.15
Arduino UNO china clone version. (not SMD)

My question is, what am I doing wrong here?
Do I have an invalid understanding of something around here?
I have worked with EEPROMs before (both internal and external) using PIC18F microcontrollers, so my experience (which may be incorrect) yields that this sketch should work perfectly.

Thank you in advance.

body:
This is NOT my answer, this is the answer of @Gerben, thank you.

The Arduino IDE suspends the serial connection while uploading, and then resumes when done. It looks like they added some delay before reopening the serial connection. So it looks like your code will run twice, even when you keep the Serial Console open


message:
Help needed with I2C LCD + Arduino - DS-LCDD5

I am new to this forum and a relative beginner to Arduino (software wise) Have built many projects, but always just copy/paste/modify example code.

I found a couple of these modules (a PIC18 daughter board on the back of a common 16x2 LCD)
It says in the data sheet that it can be controlled via I2C, but my skill level is too low to figure out how to do it.
Can somebody please give me advice on how to proceed?

The "I2C Scanner" sketch identifies it at address  0x14 , but the usual I2C-LCD libraries don't work on it.
I use it with an Arduino UNO, SDA(A4), SCL(A5), 1k8 pullup resistors on each.
The module is working 100% with the 1 wire serial method as per the manual.

This is how I think it should work, but it does nothing:

```cpp

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 0x14   // 7bit address = 0010100D, 0x14 hex

void setup () {

 Wire.begin();                           // Initialize I2C communications as Master

  // Write something to the Slave
 Wire.beginTransmission(0x14);           //  0x14  (SLAVE_ADDR)  0010100
  Wire.write(0x28);                       //  00101000
  Wire.write(0x00);                      //  Register address  "0"
  Wire.write("A");                       //  some text
  Wire.endTransmission();

 }

void loop () {

}

```

Link to manual: <http://www.i-lcd.com/PDFs/Drivers/Technical data on DS-LCDD5 Interface Module (IDS).pdf>

body:
Try Replacing the "A" to single quotes 'a'
`Wire.write('A');`
or
`Wire.write(0x41);`

you can also try and add `(byte)` before the hex value:
`Wire.write((byte)0x28);`


body:
So, after I "remembered" that I have an oscilloscope, I hooked it up and noticed that I don't receive an "acknowledge" from the module.

Then I played around with the clock speed, and found I do get an "acknowledge" if I set it between 16000kHz and 18000kHz with the "Wire.setClock" command. :thinking:

Then by mere coincidence, I found that text must got to R1 NOT R0 and control commands to R2 NOT R1. :grimacing:
But I could not get any of the RGB commands to work.
I tried this on all 6 of the modules which I have, same results.
I will just stick to serial comms when I need to use any of these.

So, either the datasheet is wrong or the firmware in the module is flawed.
At least I learned a lot about the workings of I2C in the process, which my goal was.

<https://forum.arduino.cc/t/need-help-with-i2c-code-for-a-16x2-lcd-ds-lcdd5/918289/28?u=jdev99>

Thank you for all advice.
Joe

Working code:

'''

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 0x14                      // 7bit address = 0010100D, 0x14h

void setup () {

 Wire.begin();                                    // Initialize I2C communications as Master
 Wire.setClock(16000);                            // only 16000 - 18000 work

//Clear display
 Wire.beginTransmission(0x14);
 Wire.write(0x02);
 Wire.write(0x01);
 Wire.endTransmission();

}

void loop () {

//Start print on line1, pos1
  Wire.beginTransmission(0x14);
  Wire.write(0x02);
  Wire.write(128);
  Wire.endTransmission();

 // Write something to the Slave
  Wire.beginTransmission(0x14);                       //  0x14  (SLAVE_ADDR)  0010100
  Wire.write(0x01);                                   //  Register address  "0"
  Wire.write("ABCDEFGHIJKLMNOP");                     //  some text
  Wire.endTransmission();

 delay(3000);

//Clear display
 Wire.beginTransmission(0x14);
 Wire.write(0x02);
 Wire.write(0x01);
 Wire.endTransmission();

//Start print on line2, pos1
  Wire.beginTransmission(0x14);
  Wire.write(0x02);
  Wire.write(192);
  Wire.endTransmission();

// Write something to the Slave
  Wire.beginTransmission(0x14);
  Wire.write(0x01);
  Wire.write("1234567890-=+*/@");
  Wire.endTransmission();

delay(3000);

//Clear display
 Wire.beginTransmission(0x14);
 Wire.write(0x02);
 Wire.write(0x01);
 Wire.endTransmission();

}

'''


message:
FastLED and Adafruit Gemma M0 - Getting started

I just bought a Gemma M0 and I'm trying to use it with FastLED. There are several forums that discuss the same errors I get when I try to upload my code, but they all involve editing .h files, something I'm not comfortable doing without understanding the reason behind the change. Is there a place where I can get a basic starting point for using FastLED with the Gemma M0?

I tried the Quick Example in the FastLED Overview:

```
#include "FastLED.h" CRGB leds[1];

void setup() {
  FastLED.addLeds<NEOPIXEL, 6>(leds, 1); }

void loop() {
  leds[0] = CRGB::White; FastLED.show(); delay(30);
  leds[0] = CRGB::Black; FastLED.show(); delay(30); }
```

and I get these errors:
```
Arduino: 1.8.13 (Mac OS X), Board: "Adafruit Gemma M0, Small (-Os) (standard), Arduino, Off"

In file included from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:14:21: note: #pragma message: FastLED version 3.004.000
   14 | #    pragma message "FastLED version 3.004.000"
      |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:65,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastspi.h:135:23: note: #pragma message: No hardware SPI pins defined.  All SPI access will default to bitbanged output
  135 | #      pragma message "No hardware SPI pins defined.  All SPI access will default to bitbanged output"
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:48,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h: In instantiation of 'class FastPin<6>':
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:242:29:   required from 'class FastPinBB<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/platforms/arm/d21/clockless_arm_d21.h:10:54:   required from 'class ClocklessController<6, 12, 30, 18, GRB, 0, false, 50>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/chipsets.h:578:7:   required from 'class WS2812Controller800Khz<6, GRB>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:92:34:   required from 'class NEOPIXEL<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:314:28:   required from 'static CLEDController& CFastLED::addLeds(CRGB*, int, int) [with CHIPSET = NEOPIXEL; unsigned char DATA_PIN = 6]'
/Users/jaireaux/Documents/Arduino/blink/blink.ino:4:60:   required from here
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:210:24: error: static assertion failed: Invalid pin specified
  210 |  static_assert(validpin(), "Invalid pin specified");
      |                ~~~~~~~~^~
exit status 1
Error compiling for board Adafruit Gemma M0.
```

Thanks in advance for your help.

body: The Gemma does not have a pin 6. `FastLED.addLeds<NEOPIXEL, 6>(leds, 1);` I changed to pin 2 and it works. `FastLED.addLeds<NEOPIXEL, 2>(leds, 1);`


message:
Correct usage of SPI with ISR

My Arduino needs to do:

1. Run ISR as many times as possible/ as fast as possible.
2. Occasionally receive data over I2C.
3. Output data over SPI in ISR.

My question is regarding SPI and ISR.
The documentation about SPI I found, was quite poor.

    SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
 SPI.usingInterrupt(255);
 SPI.begin();

    void isr_function()
      SPI.transfer(data);
            pulse_latch();
    };

Is this the correct use of SPI in my case?
Can it be faster?

body:
It is actually fairly easy just to use the SPI peripheral without using the arduino libraries. The attached functions could be used to send a number of bytes through the SPI with one call: (Assuming ATMEGA328)

    #include <avr/io.h>
    #include <avr/interrupt.h>

    static unsigned char spiCnt, *userBufr;

    /* Call this function during setup */
    void SpiInit (void)
        {
        PPR &= ~0x04;   // Be sure the SPI has power
        DDRB |= 4;      // Be sure SS signal on PORTB bit 2 is output
        SPCR = 0x50;    // Turn SPI on, maximum CLK rate
        }

    /* Call this function to initiate the multi-byte send */
    void SpiWrite (void *data, unsigned char bytCnt)
        {
        /* Save the the caller's messsage information */
        userBufr = data;
        spiCnt = bytCnt;

        /* Enable the SPI device, send first byte */
        SPCR |= 0x40;           // Enable SPI
        SPDR = *userBufr++;     // Send the first byte
        SPCR |= 0x80;           // Enable interrupts
        }

    /* Call this one to be sure the message is finished */
    int SpiIsDone (void)
        {
        /* Non-zero when operation is finished */
        return ( ! (SPCR & 0x80));
        }

    /* Stay out of this one */
    ISR (SPI_STC_vect)
        {
        /* Check the remaining number of bytes to send */
        if (--spiCnt)
            SPDR = *userBufr++;     // Send the next byte

        /* Operation is finished, shut down SPI */
        else
            SPCR &= ~0x80;  // Disable interrupts for SPI
        }


message:
How to change brightness of LED light?

I'm trying to change the brightness of an LED light with RGB. I can change the brightness of simple colors like red, green, and blue. But I'm not sure how to change brightness of colors like purple, turquoise, and yellow green.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/HSPXZ.png
When it comes to adjusting the brightness of red, green, and blue. I have tried changing the values inside colorRGB().

With colorRGB():

    int redPin = 9;
    int greenPin = 10;
    int bluePin = 11;

    void setup(){
     pinMode(redPin, OUTPUT);
        delay(500);
     pinMode(greenPin, OUTPUT);
        delay(500);
     pinMode(bluePin, OUTPUT);
        delay(500);
    }
    void loop(){
        colorRGB(255, 0, 0); //Brightness level 255
        colorRGB(150, 0, 0); //Brightness level 150
        colorRGB(50, 0, 0); //Brightness level 50
    }
    void colorRGB(int red, int green, int blue){
     analogWrite(redPin, red);
     analogWrite(greenPin, green);
     analogWrite(bluePin, blue);
    }

I have also tried using analogWrite(), however it needs the pin as one of its arguments so I'm not quite sure how to connect that with the already set up colors inside void loop(){}.

body:
To change the brightness of any RGB color you need to multiply each color component by the brightness ratio. Lets look at some examples:

- Red is `255,0,0` in RGB. Full brightness is represented by 1, half brightness by 0.5, quarter brightness by 0.25 and so on. So we get the following values (we are doing integer calculations, so cutting away any decimal digits):
    - half brightness: `255*0.5,0*0.5,0*0.5` --> `127,0,0`
    - quarter brightness: `255*0.25,0*0.25,0*0.25` --> `63,0,0`
- Yellow is the combination of red and green, so `255,255,0`. Doing the same math as above we get:
    - half brightness: `255*0.5,255*0.5,0*0.5` --> `127,127,0`
    - quarter brightness: `255*0.25,255*0.25,0*0.25` --> `63,63,0`
- Cyan is the combination of red green and half blue, so `255,255,127`. Doing the same math as above we get:
    - half brightness: `255*0.5,255*0.5,127*0.5` --> `127,127,63`
    - quarter brightness: `255*0.25,255*0.25,127*0.25` --> `63,63,31`

So you can change your function to include a brightness parameter:

    void colorRGB(int red, int green, int blue, int brightness_percent){
        analogWrite(redPin, red*brightness_percent/100);
        analogWrite(greenPin, green*brightness_percent/100);
        analogWrite(bluePin, blue*brightness_percent/100);
    }

Here I used not the value range from 0 to 1 but instead in percent from 0 to 100. This is because floating point operations on Arduinos are rather time intensive (because the Arduino has no hardware for that and needs to do all that in software) so its better to multiply by the percent value and then divide by 100. So we have only integer calculations which is way faster. The outcome is the same.

Note: As the the color components get in the lower values you might see color errors due to the quantification. Though normally RGB LEDs aren't really color accurate either so probably you won't notice.


body:
I just created a simple simulation for the nice answer written.
Here is the code:

    int redPin = 9;
    int greenPin = 10;
    int bluePin = 11;

    void setup() {
      pinMode(redPin, OUTPUT);
      delay(500);
      pinMode(greenPin, OUTPUT);
      delay(500);
      pinMode(bluePin, OUTPUT);
      delay(500);
    }
    void loop() {
      colorRGB(255, 0, 0, 100); //Brightness level 100%
      delay(3000);
      colorRGB(255, 0, 0, 25); //Brightness level 25%
      delay(3000);

      colorRGB(255, 255, 0, 100); //Brightness level 100%
      delay(3000);
      colorRGB(255, 255, 0, 25); //Brightness level 25%
      delay(3000);

      colorRGB(255, 255, 127, 100); //Brightness level 100%
      delay(3000);
      colorRGB(255, 255, 127, 25); //Brightness level 25%
      delay(3000);
    }
    void colorRGB(int red, int green, int blue, int brightness_percent) {
      analogWrite(redPin, red * brightness_percent / 100);
      analogWrite(greenPin, green * brightness_percent / 100);
      analogWrite(bluePin, blue * brightness_percent / 100);

    }

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

i hope this is helpful. I am from the [Wokwi][2] team and I will welcome all your questions.
You can have a look at the Wokwi Arduino simulation link here:

https://wokwi.com/arduino/projects/313797447551812161

  [1]: https://i.stack.imgur.com/kOU4u.gif
  [2]: https://wokwi.com


message:
Hello, Please can someone assist me with in checking my code?..I try to generate a high freq signal (at least 150KHz) with Arduino Mega, CTC Mode

void setup() {
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A
      TCCR2B = TCCR2B & B11110000 | B00000001;//Prescaller set
      TCNT2=0;//Start Counting ffrom 0
      OCR2A=127;//Set TOP value)

    }

    void loop() {

    }

body:
```c++
TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A
```

What you have here clears `TCCR2A`'s `COM2A1` but preserves its original `COM2A0`.

When I print out `TCCR2A` prior to modification, I see a value of `0x01` (COM2A is 0; both bits of it).

Printing out `TCCR2A` after you've manipulated it 0x02.  So, in `TCCR2A`, you
are winding up with zeros for your `COM2A1` and `COM2A0` bits, which is all
cases is "Normal port operation; OC2A disconnected".  That is, you're not going
to see whatever signal you might otherwise have configured to generate because
it just hasn't been routed to the (Arduino pin 10)/(gpio PB4)/OC2A

It's usually better to not rely on the bootloader and the start code and the
Arduino core to have left a hardware register in a particular state.

The following is probably closer to what you intended:

```c++
TCCR2A = B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A
```

It's still not entirely correct to the problem description (not the correct frequency), but it does send a signal out of the Arduino MEGA's digital pin 10.  It also is configured to toggle OC2B, so unless you wanted that:

```c++
TCCR2A = B01000000 | B00000010 ; // CTC mode activated, Toggle OC2A
```

This can be made more readable by using the bit field names for the given:

```c++
TCCR2A =
   (1 << COM2A0)  // CTC mode activated (note COM2A1 is zero)
 | (2 <<  WGM20); // lower two bits of WGM value 2
```

You can do this same sort of thing for `TCCR2B`. And likewise, it is best that you don't rely on the previous value of `TCCR2B`.

With `OCR2A = 127;`, you are toggling (reaching a **half**-period) every 128/16,000,000 seconds, or a 8 uS half-period, for a 16 uS period. Generating 62.5 KHz, which is below your target 150 KHz.  Knowing it's half-periods, an `OCR2A` of 63 gets you to 125 KHz.

An `OCR2A` of 52 or less gets you into the greater than 150 kHz range, at least if we take your 16 MHz clock rate very seriously. You might need to be a little lower to be sure.


message:
Libraries are not linked

I created 4 libraries, each in .h and .cpp files, and tested them individually. I kept the project flexibility by defining 3 flags that allow or disallow the usage of the libraries.

When integrating them into project I received linking errors.
During the debugging I reduced it to minimum - a single .ino file that contains the minimal declarations and calls; but the error messages are still fired.

I looked at the shrunk code (only 63 lines!) and saw no issue. I'd appreciate any help in finding the issue.
[![enter image description here][1]][1]

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

The code:
```
#define RadioIncluded
#define IrrigationStation
#define RTCincluded

/********************************************/

#ifdef RTCincluded
  class rtcHighLevel
  {
    public:
      String rtcInterpreter(String cmd);
  };
  rtcHighLevel rtc;
#endif

#ifdef IrrigationStation
class measureEC
{
  public:
  void   initMeasurementStation ();
    String SD12_Parser (String commandLine);
};
  measureEC soilParams;

class valveControl
{
  public:
    void   valveInit();
};
  valveControl valve;
#endif

#ifdef RadioIncluded
  class LoRaAddClass
  {
    public:
      void   LoRaBegin(long BAND);
  };
  LoRaAddClass LoRaAdd;
#endif

/*********************************************************/
void setup() {
  Serial.begin(9600);
  while (!Serial) {};

#ifdef RadioIncluded
  LoRaAdd.LoRaBegin(915000000);
#endif

#ifdef IrrigationStation
  valve.valveInit();
  soilParams.initMeasurementStation();
#endif

#ifdef RTCincluded
  String s = rtc.rtcInterpreter("A");
#endif
}
/*********************************************************/
void loop() {}
```

body: Solved: while initially I devoted sub-directory for every class, no issues when all the classes were brought to the same folder with the INO file all the issues disappeared. Is this a known issue?


message:
Modifying the neopixel rainbow function to work with 4pins

So my setup is i have strips that is separated into 4 pins and would like to modify this rainbow function from the neopixel so that it will work on 4 separate strip that are on 4 separate pins. I would like to look like strip number 2 is a continuation of strip number 1 and number 3 is to 2 and number 4 is to 3. A very cool feature about this function is the start and end is a continuation so this mean i basically have a ring setup.

    void rainbow(int wait) {
      // Hue of first pixel runs 5 complete loops through the color wheel.
      // Color wheel has a range of 65536 but it's OK if we roll over, so
      // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
      // means we'll make 5*65536/256 = 1280 passes through this outer loop:
      for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
        for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
          // Offset pixel hue by an amount to make one full revolution of the
          // color wheel (range of 65536) along the length of the strip
          // (strip.numPixels() steps):
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
          // optionally add saturation and value (brightness) (each 0 to 255).
          // Here we're using just the single-argument hue variant. The result
          // is passed through strip.gamma32() to provide 'truer' colors
          // before assigning to each pixel:
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show(); // Update strip with new contents
        delay(wait);  // Pause for a moment
      }
    }

I do not understand how hue and gamma works so it a bit more tricky for me to modify this function.

Here is my attempt but my attempt is so crude and hoggs so much memory

    void rainbow(int wait) {

      unsigned int totalPixelCount = strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip4.numPixels();
      uint32_t pixelHueList [totalPixelCount];
      for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256) {
        for (int i = 0; i < totalPixelCount; i++) {
          int pixelHue = firstPixelHue + (i * 65536L / totalPixelCount);
          pixelHueList[i] = strip1.gamma32(strip1.ColorHSV(pixelHue));
        }

        unsigned int j = 0;
        for (j = j; j < strip1.numPixels(); j++)
          strip1.setPixelColor(j,pixelHueList[j]);
        for (j = j; j < strip1.numPixels() + strip2.numPixels(); j++)
          strip2.setPixelColor(j,pixelHueList[j]);
        for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels(); j++)
          strip3.setPixelColor(j,pixelHueList[j]);
        for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip3.numPixels(); j++)
          strip3.setPixelColor(j,pixelHueList[j]);

        strip1.show();
        strip2.show();
        strip3.show();
        strip4.show();
        delay(wait);
      }
    }

Is there a way to make it more efficient?

body:
Currently you are first filling an array with values from a calcuation by going through all LEDs; and then you are again going through all LEDs to actually set them. You can do that in one step. Also your current code will most likely not work, since you just count from zero to the total number of LEDs, but the individual strip doesn't know of that much LEDs. That will get you in problems with everything after the first for loop where you set the LEDs.

For doing it in one step and simultaneously solve the problem:

    void rainbow(int wait) {
      for (long firstPixelHue = 0; firstPixelHue < 5 * 65536L; firstPixelHue += 256) {
        int j = 0;
        for (int i = 0; i < strip1.numPixels(); i++){
          int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
          strip1.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
        }
        j = strip1.numPixels();
        for (int i = 0; i < strip2.numPixels(); i++){
          int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
          strip2.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
        }
        j += strip2.numPixels();
        for (int i = 0; i < strip3.numPixels(); i++){
          int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
          strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
        }
        j += strip3.numPixels();
        for (int i = 0; i < strip4.numPixels(); i++){
          int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
          strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
        }

        strip1.show();
        strip2.show();
        strip3.show();
        strip4.show();
        delay(wait);
      }
    }

Here I used `j` as an index over the whole chain of LED strips and `i` as an index for the individual LED strip. So `j` is the index starting point of each strip. The calcuation of the hue is then done with the current total index (`j` as the offset of the current strip in the whole chain and `i` as the index of the current LED in the current strip) `j+i`. For actually setting the corresponding LED we use `i` as the index of the current LED in the current strip.

This solution eliminates the need for creating an additional array. Though it still can be optimized (mostly in terms of code structure). I will leave that to you if you really want to optimize further.

Note: I haven't tested the above code, nor did I compile it.


message:
what is the maximum number of servo motors that can be connected to a l293d motor shield?

I have a requirement in which I need to run 2 motors and 6 servos.
The motors and servos won't be running simultaneously at any given time.
what best can I use. I Was hoping to use l293d shield as it powers 2 DC motors and 2 servos, but how do I get other 4 running too ?

I'm aware that l293d shield has 2 free pins pin2 and pin13 that I leverage for signal pins for servo. (am I right in this ?, if so, i'll still need 2 more free pins for signal)

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

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

body:
As to the [PDF Guide][1] on page 19:

>  How can I connect to the unused pins?
>
> The analog pins (analog 0-5 also known as digital pins 14-19) are broken out in the bottom right corner.
>
> Pin 2 has a small breakout since its the only truly unused pin
>
>The remaining pins are not broken out because they could be used by the motor shield. If you are sure
that you are not using those pins then you can connect to them by using stacking headers when
assembling the kit or soldering onto the top of the header with wires, or using a "Wing shield"

So you should have access to pins A0 to A5 (enough for 6 servos). You might need to solder a pin header in that place before you can actually use them.

The wording "Pin 2 [...] the only truly unused pin" is a bit weird, but if you follow the link to the schematics repo and look at [mshieldv12schem.png][2] (which seems to be the schematic just as an image, so you don't need to install Eagle for viewing it) it shows the Arduinos pins A0 to A5 only connected to the pin header and nothing else. This tells me that they are actually free.

  [1]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-motor-shield.pdf
  [2]: https://github.com/adafruit/Adafruit_Motor-Shield-v1/blob/master/mshieldv12schem.png


message:
In which package file is a default programmer selected?

After a clean IDE install, the programmer submenu already has a default option selected as shown below:
[![post of default selection][1]][1]

I am working on creating a core package and would like a default programmer to be selected after choosing a board, though I'm not sure which file sets the default. For example, here is a different 3rd party package that does *not* select a default programmer when a board is chosen.

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

  [1]: https://i.stack.imgur.com/9VoVN.png
  [2]: https://i.stack.imgur.com/ow90G.png

body:
The default preferences.txt file in IDE installation has this setting. It is not read from the boards package configuration files.

The `programmer` key in preferences.txt contains the last selected programmer. The default preferences.txt in lib folder in IDE installation  has `programmer = arduino:avrispmkii`. It is used if preferences.txt in Arduino15 folder doesn't exist or doesn't have the specific key.

With the recent change in Arduino IDE only programmers from boards package of the selected board are displayed, so it happens that no programmer is selected.


message:
5V alternative to Due?

I've designed a circuit controlled by an Arduino Mega 2560 involving a number of external components all running on and sending out 5V signals. I'm now realizing that the 8Kb of SRAM on the Mega 2560 is insufficient, so I wanted to upgrade to an Arduino Due.  The Due, however, can't accept the 5V outputs from the rest of the components.

Is there an Arduino compatible 5V board with memory comparable to the 96Kb on the Due?

I know that level shifting is an option, but considering that almost every digital input on the board is being used, I'd rather not have to add so many level shifters to the circuit.  A voltage-compatible board is preferred.

I'm also not fixed on Arduino-compatibility.  If there is another convenient microcontroller development board available, I'd gladly consider it.

**EDIT:**<br>
The Arduino is being used to read from a set of sensors that produce image data at a constant rate.  The data is recorded on the Arduino, then sent to a computer by USB.  The Arduino needs to store the whole image before sending it to the computer because performing a Serial write call delays the processor causing it to miss a data sample.  The ATMega2560 doesn't have enough SRAM to store the whole image at once.

body:
The Teensy 3.5 seems to be exactly what I was looking for.

[![Teensy 3.5][1]][1]

It is an Arduino-IDE-compatible 5V tolerant microcontroller board with a whopping 256Kb of SRAM and 64 digital inputs.  It pretty much blows away the Due in every way.

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


body:
The [Arduino MKR Connector Carrier][1] has input level conversion on analog inputs and logic level conversion on digital pins. It makes the 3.3 V MKR boards (SAMD21 MCU) compatible with 5 V sensors and actuators.

The SAMD21 on MKR boards has 256 KB internal flash memory and 32 KB SRAM.

  [1]: https://store.arduino.cc/collections/shields/products/arduino-mkr-connector-carrier-grove-compatible


message:
Wifi Scanning code for esp32 wroom 32

I am trying to scan wifi in sta_ap mode in my esp32 wroom 32 module but it is not scanning new wifi .Can anybody tell more about how does wifi mode works in this module and what's the problem in my code.Same code is working in esp8266.

CODE:
```
#include <WiFi.h>

const char *ap_ssid = "ESP32";
const char *ap_password = "";

const char *sta_ssid = "KKACT";
const char *sta_password = "kk25990418";
void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_AP_STA);
  WiFi.disconnect();
  delay(100);
  Serial.print("Configuring access point...");
  WiFi.softAP(ap_ssid, ap_password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(sta_ssid);
  WiFi.begin(sta_ssid, sta_password);

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

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

void loop() {
   Serial.println("Now scanning wifi continously");
   int n=WiFi.scanNetworks();
   for (int i = 0; i < n; ++i)
  {
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");

  }
    delay(2000);
}
```

body:
This is a issue raised on github about this:

https://github.com/espressif/arduino-esp32/issues/3294

And the issue seems to be that a failed connect prevent the scanning and the solution is:

> So what i did was when entering the portal:
>
>    `WiFi.mode(WIFI_OFF); // otherwise Wifi.Scannetworks() fails`
>
>    `delay(5000);`
>
>This seems to stop the processes that prevent the scanning.
>
>After that an immediate scan works without problems.