message:
Press one button then another?

Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?

body:
A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.

    enum EState
    {
      // Button 1 and 2 are not pressed
      NoButtonsPressed,

      // Button 1 is pressed, button 2 is not pressed
      FirstButtonPressed,

      // Both buttons are pressed
      BothButtonsPressed
    };

    EState _state;

    void setup() {
      // put your setup code here, to run once:
      _state = NoButtonsPressed;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      switch (_state)
      {
      case NoButtonsPressed:
        if (digitalRead(1) == HIGH)
        {
          _state = FirstButtonPressed;
        }
        break;

      case FirstButtonPressed:
        if (digitalRead(1) == HIGH)
        {
          // Button 1 is still pressed, ignore second button.
        }
        else if (digitalRead(2) == HIGH)
        {
          // Button 1 is not pressed, button 2 is pressed.
          _state = BothButtonsPressed;
        }
        break;

     case BothButtonsPressed:
       // Switch on LED
       digitalWrite(2, HIGH);

       // Reset state.
       _state = NoButtonsPressed;
       break;

     default:
       // Other state, illegal.
       break;
      }
    }

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.

Additional notes:

- Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
- I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
- I haven't tested the sketch.


sender: user

message:
Ways to add pins in an arduino

I'm making a project for school where I'm using flex sensors and converting that into words on an LCD (similar to the signing glove if you're familiar with that).
I ran into a problem since the Arduino I'm using doesn't have enough pins for all of my flex sensors and my LCD monitor.

I'm considering getting another Arduino with more pins but I might not have time to order it since my project is due in a couple of days. I was thinking about connecting two arduinos but I'm not sure if that would work (first year coding/engineering student) Any other suggestions as to how I can create more pins?

Your input is greatly appreciated!

The Arduino I'm using is a sparkfun redboard (it only has 6 analog pins and a separate place to plug in the LCD monitor which I connected to where it says ISP f you look on the link you will see what I'm talking about [SparkFun RedBoard - Programmed with Arduino][1]).

I'm using four flex sensors

[LCD][2]:

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

  [1]: https://www.sparkfun.com/products/13975
  [2]: https://learn.adafruit.com/assets/2358
  [3]: https://i.stack.imgur.com/HBsrR.jpg

sender: assistant

body:
This can be done with the existing board. LCD can be driven by only with the digital pins. Check the below link for the wiring diagram.

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

Since there are 6 Analog pins available, all flex sensors can be easily connected.

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


body:
This seems like a 1602 display. Note there are also I2C modules that connect to a 1602 making it possible to use it with only I2C wires (and VCC/GND).

See [I2C-LCD-interface][1] for a description, although there are many (similar) ones.

For the flex sensors you have 6 analog pins (hope that is enough). If not, than you need an external ADC (analog digital converter). Or connect a second Arduino and use I2C/SPI/Serial to transport the information from one Arduino to Another.

  [1]: https://opencircuit.nl/ProductInfo/1000061/I2C-LCD-interface.pdf


message:
Tinkercad but offline?

I have some issues with network and would like to work with arduino everywhere. I use Tinkercad which is great, but I would like to installit to my laptop and work without using WiFi. I couldn't find any "offline tinkercad" but maybe there are any similar programs where you can program AND write code inside.

body:
The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.

Here is a ref image:
[![enter image description here][1]][1]

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


message:
Reset Button not working + Can't Upload code , What is wrong?

I was testing and debugging a code I wrote for a robot with 3 stepper motors on  (**Arduino Uno + CNCShield V3 + a4988 stepper drivers**). I want to disable drivers at will. so I bypassed EN pin on 2 of a4988s to pin12 and pin13 of Arduino. (by defalut all EN pins of drivers are are connected to pin8 ) everything was ok but suddenly the Reset button is not working and I can't upload new codes to Arduino! I get this error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
    .
    .
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83
    Problem uploading to board.

but Arduino still is working with the last code that was uploaded to it!!! have I fried my Arduino? and Why is this happening?[![enter image description here][1]][1]

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

body:
Try manually resetting the board:

 - Before uploading, run Verify.
 - Hold the reset button and click Upload.
 - Release the reset button.

If that worked, your board's reset isn't fried, it just isn't receiving a reset via the serial cable. If it failed, either part of the board or MCU may be damaged; something attached to the board may be inhibiting the reset signal; or the software may have disabled the board's reset pin. In the latter case, see the Arduino StackExchange article, [How do I repurpose Arduino's reset button][1], for how this can happen and how to undo it if it has.

> Is here anything wrong with using pins 12 and 13?

I'm not familiar with stepper driver, but at a quick glance at its data sheet, and it's logic being 3.3v & 5 v compatible, I don't see any problem with connecting any of its logic to any of Arduino's logic pins (almost all of them). Since the driver also has a motor drive-voltage input for driving your motors, accidentally connecting an Arduino pin to a driver pin (or anything else) carrying the drive-voltage could - probably would - damage at least the connected pin driver in the MCU, and possibly other parts of it as well.

If your Arduino has a socketed Atmega chip, and since you already know another Arduino works as you expect it to, replacing the Atmega chip will be the quickest, cheapest & easiest fix. Just go over your wiring and make sure no motor drive voltages are connected to the Arduino board.

  [1]: https://arduino.stackexchange.com/questions/32378/how-do-i-repurpose-arduinos-reset-button


message:
Compute SHA256 of string and output to string

In my Arduino project I want to compute the SHA256 hash of a string and store the result to a string, and do this recursively many times (i.e. compute hash of hash of hash etc...). So my goal is to have a *reliable* function as follows:
<!-- language-all: lang-cpp -->

    String h(String input) {
    ...
    return output;
    }

where for example h("abc") would return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".

I downloaded this [library][1]
(from Tools->Manage libraries, it is also in [github][2]) and then ran the example in [TestSHA256.ino][3] which passes all the checks. However I'm stuggling to make my function work since the library doesn't have a specific example on how to compute and return a SHA256 hash.

I have been looking in function testHash_N() in TestSHA256.ino, which appears to create a hash (from struct TestHashVector data) and compare it with the precomputed hash (from struct TestHashVector hash[]).

The hash seems to be computed in lines 89-96 in TestSHA256.ino.  I just want to take the actual hash string result, so for testVectorSHA256_1  in the example, I would need to have a string = "ba7816bf....15ad" as the result.

I understand that this is related to memory referencing in Arduino but I'm not experienced so I'd be grateful if you helped me with this.

EDIT: My code snippet so far is as follows, but it doesn't output the correct hash..

    #include <Crypto.h>
    #include <SHA256.h>
    #include <string.h>

    #define HASH_SIZE 32
    #define BLOCK_SIZE 64

    char hex[256];

    char *hashvalue;

    SHA256 sha256;

    byte buffer[128];

    char *btoh(char *dest, uint8_t *src, int len) {
      char *d = dest;
      while( len-- ) sprintf(d, "x", (unsigned char)*src++), d += 2;
      return dest;
    }

    char* h(Hash *hash, char* hashvalue)
    {
        size_t size = sizeof(&hashvalue);
        size_t posn, len;
        size_t inc = sizeof(&hashvalue);
        uint8_t value[HASH_SIZE];

        hash->reset();
        for (posn = 0; posn < size; posn += inc) {
            len = size - posn;
            if (len > inc)
                len = inc;
            hash->update(&hashvalue + posn, len);
        }
        hash->finalize(value, sizeof(value));

        return(btoh(hex, value, 32));
    }

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

        bool tmp;
        char *testvalue = "abc";
        Serial.println(h(&sha256,*testvalue));

    }

    void loop()
    {
    }

  [1]: https://rweather.github.io/arduinolibs/classSHA256.html
  [2]: https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto
  [3]: https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestSHA256/TestSHA256.ino

body:
The main trick is to understand how the Arduino String class works. You can find the source code in your installation of the Arduino IDE or on github.

The basic pattern you are looking for is:

    String h(String& input) {      // Pass String by reference to avoid copying
      char output[OUTPUT_MAX];
      char* data = input.c_str();  // Access to internal buffer
      ...
      return String(output);       // Return a String object of the output
    }

Cheers!


body:
I suggest the following function. That replaces a string by its hash.
It's done in place in order to save memory. Make sure the buffer you
give it is at least 65 bytes long. **Warning**: not tested.

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

    #include <Crypto.h>
    #include <SHA256.h>

    #define HASH_SIZE 32

    SHA256 sha256;

    /*
     * Replace a string by its hash, in place.
     * `data' should point to a buffer at least 65 bytes in length.
     */
    hash_in_place(char *data)
    {
        uint8_t value[HASH_SIZE];

        sha256.reset();
        sha256.update(data, strlen(data));
        sha256.finalize(value, sizeof(value));

        // Convert to hex into the original buffer.
        data[0] = '\0';
        for (size_t i = 0; i < HASH_SIZE; i++) {
            data += sprintf("x", value[i]);
        }
    }


message:
Getting two trinkets to talk to each other via the serial pins

I'm trying to make a quick proof of concept of two trinket M0s talking to each other via their RX and TX pins and I'm not able to get it working.

I uploaded sender and receiver sketches to two trinkets:

```cpp
//sender.ino
char state[10] = "hello";

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

void loop()
{
    Serial.write(state, 5);
    delay(1000);
}

```

```cpp
//receiver.ino
char state[10];

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

void loop()
{
    Serial.println("reading bytes");
    Serial.readBytes(state, 10);
    Serial.println(state);
    delay(1000);
}
```

After the uploads I wired the two trinkets together, jumping the RX of the first to the TX of the other and TX of the first to the RX of the other. I also connected their grounds to have a common ground.

[![wiring][1]][1]

I plugged the sender into a battery and the receiver into my computer. The problem I'm running into is that when I look at the serial monitor for the receiver instead of getting the expected "hello" I'm getting broken strings of "TestingOpen":

[![serial output][2]][2]

I double checked [the pinout diagram and guide for the Trinket M0](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/pinouts) to make sure I was using the correct RX/TX pins (pin 3 for RX, 4 for TX) and it all seems fine but obviously something is still going wrong.

Anyone know what I'm missing or misunderstanding?

  [1]: https://i.stack.imgur.com/mUW8N.jpg
  [2]: https://i.stack.imgur.com/JyFj6.png

body:
1) you should use `if (Serial.available())` before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

    void loop()
    {
      if (Serial.available()) {
        Serial.println("reading bytes");
        size_t l = Serial.readBytesUntil('\n', state, 10);
        state[l] = 0;
        Serial.println(state);
      }
    }


message:
How would you add Arduino WiFi Module using I2C or serial interface?

I am new to Arduino prototyping. I bought an Arduino Automatic Smart Plant Watering Kit 2.0 thinking it was a shield to use with my Arduino Uno WIFI Rev 2.  However, it turns out to be a specially designed Arduino board with all of the components integrated together.

While the system works as designed, my goal is to stream the data to IBM Watson Studio, or some other third-party SaaS.

I welcome feedback to understand how it might be possible to integrate the ESP8266 WIFI module using either the I2C or Serial interface. Here is the sample code: [https://www.elecrow.com/download/watering_kit.zip][1] I used a Raspberry Pi to get access to the data and use it in a web/mobile application but I'd like to eliminate this element, if possible. [![enter image description here][2]][2]

  [1]: https://www.elecrow.com/download/watering_kit.zip
  [2]: https://i.stack.imgur.com/6quof.jpg

body:
You would connect the ESP8266 to the serial port.  The normal way of working with an ESP98266 is to issue AT command (like an old Hayes modem) through a serial connection. Since you have one of those available on your board it is a simple matter to just wire it directly to it.

Just follow any of the myriad of ESP8266 + Arduino tutorials, substituting the pins in the examples for your serial pins, and use the `Serial1` object instead of the `SoftwareSerial` class that you have to use on an Uno that lacks extra serial ports.


message:
DC motor phototransistor control

So basically I have a circuit with a phototransistor, and want to convert the phototransistor value into a PWM signal that can control the speed of the motor. The code I came up with is below, however it does not work. What have I done wrong in my code? I am using an l293d chip.

    int photoTran = A1;
    int reading = 0;
    int forward=2;
    int backward=3;
    int motorspeed=0;

    void setup(){
      pinMode(photoTran,INPUT);
      Serial.begin(9600);
      pinMode (backward, OUTPUT);
      pinMode (forward, OUTPUT);
    }

    void loop(){
      lcd.setCursor(0,0);
      reading = analogRead(photoTran);
      lcd.print(reading);
      lcd.print("  ");
      delay(100);
    {
      if (reading<30){
        digitalWrite(backward,HIGH);
        digitalWrite(forward,LOW);
        motorspeed = map(reading, 30, 1023, 0, 255);
        analogWrite(backward,motorspeed);
      }
      else {
        digitalWrite(backward,LOW);
        digitalWrite(forward,HIGH);
        motorspeed = map(reading, 30, 400, 0, 255);
        analogWrite(forward,motorspeed);
      }
      }
    }

body:
`analogRead()` returns an integer between 0 and 1023. Using 30 and 400 in the `map()` function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

    void setup(){

      Serial.begin(9600);

      // Prints -20 to 684
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 30, 400, 0, 255));
      }
      Serial.println();

      // Prints -7 to 255
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 30, 1023, 0, 255));
      }
      Serial.println();

      // Prints 0 to 255
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 0, 1023, 0, 255));
      }
    }

    void loop(){}


body:
If you are using l293d you must control the voltage on its ENABLE PIN rather than controlling it on other INPUT PINS (l293d). Here is simple tutorial on controlling the Motor using L293d. [here](http://www.ardumotive.com/how-to-use-the-l293d-motor-driver-ic-en.html).

And @VE7JRO is right about `map()` function as your are passing the values that are out of range please take care of that part as well.


message:
Display not showing output - Arduino Wattmeter

I have been playing with this code for some time now, I am able to show the results in an 16X2 LCD display, but I am not able to do it in an OLED.

here is the code

        #include <SPI.h>
        #include <Wire.h>
        #include "U8glib.h"  //Library for display

        U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

        int index = 0; //size of array
        const int number_of_readings = 200; //total number of readings arduino takes before it averages
        const int current_zero = 510; //initial value of current from arduino with 0 amps
        int current_reading[number_of_readings]; //create array for current_reading
        int voltage_reading[number_of_readings]; //create array for voltage_reading

        float R1=30000; //resistance of R1 in voltage sensor
        float R2=7500; //resistance of R2 in voltage sensor
        float current_average = current_zero; //initial value of current average
        float current_total = 0; //initial value of current_total
        float voltage_average = 0; //initial value of voltage_average
        float voltage_total = 0; //initial value of voltage_total

        int x = 0;
        int row = 0;
        float voltage = 0.1;

          void setup() {
           Serial.begin(9600);
           pinMode(A4,INPUT_PULLUP);
           pinMode(A5, INPUT_PULLUP);
          }

          void draw(void) {
           u8g.setFont(u8g_font_fub14r);
           {

           u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( Bat_Volt,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);

        }
        }

         void loop() {
          voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
          voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
          current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
          current_total = current_total + current_reading[index]; // add current to current_total
          index = index + 1;

          if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
            current_average=current_total/number_of_readings;
            voltage_average=voltage_total/number_of_readings;
            Serial.print("Current average=");
            Serial.print(current_average);
            Serial.print("   Voltage average=");
            Serial.println(voltage_average);
            current_total=0;
            voltage_total=0;
            index=0;

          }

          float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
          float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
          float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
          float power = (voltage*current); //calculate power

         u8g.firstPage();
          do {
            draw();
          } while( u8g.nextPage() );

        }

The function of the code is to read data from a "ACS712 - 30A Range Current Sensor Module" and a "Voltage Detection Sensor Module".
Display is a "0.96 inch 128x64 OLED Display Module - SPI/I2C - 7 Pin ", it is converted to I2C, and working with other codes.
Board : Arduino Uno
Max input voltage will be 12.8V, DC.
The code is supposed to display the voltage on top, ampere in the middle, and watt usage at the bottom.
But it is not working when edited for OLED display.

Someone please make this a working code.
I am new to C+ and coding , so need detailed help.

Here is the code that worked with 16X2 LCD

    #include <LiquidCrystal.h>
    #include <Wire.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    /*The circuits
     * LCD RS pin to digital pin 12
     * LCD enable pin to digital pin 11
     * LCD D4 pin to digital pin 5
     * LCD D5 pin to digital pin 4                                                             21333333
     * LCD D6 pin to digital pin 3
     *
     * LCD D7 pin to digital pin 2
     * LCD R/W pin to ground
     * 10K resistor
     * ends to +5V and ground
     * wiper to LCD VO pin (pin 3)
     */

    byte lightning[8] = {
      B00001,
      B00110,
      B01100,
      B11000,
      B00011,
      B00110,
      B01100,
      };

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total

    void setup (){
      Serial.begin (9600);
      lcd.begin(16,2); // size of LCD
      lcd.createChar(6,lightning); //create charecter named lightning

      //STARTUP MESSAGE
      lcd.setCursor (3,0); //set cusror to row 0, column 3
      lcd.print(" "); //lcdprint
      lcd.print("Arduino"); //lcdprint
      lcd.setCursor(1,1); //set cursor to row 1, column 1
      lcd.write(6); //lcd write charecter 6 (lightning bolt)
      lcd.print("Power Meter"); //lcd.print
      lcd.write(6); //lcd write charecter 6 (lightning bolt)
      delay(5000); //delay by 5 seconds
      lcd.clear();  //clear lcd screen
      }

    void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }
      float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      float power = (voltage*current); //calculate power

      lcd.clear(); //print voltage, current, and power values to LCD screen
      lcd.setCursor(0,0);
      lcd.print(voltage);
      lcd.print("V");

      lcd.print (" ");
      lcd.print(current);
      lcd.print("A");

      lcd.setCursor(0,1);
      lcd.print(power);
      lcd.print("W");
      delay(1);

    }

body:
In your Sketch

    void draw(void)
    {
       u8g.setFont(u8g_font_fub14r);
       u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( Bat_Volt,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);
    }

**current**, **power**, **Bat_Volt** are local variables define in `loop` function. **Bat_Volt** in not even defined in your sketch that's why they are not printing anything in `draw` function.

Initialize then as `global variable` in your sketch and in place if **Bat_Volt** you had use voltage here ` float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read` in your sketch.

Correct that to.

Your code after edit:

    #include <SPI.h>
    #include <Wire.h>
    #include "U8glib.h"  //Library for display

    U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total
    float voltage = 0.0,current_mV = 0.0,current = 0.0,power = 0.0;

    int x = 0;
    int row = 0;
    float voltage = 0.1;

      void setup() {
       Serial.begin(9600);
       pinMode(A4,INPUT_PULLUP);
       pinMode(A5, INPUT_PULLUP);
      }

      void draw(void) {
       u8g.setFont(u8g_font_fub14r);
       u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( voltage,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);
    }

     void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }

      voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      power = (voltage*current); //calculate power

     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }


message:
Power supply while using a shield

Sorry if this is a dumb question, I'm new to Arduinos. I'm planning to use a MOVI voice shield with SparkFun's RedBoard Turbo (3.3v). The RedBoard Turbo requires a power supply under 6VDC, but the MOVI website recommends a power supply of 9VDC to the Arduino, because the MOVI can't have its own power supply. Will this destroy my RedBoard? Or is this safe and just something you have to do when using shields? Thank you.

The product website says: "A 7V to 16V 500mA external power supply that powers MOVI™ through the Arduino board. The power consumption of both boards is just above what the USB port can provide. If you don't have already one, this 9V adapter from Adafruit will work perfectly."

body:
Although I have not used either SparkFun's RedBoard Turbo or the MOVI voice shield, reading the specifications, which you can find on their respective web sites, it would appear that they have incompatible power requirements.
The SparkFun's RedBoard Turbo board web page says

*The barrel jack connection on the RedBoard Turbo has a lower input voltage than most Arduino development boards. Make sure that you are using a power supply below 6V. Please be aware that the RedBoard Turbo is also a 3.3V device and not a 5V one like the original RedBoard.*

Whilst the MOVI voice shield PDF manual (page 7) says

*What you don’t see in Figure 1 is a power supply jack. MOVI is powered through the
Arduino board that needs to be powered using an external power supply. The external
power supply should provide between 7V and 16V and at least 500mA current. During tests
we usually used either 9V or 12V. Battery packs with this specification work as well.*

So the one needs less than 6V whilst the other more than 7V. I don't know if you can break the power connection between the two boards and feed the MOVI from a separate supply (9V is very common in the Arduino world) or you may have to swap your SparkFun for an Arduino that runs on 5V and uses a 9V supply.

The gotcha is that Arduino boards, their clones and code compatible boards such as the ESP32 etc fall into 2 different groups, those that run on 3.3V and those that use 5V, and you must be very careful you don't over voltage the latter.

I haven't delved into the specifications further, but you will almost certainly find that the logic levels used by the two boards are also incompatible. One will be using 0 & 5V whilst the other 0 & 3.3V. Connecting a 5V logic output to a 3.3V logic input is not conducive to long life and happiness for the latter.


message:
I2C interference SENSOR(SCL+SDA) and MasterSlave comm

I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

[![Arduino slave NodeMCU master][1]][1]

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.

When I enable `Wire.begin` for slave communication, my BMP280 readings go nuts
<!-- language-all: lang-cpp -->

 #include <Adafruit_BMP280.h>

 #define BMP_SCK 13
 #define BMP_MISO 12
 #define BMP_MOSI 11
 #define BMP_CS 10

 Adafruit_BMP280 bmp;

 // masterSlave
 #include <Wire.h>
 #define I2CAddressESPWifi 8
 ...

 void setup() {

  if (!bmp.begin()) {
   Serial.println("Could not find a valid BMP280 sensor, check wiring!");
   while (1);
  }

  // masterSlave - generates problem with BMP280...
  Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

> BMP280 Temp = -136.42 *C

> Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.

  // COMMENTED OUT FOR DEBUGGING
  //masterSlave - generates problem with BMP280...
  //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

> BMP280 Temp = 20.01 *C

> Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

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

body:
The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.

The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.

The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.


body: As per your descriptions, I'm answering here. There is a fact we forget about the load capacitance calculation for selecting I2C pull-ups. It's calculated when more than one slave and variant to distance. Check the jumpers and for pullups try 10k or 4.7K or better you can calculate. It's better to provide a small delay after the wire.begin() function to stabilize the module


body:
The solution I implemented uses the BMP280 sensor in SPI mode, connected as follows:

[![Breadboard scheme][1]][1]

with this code before `setup`

    #include <Adafruit_BMP280.h>
 #define BMP_SCK D5
 #define BMP_MISO D8
 #define BMP_MOSI D6
 #define BMP_CS D7

 //Adafruit_BMP280 bmp; // I2C
 //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
 Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

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


message:
How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?

The [`hid_keyboard`][1] example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the `F1` key, or keys with shift/control modifiers?

  [1]: https://github.com/adafruit/Adafruit_nRF52_Arduino/tree/master/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard

body:
Yo can use the `keyboardReport()` function to send key-codes with modifiers. Here is an example that will send an `!` by sending the keycode for `1` plus a shift key modifier...

        // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
        // press the keys consecutively,. it presses them simultainiously.

        // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

        uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
        blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

        // This release seems to be required. Without it, the last pressed key just repeats forever.
        blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188

...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212

Unfortunately the `hid_keycodes` example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...

https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928


message:
Aruino RTC using rtclib not understanding functions

I am missing something fundamental using RTClib.
When I use the rtc.adjust function to change the time in the RTC, I cannot get the updated time from the RTC, just increments a fixed time. I have searched for examples for what I need, and the same few samples of code keep getting quoted.

I want my code to set the RTC at compile to the system time, which it does,
then in the Loop I want to increment the hour.  In reality I will use a button for this, but for now I am just trying to understand how DateTime now = rtc.now and rtc.adjust work.  How to write to the RTC, how to read it back. I am missing something regarding these variables.

Two version of my code.  One with output showing the clock working, and one where the output is static, just increments the hour.

**This one works:**

    #include <RTClib.h>
    #include <Wire.h>
    int ArduinoHour;
    int ArduinoMin;
    int ArduinoSec;
    RTC_DS1307 rtc;

    void setup()
    {
      Serial.begin(250000);
      Wire.begin();  //sets up the I2C
      rtc.begin();   //initializes the I2C to the RTC

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
      }
        if (rtc.isrunning()) {
        Serial.println("RTC IS running!");
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }
    }
    void loop()
    {
      DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

      ArduinoHour = now.hour();
      ArduinoMin = now.minute();
      ArduinoSec = now.second();

      Serial.print("AT TOP");
      Serial.println();
      Serial.print("RTC Time");
      Serial.println();
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      Serial.print("Arduino Time");
      Serial.println();
      Serial.print(ArduinoHour, DEC);
      Serial.print(':');
      Serial.print(ArduinoMin, DEC);
      Serial.print(':');
      Serial.print(ArduinoSec, DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      //RTC increments when these are commented out. Does not when active
      //ArduinoHour = ArduinoHour +1;
      //rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

    }

Here is the output.  Looks fine:

    RTC IS running!
    AT TOP
    RTC Time
    11:38:3

    Arduino Time
    11:38:3

    AT TOP
    RTC Time
    11:38:5

    Arduino Time
    11:38:5

    AT TOP
    RTC Time
    11:38:7

    Arduino Time
    11:38:7

    AT TOP
    RTC Time
    11:38:9

    Arduino Time
    11:38:9

***This one does not Work:***
Now I try to simply increment variable ArduinoHour and then write it to the RTC using rtc.adjust. ***The only change are the two lines at the bottom are uncommented.***

    #include <RTClib.h>    //https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code
    #include <Wire.h>

    int ArduinoHour;
    int ArduinoMin;
    int ArduinoSec;

    RTC_DS1307 rtc;

    void setup()
    {
      Serial.begin(250000);
      Wire.begin();  //sets up the I2C
      rtc.begin();   //initializes the I2C to the RTC

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
      }
        if (rtc.isrunning()) {
        Serial.println("RTC IS running!");
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }
    }

    void loop()
    {
      DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

      ArduinoHour = now.hour();
      ArduinoMin = now.minute();
      ArduinoSec = now.second();

      Serial.print("AT TOP");
      Serial.println();
      Serial.print("RTC Time");
      Serial.println();
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      Serial.print("Arduino Time");
      Serial.println();
      Serial.print(ArduinoHour, DEC);
      Serial.print(':');
      Serial.print(ArduinoMin, DEC);
      Serial.print(':');
      Serial.print(ArduinoSec, DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      //RTC increments when these are commented out
      ArduinoHour = ArduinoHour +1;
      rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

    }

Here is the output, RTC time is not changing. I know I am doing something basically wrong with how I am updating the variables writing/reading from the RTC.  Can't figure it out.

    RTC IS running!
    AT TOP
    RTC Time
    11:41:54

    Arduino Time
    11:41:54

    AT TOP
    RTC Time
    12:41:54

    Arduino Time
    12:41:54

    AT TOP
    RTC Time
    13:41:54

    Arduino Time
    13:41:54

    AT TOP
    RTC Time
    14:41:54

    Arduino Time
    14:41:54

body:
If by "RTC time is not changing" you mean minutes and seconds frozen at the same value, then this is entirely of your doing.

Your sketch spends 99% of the time between the initial `rtc.now()` request

     DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

and the final `rtc.adjust()` call

    rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

This period is the period when your RTC is supposed to be "ticking", progressing forward.

But you actually store the original minutes and seconds values in `ArduinoMin` and `ArduinoSec` at the beginning of this period. And later, at the end of this period, you bash these values back into the clock. By doing this you forcefully *erase* whatever progress the clock made between these two lines. No wonder your minutes and second do not change.

This problem actually has no perfect solution. `RTC_DS1307` class (and, I suspect, the underlying RTC hardware) provide no means to change just the hours value without disrupting minutes and seconds. When you call `adjust()`, you have to set everything, which means that you will always somehow "disrupt" the whole clock.

In your sketch you can *minimize* the adverse effects by re-requesting the minutes and seconds values right before doing `adjust()`:

    //RTC increments when these are commented out
    ArduinoHour = ArduinoHour +1;
    now = rtc.now();
    rtc.adjust(DateTime(now.year(), now.month(), now.day(), ArduinoHour, now.minute(), now.second()));

Note, that I'm using your updated `ArduinoHour` values, but everything else comes from a just-refreshed `now` object.

This is still not perfect, since it still suffers from a race condition against a real-time clock, but it is better than what you had originally.


body:
This is the content of `ajust` method:
```
void RTC_DS1307::adjust(const DateTime& dt) {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)0); // start at location 0
  Wire._I2C_WRITE(bin2bcd(dt.second()));
  Wire._I2C_WRITE(bin2bcd(dt.minute()));
  Wire._I2C_WRITE(bin2bcd(dt.hour()));
  Wire._I2C_WRITE(bin2bcd(0));
  Wire._I2C_WRITE(bin2bcd(dt.day()));
  Wire._I2C_WRITE(bin2bcd(dt.month()));
  Wire._I2C_WRITE(bin2bcd(dt.year() - 2000));
  Wire.endTransmission();
}
```
You can write new `Hour` value directly to the clock without erasing other clock data:
```
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)2); // Hour location
  Wire._I2C_WRITE(bin2bcd(ArduinoHour));
  Wire.endTransmission();
```


message:
128x64 and pushButtons

Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons?
i have 5 screens.
btn1 is for display MainMenu and Selection.
btn2 and btn3 is for up and down scrolling
btn 4 and btn4 is for switching on/off and increase decrease values.

the problem which i encounter is related to btn2 and btn3.
i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).
~~~

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}
~~~

body:
First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.

About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.

E.g.suppose you want to have the following screens(a screen 'title/content' is shown in[], a button transition with ---(key)-->

    InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                                  |       ^     \---(left)----+
                               (down)    (up)
                                  v       |
                            MenuOption2Highlight---(right)-->MenuOption2Items
                                               \---(left)----+

To program this (roughly), create an enumeration for each menu page :

    enum EMenuPage
    {
   None,
     InitScreen,
     MenuOption1Highlight,
     MenuOption1Items,
     MenuOption2Highlight,
     MenuOption2Items
    };

Than create a current state for it as global variable:

    EMenuPage _eMenuPage;

And initialize it in Setup:

    _eMenuPage = None;

Create an enum for the keys :

    enum EKey
    {
  None,
     Up,
     Down,
     Right,
     Left
    };

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another,
or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.

In the loop, use a state transition diagram to program out the options :

    EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

 switch (_eMenuPage)
 {
 case None:
  InitScreen();
  break;

 case InitScreen:
  ProcessInitScreenKeys();
  break;

 case MenuOptions1HighLighted:
  ProcessMenuOptions1HighLightedKeys();
  break;

 ...
 default:
  // Illegal key
  break;
 }

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:

    void InitScreen()
 {
  _eMenuPage = InitScreen;

  // Show content on display.
 }

Also, you create a Process...Keys function to handle the keys. Like:

 void InitScreen()
 {
  EKey pressedKey = GetPressedKey();
  switch (pressedKey)
  {
  case Right:
   MenuOptions1HighLighted();
   break;

  default:
   // Ignore other keys
   break;
  }
 }

For another function it would look like:

    void ProcessMenuOptions1HighLightedKeys()
    {
  EKey pressedKey = GetPressedKey();
  switch (pressedKey)
  {
  case Down:
   MenuOptions1HighLighted();
   break;

  case Right:
   MenuOption1Items();
   break;

  default:
   // Ignore other keys
   break;
  }
 }

(Btw I did not check neither compiled the code).

Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.


message:
Can I use TCS34725 Color Sensor with Lilypad?

I have been trying to get TCS34725 color sensor working with LilyPad Arduino USB - ATmega32U4 Board but with no success. I am wondering if it possible? I have been using the following Sketch to try and get a reading but nothing appears in the monitor:
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include "Adafruit_TCS34725.h"

    /* Example code for the Adafruit TCS34725 breakout library */

    /* Connect SCL    to analog 5
       Connect SDA    to analog 4
       Connect VDD    to 3.3V DC
       Connect GROUND to common ground */

    /* Initialise with default values (int time = 2.4ms, gain = 1x) */
    // Adafruit_TCS34725 tcs = Adafruit_TCS34725();

    /* Initialise with specific int time and gain values */
    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

      if (tcs.begin()) {
        Serial.println("Found sensor");
      } else {
        Serial.println("No TCS34725 found ... check your connections");
        while (1);
      }

      // Now we're ready to get readings!
    }

    void loop(void) {
      uint16_t r, g, b, c, colorTemp, lux;

      tcs.getRawData(&r, &g, &b, &c);
      // colorTemp = tcs.calculateColorTemperature(r, g, b);
      colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
      lux = tcs.calculateLux(r, g, b);

      Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
      Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
      Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
      Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
      Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
      Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
      Serial.println(" ");
    }

body:
> Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).

Cheers!

Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


message:
Stack smashing protect failure ESP32 with Modbus RTU

I'm doing a project using an ESP32 TTGO with LoRa, the Max485 and a WELLPRO ADAM 8082 for Modbus communication. I'm trying to use the ESP32 as a master to and the ADAM as a slave.
I'm also using Node-RED to send the input signals (reading the digital inputs on the ADAM or sending signals to the digital outputs).
Whenever I send a signal there's no problem, the ADAM receives it correctly and sends the answer. But when my ESP32 receives the answer, I get the following error:
```
Stack smashing protect failure!

abort() was called at PC 0x400dc860 on core 1
```

I tried debugging my program and the error happens when my program comes back from the function that has my reading modbus loop.
I'm pretty new to Arduino, so I don't really understand what could be causing this stack overflow.

Here's my code.

My global variables:
```c
unsigned char ucSt[N_MAX];
int delayTime;

HardwareSerial modbusData(2);

WiFiClientSecure espClient;
PubSubClient client(espClient);
boolean bWifiConnected = false;

const byte button = PRG_BUTTON;
```

Modbus reading with loop:
```c
void vReadingModBus()
{
  int i, nCmpt = 0;
  unsigned int uiCRC;

  while (modbusData.available() > 0)
  {
    Serial.print("nCmpt: ");
    Serial.println(nCmpt);
    ucSt[nCmpt] = (unsigned char)modbusData.read();
    nCmpt++;
    delay(delayTime - 2);
  }
  if (nCmpt)
  {
    Serial.print("He llegit aquests ");
    Serial.print(nCmpt);
    Serial.println(" bytes: ");
    char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    client.publish(TEMA_RESPOSTA_MODBUS, szResposta);
    uiCRC = uiModRTU_CRC(ucSt, nCmpt - 2);
    if ((byte)(uiCRC >> 8) == ucSt[nCmpt - 1] && (byte)(uiCRC & 0xFF) == ucSt[nCmpt - 2])
    {
      Serial.println("Trama amb CRC correcte");
    }
    else
    {
      Serial.println("Trama amb CRC incorrecte");
    }
  }
  nCmpt = 0;
}
```

Modbus transmission:
```c
void vModbusTx(unsigned char *uc, int nLen)
{
  int i;

  Serial.print("Enviat: ");
  for (i = 0; i < nLen; i++)
  {
    Serial.print(uc[i], HEX);
    Serial.print(" ");
  }
  Serial.println();

  vModeTxRxRS485(RS485Transmit);
  delay(1);
  for (i = 0; i < nLen; i++)
  {
    modbusData.write(uc[i]);
  }
  delay(delayTime);

  vModeTxRxRS485(RS485Receive);
}
```

My setup:
```c
void setup() {
  Serial.begin(115200);    // U0_RXD:GPIO3, U0_TXD:GPIO1 (UART0)
  modbusData.begin(9600); // U2_RXD:GPIO16, U2_TXD:GPIO17 (UART2)

  pinMode(PRG_BUTTON, INPUT_PULLUP);
  pinMode(GPIO_R2, INPUT); // 39
  pinMode(SSerialTxControl, OUTPUT); // hardwired to GPIO_R2
  pinMode(LED, OUTPUT);

  vModeTxRxRS485(RS485Receive); // RS485Receive is a 0, and vModeTxRxRS485 controls the DE/RE bits for the Max485

  delayTime = 0;

  //Wire.begin(I2C_SCL_OLED);

  delay(1000); // give me time to bring up serial monitor
}
```

My loop:
```c
void loop() {
  boolean bButtonState = !digitalRead(button);
  static boolean bLastButtonState = bButtonState;

  // MODBUS READING LOOP
  vReadingModBus();

  if (!client.connected())
  {
    reconnect();
  }

  // BUTTON STATE CHECK
  if (bButtonState != bLastButtonState)
  {
    bLastButtonState = bButtonState;
    vDelayESP(50);
    if (!bButtonState)
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "UNPRESSED");
    else
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "PRESSED");
  }

  client.loop();
}
```

And finally here's an example of my program running and giving the error mentioned:

```
Connecting to WiFi network
Waiting for WIFI connection...
..............................................
Attempting MQTTS connection...connected
Message arrived [/clot/dam/biel/esp32/escriuModbus] 010F000000080111
Petició a ModBus:
010F000000080111
Mida: 8
ucSt[0] = 1
ucSt[1] = F
ucSt[2] = 0
ucSt[3] = 0
ucSt[4] = 0
ucSt[5] = 8
ucSt[6] = 1
ucSt[7] = 11
Enviat: 1 F 0 0 0 8 1 11 3E 99
He llegit aquests 8 bytes:
1 F 0 0 0 8 54 D
Trama amb CRC correcte

Stack smashing protect failure!

abort() was called at PC 0x400dc7d8 on core 1

Backtrace: 0x4008c800:0x3ffb1ef0 0x4008ca31:0x3ffb1f10 0x400dc7d8:0x3ffb1f30 0x400d1eed:0x3ffb1f50 0x400d23c0:0x3ffb1f90 0x400d513d:0x3ffb1fb0 0x4008879d:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:928
ho 0 tail 12 room 4
load:0x40078000,len:8424
ho 0 tail 12 room 4
load:0x40080400,len:5868
entry 0x4008069c

```

body:
tl;dr: The message probably means your function is overwriting its array:

A stack overflow is caused by a stack that grows downward into the allocated heap space, either causing damage to data within the heap, or code using that heap space causing damage to the contents of the stack.

But "stack smashing" refers to damage caused by function code writing past the bounds of an automatic local variable and damaging the stack contents, typically including the function's return address.

[Feel free to skip rather long explanation:]

A function's stack-frame begins with the return address - the address following the instruction that calls the function, i.e., the address of the next instruction to be executed after the function returns. Then, building downwards, the call parameters are put on the stack and become local variables. Then any variables allocated during the function execution are allocated, still building downward.

Assume one of those allocated variables is an array. Its zero-th element is in the lowest address of the allocated space, and subsequent elements are at successively higher addresses. If I start writing into the array, and continue past its length, I'll eventually overwrite other automatic locals, my parameters, and and my return address. Then, when the function tries to return, instead of jumping to the code that called the function, the MCU uses the damaged return address and jumps to ... ????

To catch this error, the compiler can insert code that 1) allocates and writes a "canary" - a known value - just after the return address, and 2), checks the canary for damage just before the function returns. If the canary has been altered, you get the message you saw, because it's likely that the return address will have been altered also. But regardless, the canary isn't part of your code and isn't accessible to it. Thus, it detects *writing-out-of-bounds errors*.

[End of wordy explanation]

Check the code in your function 'void vReadingModBus()' - my money is on the loop that writes into `szResposta[]`:

      char szResposta[N_MAX] = "", szByte[3];
        for (i = 0; i < nCmpt; i++)
        {
          sprintf(szByte, "X", ucSt[i]);
          strcat(szResposta, szByte);
          Serial.print(ucSt[i], HEX);
          Serial.print(" ");
        }

Update:

> If I understood correctly, it means szResposta must be overwriting the
> function's return address? How should I avoid this?

The short answer is make your array big enough for what you're going to put in it. But that's probably not a satisfying answer though, so let's take a closer look. I'm not sure exactly what your intent is in that loop, but since you print the `strcat()` result at every iteration and you don't seem to use `szResposta` after that, perhaps you meant to call `strcpy()` (replace the contents of the array) instead of `strcat()` (extend the contents of the array). If so, `strcat()` would quite likely write past the array bounds.


message:
esp8266 deep sleep timer slightly inaccurate?

I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets.  However, I'm getting output like this:

    08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
    08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
    08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
    08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
    08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
    08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
    08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
    08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
    08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
    08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
    08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
    08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
    08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE?  I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.

body: Yes a RTC can be very inaccurate. Some RTCs will let you synchronise them.


body:
A (now 3 year old) [GitHub thread][1] suggests using an external RTC if time tracking is of importance.  It also points at a dead NodeMCU document link.  That document appears to have [moved][2].  This document describes the lengths taken to provide a better account for time passage during sleep.  Which, apparently, includes guessing at the sleeping chip's temperature:

> Time keeping on the ESP8266 is technically quite challenging. Despite
> being named RTC, the RTC is not really a Real Time Clock in the normal
> sense of the word. While it does keep a counter ticking while the
> module is sleeping, the accuracy with which it does so is highly
> dependent on the temperature of the chip. Said temperature changes
> significantly between when the chip is running and when it is
> sleeping, meaning that any calibration performed while the chip is
> active becomes useless mere moments after the chip has gone to sleep.
> As such, calibration values need to be deduced across sleep cycles in
> order to enable accurate time keeping. This is one of the things this
> module does.

Update:

A recent [Arduino stack exchange answer][3] goes into detail using a DS3231 Real Time Clock.

  [1]: https://github.com/esp8266/Arduino/issues/2635
  [2]: https://gitlab.fionabuckner.xyz/fiona/nodemcu-firmware/blob/1.5.4.1-final/docs/en/modules/rtctime.md
  [3]: https://arduino.stackexchange.com/a/91504/78174


message:
How to connect L298N motor driver to 5v input supply?

I'm trying to connect 5v supply to a L298N motor driver at it's 12V-35V input pin but it's not working. If I'm connecting to 7.2V supply it's working. Is there any way to connect 5v supply? I want a constant 5v at output pins for motors.

body:
Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the [L298 datasheet](https://www.sparkfun.com/datasheets/Robotics/L298_H_Bridge.pdf) when listing the L298N I will assume they are reasonably equivalent.

I will assume that the "*12V-35V input pin*" is the V_S pin, despite that label. There are only two supply pins on the L298 with the following electrical characteristics:

 * V_S, Supply Voltage, pin 4, Operative Condition V_IH + 2.546V (max.: 46V)
 * V_SS, Logic Supply Voltage, pin 9, typical 5V (min.: 4.5V, max.: 7V)

with

 * V_IH, Input High Voltage, ranging from 2.3V to V_SS

Which would explain that the circuit works at 7.2V under the assumption that the logic inputs (enable A and B as well as inputs 1 through 4) are at close to 5V high levels. And here's the trick that might make it work: as noted V_S (the supply voltage) needs to be at a level of V_IH + 2.546V while V_IH could be as low as 2.3V and 2.3V + 2.546V < 5V. So driving the L298's logic inputs with a lower voltage for logic 1, i.e. closer to 2.3V high levels, could help.

Why is this? ([source](https://electronics.stackexchange.com/questions/40204/l298-h-bridge-not-working#comment1079863_195389)):

> [..] The actual restriction is that the motor supply be somewhat greater than the logic "1" input, but that need not match the logic supply. [..]

A warning though:

 * this circuit is now operating at the fringes, one might call it shady at best, intolerable at worst
 * saturation voltage is related to output current and other parameters, e.g. temperature, so this might work now under certain conditions and fails horribly another day

Therefore better bets are:

 * use a higher supply voltage
 * ditch the L298 and its high voltage drop Darlingtons and use a MOSFET H-bridge motor driver, such as the [TB6612FNG](https://www.sparkfun.com/products/14451), see [also](https://electronics.stackexchange.com/a/21225/52154)
 * ditch the L298 and use single bipolar transistors, depending on the output current

Other things to check:

Make sure V_SS is connected to the logic supply voltage (see [AnT's comment](https://arduino.stackexchange.com/questions/65535/how-to-connect-l298n-motor-driver-to-5v-input-supply#comment139637_65535)). Make sure GND of the Arduino's power supply is connected to the L298's GND.


message:
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?

Is it possible to modify the header file or use a different library?
I used the MouseTo library, but it wasn't the move I wanted.
We want to move as fast as possible to the relative coordinates, not as one pixel.
I've searched almost every community, but I haven't.
Give them a hand.

body:
For X and Y values between -64 and 64, consider multiplying the X and Y values you are passing to the method [mouse.move()][1] by 2.  In the above linked page, the example call to mouse.move() looks like this:

> mouse.move(xVal, yVal, wheel)

Consider writing it like this for twice the change in either direction:

> mouse.move((2 * xVal), (2 * yVal), wheel)

For values less then -128 or greater than 128, consider calling the method multiple times instead of once for each time it is desired to move the mouse.

A more difficult approach: You may also consider re-writing or adding to the Arduino mouse driver.  It appears the Arduino mouse driver is located [here][2].  As this is C++ you will need to change the definition of the "mouse" method as well as how you handle int as opposed to char sized variables.  In this case you can take advantage of the C++ Method Overloading feature.  That is, you can have 2 methods of the same name with different parameter types.  C++ will treat them as two individual methods.  So the original mouse.move method can remain untouched.  While the new mouse.move method will be able to handle type singed int instead of type singed char values.

  [1]: https://www.arduino.cc/reference/en/language/functions/usb/mouse/mousemove/
  [2]: https://github.com/arduino-libraries/Mouse


body:
[The USB HID protocol for mouse][1] is the limitation on sending more then a byte sized value for the mouse movement in one event.

You can't create a faster USB mouse. Repeat the call of the move() function. Of course you can use a function to call move() repeatedly to move to target destination.

    void mouseMove(long x, long y) {
      long max = max(abs(x), abs(y));
      int count = (int) (max / 127);
      signed char stepX = x / (count + 1);
      signed char stepY = y / (count + 1);
      for (int i = 0; i < count; i++) {
        Mouse.move(stepX, stepY);
      }
      signed char resX = x - (stepX * count);
      signed char resY = y - (stepY * count);
      if (resX != 0 || resY != 0) {
        Mouse.move(resX, resY);
      }
    }

  [1]: https://wiki.osdev.org/USB_Human_Interface_Devices#Report_format_2


message:
Two sensors using I2C

We have two sensor one of them([MPU6050-gyro][1]) is communicating using I2C, the other is via SPI(SD card reader). Now, we need an additional component as a sensor that [the barometer][2] which communicates via I2C.

Can we use all three modules without any problem? I wonder if two I2C modules is used in a hassle-free manner? Otherwise, what can be done?

  [1]: https://playground.arduino.cc/Main/MPU-6050/
  [2]: https://www.seeedstudio.com/Grove-Barometer-High-Accurac-p-1865.html

body: I2C is a bus. There can be many devices connected to that bus, each one having it's own address. Everytime you want to communicate with one of them, you have to send the address of the device. When you are using the `Wire` library, thats done by calling `Wire.beginTransmission()` or `Wire.requestFrom()`. Most slave devices have an adress, that is partly configurable, often by wiring special pins to Vcc or ground. Make sure, that every device on the bus has a unique address, or you will run into problems with corrupted data or a stuck bus.


body:
Yes, that's the idea behind bus protocols like i2c. You only require the sensors on i2c to have different bus adresses. A sensor's address usually can be chosen by soldering a jumper (the mpu6050 provides this feature on pin AD0). If you can't avoid an address collision you could use an i2c multiplexer or a microcontroller in between the sensor and the actual mcu (but probably that's not neccessary when using only two sensors).

Using SPI and I2C at the same time is absolutely no problem on the atmega!


message:
16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter

I'm using [Adafruit 16-Channel 12-bit PWM/Servo Shield][1] with Arduino Uno controller

In `setup()` I have a number of default positions with PWM commands for motors with plug of USB to PC and turning on

I'm trying to figure out, how to avoid `setup()` commands, or any other signals during process to servos, in case if shield is not powered from power adapter, which is 6V 8Amp in my case, to not send signal to servo while it is not powered by power supply

  [1]: https://www.adafruit.com/product/1411

body:
I would propose a circuit like the following:

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

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

<!-- End schematic -->

The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a `digitalRead()` on the corresponding digital input pin of your Arduino, to check, if the power was applied.

---

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.


message:
Reducing static on button reading

I have a very simple code for a controller I'm working on for a robot.
```
void setup() {
  // put your setup code here, to run once:
  pinMode(3,INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}
```
The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.

Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

body:
Sounds like you need a pull-down resistor.

If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.

Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.

If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.

(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting `INPUT_PULLUP` instead of `INPUT` when you configure the pin with the `pinMode()` function. That way you don't need an extra resistor.)

Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)


message:
how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees

I am currently working on a project which involves picking up plastic balls and depositing them in a box. I am trying to use a stepper motor to move an arm which is attached to a square piece of plywood which has Pringles cans on it. This is how I plan to collect the plastic balls.

The stepper motor needs to move the arm back and forth 180 degrees to collect and deposit the plastic balls. But I am unsure as to how to write the code to accomplish this as I am quite new to Arduino coding. Any form of help would be greatly appreciated. Thank you in advance.

body:
There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

 - Arduino,
 - stepper motor,
 - stepper motor driver (like [EasyDriver][1] or some kind of [Pololu drivers][2])
 - power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is **example of EasyDriver**). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply **when you do not use microstepping**). To spin motor 180 degrees you need 100 steps.
To summarise:

 - Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
 - DIR low (selecting one of directions)
 - STEP pulse 100 times (step motor rotates 180 degrees)
 - pause (for whatever needs to be done)

 - DIR high (opposite direction to rotate back)
 - STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)

  [1]: http://www.schmalzhaus.com/EasyDriver/index.html
  [2]: https://www.pololu.com/category/120/stepper-motor-drivers


message:
Looking for some help with an RGB LED animation

I'm working on a project that is running off of a Sparkfun Pro Micro 5V. I'm trying to accomplish a color rainbow cycle animation which will have a function when triggered to fade the rainbow to black and fade-in some white LED. I'm using a Adafruit RGBW Neopixel for this. I'm having trouble getting some code that does this as when I try to trigger my fade-out it's turning off faster than expected due to the way I wrote it. I'm hoping someone can point me to a piece of code or suggest an edit that will help.

Constraints for animation:

 - Must execute quickly (if at all possible avoid floats or other constructs that take a lot of time; relatively)
 - Be able to configure a maximum brightness set on initialization (0 - 255)
 - Must not have any "delay" or "while" loops that are designed to hold the code up.
 - When triggered by a button press the rainbow should fade to black (i.e. off) and previously off white LED should fade in.
 - When button pressed a second time white should fade out and rainbow starts or resumes.

I don't really care how the color animation works. It can cycle to/between specified colors or use whatever. To keep it simple what I tried was to have it just cycle RGB values with each 1/3 out of phase. My cycle includes a "dead" time where the color stays off for a part of the loop to keep the colors more distinct so they don't merge into white through color mixing. I specifically didn't use any sort of HSV conversion or sin/cos/whatever to calculate position in the cycle I am because those require a lot of calculation relative to incrementing a number.

Here is the code I wrote for your review. This has some servo control and the button checking and the LED in it. The bit at the very end is to prevent the pixels from updating during the time the servo pulses are being sent which prevents servo jitter due to the neoPixels.
<!-- language-all: lang-cpp -->
```
#include <Servo.h>
#include <Adafruit_NeoPixel.h>

#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8)

class ColorCycle {
  private: int maxB;
  private: int offH;
  private: int stepD;
  private: int curD;
  private: int rVal;
  private: int gVal;
  private: int bVal;
  private: int wVal;
  private: int rHold;
  private: int gHold;
  private: int bHold;
  private: int wHold;
  private: bool rDir;
  private: bool gDir;
  private: bool bDir;
  private: bool wDir;
  private: bool showWhite;

  public: ColorCycle(int maxBrightness, int offHold, int stepDelay) {
      maxB = maxBrightness;
      offH = offHold;
      rVal = gVal = bVal = wVal = 0;
      rHold = 0;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      wHold = 0;
      rDir = gDir = bDir = true;
      wDir = false;
      stepD = stepDelay;
      curD = 0;
    }

    void moveStep() {
      moveSteps(1);
    }

    void moveSteps(int count) {
      if (count == 1) { //going to skip the delay if you are trying to move more than one step intentionally.
        if (curD > 0) {
          curD--;
          return;
        }
        curD = stepD;
      }

      for (int s = 0; s < count; s++) {
        if (showWhite) {
          whiteHold();
          wDir = true;
        } else {
          wDir = false;
        }

        //setting the direction and holds when appropriate
        if (rVal == 0)
          rDir = true;
        if (rVal == maxB) {
          rDir = false;
          rHold = offH;
        }

        if (gVal == 0)
          gDir = true;
        if (gVal == maxB) {
          gDir = false;
          gHold = offH;
        }

        if (bVal == 0)
          bDir = true;
        if (bVal == maxB) {
          bDir = false;
          bHold = offH;
        }

        //stepping the values
        if (rDir && rHold == 0)
          rVal++;
        if (!rDir && rVal > 0)
          rVal--;
        if (rVal == 0 && rHold > 0) {
          rHold--;
        }

        if (gDir && gHold == 0)
          gVal++;
        if (!gDir && gVal > 0)
          gVal--;
        if (gVal == 0 && gHold > 0) {
          gHold--;
        }

        if (bDir && bHold == 0)
          bVal++;
        if (!bDir && bVal > 0)
          bVal--;
        if (bVal == 0 && bHold > 0) {
          bHold--;
        }

        if (wDir && wVal < maxB)
          wVal++;
        if (!wDir && wVal > 0)
          wVal--;
      }
    }

    int getRedValue() {
      return rVal;
    }
    int getGreenValue() {
      return gVal;
    }
    int getBlueValue() {
      return bVal;
    }
    int getWhiteValue() {
      return 0;
    }

    void setShowWhite(bool sw) {
      showWhite = sw;
    }

    void whiteHold() {
      rHold = 5;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      rDir = gDir = bDir = false;
    }
};

#define BUTTON_LED_PIN 16
#define BUTTON_SWITCH_PIN 14

Servo lidServo;
int lidServoPosition;
Servo leftServo;
int leftServoPosition;
Servo rightServo;
int rightServoPosition;

#define LID_LED_CONTROL_PIN 3
#define LID_LED_COUNT 8
Adafruit_NeoPixel lidPixel(LID_LED_COUNT, LID_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccLid(50, 50, 10);

#define BASE_LED_CONTROL_PIN 4
#define BASE_LED_COUNT 8
Adafruit_NeoPixel basePixel(BASE_LED_COUNT, BASE_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccBase(50, 50, 10);

void setup() {
  pinMode(BUTTON_LED_PIN, OUTPUT);
  digitalWrite(BUTTON_LED_PIN, LOW);
  pinMode(BUTTON_SWITCH_PIN, INPUT);
  lidServo.attach(5);
  leftServo.attach(6);
  rightServo.attach(9);
  lidPixel.begin();
  lidPixel.show();
  basePixel.begin();
  basePixel.show();

  Serial.begin(9600); //This pipes to the serial monitor
  Serial.println("Starting");
}

void loop() {
  if (digitalRead(BUTTON_SWITCH_PIN) == true)  {
    digitalWrite(BUTTON_LED_PIN, HIGH);
    lidServoPosition = 0;
    leftServoPosition = 0;
    rightServoPosition = 0;
    ccLid.setShowWhite(true);
    ccBase.setShowWhite(true);
  } else {
    digitalWrite(BUTTON_LED_PIN, LOW);
    lidServoPosition = 180;
    leftServoPosition = 180;
    rightServoPosition = 180;
    ccLid.setShowWhite(false);
    ccBase.setShowWhite(false);
  }
  lidServo.write(lidServoPosition);
  leftServo.write(leftServoPosition);
  rightServo.write(rightServoPosition);

  ccLid.moveStep();
  ColorCycle tempCc = ccLid;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    lidPixel.setPixelColor(i, lidPixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  ccBase.moveStep();
  tempCc = ccBase;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    basePixel.setPixelColor(i, basePixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  if (TCNT1 > usToTicks(8192)) {
    lidPixel.show();
    basePixel.show();
  };
}
```

body:
You are writing your code non-blocking, but you don't introduce any way of timing code. This way the calculation of the new color values happens as fast, as the code can run. You can write timed action in a non-blocking way by using the coding style from the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Then the LED code will only be executed, if the correct time has come. You save a timestamp of the last calculation execution in a global variable  and then check, if enough time since then has passed. Only then you again execute the calculation and update your timestamp.

    unsigned long timestamp = 0;
    unsigned int interval = 10;

    void loop(){
        //--------
        // Omitted the servo code
        //--------
        if(millis() - timestamp > interval){
            timestamp += interval; // update the timestamp to the next value
            //--------
            // Omitted the calcuation and the LED update (show() method)
            //--------
        }
    }

Note, that here I used `millis()`, which will return the number of milliseconds, that passed since the Arduinos startup. I used an interval of 10 milliseconds, so that the LEDs will be updated every 10 milliseconds. You can change this value as you need it (also during the code execution). If you need faster execution, than a few milliseconds, you can use `micros()` instead of `millis()`, so that you work with microseconds. Of course, you cannot get faster, than the rest of the code runs.

For further explanation of this principle, you can google it. It has been described numerous times on the web and on this site.


message:
Arduino yes! and after?

I am new to electronics and am currently working with an Arduino UNO. I know the basics of PCB manufacturing (Besides, I'm fiddling with mine, very basic of course) Anytime I'm curious about how to get from Arduino to a finished PCB with the same result only on my Arduino prototype?

For example, my project has several components such as leds, An RFID module, a TFT LCD Shield 3.5 ", another 240x320 OLED screen ... How to put all this on a printed circuit board?

Do I need to solder the same components to my PCB?
-Do I need to run my Arduino code on my PCB once it is assembled?
-.......................................

body:
A printed PCB can be used to place your components on (typically resistors, ICs, capacitors etc).

However, if you want to connect an LCD or big components, it would be a waste of space for your PCB. So in that case, I guess the best way is to create an enclosure where your displays fit in (and your RFID module if it is big too), and create some kind of connector from the PCB (e.g. using a terminal block or other way) and connect it to your displays.

On your PCB also an Arduino needs to be added, I guess the best solution is to use the Arduino chip (AtMega328P probably), and some external circuitry needed. Optionally using an IC socket in case you want to change the program later on.

On some Arduinos you can take out the AtMega328 DIP28 IC from your Arduino Uno board. Program it, than place it in the socket on your PCB board.

**Update**

Maybe you can use an Arduino Micro or Nano and place that directly onto your PCB (with headers preferably). Than you get something like below:

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

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


body:
" Optionally using an IC socket in case you want to change the program later on."
No need, put an FTDI header on for serial programming, or put an ICSP header on and use a Programmer to program via the SPI pins.

Making your own PCB is very straightforward. I use EAGLE CAD software and design boards all the time. To duplicate a Promini for example, one only needs a '328P, 16 MHz xtal, two 22pF caps, 4 0.1uF caps, and a 10K resistor.  Then the 2 headers for convenient bootloading and/or programming.  Bootload and program it just like it was an Uno.


message:
Why I am connecting positive wire in the circuit?

[![enter image description here][1]][1]I have constructed a simple fade in and fade out circuit similar to given on this website https://roboindia.com/tutorials/arduino-analog-output-led-fade Now I am connecting a wire from 5V power pins to +ve side line, but i don't know why I am doing this because when I remove this wire or connect it to 3.5V pin the led is still running fine. Also as side lines are connected horizontally there is no other further connection given to the +ve wire. Can you tell me why I am joining the wire?

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

body:
This is indeed not needed. As you can see in the diagram, the horizontal line which you connected the 5 V pin to.

The horizontal line of holes just above the red horizontal line) are connected. However, since it only connected to the 5V pin of the Arduino, the all pins on that horizontal line have 5 V, but since there is nothing connected to it (thus no closed circuit), the effect is zero.

The reason why the connection is made (the wire from Arduino to 5V), is that it is 'default' to connect both GND and 5V (or 3.3V) as a starting point. It is easy to forget later and than no current will flow when you connect something to the +5 V horizontal line of pins.

Btw, the 3.5 V pin you mention, is 3.3 V, not 3.5 V.


message:
Code for two bulb fading alternatively

I have written this code

    const int A = 3;
    const int B = 5;
    void setup() {
      pinMode(A, OUTPUT);
      pinMode(B, OUTPUT);

    }

    void loop() {
      for(int i=1;i<=255;i++)
      {
        int j =255-i;
        analogWrite(A,i);
        analogWrite(B,j);
        delay(100);
      }
      for(int i=255;i>0;i--)
      {
        int j =255-i;
        analogWrite(B,j);
        analogWrite(A,i);
        delay(100);
      }
    }
Is  this code correct? If yes then can it be modified in any way to make it better?

body:
To keep the two loops more symmetrical, let the first loop go from 0 until 254: [0 .. 255) and the second loop from 255 to 1: [255 .. 0), so both iterations have 255 values each.

Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: [start_element .. end_element).

Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.

Than you get:

    const int A = 3;
    const int B = 5;

    const int MIN_INTENSITY = 0;
    const int MAX_INTENSITY = 255;
    const int DELAY_TIME    = 100;

    void setup() {
      pinMode(A, OUTPUT);
      pinMode(B, OUTPUT);
    }

    void loop()
    {
      for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
      {
        analogWrite(A, i);
        analogWrite(B, MAX_INTENSITY - i);
        delay(DELAY_TIME);
      }

      for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
      {
        analogWrite(B, MAX_INTENSITY - i);
        analogWrite(A, i);
        delay(DELAY_TIME);
      }
    }

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:

    const int LED_1_PIN     =   3;
    const int LED_2_PIN     =   5;

    const int MIN_INTENSITY =   0;
    const int MAX_INTENSITY = 255;
    const int DELAY_TIME    = 100;

    void setup()
    {
      pinMode(LED_1_PIN, OUTPUT);
      pinMode(LED_2_PIN, OUTPUT);
    }

    void loop()
    {
      fade(MIN_INTENSITY, MAX_INTENSITY,  1);
      fade(MAX_INTENSITY, MIN_INTENSITY, -1);
    }

    void fade(int startIntensity, int endIntensity, int stepValue)
    {
      for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
      {
        analogWrite(LED_1_PIN, intensity);
        analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
        delay(DELAY_TIME);
      }
    }


message:
RGB LED circuit problem

I have written the following code for RGB LED:-

    const int RED =11;
    const int GREEN = 10;
    const int BLUE= 9;
    void setup() {
      pinMode(RED,OUTPUT);
      pinMode(GREEN,OUTPUT);
      pinMode(BLUE,OUTPUT);
    }

    void loop() {
      analogWrite(RED,0);
      analogWrite(GREEN,255);
      analogWrite(BLUE,0);
      delay(1000);
    }
Now according to my understanding if I run the above code then only  pin named `GREEN` i.e. 10th pin will give me current not 9, 11th pin. But when I upload the code and run it I see that 9 and 11 pin are giving me current not 10th pin as it is supposed to. Is there a problem in my code? I have checked my circuits are correct. To check current I took jumper wire that was connected to one of my colour and tried inserting it's other end at pins(9, 10 or 11) of Arduino board. If there is current bulb will glow. For above code the bulb was glowing when I inserted the wire at 9 and 11th pin.

body:
A common anode RGB LED can be sketched in a schematic like this:

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

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

<!-- End schematic -->

The positive voltage has to be applied to the top, for all the LEDs together. To light the LEDs up, you have to sink the current on the other end, meaning providing ground level at the bottom of that schematic at the corresponding pins. The current will then flow from your 5V pin, through the LEDs into the Arduinos pin.

That means, that `analogWrite(pin, 0)` will turn the LED on that pin ON and `analogWrite(pin, 255)` will turn the LED OFF. The logic is inverted here, because the Arduinos output pin is on the other side of the LED.

So your circuit and code work perfectly, you just didn't expect the inverted logic.

---

Note: The pins of the Arduino can only source/draw a certain amount of current (20mA continuously, 40mA at maximum) without getting damaged. A single, not too strong RGB LED should be OK, but as soon, as you want to drive more LEDs, you should consider using a driver circuit (for example simple transistors). That way the output pins don't have to provide the LEDs current, but only the current to control the transistor.


message:
Is there a digital/ultrasonic Anemometer for Arduino?

I use Arduino DUE and I noticed that many forum users use the TX-23U Wind Sensor.

https://www.amazon.com/Crosse-Technology-TX-23U-Weather-Stations/dp/B0016MYA7U

Also, many people tried to create a DIY ultrasonic anemometer like this;
https://soldernerd.com/category/arduino-ultrasonic-anemometer/

Instead of using the DIY ultrasonic anemometer, I wanted to purchase one but I couldn't find one.

Is there an ultrasonic anemometer which I can purchase and connect it with my Arduino DUE?

3.3V power, non-mechanical rotation, I2C/SPI/UART support are the requirements. Thanks.

body:
Frame challenge: pick a sensor that complies with your needs and specification - especially the performance characteristics you're interested in, e.g. range of wind speed to measure, required accuracy and resolution, response time and data acquisition rate, to name just a few. Don't look for something specific to Arduinos to not unnecessarily narrowing down your options. Then design or adapt an appropriate interface to make them both work together.

Common interfaces of "industrial grade" ultrasonic anemometers (e.g. [1] and [2]) are RS232/RS422/485, so technically UART, though in need of level shifters or a RS-485/RS-422 transceiver, e.g. [Maxim](https://www.maximintegrated.com/en/products/interface/transceivers/rs-485-rs-422-transceivers.html). Some also offer analogue output that might be feed into an Arduino's analogue in after matching voltage levels.

I would assume that I2C/SPI are rather uncommon as these are for short-distance, intra-board communication not for connecting a separate sensor module.

The same thought applies to the power supply, I recommend to drop the requirement of powering the sensor with 3V3 put rather select a power supply for a sensor available and affordable. The anemometers available at the linked vendors typically list a supply voltage of 5-30VDC or 6-24VDC.

 [1]: https://www.thiesclima.com/en/Products/Wind-Ultrasonic-Anemometer/
 [2]: http://gillinstruments.com/products/anemometer/anemometer.htm


body:
You can see this one: SONIC-ANEMO-MICRO
https://lcjcapteurs.com/en/girouette-anemometres-capteur-vent/sa-micro-2/


message:
Error compiling for any board arduino ide 1.8.9

my arduino ide Until yesterday it worked properly . but today All previous projects   dont compiling and all of them have one error : Error compiling for  board
and It's no different that Which board I choose in all of board i have this error .
please help me .

image link : http://uupload.ir/files/6hjr_capture1.jpg
error : * Error while detecting libraries included by C:\Users\ali_m\AppData\Local\Temp\arduino_build_706504\sketch\timer.ino.cpp

* xtensa-lx106-elf-g++: error: CreateProcess: No such file or directory

* Error compiling for board NodeMCU 1.0 (ESP-12E Module).

body:
I hope this [link][1] helps you or please try a fresh install.

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


message:
Atmega328p and cp2102 with error avrdude: stk500_getsync(): not in sync: resp=0x00

I recently bought a usb/ttl cp2102 converter for testing with a standalone Atmega328p, I made the DTR connection with the pin 1 in the Atmega  using a ceramic capacitor of 0.10uf (104) so that when I send my code to my Atmega standalone it save the code without having to worry about the reset. However, when trying to send it the first time it worked and the other attempts failed, it seems that whenever I restart the computer and turn it on again it sends the code to the Atmega and in the other attempts it fails.
To try to solve I tested with IDE Arduino 1.8.5 and 1.8.9 in Linux Mint and Windows 10 and gave the same problem, I recorded the bootloader again and did not solve.

The error that appears in the output of the IDE is this:

```
avrdude: stk500_getsync(): not in sync: resp=0x00
```

From what I read, this error is generic and hardly helps to solve the error.

body:
Researching a little and found the solution! In addition to capacitor 104, its necessari need to add a 10k resistor by connecting the 5 volts to pin 1.

This is the link of the GitHub project where I found the solution with the assembly scheme, I hope this helps somebody else!

https://github.com/leonvandenbeukel/Arduino-on-a-breadboard/blob/master/README.md