message:
Dice is not showing the correct numbers

I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?

    #include <LiquidCrystal.h>
    // select the pins used on the LCD panel
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    #include "DFRkeypad.h"
    String line2 = "Press Select to roll"; // Scrolling line

    // just some reference flags
    //int stringStart, stringStop = 0;
    //int scrollCursor = screenWidth;

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    // read the buttons
    int read_LCD_buttons()
    {
      adc_key_in = analogRead(0);      // read the value from the sensor

      // For V1.0 comment the other threshold and use the one below:

      if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
      for speed reasons since it will be the most likely result
      // For V1.1 us this threshold
      if (adc_key_in < 50)   return btnRIGHT;
      if (adc_key_in < 195)  return btnUP;
      if (adc_key_in < 380)  return btnDOWN;
      if (adc_key_in < 555)  return btnLEFT;
      if (adc_key_in < 790)  return btnSELECT;

      return btnNONE;  // when all others fail, return this...
    }

    void setup() {
      randomSeed(analogRead(1));
      lcd.begin(16, 2);              // start the library
      lcd.setCursor(3, 0);
      lcd.print ("Catan Dice");
      lcd.setCursor(0, 1);

      // while(line2)
      //
      // lcd.print(line2);
      // break;
    }

    void loop() {

      //Dice
      byte DiceOne = random(1, 7);
      byte DiceTwo = random(1, 7);

      //local varables
      int buttonState = read_LCD_buttons(); // read the button pad
      int lastButtonState = btnNONE; // previous state of the button

      // the following variables are unsigned longs because the time, measured in
      // milliseconds, will quickly become a bigger number than can be stored in an int.
      unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
      unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

      switch (buttonState)
      {
        case btnSELECT:
          lcd.clear();
          //Row, Colum
          lcd.setCursor (0, 4);
          lcd.print(DiceOne);
          lcd.setCursor (1, 4);
          lcd.print(DiceTwo);
          break;
      }

      DELAY(100)

      // read the state of the switch into a local variable:
      int reading = digitalRead(buttonState);

      // check to see if you just pressed the button
      // (i.e. the input went from LOW to HIGH), and you've waited long enough
      // since the last press to ignore any noise:

      // If the switch changed, due to noise or pressing:
      if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
      }

      if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer than the
        debounce
        // delay, so take it as the actual current state:

        // if the button state has changed:
        if (reading != buttonState) {
          buttonState = reading;
        }
      }

UPDATE, i got it working now

body:
It seems that your issue is probably connected with LCD timing. Sending data to LCD requires a precise timings, and the onboard chip of the LCD module very much like a few milliseconds of time to finish processing the data sent, instead you pass the entire clear and draw command each loop cycle.

I used the default Tinkercad LCD display example.
This code works fine:
```c++
#include <LiquidCrystal.h>

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

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);
}

void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  delay(100);
}
```
[![tinkercad example][2]][2]

but as soon as I remove the `delay(100)`
```c++
void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  //delay(100);
}
```
Weird things start to show on the LCD.

[![incorrect number displayed][1]][1]

Try rewriting your code that the commands are sent to LCD only once per button press.

  [1]: https://i.stack.imgur.com/J2gpv.png
  [2]: https://i.stack.imgur.com/0npPk.png


sender: user

sender: assistant

body:
You are calling setCursor() with:

    //Row, Colum
    lcd.setCursor (0, 4);
    lcd.print(DiceOne);
    lcd.setCursor (1, 4);
    lcd.print(DiceTwo);

While your comment notes the order is `Row`, `Column`, there appear to be several LiquidCrystal libraries floating about, some of which use `Column`, `Row` order in the `SetCursor()` function. The [official Arduino library source][1] indicates the `col`, `row` order.

You are writing both values on row 4 (even though that doesn't exist on your display), and in columns 0 and 1, thus you are correctly computing the Dice values, but they are being written with no gap between.

  [1]: https://github.com/arduino-libraries/LiquidCrystal/blob/master/src/LiquidCrystal.cpp#L188


message:
I want to print onto serial monitor when it's detected the value change

This code is measuring distance from object by using the Ultrasonic Sensor and print onto serial monitor.

However, serial monitor constantly output values.
I want to print only one time if detected value not change.
and serial monitor print again only when detected value change.
and The above condition keeps repeating.

How can i change the code?

    int distance ;
    int trig = 3;
    int echo = 2;

    void setup()
    {
      Serial.begin(9600);
      pinMode(trig, OUTPUT);
      pinMode(echo, INPUT);
    }

    void loop()
    {
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      distance = pulseIn(echo, HIGH) / 58;
      Serial.println(distance);
    }

body:
    int distance;
    int last_distance; // <== To hold the value from the previous pass
    int trig = 3;
    int echo = 2;

    void setup()
    {
      Serial.begin(9600);
      pinMode(trig, OUTPUT);
      pinMode(echo, INPUT);
    }

    void loop()
    {
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      distance = pulseIn(echo, HIGH) / 58;
      if (distance != last_distance) {  // <== Check if new distance is different
        Serial.println(distance);       //     Print only if the values are different
      }
      last_distance = distance;         // <== Store this loop's distance for next round
    }


message:
Can you connect BH1790GLC and TMP117 sensors to an Arduino board?

I would like to use those two components for an upcoming project :

 - [BH1790GLC heart rate sensor](https://www.rohm.com/datasheet/BH1790GLC)
 - [TMP117 temperature sensor](http://www.ti.com/product/TMP117)

I especially like the fact that they’re so tiny.

Could I connect them directly to an Arduino board or some other well-known microcontroller ?

body:
Yes, the sensors will work with microcontroller(s). What you look for is the **interface** they use. In this case it is **I2C** interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

 - Choose 3V powered microcontroller
 - Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


message:
mBlock update firmware

Total Arduino newbie here.
I was playing with mBlocks, with the Arduino Uno extension enabled. That extension offers you to "update firmware" which I accidentally did. What exactly is this firmware? Is it just a compiled sketch or does it alter stuff like bootloader or reside permanently in the memory?

body: Usually by Firmware we understand "a program that was prepared by company that produced the hardware and that is necessary for that hardware to work correctly". I suppose that developers of mBlock are smart enough not to allow people to "brick" their Arduino's. I suspect that ether you updated your bootloader (it's also a firmware) to latest version or simply nothing happened. In both cases your device should be operational. Burning a bootloader onto an Arduino is not as hard as it seems so even if you broke something you should be able to fix it.


message:
ESP8266 seems to be bricked , how to recover?

In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.

Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.

When I connect to module with boad-rate 74880 chip returns
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)
please check what happens when I try to upload the code [upload error][1]

  [1]: https://hastebin.com/oxeyuqeyib.rb

body:
No, your sketch can not brick the device in that way. It's the bootloader that decides after a reset/power-up whether the esp has to accept a firmware (flash button is pressed) or has to run the uploaded sketch. At that point, nothing of your sketch has yet been executed and gpios have their default configuration, which is input anyway.

Also, when a pullup is in charge, one can still apply a logic level to the respective pin. The gpio then won't see any effect from the pullup.


body:
No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.

You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.

The boot sequence of the ESP8266 is as follows:

    - Start executing the bootloader from the built-in ROM
      - Read the GPIO pins to determine code execution source
      - If flash is selected then initialize flash chip and read from address 0
        - Code on flash examines partition table to find code entry point
        - Jump to code entry point
      - If UART is selected then initialize UART
        - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.

You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.

However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.

So chances are that if you *have* bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.


message:
How to manage button state

Extreme Newbie here ...I am using an Arduino Uno and a PCA9685 16 Ch. Driver board to control servos using a push button and LED feedback.  When I pust the button, the servo move but when I release the button, the servo move back to it original position.  What I would like to have happen is that when I push the button once, the servo moves and holds its position.  When I push the button again, return to its starting position.  Thanks in advance for the assistance.

Here is the sketch:

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    int buttonPin0 = 2;   // Can add as many buttons as needed
    int ledPin0C = 3;     // C designates Closed position of turnout
    int ledPin0T = 4;     // T designates Thrown position of turnout
    int buttonState0 = 0;

    int buttonPin1 = 5;
    int ledPin1C = 6;
    int ledPin1T = 7;
    int buttonState1 = 0;

    void setup() {
        Serial.begin(9600);
        Serial.println("pca9685_TurnoutFinal!");
        pwm.begin();
        pwm.setPWMFreq(60);
        delay(30);

        pinMode(ledPin0C, OUTPUT);
        pinMode(ledPin0T, OUTPUT);
        pinMode(buttonPin0, INPUT);
        pinMode(ledPin1C, OUTPUT);
        pinMode(ledPin1T, OUTPUT);
        pinMode(buttonPin1, INPUT);
    }

    void loop() {
        ///////////
        buttonState0 = digitalRead(buttonPin0);
        if (buttonState0 == HIGH) {
            pwm.setPWM(0, 0, 370);
            digitalWrite(ledPin0T, LOW);
            digitalWrite(ledPin0C, HIGH);
        }
        else {
            pwm.setPWM(0, 0, 285);
            digitalWrite(ledPin0C, LOW);
            digitalWrite(ledPin0T, HIGH);
        }
        //////////
        buttonState1 = digitalRead(buttonPin1);
        if (buttonState1 == HIGH) {
            pwm.setPWM(1, 0, 370);
            digitalWrite(ledPin1T, LOW);
            digitalWrite(ledPin1C, HIGH);
        }
        else  {
            pwm.setPWM(1, 0, 285);
            digitalWrite(ledPin1C, LOW);
            digitalWrite(ledPin1T, HIGH);
        }
        //////////
    }

body:
The code in loop is always running so when you release the button, the code sees this as digitalRead(btn) = HIGH.

You need a state variable to know where the motor is currently.  Something like this:

    boolean state = false;
    int oldButton = HIGH;

    void loop() {
        delay(20); // enough to debounce very most buttons

        int newButton = digitalRead(buttonPin0);
        if (oldButton == HIGH && newButton == LOW) { // only when button changes from "released" to "pressed"
            state = !state;

            // tell the servo where to go
            if (state) {
                pwm.setPWM(0, 0, 370);
            } else {
                pwm.setPWM(0, 0, 285);
            }
        }
        oldButton = newButton;
    }


message:
How to use more than 2 I2S microphones on MKR Zero?

I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.

body:
By definition, the I2S bus only allows up to 2 channels to be transmitted at the same time.  Here is a quote from the [Details section][1] of the Wikipedia's [I2S page][2]:

> The word select clock lets the device know whether channel 0 or
> channel 1 is currently being sent, because I²S allows two channels to
> be sent on the same data line.

This is further illustrated in Figure 8 / Page 6 of the [Knowles SPH0645LM4H data specifications][3].  In this figure we see where 2 SPH0645LM4H microphones are configured (ground or Vcc to the SEL pin 2) such that they can be multiplexed onto the I2S bus by the I2S bus master.

  [1]: https://en.wikipedia.org/wiki/I²S#Details
  [2]: https://en.wikipedia.org/wiki/I²S
  [3]: https://media.digikey.com/pdf/Data Sheets/Knowles Acoustics PDFs/SPH0645LM4H-B.pdf


message:
Can 1 wiegand output for 2 controllers?

recently I have this project which needs to read 2 wiegand signal using Arduino Mega 2560.

I have an access control device which will output wiegand signal once the user is allow to enter, and there's a RFID reader which will transmit the card no in wiegand signal to my access control device.

So I need to get card no from the RFID reader and also from the Access control device, so I connect them like the attachment given, using a library here: ( https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino ), everything works fine at first, but once a while, I can't read signal from the RFID Reader, and sometimes I can. Could anyone let me know why is this happening?

[![Can 1 wiegand output for 2 controller?][1]][1]

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

body:
There is missing information.  Assuming a 5V Arduino and all D0s and D1s swing from 5V to 0V as the Wiegand protocol defines.  This despite the 12V power supply in the question's diagram.

Examining the [driver code on GitHub][1], we see it's [falling edge interrupt][2] driven.  So any noise when the line is expected to be at a steady 5V will cause the driver to run.  And there are a number of locations in the code where data is dumped because it is considered bad. It appears that any unexpected noise during a valid signal will cause missing data.

Consider the possibility of noise affecting the RFID data.  Shorten the length of the RFID's Wiegand cable in an effort to improve the RFID reliability.

Consider re-writing the driver code to improve noise rejection.  Currently, it appears the driver code will accept any falling edge as valid data to be processed.  Alternatively, the driver code could detect a falling edge then sample the same input a fixed interval of time later.  A valid signal is assumed to last longer than noise.  Therefor any falling edge interrupt followed by a high sample can assumed to be noise and ignored / not-processed.

  [1]: https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino/blob/master/Wiegand.cpp
  [2]: https://en.wikipedia.org/wiki/Interrupt#Edge-triggered


body:
In the readers there is switch transistors that pull down voltage provided from controllers, in other words is shutting signal to the ground. In my practice i tested many solutions and simplest one is with diodes from each controller D0 D1 in direction to the reader. In that case is not crossing voltage from controllers. For 2 controllers and 1 reader you need 4 diodes - 2 on each line.

Controller 1 - D0 --> anode on Diode 1 --> cathode to common connection for line D0

Controller 1 - D1 --> anode on Diode 2 --> cathode to common connection for line D1

Controller 2 - D0 --> anode on Diode 3 --> cathode to common connection for line D0

Controller 2 - D1 --> anode on Diode 4 --> cathode to common connection for line D1

Common connection D0 --> reader D0

Common connection D1 --> reader D1

Works fine up to 20 meters since every diode makes voltage drop.
For diodes 1N4001/4007 works fine.
Noise is not a problem, this is very slow connection with 5v amplitude.


message:
Where is tcp.h?

This is for an esp8266 project that uses EasyAsyncTCP. In EasyAsyncTCP.cpp they   `#include "lwip/tcp.h"`. But I can't figure out where that file is. I've found a tcp.h in the following directories on my c drive:

- c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
- c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\prot

but so far I've only tested the first two. I've tested them by either straight up deleting the directory and using the `#error got here` directive. No matter what I do my project builds. So I think I must either have the wrong file or it doesn't rebuild the entire thing.

How can I determine which tcp.h my program is including?

body:
While this isn't the right way of doing it I'm sharing the way that I figured it out.

**Step1:**

cd c:\

dir tcp.h /s

c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip

c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip

c:\c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\protUsers\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip

c:\Users\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot

c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip

c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip

**Step2:**

I went through and tested each one. It was... `C:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\tcp.h`


message:
How fast is flash reading compared to SRAM?

I'm working on a project that will eventually scale to 864 LEDs on WS2815 LED strips (three rows of 288 LEDs). I'm currently running it on an Arduino Uno with a single test strip of 144 LEDs.

FastLED stores its data in 3-byte structs, so I obviously cannot simply hold all of the data in SRAM and work with it directly (at least not without upgrading to a controller with more memory). I'm going to use a Raspberry Pi to send the Arduino data, one section at a time. To *further* save memory, I want to implement an RGB color lookup table in flash, then instead of

    CRGB pixels[PIXEL_COUNT];

taking up over 2KiB of memory 800+ values, or

    CRGB pixels[PIXEL_BUFFER_COUNT];

with a buffer of 288 RGB values consuming most of my working memory (864 bytes), I would have

    CRGB *pixels[PIXEL_BUFFER_COUNT];

Where each pointer would reference a location in a `PROGMEM` 256-entry table of `CRGB` values. This is a more manageable 576 bytes in SRAM.

**I realize FastLED does not work this way**. There's a  lot of work ahead of me if I do this, but before I get started, my question:

---------

Will I run into issues with reading the actual data from flash memory while sending to the LED strips? As currently implemented in FastLED, RGB data is in SRAM, but each pointer dereference will require reading from flash. Is the subsequent delay enough that it will cause an issue with sending data to the strips?

body:
Because flash is on a different data bus to SRAM there is extra shuffling around needed internally in the CPU to get the data to where it needs to be.  This uses a special "LPM" instruction (Load Program Memory), which takes an extra clock cycle to operate. On top of that the only way of using it is through the Z "index" register - there's no kind of immediate or offset loads.  So it can be a little clunky to work with.  All that is masked by the provided C functions, of course.

The upshot is that yes, it is somewhat slower reading from flash.  How much slower, though, is impossible to say.  Best case scenario: each access will take 1 more clock cycle. Worst case: well, it's impossible to know.  That somewhat depends on both how you implement your reading of the CLUT and how the compiler batches things together.

I would suggest that you will need to employ the use of an oscilloscope and just try it out.  Implement your changes, then manually adjust the delays and timing to get the output waveform just right.


body:
On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

 * 2 cycles for reading the color index from RAM
 * 3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.

It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post [NeoPixels Revealed: How to (not
need to) generate precisely timed signals][post].

**Edit**: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:

```c++
uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles
```

[post]: https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/


message:
How to set "IPAddress ip" using a variable?

Created a "variableInput.h" file for editing variables in one place; instead of searching multiple lines of code, to find lines needing editing.

    //   variableInput.h
    //
    //   User defineable variables; one location for editing variables

    // Replace with your network details
    #define host = "esp32"
    #define ssid = "YOURSSID"
    #define password = "YOURPASSWORD"

    //NTP Time Servers
    #define udpAddress1 = "198.50.238.156"  //NTP Time server
    #define udpAddress2 = "132.163.96.3"  //NTP Time server

    //publicIP accessiable over Internet with Port Forwarding; know the risks!!!
    //WAN IP Address.  Or use LAN IP Address --same as server ip; no Internet access.
    #define publicIP = "YOURPUBLICIP"
    #define LISTEN_PORT  8030  //default listening Port 80 for "GET" requests.

    //Graphing requires "FREE" "ThingSpeak.com" account..
    //Enter "ThingSpeak.com" data here....
    //iframes of graphed data are available from "ThingSpeak.com."
    #define myChannelNumber = 123456
    #define myWriteAPIKey = "E12345"

    //FTP Credentials
    #define ftpUser = "FTPUSER"
    #define ftpPassword = "FTPPASSWORD"

    //setting the addresses
    #define ip(10,0,0,200);
    #define gateway(10,0,0,1);
    #define subnet(255, 255, 255, 0);
    #define dns(10,0,0,1);

    //Restricted access to client ip list.
    #define Restricted = "/ANYNAME"

    //OTA Credentials
    //default username: USERNAME
    //default password: PASSWORD

    // "setting the addresses" is the part that I do not understand.

Segment of related code from "wifi_Start" function:

    //setting the addresses
    IPAddress ip;
    IPAddress gateway;
    IPAddress subnet;
    IPAddress dns;

Is there a solution?

William

body:
Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):

    #include <Ethernet.h>
    #include <PubSubClient.h>
    EthernetClient ethClient;
    PubSubClient client(ethClient);

    byte mac[]    = {
      0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
    };
    IPAddress ip(192, 168, 1, 75);
    IPAddress server(192, 168, 1, 11);
    void setup() {

      client.setServer(server, 1883);
      client.setCallback(callback);

      Ethernet.begin(mac, ip);

    }


body: You are not using #define correctly. The syntax is #define {name}  {value}.  There is no = between name and value so for your IP address lines you want #define myIp ip(192, 168, 1, 11)


message:
Weird sound when modulating the pulse width on Arduino

I'm trying to generate a pulse width modulated sound using Arduino Nano.

But it generates the weird sound unlike my expectation.

**Here's my code:**

    class Phasor
    {
    public:
        Phasor(const float frequency)
        :frequency(frequency)
        ,phase(1.0f)
        ,lastTimeMicros(0){};
        virtual ~Phasor(){};
        void setFrequency(const float frequency)
        {
            this->frequency = frequency;
        }
        float process()
        {
            const unsigned long currentTimeMicros = micros();
            if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
            const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
            const unsigned long cycleDurationMicros = static_cast<unsigned long>(1000.0f / frequency) * 1000;
            if (elapsedTimeMicros < cycleDurationMicros)
                phase = static_cast<float>(elapsedTimeMicros) / static_cast<float>(cycleDurationMicros);
            else
                phase = 1.0f;
            return phase;
        }
    private:
        float frequency;
        float phase;
        unsigned long lastTimeMicros;
    };

    class PulseOsc
    {
    public:
        PulseOsc(const float frequency, const float pulseWidth)
        :phasor(frequency)
        ,pulseWidth(pulseWidth){};
        virtual ~PulseOsc(){};
        void setFrequency(const float frequency)
        {
            this->phasor.setFrequency(frequency);
        }
        void setPulseWidth(const float pulseWidth)
        {
            this->pulseWidth = pulseWidth;
        }
        float process()
        {
            const float phase = phasor.process();
            if (phase <= pulseWidth)
                return 1.0f;
            else
                return -1.0f;
        }
    private:
        Phasor phasor;
        float pulseWidth;
    };

    Phasor *phasorLFO;
    PulseOsc *pulseOsc;

    void setup()
    {
        Serial.begin(9600);
        pinMode(9, OUTPUT);
        phasorLFO = new Phasor(0.1f);
        pulseOsc = new PulseOsc(440.0f, 0.5f);
    }

    void loop()
    {
        pulseOsc->setPulseWidth(phasorLFO->process());
        int outVal = LOW;
        if (pulseOsc->process() > 0.0f) outVal = HIGH;
        digitalWrite(9, outVal);
    }

The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)

What is wrong with my code?
How do I fix this? I would appreciate any advice.

body: Seems like you are using the system clock `micros()` to  calculate `elapsedTimeMicros`, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.


body:
I see two issues with this program. The first one has already been
pointed out by Majenko in a comment: you are doing too much floating
point calculations. The second has to do with the way your `Phasor`
manages the time.

If you take a look at the [Blink Without Delay][] Arduino tutorial, you
will see something along these lines:

```c++
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    toggle_the_LED();
}
```

In this code, `interval` is the _minimum_ time between toggles. Whenever
the program gets a little bit late and `currentMillis - previousMillis`
is strictly larger than `interval`, this extra time is lost and the
program will be late for all the subsequent LED toggles. If instead of
the minimum you are interested in the _average_ time between toggles,
then you should write:

```c++
if (currentMillis - previousMillis >= interval) {
    previousMillis += interval;  // <- advance by exactly one period
    toggle_the_LED();
}
```

Now, `previousMillis` is no more the time when the last toggle was
_performed_, it is the time when the last toggle was _scheduled_. With
this version you can still have some jitter, but at least the average
frequency should be right. If the program is so busy that it can get
late by a full period, then it would be better to replace the `if` by a
`while`, in order to catch up all the missed periods.

Your `Phasor::process()` method is a little bit more involved than the
tutorial above, yet the line

```c++
if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
```

is going to get you out of schedule for exactly the same reason.

That being said, here is my take at your phasor idea, _completely
untested_:

```c++
class Phasor()
{
public:
    Phasor(float frequency_Hz)
    {
        period = round(1e6 / frequency_Hz);
        frequency = 0x10000 / period;
    }
    uint16_t process()
    {
        uint16_t now = micros();
        while (now - last_time >= period)
            last_time += period;
        return (now - last_time) * frequency;
    }
private:
    uint16_t period;     // unit = 1 us
    uint16_t frequency;  // unit = 1/(2^16 us) ~ 15.3 Hz
    uint16_t last_time = 0;
};
```

I changed a few things from your implementation:

 * removed the `setFrequency()` method because [YAGNI][]
 * no floating point except in the constructor, for performance reasons
 * only 16-bit arithmetics, for the same reason
 * no division in `process()`, because division is expensive
 * the phase is not stored, because there is no use to storing it
 * the phase is an integer in units of 2<sup>−16</sup> periods

Note that the unit chosen for the phase is the most natural one when
dealing with 16-bit arithmetics. Note also that storing microseconds in
16-bit variables only works for frequencies higher than 15.3 Hz. A
very low frequency phasor (your “LFO” for instance) would need 32-bit
arithmetics.

[Blink Without Delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
[YAGNI]: https://en.wikipedia.org/wiki/You_aren't_gonna_need_it


message:
random characters

I am using arduino mega with LCD 4X20 character to measure weight by 40 kg load cell and pt 100 to measure the temp. I have 4 output to 4 relay module. all are powered from 12vdc /3 amp Power supply..
the problem is.. the display started normally showing every thing perfectly.. but when the output comes out and the loads runs.. random characters appear
is the power supply is not enough? or another problem..
Please advice. ![enter image description here](https://i.stack.imgur.com/fg3A9.jpg)![enter image description here](https://i.stack.imgur.com/Mf0en.jpg)

body: I'd suspect that it is a software error. Did you check your circuit if it induces desync between the Arduino and the LCD, or did you just use the wrong drivers?


body:
Random Characters can Happen in several ways.

- Check the Wires for: Loosen Ends; Broken Wires and Wrong Pin Connections.
- Check your Code.


message:
I2C Communication with the ICM-20789

I am trying to interface with the ICM-20789 over I2C. [DataSheet][1]

I have been successfully able to get all three gyroscope readings and all three accelerometer readings. I am now trying to get the pressure readings from the device, since it has a built-in pressure sensor, but cannot seem to get it working.

In the datasheet, it says to enable Bypass Mode.

> Bypass Mode: Set register INT_PIN_CFG (Address: 55 (Decimal); 37 (Hex)) bit 1 to value 1 and I2C_MST_EN bit is ‘0’
(Address: 106 (Decimal); 6A (Hex). Pressure sensor data can then be accessed using the procedure described in Section 10

In the setup I use this code:

      Wire.beginTransmission(gyro_address);
      Wire.write(0x37);      //INT_PIN_CFG
      Wire.write(0x02);      //00000010
      Wire.endTransmission();

I am having trouble finding I2C_MST_EN in the datasheet as well, as I cannot find it in the 6A Address.

Once I have the bypass bit enabled, I try to request the pressure and temperature data from the sensor using this code:

    Wire.beginTransmission(0x63);
    Wire.write(0x7866);
    Wire.endTransmission();
    Wire.requestFrom(0x63, 16);

    while (Wire.available() < 16);
    pressure = Wire.read() << 16 | Wire.read() << 8 | Wire.read();
    temp_2   = Wire.read() << 16 | Wire.read() << 8 | Wire.read();

Unfortunately, the device freezes when I try to run this code. I know I am obviously doing something wrong here, just don't know exactly what yet.

  [1]: http://www.invensense.com/wp-content/uploads/2017/10/DS-000169-ICM-20789-TYP-v1.3.pdf

body:
There are four things wrong with your code.

1. You are not sending the "start measurement" command properly. The `Wire.write()` function can only send 8 bits, but you are passing it a 16-bit value. Instead you should break it apart into 2 separate 8-bit values:

    Wire.beginTransmission(0x63);
    Wire.write(0x78);
    Wire.write(0x66);
    Wire.endTransmission();

2. The data returned is spread over 9 bytes, not 16.  According to the datasheet:

> Temperature data is transmitted in two 8-bit words and pressure data is
transmitted in four 8-bit words.

and:

> Two bytes of data are always followed by one byte CRC checksum

That's 2 + 4 = 6 + (6/2) = 9

3. You aren't waiting for the conversion to complete. According to the datasheet, in "ultra low noise" mode (0x7866) it takes up to 94.5ms to perform the measurement.  So you should add a delay of slightly more than that to allow it to do what it needs to do.

4. The command you are sending responds with temperature first, not pressure, but you are reading pressure first (and reading the wrong bytes anyway).

In all, your code should look more like:

    Wire.beginTransmission(0x63);
    Wire.write(0x78);
    Wire.write(0x66);
    Wire.endTransmission();

    delay(100);

    Wire.requestFrom(0x63, 9);
    uint8_t tmsb = Wire.read(); // Temperature highest byte
    uint8_t tlsb = Wire.read(); // Temperature lowest byte
    Wire.read();

    uint8_t pmmsb = Wire.read(); // Highest pressure byte
    uint8_t pmlsb = Wire.read(); // Next highest pressure byte
    Wire.read(); // Discard checksum
    uint8_t plmsb = Wire.read(); // Next lowest pressure byte
    uint8_t pllsb = Wire.read(); // Lowest pressure byte
    Wire.read(); // Discard checksum

    pressure = (pmmsb << 24) | (pmlsb << 16) | (plmsb << 8) | pllsb;
    temp_2   = (tmsb << 8) | (plsb << 8);


message:
Copy one SD card to another

I want to copy an SD card to another.

What is the best way to attack this problem?

Should i get two sd card shields?
If yes, is it possible to stack two together, or will there be problems with the interface protocols (SPI/I2C)?

body:
It should be perfectly possible to do it. As long as the SD cards and shields play ball then there should be no problem from a hardware perspective.

From a hardware perspective you should be able to share the MOSI, MISO and SCK lines and just have separate CS pins per card.

However some SD card shields employ level translation that doesn't properly release the SPI bus when idle, and some cheap SD cards don't release the bus in a timely manner too.

From a software perspective though it may be a different matter. I am not sure how well you can run two instances of the SD classes at once on an Arduino.  You may be better off looking at FatFS instead which is far more flexible.

You have two strategies when copying cards, each of which has a different way of programming it.

1. Block copy the entire card: this involves reading a 512 byte block from one card and writing it to the other one.  This would be the most efficient from a resource perspective (you don't need to care about the contents of the card, so don't need any filesystem code), but if the card is not close to full it will be very inefficient from a runtime perspective. Also the two cards have to be the same size for it to work well.
2. File copy. For this you need much more complex code, but it you only copy each file from one card to the other. It's much better though if the cards don't have much data on them - also the cards can be different sizes.


message:
RtcUtility.h: No such file or directory

I have a problem with remaining headers. Can't seem to find the first header "RtcUtility.h". Anyone how to fix? I've provided a picture for you to see.

[![Sample picture][1]][1]

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

Error Messages:

> Arduino: 1.8.10 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

> sample_time:6:24: error: RtcUtility.h: No such file or directory

> Multiple libraries were found for "ArduinoOTA.h"
 #include <RtcUtility.h>

> Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ArduinoOTA
                        ^

> Multiple libraries were found for "Wire.h"
compilation terminated.

> Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\Wire
Multiple libraries were found for "ESP8266WiFi.h"
 Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
Multiple libraries were found for "ESP8266mDNS.h"
 Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266mDNS
exit status 1
RtcUtility.h: No such file or directory

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

body:
Please add the RTC library in the Arduino as below.

*Open the Library Manager and search for "Rtc by Makuna" and install.*

You can also checkout the Github page for that particular library at

https://github.com/Makuna/Rtc


message:
Nodemcu is connected to 5v relay with logic converter but still not working

I am using a bi-directional 3.3-5V logic converter to control 5V relay with 3.3V D5 pin of nodemcu. link of logic  converter is [here][1]

However, I expected to control the relay but it didn't work. I don't think there is a problem with electrical connection or code since that is simple.

3.3V sides of nodemcu is connected to LV and 5V side of Relay is connected to HV.

Code:-

    void setup() {
      // put your setup code here, to run once:
    pinMode(D5, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    digitalWrite(D5, HIGH);
    delay(2000);
    digitalWrite(D5, LOW);
    delay(2000);
    }

My Observations:-
1) When relay is removed, multimeter shows 3.3V at the LV & HV side. (so logic converter is not working i guess)
2) When relay  is  connected, multimeter shows 2.5V on  both sides.

Everything is powered from nodemcu pins. Does  it means that i have to supply extenal power or something wrong with logic converter?[![enter image description here][2]][2]

What do you guys think?

PS  - I  soldered the pins another way around on logic converter. Does it change anything?

circuit image, nodemcu is powered by the laptop USB

[![circuit][1]][1]

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

body:
The converter and/or the nodemcu can't provide enough current to drive the relay. So you should get a 5V psu.
For further details we need more information about the parts you use.


body: To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.


body:
You must supply a steady, regulated voltage to both 3.3v and 5v pins at all time (see Voltage Inputs on https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all).

Logic level controller does NOT convert 3.3v to 5v for powering the relay, it just let you turn 3.3v signal to 5v so a relay can get activated. Relay's positive pin still needs to be supplied with a 5v from a PSU or other sources.


message:
LED and MOTOR "ON" when A BLE DEVICE APPROACH ESP32 MICROCONTROLLER DFR0575

I have this code that is working perfectly but I want my device to start vibrating too (right now only the led is working)

On a Wemos Battery Module I have simply connected the vibration motor on the same PIN of the LED and it works perfectly.

Now I want to do the same on an **Beetle ESP32 Microcontroller DFR0575**. I used the same code But I can't make the module vibrating (The led light is working perfectly)

this is the code:

     #include <BLEAdvertisedDevice.h>
       #include <BLEDevice.h>
       #include <BLEScan.h>

       const int PIN = 2;
       const int CUTOFF = -50;

       void setup() {
         pinMode(PIN, OUTPUT);
         BLEDevice::init("tkr");
       }

       void loop() {
         BLEScan *scan = BLEDevice::getScan();
         scan->setActiveScan(true);
         BLEScanResults results = scan->start(1);
         int best = CUTOFF;
         for (int i = 0; i < results.getCount(); i++) {
           BLEAdvertisedDevice device = results.getDevice(i);
           int rssi = device.getRSSI();
           if (rssi > best) {
             best = rssi;
           }
         }
         digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
       }

body:
It is generally very dangerous to drive any motor directly from a digital output pin. Motors often need way more current, than the digital pin can provide. Based on the answer to [this question][1], an ESP8266 can provide 20mA or 12mA depending on current direction (may be a bit different for an ESP32, but not substantially). Drawing more current, than the pin can provide, can lead to the destruction of the output hardware of the pin. It is not easy to say, when this will happen, because it depends not only on the current draw, but also on time and fabrication variation.

Also a motor is an inductive load, which means, that fast changes (for example turning on and off) will induce a reverse voltage in the motor coils. These can easily be very high relative to the supply voltage and thus destroy you output pin or even the complete microcontroller.

I cannot give you a full reasoning, why it works with the first board, but not with the second. I think, it has to do with the above.

You should always do 2 things, when driving motors with a microcontroller:

1. **Use a motor driver circuit:** You can either buy a ready to use motor driver or you can build one yourself. If you only want to turn the motor in one direction (as with a vibration motor), all you need is a MOSFET, which will act as a switch between the motor and the power supply. This switch get's controlled by the Arduino's output pin (which only needs to supply a very low current for switching). You can google "MOSFET as a switch". Be sure to use a MOSFET, that can provide the needed current and that is good in saturation for the used gate voltage (the working voltage of the microcontroller).

2. **Use a flyback diode:** The reverse induction voltage can also hurt MOSFETs. You want to let these voltage spikes quickly plenish by letting the current flow to ground. You can do this with a flyback diode. That is a diode, that bridges drain and source of the MOSFET. It is oriented so that block for normal operation (the normal positive supply voltage). When the MOSFET get's turned off, a great negative voltage will build up in the motor, but since the diode is conducting in this way, the voltage will safely flow to ground, so that the induction voltage cannot hurt the other electronic parts.

  [1]: https://arduino.stackexchange.com/questions/68880/nodemcu-max-draw


message:
How can I connect 6 solenoid locks to an arduino

Im in college and our research is about a fingerprint based door lock system.  We really dont have any idea about arduino.  Now we bought arduino mega for our research but I dont know how to connect all 6 solenoid locks to an arduino.  Please help It would be very much appreciated if you answer and it will be very helpful to us. I know there are same research about this in the internet but  i cant find any of these.  If you have any website about this research it would be very helpful.  Thanks

body:
Supposing the lock you use is a simple solenoid that works with 12V, you should connect them to the output of a relay module, and then connect the Arduino to the module. Like this example here: [link.][1]

You will probably want to connect each solenoid to an individual relay, so you can activate each one of them individually. With that in mind you might want to use an 8-channel relay module like [DataFiddler][2] recommended. [example][3]

You will need a 12V power supply, and be sure to check the current drawn from your solenoids and see if the power supply can handle it.

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

  [1]: http://www.arduinotutorialonline.com/2018/05/relay-module-solenoid-door-lock-how-to.html
  [2]: https://arduino.stackexchange.com/users/16780/datafiddler
  [3]: https://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTELP3I/ref=sr_1_3?__mk_pt_BR=ÅMÅŽÕÑ&keywords=8 channel relay module&qid=1569852488&sr=8-3
  [4]: https://i.stack.imgur.com/mo0ih.png


body:
To follow up on CrossRoads' suggestion of a power MOSFET circuit, there is more detail on how to do it in an answer over in the Electrical Engineering group. Digikey.com is a great source for components.

https://electronics.stackexchange.com/questions/29065/how-to-control-a-12v-solenoid-valve-with-a-mosfet


message:
Push Button to Drive Power to Servo

I am currently doing a project for a class which uses a few other components such as an LCD, a servo, and such. I want to use a button which acts as a circuit breaker on the Vin of the servo in which the servo will only be powered when the switch is pressed. I wanted to implement something like this because I wanted to minimize the power consumption and also acts as a mechanical counter-measure in case the servo keeps on spinning in unwanted situations, such as having the servo entangled by hair or something like that.

I know that I can just connect the button to the I/O pins but I wanted to rely on a hardware solution for power minimization and safety reason.

The servo draws 170mA when idle and can draw a maximum of 1.2A, but I believe it will only draw about 500-600mA with the intended load. It can run between 4.8-6V.

So my question is, would my circuit configuration work for my application? Would it be safe? Do I need any other additional components? Thanks for anyone that can help!

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

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

body:
Yes, that should be safe, as long as the button can conduct the needed current. That depends on the type of button. You can simply test this. If the button get's hot, it is too small for this.

If it should happen, that the button cannot conduct the needed current, you have 2 ways to go:

1. Just use a bigger button. You can buy buttons, that are meant for mains supply, which will be able to conduct way enough. Every button, that you buy (at least at electronics shops, maybe not on aliexpress or ebay), should have some kind of data sheet, which states the absolute maximums for the electrical characteristics. A maximum current can be found there.
2. You can use a MOSFET (that is capable of providing the needed current) and control it with your button. That would be the way to go, if you really need or want to use this specific button.


body:
There is a chance that this arrangement *could* damage the servo and possibly the Arduino.  The problem is that, depending on the internals of the servo, it could try and draw power for the servo through the data pin when the button is not pressed.  This would both over-stress the internals of the servo and the internals of the Arduino's GPIO pin.

What you could do to mitigate that is to connect the servo's switched power to another GPIO pin of the Arduino, which is set as INPUT.  That will then tell the Arduino when the button is pressed and when it's not pressed. Then you use that information to `attach` and `detach` the servo in your code so it is only being actively driven when the button is pressed.


message:
Is digitalWrite(pinnumber,LOW) different from ground pin

I am using Tinkercad simulator, but an unusual thing happened. When I connect one wire of dc motor to pin 9 with `digitalWrite(9,HIGH)` and other wire to ground, the motor runs with rpm of 5555.

    void setup()
    {
      pinMode(9, OUTPUT);
    }

    void loop()
    {
      digitalWrite(9, 1);
    }

 But instead if I connect the other wire to pin 13(say) and set `digitalWrite(13,LOW)` the motor runs at an rpm of 3846.

    void setup()
    {
      pinMode(9, OUTPUT);
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      digitalWrite(9, 1);
      digitalWrite(13,0);
    }

Can anyone explain this?

body:
In the real world, either pin sinks current to Gnd via an onchip N-channel MOSFET. They will safely sink 20, 25mA. If your motor allows more than 40mA to flow, you risk damaging the pin and likely the whole chip.

Similarly, either pin can source the same current to a load, likely via P-channel MOSFET, with the same current limitations.

Using both together, you have one transistor sourcing current, one transistor sinking current, so you have twice the Rds (MOSFET on-resistance) limiting current to the load, hence the simulator might have the motor going slower due to less current being available.


body:
Yes, it is different.

First: **Never run a motor directly from IO pins - you will damage your Arduino**. Not only can a real Arduino not supply enough current, but motors generate a lot of back-EMF that will kill an Arduino.

Secondly a pin doesn't connect direct to GND or VCC - it is connected through a MOSFET that performs the switching.  That MOSFET has an ON resistance, which causes a voltage drop across it determined by the current being sourced or sunk through the pin.

You can read more about GPIO pins [here](https://majenko.co.uk/blog/what-exactly-gpio-pin).


message:
Connecting Logitech F310 gamepad to Arduino Uno and Arduino USB Shield

I am trying to connect Logitech F310 gamepad to Arduino Uno with ARDUINO USB HOST SHIELD https://store.arduino.cc/arduino-usb-host-shield using http://github.com/felis/USB_Host_Shield_2.0 library.

The closest is https://github.com/felis/USB_Host_Shield_2.0/tree/master/examples/HID/USBHIDJoystick example
After compiling there is no print output in serial window after "Start".
Tried keyboard sketch on same board - it worked.

There is "Mode" button on joystick - by pressing green led is switched ON and OFF.
Behind the joystick there is switch between "X" and "D" .
On "D" green led is working, on "X" - not.

Is this joystick even compatible with HID library? Is there other way how to configure it to USB shield?
Joystick is working on different other devices.

body:
I found it here : https://github.com/AlanFord/Logitech_F310_and_Arduino
So there is a glitch in library and driver customization was necessary


message:
esp_partition_get_sha256() mismatches PHP's hash() function in HTTPUpdate

Disclaimer: It may be that this question belongs to a PHP forum instead of this one. However, this question is _also_ very ESP32/Arduino related. Please correct me if this is the case.

The scenario:

 - Implementing self-update routines for my ESP32 project, using HTTPUpdate
Using a server-side PHP script to decide which binary image to serve to the device, or return HTTP 304 return code if no updates available.
 - Using the sketch's MD5 **and** SHA-256 hashes provided by the HTTPUpdate library as request headers, server-side, to check binary version.

The problem:

 - The MD5 hash contained in the request header "x-ESP32-sketch-md5" _is the same_ as the MD5 hash calculated by a simple ```md5()``` call using the raw binary for the currently running version.
 - The SHA256 hash contained in the request header "x-ESP32-sketch-sha256" **is not the same** as the hash obtained by calling PHP's ```hash("sha256", $v)``` (where ```$v``` contains the same raw binary).

Example:

 - MD5 (HTTPUpdate): c93d814989b53a24a0164e561b6a8bf8
 - MD5 (PHP): c93d814989b53a24a0164e561b6a8bf8 (no difference)
 - SHA256 (HTTPUpdate): 5634674253E095600CD863A34287FCA742BCFCF9B5BF409870DD65AF0ADEF7A0
 - SHA256 (PHP): 1ECDDF3215520C79AAD13BBC1D116D9286910490DF316B9B203FCBFC89CBCCC2 (different)

Am I doing something wrong?

Note: The ```esp_partition_get_sha256()``` function is called internally by the ```update()``` method of the HTTPUpdate library.

PHP Code (for calculating the hashes):
```PHP
<?php

$v = file_get_contents("fw.bin");

print("MD5: ". md5($v)."\r\n");
print("SHA256: ".hash("sha256", $v)."\r\n");
```

Arduino code (the relevant part):
```Arduino
// Called once or twice a day
void update_fw()
{
    Serial.println("Checking for updates...");

    t_httpUpdate_return ret = httpUpdate.update(client, "http://my_server/fw/check_fw.php");  // For now it only logs the headers and returns HTTP 304 code

    switch (ret)
    {
      case HTTP_UPDATE_FAILED:
        Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
        break;

      case HTTP_UPDATE_NO_UPDATES:
        Serial.println("HTTP_UPDATE_NO_UPDATES");
        break;

      case HTTP_UPDATE_OK:
        Serial.println("HTTP_UPDATE_OK");
        break;
    }
}
```

PHP code (logs headers and returns HTTP 304 code):
```PHP
<?php

$headers = getallheaders();

if (!file_exists("log.txt"))
{
 file_put_contents("log.txt", print_r($headers, true));
}

http_response_code(304);   // No updates.

exit;
```

Thanks in advance.

body:
Your problem stems from a misunderstanding of what the functions are doing.

Your MD5 hashes are the hash of the binary file itself. And so they match.

Your PHP SHA256 is the hash of the binary file (like the MD5), but the ESP's SHA256 is not.

The file itself contains an SHA256 hash of the *content* of the file, not the whole file.  The function esp_partition_get_sha256 merely returns that SHA256 hash.

According to the [SDK documentation](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/storage/spi_flash.html):

> For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition.

If you were to take the binary file and somehow strip off the extra sha256 information and then perform a hash of the results you should (theoretically) get the same hash, which would be the same has as is contained within the file itself.


message:
I2C - Confusion

It's not often I ask a question. This one has me a little stumped though.

Scenario:

I have an 328PB (internal 8mhz), it speaks to a multiplexer on Wire1 (the PB's second IC2 - Minicore lib). The multiplexer speaks to many sensors. That is all working just fine.

I have a logic analyser hooked up to the key points so I can see what is going on.

I have a Nano (external 16mhz) hooked up to Wire (the PB's first I2C), it sends a master request.

The PB is master on Wire1 and slave on Wire.

For some reason the Nano's request on (address 8) is acknowledged by the PB but then the subsequent reads deliver a zero byte and an NACK.

I'm just asking for one byte to troubleshoot. Previous attempts at multiple bytes would deliver the expected bytes but all of them zero.

Strange thing I'm seeing on the logic analyser is that the PB to Multiplexer communication seems to be slower than the Nano to PB (much slower).

I've looked through the libraries and both Wire and Wire1 seem to calculate the speed down to 100khz. I'm using the standard Arduino Wire on the Nano. Given that the initial Address comms gets an ACK. I'm stumped why the subsequent read gets zero and a NACK.

Any help to restore my sanity is much appreciated.
Chances are I'm having a dumb moment. My suspicions are that the clock differences are to blame (but logically they shouldn't be).

----------
Edit:
This is the analyser recording. The dodgy byte is highlighted in Blue.
[![enter image description here][1]][1]

The communication from the Atmega328pb to the multiplexer and then on to the temperature sensor is working fine. Not all of the multiplexer channels have sensors at the moment hence the NACKs but you can see success on channel 1 to the right of the screenshot. The Nano to Atmega328pb communication starts off good but I'm expecting to see 0X41 in the blue box not 0x00.

This is going to end up being something simple, I'm going to kick myself.

Nano code:

```
#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);             // start serial for output.
}

void loop() {
  Wire.requestFrom(8, 1);         // request 1 byte from slave device #8
  char c = Wire.read();           // receive a byte as character
  Serial.print("The character: ");
  Serial.println(c);              // print the character
  delay(1000);
}
```
Atmega328pb requestEvent code:

```
void requestEvent() {
  Wire.write("A");
}
```

Edit:
There are other wires for programming etc, but they are disconnected during test.
[![Schematic][2]][2]

  [1]: https://i.stack.imgur.com/AwKTe.png
  [2]: https://i.stack.imgur.com/g1rP4.png

Edit:
I commented out all the usage of Wire1 in the PB code. And the result was that the Nano got it's byte. I wove the usage of Wire1 back into the code. Right up until it was actually active i.e. communicating with the multiplexer. At that point the Nano started getting a zero byte again.

It seems to be when they are both active. Which suggests it is something in the Wire/Wire1 library by Minicore.

I suspect there is something in the registers but scanning the datasheet for the PB is not yielding any insights. Except for this:
26.1 - Device can Operate as Transmitter **or** Receiver

There is no elaboration in the document that I can see.

I've tried staggering the communication so that neither is active at the same time. Still the same result.

Still hoping that someone here has the answer ;-)

body:
I  got it to work ... sort of. I had to move some lines from init to the loop.
I found that by delaying the Wire1 communication (pb to multiplexer) I could get Wire (Nano to pb) to work. Then as soon as the Wire1 communication had *finished* Wire no longer worked. Interestingly Wire continued to work while Wire1 was also active.
This has lead me to believe the end of the Wire1 communication is leaving something in a conflicted state (the events on Wire were not connected any longer). The blunt answer was to re-initialise on each loop. This seems to work but is not particularly elegant.
```
void loop()
{
    Wire1.begin();
    getTemperatures();
    Wire1.end();
    Wire.begin(8);                                               // Join i2c bus 0 with address #8
    Wire.onReceive(receiveEvent);                                // Register event.
    Wire.onRequest(requestEvent);                                // Register event.
}
```
I'm going to continue with this and see if it offers an appropriate degree of reliability. I'm still hunting for the root issue though.


body:
I've been rebuilding using Atmel Studio. After a long time bringing my C++ skills up to scratch I've managed to get it to work very reliably. I like the greater level of control it brings. I suspect that I was trying to do something in Arduino IDE that cannot be done with the Wire library. I had to effectively rewrite the Atmel Start Slave driver  to get it to behave as I expected it to. I have no other experience of using I2C. So I cannot say whether it is the Atmega328pb that is different or not.<br/>
I'm going to stick to Atmel Studio for this project, thanks for all the responses.


message:
Arduino wont start up and it wasnt succesfully booted in any time it was downloaded

I know the title sounds stupid but I never found a question like mine so I wanted to be specific because I downloaded the Arduino IDE to start my first project and I never managed to boot it because nothing happens when I try and I also tried every kind of thing to make it work I could think of. I reinstalled it, downloaded from another link like the zip version and also tried the windows repairtool. I also tried to boot it as admin several times but nothing changed anything. I did all of that yesterday and today when I started the Pc and retried I atleast saw something of a bootingscreen of the app so I thought I just had to restart but then it just went off again and the pain from yesterday began once again.

´´
I own windows 7 64 bit
´´
and tried every download except the one for windows 8.1 and 10

I saw a question about Arduino IDE not starting but this person atleast got any response from the program and the tipp they suggested with the folder in

´´
AppData/Lokal where you delete broken data to reinstall doesnt work too because the arduino folder doesnt even excist in the whole appdata section.
´´

´´
Windows repair tool said the program is not compatible, only in Windows xp (service pack 2) version but in compatibility mode nothing changes
´´

Ok *thew* this question is really long but I gave my best to explain everything I could about my problem so I really hope somebody could help me on my problem so I didnt waste my 45 Euro and time on tech stuff that I cant use

one thing to meantion I have left is that i bought my stuff from a teacher (Erik Verbene) on the internet

but that doesnt matter because it is your program that is not working so
yeah
hope somebody can help me out on this dilemma

body:
The Arduino IDE is written in Java. It's 100% platform independent, so the version that you download makes no real difference.

The most likely culprit is the version of Java that is installed in your computer.  I am not sure off hand what versions of Java the Arduino IDE works with, but for certain version 8 will be your best bet.  Make sure that you have the latest version of Java 8 installed.  If you have any older version installed you should uninstall it and replace it with Java 8.  I'm not sure how the IDE works with newer versions than 8, but removing anything newer than 8 and installing Java 8 may be a good idea.


message:
Concern myself with current draw from digital pins used as INPUT with internal pullups?

My project is using a genuine Arduino Mega 2560, probably 3-4 yrs old since purchased (I don't see any revision numbers on the PCB).  It's being used to read a lot of switches, buttons and drive some LED's and displays.

When using a digital pin as INPUT with the internal 10k pullup enabled, do I need to consider the draw with respect to the 200mA total through all pins?  Is it simply the 10k ohm resistor with 5V so 0.5mA?  Can I just ignore it? (there's only so many pins I suspect I can ignore it)

I've seen several posts/pages about driving LED's using transistor arrays powered by an external source and those spec sheets describe the transistor input currents so I can estimate the draws for those elements, but not sure if I need to concern myself with the Arduino pins used as INPUT.

body:
You are right. The current through digital inputs is so low, that you can normally ignore it.

And the 0.5mA, that you calculated don't flow all the time, just, when the corresponding button is pressed and thus shorted to ground, because only then a current will flow through the pullup resistor. The current into the actual input hardware is even smaller. So, as long as not all buttons are pressed at once, the current will be even lower as calculated.

Buttons are somewhat voltage devices. They don't need a specific amount of current, just of voltage. So the actual value of pullup/pulldown resistors are not critical. LEDs in contrast are current devices. They need a specific current to light up, which is often higher, than the maximum output current of a digital pin. Thus they are often driven with an additional transistor.


message:
Connecting 2-pin JST PH connector to Arduino Mega

I’m want to connect 50 LDR to my Mega, I wondering if I use a 2-female pin JST PH connector to connect the LDR, how can I link 2-pin male JST PH connector board to the Mega and does this board exist?

body:
There exists 2.00 to 2.54mm adapters, like in [this link][1].

They look like below (example of 1.27, 2 and 2.54mm):

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

  [1]: https://www.gorilladistribution.com.au/product/8-pin-adapter-board-1-27mm-2-0mm-2-54mm/
  [2]: https://i.stack.imgur.com/akvfJ.jpg


message:
Audio Recording using Arduino BT module

I want to take audio signal through mic connected to Arduino and then transfer it to PC using BT module. I want to do it with BT (HC05) and Arduino Mega. I need audio packages at 44 KHz and 24-32 bits per sample.

Can I use AudioInI2S library to receive audio samples? Does HC05 support this type of communication?

I want to save and analyze the audio samples later on. I have worked on Arduino before but I am totally new to audio streaming and I am not sure where to begin from. Any guidance would be appreciated.

body:
In short: No and no.

----

> Can I use AudioInI2S library to receive audio samples?

No.  The library is not for the Mega:

> This library provides simple way to play and analyze audio data using Arduino on SAMD21 based boards (i.e Arduino or Genuino Zero, MKRZero or MKR1000 Board) using the I2S bus.

----

> Does HC05 support this type of communication?

No.  The HC05 is a serial module. It works at baud rates that are far to low to transfer the data in a timely fashion, and can't send data in a form the PC sees as audio (so you'd need to write your own translation software to convert serial data into an audio file).

----

> Any guidance would be appreciated.

Just buy a cheap bluetooth headset.


message:
Is there a library for non-SAMD Arduinos to use the DMP on MPU9250

I would like to use the DMP of the MPU9250 with my BTLE Feather board but the docu of the [official library][1] says that only SAMP-Processors are supported.

Is the a different library I can use?

  [1]: https://github.com/sparkfun/SparkFun_MPU-9250-DMP_Arduino_Library

body:
I did have a look at the MPU9250 DMP library provided by Sparkfun and it seems that it is specifically built for their own board which has an M0 chip on the board. However looking at the library, there seems to be no reasons why it would not work with any other board. The main reason why it might not work with something like the 32u4 board would be because the end firmware is too large or the program need too much RAM that what the 32u4 has.

There is a fix provided on the github issues page for using it with a Nano, which might help you get it work with the 32u4 [here](https://github.com/sparkfun/SparkFun_MPU-9250-DMP_Arduino_Library/issues/11#issuecomment-449472273) and there is another library [here](https://github.com/kharlashkin/MPU-9250DMP) that you might be able to use or build up on.

However the best way might be to use a M0 chip itself if you really want to use the same IMU since getting the library to work can turn out tricky. Adafruit does sell a M0 with a Bluetooth board [here](https://www.adafruit.com/product/2995) that you might be able to use.


message:
Receiving i2c bytes on an attiny85

I've been trying to write a small i2c lib in C over the past week. I managed to get writing to slaves working (for example I can write to an ssd1306 oled) but reading (for example date/time from an ds3231) never works as my slaves don't seem to set SDA high when I request bytes.

```c
uint8_t
i2c_read(uint8_t ack)
{
 uint8_t i, val;

 val = 0;
 cbi(SCL);
 DDRB &= ~(1 << SDA); /* Use SDA for input. */
 cbi(SDA); /* We need to pull down SDA to receive input. */

 /* Read 8bit from the slave. */
 _delay_us(DELAY);
 for (i = 0; i < 8; ++i) {
  sbi(SCL); /* Request one more bit. */
  _delay_us(DELAY); /* Wait a little so the slave can send his answer. */
  if (PORTB & (1 << SDA)) { /* Here the slave should have set SDA to 1 but it never does. */
   PORTB |= (1 << PB4);
   val = (val << 1) | 1;
  } else {
   val = (val << 1);
  }
  cbi(SCL);
  _delay_us(DELAY);
 }

 /* Send back an ACK or NAK. */
 DDRB |= 1 << SDA; /* Use SDA for writing. */
 if (ack)
  cbi(SDA); /* Set SDA to 0 to send ACK. */
 else
  sbi(SDA); /* Set SDA to 1 to send NAK. */

 sbi(SCL);
 _delay_us(DELAY);
 cbi(SCL);
 cbi(SDA);

 return val;
}
```

I set PB4 with to 1 when a slave actually sends a 1. Apparently that never happens.
I also had a look at how the various other libs out there do it but I didn't spot anything that would make a difference.

Any clues on what I migth be missing? Before reading my program sends the slave address to the bus. Also: please don't tell me to use other libraries since this is a learning project.

body:
Not sure, if this is the only problem, but you are reading from the wrong register.

There are 3 registers associated with a digital output pin: DDR, PORT and PIN. To read a pin, you need to read from the PIN register. Currently you are reading the PORT register, which will only ever have the value, that you set it to (zero in this case, because you cleared the bit beforehand with `cbi(SDA);`). When you configure the pin as input with the DDR register, the PORT register determines, if the internal pullup resistor is activated or not, so it cannot reflect the actual state of the pin. For this you need the PIN register.

---

Besides that, you might want to look into another thing, that might or might not be a problem in your case: I2C is an open drain bus, meaning, that it is driven actively low and passively high (through pullup resistors). I guess you already have external pullup resistors on your lines, so that you really can deactivate the internal pullup without breaking the communication. But imagine the following situation: The slave get's a request, but cannot clock it out that fast (for whatever reason). It can pull the clock to LOW, until it is ready to push out the data bit, slowing down the clock speed. (This can be done for every bit, unless you are in highspeed mode, then only before the start of a new byte). (This behavior is called clock stretching - Thanks to Edgar for the information) You don't monitor the line, so it can happen, that you drive the clock line actively to high, before the slave has released it. This results in a significant current between master and slave, since the master drives actively high and slave actively low.

There are implementations of I2C communication, that are just doing that and are working fine in most situations. I just wanted to give you this information. And if you at some point want to implement bus arbitration (to allow a multi-master setup), you definitely need this open drain behaviour.


message:
Is there a way to add external RAM (let's say 100 MB or 200 MB) in this audio buffer mixing context?

I'm coding a music sampler device: for fast playback / minimal latency (only a few milliseconds), it's better to have all audio .wav samples we want to use in RAM, so that when some of them are  played, the data arrays are immediately accessible. That's what I did for a Raspberry Pi project called [SamplerBox](http://www.samplerbox.org). It was possible because RPi had 1 GB RAM.

Note: When using SDcard reading, and playing many notes at the same time (imagine a pianist playing a big chord), it's usually not good in terms of latency.

Now I'm thinking about porting this project to Arduino: in which extent can we add external RAM to an ATmega? Or if not "RAM", some volatile memory (let's call it "RAM2") that would be 10 times faster than reading an SD card.

What I'd like to achieve:

* load 200 MB of audio samples into the "RAM2"

* Max polyphony allowed = 100, so at a given time, all audio buffers that have to be mixed can be copied from "RAM2" to the "real" RAM of the microcontroller, and the mixing will be done with the (maximum 100 of them) buffers in the real RAM

body:
There are SRAM ICs / boards, however, don't expect 100 MB, more like 1 MB (with the pin numbers and connectivity / protocols that an Arduino offers).

With Flash you can get much further, but it can only be written a number of times; not sure if that suits your requirements.

Beyond that, I'm afraid the real problem is in the processing speed. Mixing 100 samples with 48 KHz stero would mean (48000 * 2) = 96 KSamples/s. Since the Arduino is only 16 MHz you have just 16e6/96e3 = 166 clock cycles to mix all those 100 samples. Probably way too less.

**Update**

Winbond is a brand that is supported by Arduino libraries and the biggest supported IC is e.g. W25Q128FVSSIG, which is 128 Mbit, thus 8 MB. For 200 MB you need 25 of them which is quite a lot, and not sure if there will be issues using so many (let alone the cost). For this you do not need a file system, however you need to write it per page (if you want to do it efficiently). Which should be ok, since the SD card also is read per page (maybe not the same page size though).
However, you still have to copy the Flash memory into SRAM to be able to process it, so it's not the same as SRAM. Getting 200 MB SRAM will be very costly.


body:
I'd also suggest looking into different microprocessors. The Teensy models often have an SD card socket, and the Teensy 4 (especially if they release one with a built-in SD socket) is extremely fast and capable (600MHZ, dual instructions/cycle). That would be far better suited than an Arduino, though you'll still have RAM limits. (Nowhere near 200 megs, but you'd have slightly less of an issue than with the Arduino's mere 2-8K of RAM. These have a few hundred K up to maybe a couple MB (note that I'm not sure if it actually goes that high))

There's also the RPI Zero, Zero W, and Compute Module to try using. Those are the Raspberry Pi system you are used to using at a low-ish cost or easily-integrated form factor.

In short, to do audio processing, you also need a better processor than a stock Arduino probably has. Lots of RAM is the easy-to-see issue, but having the computing power to do something with it is also important.

Do note that the Winbond chips mentioned in the other answer ARE a flash memory, so they may go bad on you if they see a lot of writes.


message:
Pressure Gauge analog reading via RS232

I am trying to read the analog signal from a Pfeiffer TPG 261 Single Gauge (https://www.idealvac.com/files/brochures/Pfeiffer_Single_Gauge_TPG261.pdf)

The pin assignment of the connector I am using is the following:

[![RS232Pinassingement][1]][1]

Here is the circuit I have built:

[![BreadboardConnection][2]][2]

And here is the code used:

    int pressureSensorPin = A0;

    int analogValueP = 0;

    void setup(void)
    {
      Serial.begin(9600);
    }
    void loop()
    {
      analogValueP = analogRead(pressureSensorPin);
      Serial.println(analogValueP);
      delay(1000);
    }

Unfortunately the ouput I get with such a build is only 0 with now and then a 1023.

Any idea of what I am doing wrong ?

  [1]: https://i.stack.imgur.com/KfCBD.png
  [2]: https://i.stack.imgur.com/7XRfm.png

body:
You have a misconception, which signals get's outputted where. If you want to simply read the analog signal of the sensor, you need to use the "control" connector. There you can find the analog signal on pin 2. But this analog signal goes up to 10V, so you need a voltage divider between the sensor and the Arduino, to divide the voltage down to 5V max.

Currently you are using the RS232 connector. RS232 is a communication standard, which transmits digital data, not analog data. Thus you read only digital values (min voltage and max voltage, nothing inbetween). You can use it do talk with the sensor, change configuration settings and reading data digitally. But to actually do this, you need to consider 2 important things:

1. RS232 is an interface, which involves it's own voltage levels (namely +-12V), which do not fit the TTL level (0 - 5V) that the Arduino Uno uses. You can very well destroy your Arduino by connecting it directly to RS232. For making this work, you need a level converter chip (I think the MAX232 is commonly used for this), to convert the voltage levels to TTL logic. From there on this communication is normally called UART.

2. You need to understand and then implement the sensors communication protocol (when to send what data), so that the sensor and Arduino are understanding each other

---

For me it seems, that the analog signal from the "control" connector is all, that you currently need, so for simplicity you can use this. RS232 is used for more control over the functionality of the sensor.


message:
Code conversion

Following is the zabbix documentation with the query header format.
[Document Zabbix][1]

I have difficulty implementing this header in C ++ (Arduino),

I saw an implementation of what I need in this forum [here][2] , however it is in Russian and is implemented in C #, I tried to translate it but to no avail.

So I need someone to help me write the function of the header examples in C ++ (Arduino).

  [1]: https://www.zabbix.com/documentation/4.4/manual/appendix/protocols/header_datalen
  [2]: https://www.zabbix.com/forum/in-russian/20295-zabbix_sender-net-готовый-пример-на-c?t=20047

Follows full Arduino code after @EdgarBonet change suggestion

```c++
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>

// Config IP
IPAddress ip(192, 168, 0, 130);
IPAddress gw(192, 168, 0, 1);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
float contador = 0;

EthernetClient client;

//Config Server address
const char* server = "192.168.0.135";
int porta = 10051;

void setup() {
    Serial.begin(9600);
    Ethernet.begin(mac, ip);
}

void loop() {
    // Begin Json
    const size_t capacity = JSON_ARRAY_SIZE(1)
                          + JSON_OBJECT_SIZE(2)
                          + JSON_OBJECT_SIZE(3);
    DynamicJsonBuffer jsonBuffer(capacity);

    JsonObject& root = jsonBuffer.createObject();
    root["request"] = "sender data";

    JsonArray& data = root.createNestedArray("data");

    JsonObject& data_0 = data.createNestedObject();
    data_0["host"] = "ethernet";
    data_0["key"] = "variavel1";
    data_0["value"] = contador;

    String json = "";
    root.printTo(json);

    const uint8_t *dataSend = (const uint8_t *) json.c_str();
    uint64_t data_length = json.length();
    uint8_t packet[13 + data_length];  // 13-byte header + payload

    // Write the 5-byte signature.
    memcpy(packet, "ZBXD\1", 5);

    // Add the 8-byte packet length, LSB first.
    for (int i = 0; i < 8; i++) {
        packet[5+i] = data_length >> 8*i;
    }

    // Add the payload.
    memcpy(packet + 13, dataSend, data_length);
    if (client.connect(server, porta)) {
        Serial.println("Enviando ao servidor");
        delay(1000);
        // Send the packet.
        client.write(packet, sizeof packet);
        delay(1000);
        contador ++;
    }
}
```

Following server response:

    2034:20191003:101411.196 Message size 2066888786 from 192.168.0.130 exceeds the maximum size 1073741824 bytes. Message ignored.

body:
The problem is quite explicit in the error message:

> expected 808529969 bytes

You told the server that you were going to give it 808529969 bytes, yet
you provided much less. Why did you tell it you were going to send so
much data? Maybe we can get a clue by rewriting this number in
hexadecimal:

808529969 = 0x30313031

Breaking this into individual bytes, LSB first (as this is how the
server expects it), you have

0x31 0x30 0x31 0x30

These are the bytes you sent to the server, and they all happen to be
ASCII codes for digits, which make up the string "1010". I don't know
how you came up with this, as the code you posted is not the one you
tested (the posted code does not even compile!). But it seems at one
point you tried to convert something to ASCII binary, and indeed
`String(10, BIN)` produces exactly the string above.

The server expects the data length to be provided as binary bytes,
**not** as an ASCII string. I personally try to avoid the `String`
class, which can create memory issues. In this situation I would just
work with an array of bytes, typed as `uint8_t` (the same as the Arduino
`byte` type, only more standard). In the code below, I assume for
simplicity that you keep a `String` for building the payload, but then I
switch to a raw byte array:

```c++
const uint8_t *data = (const uint8_t *) json.c_str();
uint64_t data_length = json.length();
uint8_t packet[13 + data_length];  // 13-byte header + payload

// Write the 5-byte signature.
memcpy(packet, "ZBXD\1", 5);

// Add the 8-byte packet length, LSB first.
for (int i = 0; i < 8; i++) {
    packet[5+i] = data_length >> 8*i;
}

// Add the payload.
memcpy(packet + 13, data, data_length);

// Send the packet.
client.write(packet, sizeof packet);
```

Note that when working with binary, rather than text data, you have to
use `memcpy()` instead of `strcpy()`, and `client.write()` instead of
`client.print()`.


message:
Sending multi-byte data over I2C between different processors

I have been attempting to read data from an ATTINY84 via an ESP8266. Both are programmed via the Arduino IDE, though as PlatformIO is a proxy for that, I'm not certain what version of the ATTINY core is in use.

I have both devices connected to the I2C bus, with the Arduino as a slave.
The ESP sends a code requesting a particular type of data, then calls Wire.requestFrom() to get 8 bytes of data. I am concerned over both my implementation and about potential endian-ness issues (even if it should turn out not to be an issue on these two particular devices, I'd like to know my future options).

The ATTINY code is a complex function that is called when there is a request (and the right option code, but that's probably not very relevant). It writes eight bytes using Wire.write after uncompressing them from the relevant arrays. (I have a lot of ADC data that technically should not fit in RAM.)
Since this is is a callback function or possibly an interrupt, **do I need to be concerned about data corruption if the code is too slow to write the values onto the bus**? I have to imagine it's trying to read them even as it writes. I can also provide code snippets if it would help.

----------

I am also unsure if I am running into Endian-ness issues by using bitshift to grab the 2 and 8 bits from the ADC return value. Would this always give me the correct values, or does the C++ compiler (as I assume it does not) simply refuse to handle differences between the data order?
**Specifically, if I shift a uint16_t (or any non-trivial datatype) right by 8 bits, and mask out the bottom 8 with &0xFF, do I *always* get the second-least-significant (in this *particular* case, high) byte, or can the compiler produce alternate outputs based on byte order?**

Does Arduino have an equivalent of network byte order (or does Wire automatically do so for its overrides of the functions) that I can get around this potential issue with?

body:
There seems to be multiple questions in what you are asking. Here I try
to answer specifically this one:

> if I shift a `uint16_t` (or any non-trivial datatype) right by 8 bits,
> and mask out the bottom 8 with `&0xFF`, do I always get the
> second-least-significant (in this particular case, high) byte, or can
> the compiler produce alternate outputs based on byte order?

Short answer: yes, you get the second-least-significant byte,
irrespective of the platform's native endianness.

Now, I'll expand on this answer by showing the different ways you
can convert an `uint16_t` to a sequence of bytes, and the implications
on the byte order.

If you want to control the endianness, and you want your code to work
independently of the native endianness of the platform, then bit
shifting is the way to go. Let's assume you want to convert this:

```c++
uint16_t data;
```

into this:

```c++
uint8_t bytes[2];
```

You can do it this way in order to get the least significant byte first:

```c++
bytes[0] = data >> 0;  // least significant byte
bytes[1] = data >> 8;  // most significant byte
```

Or you can instead do the assignments the other way around
(`data >> 8` goes to `bytes[0]`...) if you want MSB first. Note that
there is no point in masking, as the assignment does it implicitly.

In contrast, if you wanted to put the bytes in _native_ endianness (the
endianness of the platform), the traditional way to do it is to cast the
address of the number to a pointer to bytes, then read from this
pointer:

```c++
bytes[0] = ((uint8_t *) &data)[0];  // first byte
bytes[1] = ((uint8_t *) &data)[1];  // last byte
```

You can swap the indices on one side of the assignments if you want to
instead reverse the byte order. But note that this kind of casting is
now frowned upon, as it violates aliasing rules. A common alternative is
to have the number and the byte array share the memory within an
`union`:

```c++
union {
    uint16_t data;
    uint8_t bytes[2];
} x = { .data = some_16_bit_value };
do_something_with(x.bytes[0]);  // use first byte
do_something_with(x.bytes[1]);  // use second byte
```

These are the main byte-splitting idioms you may come across. If your
purpose is to have an endianness that you control and is independent of
the platform, then stick with the first option: the old good bit
shifting.


message:
Arduino Nano burns with ESP-01 in parallel

So I have an Arduino Nano powered in parallel with an ESP-01 (for the ESP there is an extra LM1117-5.0 voltage regulator in series).

    +12V ---------+---------+
                  |         |
                 Reg        |
                  |        NANO
                 ESP        |
                  |         |
     GND ---------+---------+

My problem is that after a while, the Nano burns (my guess is the difference in current that both devices draw).

In any case, what could be the reason and what could I do to fix it?

Thanks!

body:
Use the 5v regulator to power both the ESP and the Nano. Those onboard regulators have minimal heat dissipation and if they burn out you lose the whole Nano. Check how hot your external regulator gets and mount it on a heat sink if it gets too hot to touch.
NB Connect the regulator output to the Nano 5v pin directly


body:
12V is the upper limit for input voltage on an Arduino. With a 12V input the regulator has to convert 12-5, or 7 volts, to heat. (That's how linear voltage regulators work.) As the other poster said, Arduinos don't have much heat dissipation on their voltage regulators.

Like jksemple, I would suggest powering both the ESP and the Nano from the external regulator (You might want to cut a USB cable and wire it to your external voltage regulator, then plug it into your Nano. That way you're not bypassing the power control circuits on the Nano.

By the way, did you build a full voltage regulator with the LM1117 chip? You need some extra components like capacitors and resistors to complete the voltage regulator.

Finally, you might think about using a DC-DC buck converter rather than a linear regulator. That will run a lot cooler and waste a lot less power.


message:
ESP8266 ESP-07 does not respond to commands

I just bought an ESP8266 ESP-07 V1.0 Serial Wifi Transceiver. Similiar to this: https://www.ebay.com/itm/ESP8266-Serial-Wifi-Transceiver-Module-for-Arduino-ESP-07-V1-0-New-/331868488091

I have connect the RX and TX pins to the RX and TX pin of the Arduino (RX to TX and TX to RX), VCC is connected to 3.3V and GND is connected to Arduino ground.
I have used the following code and writing commands to the module using the serial monitor:

    #include <SoftwareSerial.h>

    int RX_PIN = 3;
    int TX_PIN = 4;

    SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

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

        while (!Serial){
        ;
      }

        while (!mySerial){
        ;
      }
      Serial.println("Ready");
    }
    void loop()
    {
        // listen for communication from the ESP8266 and then write it to the serial monitor
        if ( mySerial.available() )   {  Serial.write( mySerial.read() );  }

        // listen for user input and send it to the ESP8266
        if ( Serial.available() )       {  mySerial.write( Serial.read() );  }
    }

Whatever I type (for example AT+GMR) in the serial monitor at 9600 baud I don't get any response. What could be the reason? Both NL and CR is added to the command.

When pressing reset on the ESP-module I get this in the Serial monitoring:

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

Thanks for any help!

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

body:
The esp8266 is without AT firmware. Even with SoftwareSerial at 115200 baud you should see "ready" from AT firmware and get some response to AT commands.

This esp8266 module adapter is simple to flash. It makes the 5 V to 3.3 V conversion for power and RX pin and has a program switch (io 0) and a reset button to put the esp8266 into flashing mode.

Use an USB-to-TTL-Serial adapter or an Arduino with USB chip to connect the adapter to PC. Then switch to "program" and reset it and it will be in flashing mode.

You can download the AT firmware [here][1]. I recommend ESP8266 NonOS AT Bin V1.7.1. Don't try 2.0, it is very different (ESP32 AT firmware build for esp8266).

To flash it, use [esptool][2]

The command to flash the AT firmware binaries to any module with at least 1 MB flash memory is:

    esptool.py write_flash --flash_size 2MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin

don't wonder about the 2MB-c1 setting and don't change it. The AT binaries are build for 2MB-c1 partitioning. On 1 MB flash it will not support AT firmware OTA update.

If you want to use the [Espressif Flash Download Tool][3], use the same settings as on esptool command line.

  [1]: https://www.espressif.com/en/support/download/at
  [2]: https://github.com/espressif/esptool#installation--dependencies
  [3]: https://www.espressif.com/en/support/download/other-tools?keys=&field_type_tid[]=14


message:
Use std::list in Arduino programming

When trying to compile

    #include <list>
    std::list<byte> l = { 7, 5, 16, 8 };

in the Arduino IDE (with [ATtinyCore](https://github.com/SpenceKonde/ATTinyCore) for ATtiny4313), I get this message:

> error: list: No such file or directory
  #include <list\>

**How to use the standard C++ `std::list` with Arduino/ATtiny?**

body:
I don't think that this library is supported by attiny (or even Arduino in general).

However, beyond that, it is not advised to use it, since it is uncertain how much memory and flash overhead it consumes.

Especially the memory is an issue for two reasons:

- Internally, you don't know the exact data structures used for the list. In most efficient way, it will only use 4 bytes (4 times 1 byte for the array), however, since it is a class under the hood a vtable is added, and who knows what more memory (maximum capacity, current capacity of the list etc).
- Also when adding/removing an item from the list, either the entire list is copied, or some tricks with pointers are used. In the first case you get memory gaps, in the second case maybe (and additional memory for the pointers is used).

My advice is to use just a simple array, and define a maximum of the array at compile time (if possible). Not as flexible, but robust, less memory usage and more reliable with a low SRAM  device like the Attiny (and Arduino in general).

**Removing elements**

Based on your first comment:

Removing items is indeed an issue, however, note that if you use the standard library it might copy the entire array (excluding) the new item, so temporarily you will have double the array AND a memory gap.

There are some ways to implement it yourself:

- If you only want to remove items (and never add), add a new array with booleans that denote which are present and which are deleted (e.g. deleted[4] = 1 means that item 4 is deleted. This only cost 1 bit per element.
- Use two arrays with items, and copy them back and forth each time. This will cause not really a memory gap, but you need the storage needed for two arrays. And keep a variable which of the two arrays is the 'current'.


body:
I back up Michel Keijzers' suggestion to use a plain array, especially
given the tiny amount of RAM in your MCU (only 256 bytes).

Concerning the removal of items from the list, and given that your list
will be 16 bytes at most, you don't need to get fancy: just move back
the items that are past the one you removed. It will not take long.

Here is a barebones implementation of a list that can hold at most
16 bytes and supports removal:

```c++
class List {
public:
    byte length;
    byte data[16];
    void append(byte item) {
        if (length < 16) data[length++] = item;
    }
    void remove(byte index) {
        if (index >= length) return;
        memmove(&data[index], &data[index+1], length - index - 1);
        length--;
    }
};
```

Note that this only takes 17 bytes of RAM (16 items max plus a
length count). There is not vtable, as it has no virtual methods. You
can get fancier if you want, make this a template parametrized by the
data type and the maximum length, add accessors and such... but if you
are just writing a simple sketch (as opposed to a general purpose
library), I would recommend keeping it as simple as possible.

Example usage, based on your pseudo-code:

```c++
List l { .length = 3, .data = { 12, 82, 29 } };
l.remove(1);
```

This will indeed result in the list [12, 29].