message:
Using Software Serial on Arduino Mega

So Im using this sensor:
https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386 with this library https://github.com/DFRobotdl/DFRobot_WT61PC

Im using 2 sensors but got poor frequency on Arduino Uno and decicded to switch to Mega since it supports multiple communications at once.

This code works perfectly fine on Uno, but doesnt on Mega. Of course I tried using this method: https://docs.arduino.cc/built-in-examples/communication/MultiSerialMega and I know I shouldnt be using Software Serial on Mega but **this library has been written using Software Serial and I cant use a different method** (or at least thats how I understand it).

Here is the reason.
```c++
SoftwareSerial mySerial(10, 11);
DFRobot_WT61PC sensor(&mySerial);
```
So I tried multiple variations of pins (ones supporting UART, pcint, TX/RX) https://docs.arduino.cc/learn/built-in-libraries/software-serial and nothing seems to we working. Also tried removing the SD card reader, tried the original example code. I also tried Hardware Serial as it should be but again, it doesnt support this sensor and ends up resulting in errors(or vice versa). Nothing.

Here is the working Uno code:
```c++
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

  pinMode(VCC2,OUTPUT);
  digitalWrite(VCC2,HIGH);

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_10HZ);
  sensor2.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{

  long timestamp = millis();

  float acc1;
  float acc2 ;
  float acc3 ;
  float gyro1 ;
  float gyro2 ;
  float gyro3;
  float angle1;
  float angle2;
  float angle3;

  float acc12 ;
  float acc22 ;
  float acc32 ;
  float gyro12;
  float gyro22 ;
  float gyro32 ;
  float angle12 ;
  float angle22;
  float angle32;

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}
```
I also found this question: https://arduino.stackexchange.com/questions/37333/arduino-mega-2560-softwareserial-not-working.
The guy has exact problem as I do but nooone found a solution to it.
I also want to note that the manufacturer states that this library and sensor works fine on Mega. Really need your help.

cheers

@edit
So I did some tests and the only code that actually shows something in monitor is:
```c++
#include <DFRobot_WT61PC.h>

DFRobot_WT61PC sensor(&Serial);

void setup()
{
  //Use Serial as debugging serial port

  //Use software serial port mySerial as communication seiral port
  Serial.begin(9600);
  sensor.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{
  if (sensor.available()) {
    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }
}
```

[![monitor][1]][1]
But as you see the output is corrupted.

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

body:
There are three fairly major issues in your code:

* The Mega does not support SoftwareSerial on pins 2, 3, 5, 6 because those pins do not support change interrupts. Thus it simply can't work on those pins. This itself is a show-stopper.

* Your code to read data is flawed. You test if a single byte is available (sensor.available()) and then proceed to read 9 bytes. There is no guarantee that 8 of them are actually there.

* I'm confused about what you are doing in your second block of code. You are telling the sensor library to get its data from Serial, which is where you type stuff. All that would do is echo what you type, bearing in mind my point directly above.


sender: user

sender: assistant

body:
It's quick and dirty but you can make it Mega compatible by deleting the line `#include <SoftwareSerial.h>`, and replacing the lines

    SoftwareSerial mySerial(2, 3);
    SoftwareSerial mySerial2(5, 6);
with

    #define mySerial Serial1
    #define mySerial Serial2
replacing `Serial1` and `Serial2` with whichever of the Mega's serial ports you wish to use for mySerial and mySerial2, and connecting your DFRobot sensor signals to the correct pins for your chosen hardware serial ports.


message:
Tone() function pauses between notes

I tried to experiment with the `tone()` function that comes with the arduino library.

I played around with the standard code example located here:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody

This is the code:

    #include "pitches.h"

    int melody[] =
    {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };

    int noteDurations[] =
    {
      4, 8, 8, 4, 4, 4, 4, 4
    };

    void setup()
    {
       for (int thisNote = 0; thisNote < 8; thisNote++)
       {
          int noteDuration = 1000 / noteDurations[thisNote];
          tone(8, melody[thisNote], noteDuration);

          // to distinguish the notes, set a minimum time between them.
          // the note's duration + 30% seems to work well:
          int pauseBetweenNotes = noteDuration * 1.30;
          delay(pauseBetweenNotes);

          // stop the tone playing:
          noTone(8);

       }
    }

    void loop()
    {
      // no need to repeat the melody.
    }

However, the problem is that there is always a pause between notes.
In musical terms, this is called `staccato`.
I want to be able to play short melodies where there are no delays between the notes, and one note progresses to the next naturally. By the way, this is called `legato` in music theory.

Now, in this example, the delay between the notes sounds good because this "music piece" is supposed to be played this way. But in every other song that i experimented with, there were always some pauses between notes.

This is what this song sounds like: https://soundcloud.com/nikowow-1/normal

Naturally, my mind went to the `delay(pauseBetweenNotes)` function. So i thought this is what causes the delay between the notes. So i set it up to `0.5`. This is what it sounds like: https://soundcloud.com/nikowow-1/05a

As you can hear, it just speeds up the whole song. The delay between the notes remain, but the whole song is sped up (in a higher tempo, so to speak).

In order to better hear the delay between the notes, please take a listen at the song when i selected a value of `3` - causing a smaller tempo, so that the delay between the notes can be more easily audible: https://soundcloud.com/nikowow-1/3a-1

I want to create some melodies where there are no delays between the notes and i am stuck.

EDIT: If you remove the delay line alltogether, the song is played so quickly that only a click sound is heard.

body:
there is
```
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
```

so the *1.30 creates the pause.

if you change it to
```
   int pauseBetweenNotes = noteDuration;
```
there will be no pause between notes.

The tone length is specified with the last parameter of the tone() function (`noteDuration` here).


message:
Anyone had Digispark Attiny85 not SEEN by some USB controllers but seen via HUB or DOCK on same device?

I have purchased a couple of different types of DigiSpark Attiny85 clones (couldn't find originals available) and they have worked great except some devices (so far, just laptops) don't see the device AT ALL.

It's not that they don't recognise it and so is a driver issue - there is nothing to apply the driver to, no indication that the thing is even plugged in other than the light comes on (so I know it has power).

More frustratingly, if I plug the Digisparks in to any problematic device via a docking station, USB hub, etc. everything works as expected (confirming the drivers are ok) and I can write scripts to the digispark.

I've tried updating the Nucleous bootloader but the problem persists.  I get this problem on three modern laptops (HP & 2 Dells) but my older Lenovo laptops have no problems.  Not sure if here is an issue with modern USB controllers?

UPDATE: Everything points towards it just being an issue with Digispark's and some USB 3.0 controllers.  The clock is correctly set at 16.5Mhz so not sure what else to do other than write these-off as a reliable device.

Anyone had any experience of this or have any suggestions?

Thanks!

body: It appears the problem is down to issues around Attiny85 timing with USB 3.0 chipsets and so isn't something that can be solved.


body:
The four USB traces on the digistump board are NOT to perfect specification and don't work with 4/5 conductor USB3 ports.  Use a dremel or band saw and cut about 2/3 of the end off the digistump Printed Circuit Board USB plug. Leave enough of the original four traces to solder to.  Cut off the plug end from an older USB cord. After carefully cutting away and cleaning off the plastic and old wires on the actual USB plug, it fits perfectly to line up to the old (now shorter) traces on the digistump. Be sure trace sides are the same direction on old and new plug and solder all four connections.  Add some superglue and/or silicone for strength and it should work every time with any USB port.

WZ


message:
Quaternion values from Arduino 9-axis motion shield seem very wrong

I am currently usinga BNO055 sensor fitted on the Arduino Nine-axis motion shield to measure ocean wave heights and periods. To do this, I'd like to use the quaternions provided, however I have a slight issue. A quaternion should be <cos(theta/2), X*sin(theta/2), Y*sin(theta/2), Z*sin(theta/2)>, with X, Y and Z the coordinates of a unit vector and theta the angle of rotation around that vector. Therefore, I expect all three to be inferior to one.

However, when I run a simple code to see the raw data, the W given by my sensor when on the table is 16 375, and X, Y and Z values are in the high hundreds range...

This gives me a wave height of hundreds of thousands of kilometers :slightly_smiling_face:

Does anyone know why this happens? Do I need to divide the quaternion by it's norm to get the correct result? Or maybe I am misunderstanding the use of a quaternion?

Oh, and I have calibrated the sensor beforehand

Thanks in advance for your help

body:
I am not familiar with this sensor, so I am just guessing.

The sensor is likely giving you [fixed-point][] numbers. Judging from
the real part, there are most likely 14 bits right of the implicit
radix point. If that is the case, the actual quaternion can be computed
as:

```c
float w = raw_w / 16384.0;
float x = raw_x / 16384.0;
float y = raw_y / 16384.0;
float z = raw_z / 16384.0;
```

You can check whether this is reasonable by computing the norm, which
should be very close to one.

[fixed-point]: https://en.wikipedia.org/wiki/Fixed-point_arithmetic


message:
Perform Volume Control on arduino speaker

I am following this guide to produce tones with the arduino:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody

This uses the `tone()` builtin function. The connections is that one pin of the speaker got to one digital pin of the arduino, while the other goes to ground.

Is there a way to perform volume control (perhaps with a potentiometer) on this setup?
What worries me is that this is digital information (PWM) that goes to the speaker, and not an analog signal that can be adjusted.

body:
The `tone()` function generates a 50% duty cycle square wave using a timer and interrupts. 50% duty cycle is basically full volume.

It's possible to reduce the volume by reducing the duty cycle, but the `tone()` function does not support it. It is of course possible to change the software PWM generation to change the duty cycle (I wouldn't know how, so don't ask me), but I'll leave that as an academic exersize for you to experiment with should you wish.

An alternative is to do it in hardware. You can use an op-amp as buffer (or speaker driver) and a couple of resistors (or a potentiometer) as an "attenuator" before it to change the voltate of the signal going to the op-amp.

You need the op-amp as a buffer because the speaker will mess with the potentiometer otherwise.


body:
There is a [library][1] from LixieLabs that implements an audio-based PWM at super high frequencies that allows you to change the tone volume without additional hardware.

  [1]: https://hackaday.io/project/11957-10-bit-component-less-volume-control-for-arduino


message:
External Interrupt not working on 3.3V atmega168

I made a 3.3V board and I've put both atmega328p (that I pulled off of a 3.3V pro mini), and an atmega168 that I bootloaded (using USBtinyISP whilst selecting board "Arduino Pro or Pro Mini" and "atmega168 (3.3V, 8MHz") .

Everything works perfectly with the atmega328 - code works and interrupts do as well - which function to pull the Arduino out of sleep when INT0 rises.

However on the Atmega168, the interrupt doesn't seem to work. All the normal code works as expected (communications, instructions etc), just not the interrupt. After the Arduino goes to sleep, I can't wake it since the interrupt isn't working.

Basic code below:

    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes

    byte interruptPin = 2; //Turn board on/off
    unsigned long shutDownTimer = 0; // Timer for shutdown

    void setup() {
      Serial.begin(57600);
      pinMode(interruptPin, INPUT); //Set pin d2 to input using the buildin pullup resistor
      Serial.println("Starting");

    }

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

      // Shutdown control
      if (digitalRead(interruptPin) == LOW ) {
        Serial.println("Shutdown detected");
        shutDownTimer = millis();
        while (digitalRead(interruptPin) == LOW ) {
          if (millis() - shutDownTimer > 1000) {
            Serial.println("sleep mode triggered");
            Going_To_Sleep();
          }
        }
      }
    }

    void Going_To_Sleep() {
      sleep_enable();//Enabling sleep mode
      delay(1000);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
      delay(1000); //wait a second to allow the led to be turned off before going to sleep
      attachInterrupt(0, wakeUp, RISING);//attaching a interrupt to pin d2

      Serial.println("Interrrupt attached");//Print message to serial monitor
      sleep_cpu();//activating sleep mode
      Serial.println("just woke up!");//next line of code executed after the interrupt

    }

    void wakeUp() {
      sleep_disable();//Disable sleep mode
      detachInterrupt(0); //Removes the interrupt from pin 2;
      Serial.println("Interrrupt Fired - wakeup");//Print message to serial monitor

    }

Instead of using "attachInterrupt(0, wakeUp, RISING);" Ive also tried the following which also don't work:

    attachInterrupt(INT0, wakeUp, RISING);
    attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, RISING);
    attachInterrupt(32, wakeUp, RISING);  //since its the pin of the chip? Hail Mary
    attachInterrupt(2, wakeUp, RISING);  //obviously this won't work, Hail Mary 2

I have no idea why the interrupts aren't working. I have an inkling it might be due to something fuse related within the boot loader, but I don't really understand things at that level (Though I'm happy to dive in with some guidance). Any guidance will be appreciated!

body:
According to the [datasheet for the Atmega168](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-9365-Automotive-Microcontrollers-ATmega88-ATmega168_Datasheet.pdf):

> Note that recognition of falling or rising
edge interrupts on INT0 or INT1 requires the presence of an I/O clock, described in
Section 6.1 “Clock Systems and their Distribution” on page 23. Low level interrupt on INT0 and INT1 is detected
asynchronously. This implies that this interrupt can be used for waking the part also from sleep modes other than idle mode.
The I/O clock is halted in all sleep modes except idle mode

In other words, only the LOW interrupt wakes it from sleep.

Having said that, the Atmega328P does wake from sleep with a rising or falling interrupt, as I have previously had confirmed by Atmel, however I can't say for sure that this enhancement (over what is stated in the datasheet) applies to the 168.

You could try doing a bit of testing to confirm that. Maybe rejig so that the interrupt occurs when the signal goes low rather than high, and then use a LOW interrupt and not a RISING one.

Also, don't do serial prints inside an ISR. The modern versions of the library handles that better than in the past, but this may still be an issue. As suggested in a comment, try flashing an LED rather than printing something. Or don't print anything, after all you print something when it wakes up. Why print something extra inside the ISR? That is just asking for trouble.


body:
Depending on what signal you are using to wake the Arduino, you may also find pin change interrupts an alternative to the edge triggered interrupts you are currently using.
These are usually more predictable in behaviour and less subject to nuanced interpretations of the data sheets.
See https://playground.arduino.cc/Main/PinChangeInterrupt/ for examples of how to use these.


message:
PubSub'a - KeepAlive function not as expected

I'm using `PubSubClient` to pub/sub MQTT messages using ESP8266.

As far as I know "Keep-alive" detects when a client went off-line after a period of time.

I'm using library's example `mqtt_ESP8266` with 2 minor adjusments (noted "<----- 1/2"), to use keepAlive.

1. Timeout was set to 45 sec (`client.setKeepAlive(45);`), in order to be "far enough" from reboot.
2. Pressing on-board Reset button.
3. Although Wifi+MQTT connection establish after 10 sec, and mqtt sends messages as shown `loop`, a "DEAD" publish is sent to designated topic after roughly 45 seconds from (2) , whuch makes no sense since MQTT was reconnected 35 seconds before.

Appreciate assistance,
Guy

    /*
      Basic ESP8266 MQTT example
      This sketch demonstrates the capabilities of the pubsub library in combination
      with the ESP8266 board/library.
      It connects to an MQTT server then:
      - publishes "hello world" to the topic "outTopic" every two seconds
      - subscribes to the topic "inTopic", printing out any messages
        it receives. NB - it assumes the received payloads are strings not binary
      - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
        else switch it off
      It will reconnect to the server if the connection is lost using a blocking
      reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
      achieve the same result without blocking the main loop.
      To install the ESP8266 board, (using Arduino 1.6.4+):
      - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
           http://arduino.esp8266.com/stable/package_esp8266com_index.json
      - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
      - Select your ESP8266 in "Tools -> Board"
    */

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.

    const char* ssid = "Wifi";
    const char* password = "Password";
    const char* mqtt_server = "192.168.2.100";

    WiFiClient espClient;
    PubSubClient client(espClient);
    unsigned long lastMsg = 0;
    #define MSG_BUFFER_SIZE (50)
    char msg[MSG_BUFFER_SIZE];
    int value = 0;

    void setup_wifi() {

      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

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

      randomSeed(micros());

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

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is active low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        client.setKeepAlive(45);  \\ <--------- Line 1
        if (client.connect(clientId.c_str(), "guy", "kupelu9e", "myHome/log", 0, true, \\ < "DEAD")) { \\ <---- Line 2
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("outTopic", "hello world");
          // ... and resubscribe
          client.subscribe("inTopic");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
    }

    void loop() {

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

      unsigned long now = millis();
      if (now - lastMsg > 2000) {
        lastMsg = now;
        ++value;
        snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("myHome/debug", msg);
      }
    }

body:
This is the correct behavior.

The “last will” message is sent by the broker when it detects that the client has gone away.

When you reset the ESP8266, the original connection to the broker is destroyed. When it restarts, it creates a new, second connection, it does not resume the original connection. So the broker correctly transmits the last will message when the original connection times out.


message:
passive buzzer is drawing 500mA

I am having a ridiculously hard time trying to make a passive buzzer work correctly on my Seeeduino XIAO.

Here is the buzzer module :
[![enter image description here][1]][1]

Here is how I believe it works, assuming the SOT23 smd is a PNP transistor? :
[![enter image description here][2]][2]

I plugged VCC to a +5V rail, GND to the ground rail, and I/O pin to my Seeeduino XIAO's pin 2 (aka "A2 / D2" :
[![enter image description here][3]][3]

When I write ```DigitalWrite(2, LOW)```, I can mesure about 0.4V on pin 2, while ```DigitalWrite(2, HIGH)``` reads about 3.3V (I assume the 5V rail feeding my Seeeduino XIAO's VCC gets converted to 3v3 through an internal regulator)

I understand I have to oscillate the signal to make this module buzz (remember it is a passive buzzer, or a transducer, whatever it is called), or simply use the ```tone()``` method, and I eventually managed to make this beep on and off every 1 second successfully during 10 seconds, but what bothers me is that I can NOT turn this module OFF after 10 seconds as a test in my sketch. It stops beeping after 10 sec as expected (```ìf (millis() < 10000) { doBeep(); }``` , but it still draws massive current and gets hot after that delay. It's like the PNP transistor never turns off? I tried both digitalWrite HIGH and LOW but no success.

This is driving me crazy. What am I doing wrong?

  [1]: https://i.stack.imgur.com/KTWnE.png
  [2]: https://i.stack.imgur.com/ZFGoT.png
  [3]: https://i.stack.imgur.com/yf5Fj.jpg

body:
You're right that it's a PNP transistor - the SS8550 to be precise.

And therein lies the problem.

When running at 5V to "make no current flow" through the base the voltage at the base has to be higher than 4.4V (5v - 0.6v), and since you're controlling it from a 3.3V microcontroller that can never happen. So you are right in thinking it never turns off - it never does.

Even when you're "beeping" it it's not turning fully off, so the beep sounds you make will be reduced accordingly.

You should power the board from 3.3V instead of 5V so the PNP can turn off fully. If that is not possible then switching the GPIO pin to INPUT mode will prevent it from driving the PNP thus allowing it to turn itself off.


message:
Where should unit tests go in the Arduino IDE

I have an Arduino project where the file structure looks like this

```
myProject/
    myProject.ino
    ImportantClass1.hpp
    ImportantClass1.cpp
    ImportantClass2.hpp
    ImportantClass2.cpp
    Etc….

```

It compiles and runs fine. No problem pulling the cpp and hpp files into the ino program. However to really make sure of reliability I want to make additional ino files for unit testing of importantClass1 & etc. I have made files ``` importantClass1UnitTest.ino ``` & ``` importantClass2UnitTest.ino ``` however these can’t be in the same dir as the respective source files as the arduino compiler requires the ino file and the dir to have the same name.

The tests run when I move the files around. But I am not happy with that, I want to be able to run the tests at any time with the standard arduino compiler without having to script filecopy commands.

If I put the unit test in its own dir separate to the class source and ```#include``` using the full path it also works. However this solutions is not portable, when I (or any collaborator) pull the project from git hub on any other computer the paths are wrong and it doesn’t work.

Where am I going wrong? How can I do this so as to avoid moving/copying files and also avoid using full paths?

body:
One way to do it is to use preprocessor conditionals. Name your project file and unit-test files with `.cpp` extensions and put them in a subfolder (called "sources" in my example). Then your `.ino` file would only be used to instruct the preprocessor which of the several "main" file to start compiling with:

myProject.ino:

    /*
     * myProject.ino
     * define which "main" CPP file to compile:
     */

    #define PRODUCTION
    // #define UNITTEST1
    // #define UNITTEST2
    // #define UNITTEST3

    // The compilation starts here with the requested "main" file:
    #if defined PRODUCTION
    #include "sources/myProject.cpp"

    #elif defined UNITTEST1
    #include "sources/unitTest1.cpp"

    #elif defined UNITTEST2
    #include "sources/unitTest2.cpp"

    #elif defined UNITTEST3
    #include "sources/unitTest3.cpp"

    #else
    // If nothing defined, compile for production
    #include "sources/myProject.cpp"
    #endif

    /* END */

Only the .ino file would need to be edited to compile one of the unit tests, and only one project file would be needed.

Update:
"did you try it? "

Yes, and it does work. The only caveat I'd add is: don't name your subfolder "src" - that seems to be a magic-name to the IDE, and you'll get complaints of compilation errors (multiple definitions) if you use it. And further, if you try it, you can't get back simply by changing the folder's name (on disk and in the code); you'll have to restart the IDE as well.
<br>I tested it with v1.8.19 of the IDE.


message:
Help with reading data from ADXL373 Accelerometer (I2C)

I am using [ADXL373Z][1] accelerometer with Arduino Uno for a project.

When I run the code, I am getting incorrect values which are probably not even acceleration data. I am thinking it might be a wiring problem, I attached circuit diagram below. This is my first Arduino project, and I couldn't find any other applications with the sensor I am using so any help would be much appreciated. Thanks in advance.

Datasheet for sensor : https://www.analog.com/media/en/technical-documentation/data-sheets/adxl373.pdf

Code ( for x-axis data only) :

    // ADXL373 Accelerometer Test

    #include <Wire.h>

    /* -------- REGISTERS -------- */
    #define ADDRESS_ADXL373 0x53 // sensor adress (assumes MISO pin high)
    #define ADDRESS_POWER_CTL 0x3F // power control
    #define ADDRESS_MEASURE 0x0E // measurement control
    #define ADDRESS_TIMING 0x3D // output data rate and extarnal timing triggers
    #define ADDRESS_XDATA_H 0x08 // x-axis acceleration data [11:4]
    #define ADDRESS_XDATA_L 0x09 // x-axis acceleration data [3:0]
    #define ADDRESS_YDATA_H 0x0A // y-axis acceleration data [11:4]
    #define ADDRESS_YDATA_L 0x0B // y-axis acceleration data [3:0]
    #define ADDRESS_ZDATA_H 0x0C // z-axis acceleration data [11:4]
    #define ADDRESS_ZDATA_L 0x0D // z-axis acceleration data [3:0]
    /* -------- REGISTERS -------- */

    #define SCALE_FACTOR 0.2f // 200 mg per LSB scaling factor
    #define GRAVITY_EARTH 9.80665f // gravity of earth in m/s^2

    void setup() {
      Serial.begin(115200);
      while(!Serial);
      Serial.println("ADXL373 Accelerometer Test");
      Wire.begin();
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_POWER_CTL);
      Wire.write(0x03); // activate full bandwith measurement mode
      Wire.endTransmission(true);
      delay(50);
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_MEASURE);
      Wire.write(0x04); // set output signal bandwith to 2560 Hz
      Wire.endTransmission(true);
      delay(50);
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_TIMING);
      Wire.write(0x80); // set output data rate to 5120 Hz
      Wire.endTransmission(true);
      delay(50);
    }

    void loop() {
      byte xAxisH, xAxisL;
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_XDATA_H);
      Wire.endTransmission(false);
      Wire.requestFrom(ADDRESS_ADXL373, 1, true);
      xAxisH = Wire.read();
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_XDATA_L);
      Wire.endTransmission(false);
      Wire.requestFrom(ADDRESS_ADXL373, 1, true);
      xAxisL = Wire.read();
      int16_t xAxisFinal;
      xAxisFinal = (uint16_t) xAxisH << 8 | xAxisL; // bit shift and combine two components
      xAxisFinal = xAxisFinal >> 4; // 12-bit resolution
      float xAccel;
      xAccel = xAxisFinal * SCALE_FACTOR * GRAVITY_EARTH;
      Serial.print("Xa = "); Serial.println(xAccel);
      delay(200);
    }

Circuit Diagram :

[![Circuit Diagram][2]][2]

Results from Serial Monitor (in m/s^2) :

[![Serial Monitor][3]][3]

  [1]: https://eu.mouser.com/ProductDetail/Analog-Devices/EVAL-ADXL373Z?qs=QNEnbhJQKva6ENie%2BWXLsQ==
  [2]: https://i.stack.imgur.com/qFgje.png
  [3]: https://i.stack.imgur.com/Gnn1p.png

body:
According to the datasheet, the 12 bits of the X acceleration are stored
into the registers `XDATA_H` and `XDATA_L` as follows:

```text
XDATA_H:   b₁₁b₁₀b₉ b₈ b₇ b₆ b₅ b₄
XDATA_L:   b₃ b₂ b₁ b₀ x  x  x  x
```

where `x` means “reserved”.

Now, there are two issues with this code:

```c++
xAxisFinal = xAxisH << 4 | xAxisL; // bit shift 12-bit output data
```

The first issue is that, by shifting `xAxisH` by four places, the bits
b₇–b₄ end up in the same positions as the bits b₃–b₀ in `xAxisL`. Then,
when those values are combined with `|`, the bit b₇ gets mixed with b₃,
b₆ with b₂, etc. If you really want to shift `xAxisH` left by four
places, you should also shift `xAxisL` right by four places.

The second issue is that the x data is a signed number represented as
two's complement, and the sign bit (b₁₁) ends up in the wrong place. For
example, if the measured value is −16 (XDATA\_H:XDATA\_L = 0xff:0x00),
you end up reading 4980 (0x0ff0). In order to avoid this issue you could
[sign extend][] the 12-bit number to 16 bits.

I would suggest, though, a completely different approach. The number is
left justified in the sensor registers, so just keep it like this:

```c++
xAxisFinal = (uint16_t) xAxisH << 8 | xAxisL;
```

The intermediate cast to `uint16_t` is here to avoid an undefined
behavior, the final result is signed. If there is some risk that the
reserved bits are non-zero (the datasheet is not very clear in this
respect), you could

```c++
xAxisFinal &= 0xfff0;  // clear last 4 bits
```

Note that now the unit of the acceleration is 1/16 of the resolution of
the sensor, and all values you get are multiples of 16. I don't expect
this to be an issue. If you really want to use the sensor resolution as
your unit, you could now shift `xAxisFinal` four places to the right,
which would automatically perform the sign extension.

[sign extend]: https://en.wikipedia.org/wiki/Sign_extension

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

**Edit**: Addressing the edited code from the OP:

> I modified the code according to your suggestions. But I am still
> getting incorrect values from serial monitor.

What I see in your post is very small values, around ±3 LSBs of the
sensor. This could very well be sensor noise. But then, there is the
occasional larger value. Interestingly, those larger values seem to be
very close to ±16 LSBs, hinting at some kind of communication
problem.

I guess the answer is in this warning from the sensor's datasheet:

> Always read acceleration data using multibyte transfers to ensure that
> a concurrent and complete set of x, y, and z acceleration data is
> read.

Imagine the sensor is outputting only noise, and the noise fluctuates
between −1 and +1 LSB. What you expect then is:

    value  XDATA_H   XDATA_L
      −1   11111111  11110000
      +1   00000000  00010000

If you read `XDATA_H` and `XDATA_L` in two different transactions, you
may well read 0b11111111 for `XDATA_H` (as the sensor is reading  −1),
then read `00010000` for `XDATA_L` (as it is getting +1). When you
combine these two readings together, you get

    value  XDATA_H   XDATA_L
     −15   11111111  00010000

I suggest you follow the recommendation from the datasheet and read both
registers in one go:

```c++
Wire.beginTransmission(ADDRESS_ADXL373);
Wire.write(ADDRESS_XDATA_H);
Wire.endTransmission(false);
Wire.requestFrom(ADDRESS_ADXL373, 2, true);
xAxisH = Wire.read();
xAxisL = Wire.read();
```


message:
Measured voltage higher than AREF

What happen when a  voltage measured by analogRead() is higher than AREF voltage?

Example: AREF = 2.5V AO = 3.2V

What is the maximum voltage ?

body: You will be reading the maximum ADC value. If you were sampling a waveform the top of it would be clipped off at 2.5v.


message:
PWM on Wemos D1 Mini (esp8266 chip) does not work

I am working on a hobby project: creating an rc-(radio controlled)-toy car.

I'm working with a **Wemos D1 Mini** (esp8266) microcontroller, **L298N** H-bridge (for controlling the motor) and I'm using the **Arduino IDE** to program it all.

The project is quite simple: make the car drive around via an virtual joystick on an app. The project is quite fun and a nice learning experience for me. The project is going pretty well until this point.

I can move the car forwards and backwards with a constant speed, but I'm not able to change the speed via a **PWM** signal. Actually, I'm not even sure if it is even possible to create a PWM signal on the Wemos D1 Mini, I have never done it before on this specific controller. I'm not an electrical engineer, so I'm not really familiar with very specific details about the controller itself.

Can somebody help me create a PWM signal to control the speed of the car?

This is what I have got now, very basic stuff:

```c
void setup() {
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);
}

void forward() {
  digitalWrite(D5, LOW);
  digitalWrite(D6, HIGH);
}

void backward() {
  digitalWrite(D5, HIGH);
  digitalWrite(D6, LOW);
}

void setVelocity(int value){
  analogWrite(D2, value);
}

void loop() {
  setVelocity(1023);
  forward();
}
```

Thanks in advance!

Sincerly,

Stefan

body:
At one point `analogWrite` as it was implemented in the esp8266-core had defaulted to a 10-bit range. This is [no longer the case](https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output). It defaults to 8-bit range now.

In any case `analogWrite` is implemented to [clamp](https://github.com/esp8266/Arduino/blob/f2d83ba/cores/esp8266/core_esp8266_wiring_pwm.cpp#L57,L59) the given value to be within the range.

If you were not experimenting in the bottom quarter of the velocity range with your code as written then you would have seen full velocity.

You can change to working with the 8-bit range or use `analogWriteRange(new_range)` or `analogWriteResolution(bits)` as [this](https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output) mentions.

Your code as is will produce a 50% duty cycle 1Khz signal on D2 if setVelocity is given 128 with the current core.


message:
ISR for very fast processes, strange code found. Has ISR effect on timer behaviour?

I found the following code within an example for performing very fast changes on a PWM-output. It works, however I'm wondering about some details.

TIMER2 was set up in setup() as follows:

    TCCR2A = 0;               // We need no options in control register A
    TCCR2B = (1 << CS21);     // Set prescaller to divide by 8
    TIMSK2 = (1 << OCIE2A);   // Set timer to call ISR when TCNT2 = OCRA2
    OCR2A = 32;               // sets the frequency of the generated wave
    sei();                    // Enable interrupts to generate waveform!

If I understand that correctly, the timer will run until overflow and generate interrupts any time in between as defined by OCR2A.

    ISR(TIMER2_COMPA_vect) {  // Called each time TCNT2 == OCR2A
      static byte index=0;    // Points to successive entries in the wavetable
      OCR1AL = wave[index++]; // Update the PWM output
      asm("NOP;NOP");         // Fine tuning
      TCNT2 = 6;              // Timing to compensate for time spent in ISR
    }

TIMER2 is used to call this routine in equidistant points in time.
To adapt the timespan between two calls of the ISR the author sets OCR2A and within the ISR resets TCNT2. As the timer is reset at the end of the ISR there's some time "already gone" written into the start value of the timer. However there are two things I don't understand.

 1. Why isn't CTC mode used by setting WGM21 in TCCR2A? This should call the ISR in precise intervals.

 2. If not using CTC mode the counter has to be reset by the ISR. But why isn't that done directly at the beginning of the ISR? Everytime the ISR gets some minor changes the correction value written into TCNT2 has to be changed.

Am I missing some vital detail? Or is my idea of using CTC better?

For sake of completeness, the only other things done in setup() are configurations on timer1:

    pinMode(9, OUTPUT);       // Make timer's PWM pin an output
    TCCR1B  = (1 << CS10);    // Set prescaler to full 16MHz
    TCCR1A |= (1 << COM1A1);  // PWM pin to go low when TCNT1=OCR1A
    TCCR1A |= (1 << WGM10);   // Put timer into 8-bit fast PWM mode
    TCCR1B |= (1 << WGM12);

loop() is empty.

body:
> Why isn't CTC mode used by setting WGM21 in TCCR2A?

As we cannot read the author's mind, we cannot say for sure. That being
said, to me, the most likely reason is that either the author was not
aware of CTC mode, or they just didn't think about it.

You are right that CTC is the most straightforward way to get precise
intervals. You are also right that the resetting the timer at the end of
the ISR makes the code somewhat fragile. If, for some reason, I needed
to avoid CTC in a code like this, I would

```c++
OCR2A += 32;
```

rather than resetting `TCNT2`.


message:
Determining ArduinoJSON document size based on file size

I'm trying to effectively allocate a doc's size, based on the size of the file saved in flash of ESP8266. Is there a way?

For example: `file.size()` X 1.5

body:
There is unfortunately no way to predict the size of the [`JsonDocument`](https://arduinojson.org/v6/api/jsondocument/) from the file size alone.

As a workaround, I suggest that you allocate a very large memory pool and shrink  it after deserialization; like so:

```c++
DynamicJsonDocument doc(ESP.getMaxAllocHeap());
deserializeJson(doc, file);
doc.shrinkToFit();
```

Indeed, this program consumes more memory than strictly required, but only for a fraction of a second.

See also:

* [How to determine the capacity of the JsonDocument?](https://arduinojson.org/v6/how-to/determine-the-capacity-of-the-jsondocument/)
* [BasicJsonDocument<T>::shrinkToFit()](https://arduinojson.org/v6/api/basicjsondocument/shrinktofit/)


message:
Funduino USB Host Shield problems

I'm currently working on connecting a Funduino version of usb host shield onto an arduino mega board. But the serial output shows "osc did not start", which means the board can't find the shield. However the reset button works, so I estimate insufficient power being supplied.

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

I'm aware of the bridging solution for the regular arduino module for the 3.3v and 5v ([example][2]). But how can this solution be applied to the Funduino model.

Update: I've changed the SPI lines on the shield to the 6 ISCP pins on the Mega, but still no change in results.

I performed a second test using board_qc, which returned:

Circuits At Home 2011

USB Host Shield Quality Control Routine

Reading REVISION register... Die revision invalid. Value returned: 00

Unrecoverable error - test halted!!

0x55 pattern is transmitted via SPI

Press RESET to restart test

  [1]: https://i.stack.imgur.com/2KNVC.jpg
  [2]: http://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html

body:
That shield communicates over SPI. However the SPI pins it uses are the "old" style (10-13) for the Arduino UNO.

The Mega doesn't use those pins, which is why the "new" style 6-pin SPI/ICSP header was added to boards.

You will have to manually jumper the right pins to the SPI pins of the Mega using wires.


message:
Can we use more than one timer when programming an Atmega32/16?

I tried to do a simple program using the ATmega16 microcontroller, the program is to toggle two LEDs the first one by using timer0 interrupt and the other using timer2 interrupt.

body:
Yes, we can.

(stackexchange wants the body of the answer to be at least 30 characters, so I have to add some filler. Truth is, for answering the question _as asked_, there is nothing more to say.)


body:
Yes, you can. However there is one thing to note:

**Only one ISR can run at once.**

That means that if one LED wants to toggle while the other one is in the process of toggling it will have to wait until that first ISR is finished before it can toggle.

For simple LED toggling that won't be noticeable, but it's something you need to bear in mind if you are doing multiple things that require precise timing.


message:
ESP8266 Wemos D1 min pro - how to change TCP_SND_BUF?

Is there any way to change the TCP send buffer size (TCP_SND_BUF) on this module ?

Now it is equal to `TCP_SND_BUF = 2 * TCP_MSS = 2 * 1460 = 2920`.

Editing `lwipopts.h` doesn't make any difference.

The same question applies to `ΤCP_MSS`, `TCP_WND` etc.

I am using v2 Higher Bandwidth variant. Platform is Microchip Studio with vMicro Arduino addon.

body:
No, you can't.

The macro you are trying to tweak is for reference only and does not control the size of the buffer.

On the ESP8266 the IP stack (and much of the rest of the system) is precompiled as `.a` libraries. Changing things like the `TCP_SND_BUF` macro will never change what has been compiled into those libraries. Instead all it will do is cause problems of buffer overruns and corrupted data as other code is then given incorrect information about the size of the buffer.


body:
I finally figured it out the hard way :

https://github.com/esp8266/Arduino/discussions/8616

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

Install **Git** for windows (https://git-scm.com/download/win)

Install **MinGW** for windows (https://sourceforge.net/projects/mingw)

In **MinGW** installation manager, enable:

- mingw-developer-toolkit
- mingw32-base
- mingw32-gcc-g++
- msys-base

_(not sure if all are necessary but just in case)_

put _C:\MinGW\bin_ in Windows PATH (check this https://www.rapidee.com)

**reboot PC**
--------------------

rename **C:\MinGW\bin\mingw32-make.exe** to **C:\MinGW\bin\make.exe**

open **bash** terminal (just type bash in run)

_(from now on assume that hardware files are in \Documents\Arduino\hardware\esp8266com\esp8266)_

go to _\tools\sdk\lwip2_

optional: change **lwip options** in _\tools\sdk\lwip2\builder\glue-lwip\arduino\lwipopts.h_

(caution : **NOT** _\tools\sdk\lwip2\include\lwipopts.h_, this will be overwritten !)

type in bash: **make install** to build libraries in _\esp8266com\esp8266\tools\sdk\lwip2\builder_

type in bash: **make clean** to clean _\esp8266com\esp8266\tools\sdk\lwip2\builder_

finally copy new libraries to _\esp8266com\esp8266\tools\sdk\lib_


message:
Create member object using constructor arguments, or pass reference to object via constructor

I'm not entirely sure about the proper C++ terminology, so I'll just illustrate what I'm trying to achieve by giving a Java example since it should be pretty obvious:

~~~
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(int rows, int cols, int i2cAddress) {
        this.lcd = new HD44780Lcd(rows, cols, i2cAddress);
    }
}
~~~

or... alternatively...

~~~
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(HD44780Lcd lcd) {
        this.lcd = lcd;
    }
}
~~~

For what it's worth, there's no real concern about scope... LcdDecorator is a Singleton that gets created in setup(), then lives forever and gets used by loop() until the power gets shut off.

#### Here's what I've attempted so far:

`LcdFacade.h`:
~~~
#ifndef CORECONTROLLER_LCDFACADE_H
#define CORECONTROLLER_LCDACADE_H

#include <stdint.h>
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

class LcdFacade {

public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) ;
};

#endif //CORECONTROLLER_LCDFACADE_H
~~~

`LcdFacade.cpp`:
~~~
#include "LcdFacade.h"
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

HD44780LCD lcd;

LcdFacade::LcdFacade (uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd{rows, cols, i2cAddress} {
    // ... the rest of the constructor goes here ...
}
~~~

note: I also tried using parentheses instead of braces for lcd's constructor:
~~~
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd(rows, cols, i2cAddress) {
~~~

In CLion, the 'lcd{rows, cols, i2caddress}' portion of the constructor in LcdFacade.cpp is red-underlined, and reports `member initializer 'lcd' does not name a non-static data member or base class`

Meanwhile, gcc(?) reports `error: no matching function for call to 'HD44780LCD::HD44780LCD()` on line 4 of LcdFacade.cpp.

Any ideas?

body:
When you define

```c++
HD44780LCD lcd;
```

at global scope, you are creating a global variable that is initialized
before `main()` is called. In this case, it is initialized with the
default constructor `HD44780LCD::HD44780LCD()`, which does not exist,
hence the error. You could avoid this error by calling a suitable
constructor in the initialization, e.g.

```c++
HD44780LCD lcd(4, 20, 0x23);
```

but this may be inconvenient to you.

If you want to initialize `lcd` in the constructor of `LcdFacade`, then
it must be a non-static member of the class:

```c++
// In LcdFacade.h:
class LcdFacade {
public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress);
private:
    HD44780LCD lcd;  // <- non-static member
};

// In LcdFacade.cpp:
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress)
: lcd(rows, cols, i2cAddress) {
    ...
}
```


message:
Why does the data I send to the server get rounded off and how do I send the entire float instead?

#include <Arduino.h>
    #include <WiFi.h>
    #include "WiFiManager.H"
    #include <HTTPClient.H>
    #include "ESPAsyncWebServer.h"
    #include <AsyncTCP.h>

    float version = 1.9;

    uint32_t chipId = 0;
    String chipId2 = "";
    int i;

    String serverName = "http://d";

    // WiFiManager
    // Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;

    // Create AsyncWebServer object on port 80
    AsyncWebServer server2(80);
    WiFiServer server(80);

    // variables to count the pulses of the meters.
    int count1=0;
    float prior_count1=0;
    int count2=0;
    float prior_count2=0;
    int count3=0;
    float prior_count3=0;
    int count4=0;
    float prior_count4=0;
    int countgas=0;
    float prior_countgas=0;
    int countwater=0;
    float prior_countwater=0;

    String payloadpulse = "0";

    unsigned long lastTime = 0;
    unsigned long timerDelay = 6000;

    String guifactor1 = "1000";
    String guifactor2 = "1000";
    String guifactor3 = "1000";
    String guifactor4 = "1000";
    String guifactorgas = "1000";
    String guifactorwater = "1000";

    String counter1 = "1";
    String counter2 = "1";
    String counter3 = "1";
    String counter4 = "1";
    String counter5 = "1";
    String counter6 = "1";

    // function to increment the meters value by 1.
    void pulse1() {
      if (counter1.toInt() == 1) {
        count1 = count1 + 1;
      }

      if (counter1.toInt() == 2) {
        count1 = count1 - 1;
      }
    }

    void pulse2() {
      if (counter2.toInt() == 1) {
        count2 = count2 + 1;
      }

      if (counter2.toInt() == 2) {
        count2 = count2 - 1;
      }
    }

    void pulse3() {
      if (counter3.toInt() == 1) {
        count3 = count3 + 1;
      }

      if (counter3.toInt() == 2) {
        count3 = count3 - 1;
      }
    }

    void pulse4() {
      if (counter4.toInt() == 1) {
        count4 = count4 + 1;
      }

      if (counter4.toInt() == 2) {
        count4 = count4 - 1;
      }
    }

    void pulsegas() {
      if (counter5.toInt() == 1) {
        countgas = countgas + 1;
      }

      if (counter5.toInt() == 2) {
        countgas = countgas - 1;
      }
    }

    void pulsewater() {
      if (counter6.toInt() == 1) {
        countwater = countwater + 1;
      }

      if (counter6.toInt() == 2) {
        countwater = countwater - 1;
      }
    }

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

      wifiManager.autoConnect("ss", "ss");

      pinMode(25, INPUT_PULLDOWN); // Set GPIO25 as digital output pin
      attachInterrupt(digitalPinToInterrupt(25), pulse1, RISING);

      pinMode(19, INPUT_PULLDOWN); // Set GPIO19 as digital output pin
      attachInterrupt(digitalPinToInterrupt(19), pulse2, RISING);

      pinMode(23, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
      attachInterrupt(digitalPinToInterrupt(23), pulse3, RISING);

      pinMode(18, INPUT_PULLDOWN);// Set GPIO18 as digital output pin
      attachInterrupt(digitalPinToInterrupt(18), pulse4, RISING);

      pinMode(21, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
      attachInterrupt(digitalPinToInterrupt(21), pulsegas, RISING);

      pinMode(5, INPUT_PULLDOWN); // Set GPIO5 as digital output pin
      attachInterrupt(digitalPinToInterrupt(5), pulsewater, RISING);
    }

    //--------------------------------------------------------------------
    void loop() {
      float new_count1  = static_cast<float> (count1) / guifactor1.toInt();
      float new_count2 = static_cast<float> (count2) / guifactor2.toInt();
      float new_count3 = static_cast<float> (count3) / guifactor3.toInt();
      float new_count4 = static_cast<float> (count4) / guifactor4.toInt();
      float new_countgas = static_cast<float> (countgas) / guifactorgas.toInt();
      float new_countwater = static_cast<float> (countwater) / guifactorwater.toInt();

      // keeps track of the amount of pulses of pulse meters
      if (new_count1 != prior_count1 ||
       new_count2 != prior_count2 ||
        new_count3 != prior_count3 ||
         new_count4 != prior_count4 ||
          new_countgas != prior_countgas ||
           new_countwater != prior_countwater) {
         Serial.println(new_count1, 4);
         Serial.println(new_count2, 4);
         Serial.println(new_count3, 4);
         Serial.println(new_count4, 4);
         Serial.println(new_countgas, 4);
         Serial.println(new_countwater, 4);
         prior_count1 = new_count1;
         prior_count2 = new_count2;
         prior_count3 = new_count3;
         prior_count4 = new_count4;
         prior_countgas = new_countgas;
         prior_countwater = new_countwater;
      }
      // sends an update to the web
      if ((new_count1 > 0 && ((millis() - lastTime) > timerDelay)) ||
       (new_count2 > 0 && ((millis() - lastTime) > timerDelay)) ||
        (new_count3 > 0 && ((millis() - lastTime) > timerDelay)) ||
         (new_count4 > 0 && ((millis() - lastTime) > timerDelay)) ||
          (new_countgas > 0 && ((millis() - lastTime) > timerDelay)) ||
           (new_countwater > 0 && ((millis() - lastTime) > timerDelay))) {
      {
          // checks if wifi is connected.
          if (WiFi.status()== WL_CONNECTED) {
            HTTPClient http;
            // preparation HTTP GET request.
             String serverPath = serverName + "?chip_id=" + chipId + "&count1=" + new_count1 + "&count2=" + new_count2 + "&count3=" +
             new_count3 + "&count4=" + new_count4 + "&countgas=" + new_countgas + "&countwater=" + new_countwater;
            // Your Domain name with URL path or IP address  with path.
            http.begin(serverPath.c_str());
            // Send HTTP GET request.
            int httpResponseCode = http.GET();
            // confirms the arrival of a response from the server or sends an error.
            if (httpResponseCode>0) {
              count1 = 0;
              count2 = 0;
              count3 = 0;
              count4 = 0;
              countgas = 0;
              countwater = 0;
              payloadpulse = http.getString();
              Serial.println(payloadpulse);
             }
             else {
              Serial.print("Error code: ");
              Serial.println(httpResponseCode);
             }
            // closes the HTTP connection.
            http.end();
          }
          else {
           Serial.println("WiFi Disconnected");
          }
        }
      }

      //reset timer when done sending data
      if (((millis() - lastTime) > timerDelay)) {
        lastTime = millis();
      }
    }

The program is a pulse counter which should add 0.001 pulse everytime it detects one. I expect it to send 0.006 to the server, but instead it sends 0.01. How do I make sure it doesn't send rounded data?

body:
The constructor for the String object from float is this:

    String(double, unsigned char decimalPlaces=2);

So if you don't want to have 2 decimal digits, you have to use `String(someFloat, 3)`.

Also you have to remember there are limits for the floating point numbers, but in this case it shouldn't be the case.

And as Edgar mentioned, String objects are bit dangerous if they are overused, particularly building that serverPath is the worst way how to do it (every single level of it creates new temp object to be copied into next bigger one and released).

It would be cheaper to do it like:

    String serverPath;
    serverPath.reserve(100); // reserve space so it doesn't have to resize; should be proper estimate
    serverPath += serverName;
    serverPath += "?chip_id=";  // on AVR it should be F()
    serverPath += chipId;
    serverPath += "&count1=";
    serverPath += new_count1;
    serverPath += "&count2=";
    serverPath += new_count2;
    serverPath += "&count3=";
    serverPath += new_count3;
    serverPath += "&count4=";
    serverPath += new_count4;
    serverPath += "&countgas=";
    serverPath += new_countgas;
    serverPath += "&countwater=";
    serverPath += new_countwater;

or you can use some c++ magic:

    template <class T> inline String & operator<<(String & out, T const & what) {
        out += what;
        return out;
    }

    String serverPath;
    serverPath.reserve(100); // reserve space so it doesn't have to resize

    serverPath << serverName << "?chip_id=" << chipId << "&count1="
               << new_count1 << "&count2=" << new_count2 << "&count3="
               << new_count3 << "&count4=" << new_count4 << "&countgas="
               << new_countgas << "&countwater=" << new_countwater;

this code takes `serverPath << serverName` adds serverName into serverPath and the result is serverPath again, and then it continues as `serverPath << "?chip_id="` and so on


message:
No text in the IDE menu items

I installed arduino 1.8.19 (64-bit) on a Fedora Linux 35 Workstation Edition system. When I started the IDE, and selected the "Open" menu icon, the menu item list appeared, but there was no text displayed with the items. I could open sub-menu items, but there was still no text. It looked like:

[![The "Open" menu with no text][1]][1]

I tried several other 1.8.x versions, but with the same result. I haven't found any discussion about this on the Web. so I suspect that it is problem with my configuration. Nevertheless, any suggestions will be most welcome. I have not tried to install the IDE on Windows 10, but that is an option.

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

body:
There is a incompatibility between Arduino 1.8.19 and Fedora 35. On another PC, where I was running an older version of Arduino, I upgraded to Fedora 36 and the upgrade warned me of the incompatibility with the older Arduino and Fedora 36 and said it was deleting Arduino. After the Fedora upgrade completed, I installed Arduino 1.8.19 and it worked as expected. When I upgraded the original PC, the one with the no text in the menus, to Fedora 36, the menus also worked as expected. Hallelujah!! So, all is well and I have my answer. Thanks for your replies.

[![Arduino 1.8.19 and Fedora 36 are working as expected][1]][1]

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


message:
Will the atmega8-U2 work with Arduino IDE

I use a homemade board that hosts a PIC16F1829 and an ATmega328P on the same board.  We use the ATmega328P with the Arduino IDE and the PIC with the MPLABX IDE for about 100 EE students a semester at UTSA.  I have 100 pic chips but no ATmega328P chips, I can re-spin the board and adapt it to the ATmega8-U2, since right now I can by 250 ATmega8-U2 chips that are in stock but there are no ATmega328P chips available anywhere and I need 100 at least. I am currently using a different UART to TTL adapter, the CP2102 to connect the ATmega328P to the Arduino IDE.  I have the 2 chips talk via a shared I2C line. How difficult will it be to use the Arduino IDE with the ATmega8-U2?  (Again, not as the UART to USB interface but as the main processor.  Thanks,

body:
I never tried, but it seems to me it should work without issues.

In the Arduino IDE, Menu Tools → Board, you can select “Arduino NG or
older”. You then have a menu Tools → Processor where you can select
either “ATmega168” or “ATmega8”. These options don't require you to
install any extra board support package: they come with the default
“classic” AVR core, which does support the ATmega8.


message:
Servo retaining its position every time I send some value

I wanted to control my servo with a Bluetooth module.

I gave certain values for rotating it. When I press those values the servo rotates, but then retains its original position and the PC also makes the sound of the Arduino board disconnecting because I powered the board with my PC (tried with powerbank also). Even my Bluetooth disconnects.

This is my code:

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    char data = 0;

    void setup() {
      myservo.attach(9);
      Serial.begin(9600);
    }

    void loop() {
      if (Serial.available() > 0) {
        data = Serial.read();
        if (data == 'F') {
          // for (pos = 0; pos <= 180; pos += 1)
          myservo.write(180);
          delay(1);
        }
      }
      else if (data == 'B') {
        // for (pos = 180; pos >= 0; pos -= 1)
        myservo.write(0);
        delay(1);
      }
    }

Connections:

Servo:
```
red wire -- 5 V (not working at 3.3 V)
orange wire -- pin9
brown wire -- gnd
```
Bluetooth (hc05):
```
5 V -- 5 V
gnd -- gnd
rx -- tx
tx -- rx
```

body: I tried changing the USB B cable with a better quality one and it worked.


message:
Efficient way to save accelerometer data on sd card

I have analog accelerometer that transfer acceleration on 3 axis with frequency 5 kHz. I want to store that data in SD card for in txt file. My sketch is the following:

```
void loop()
{

  // Get raw accelerometer data for each axis
  int rawX = analogRead(A0);
  int rawY = analogRead(A1);
  int rawZ = analogRead(A2);

  // Scale accelerometer ADC readings into common units
  // Scale map depends on if using a 5V or 3.3V microcontroller
  float scaledX, scaledY, scaledZ; // Scaled values for each axis
  if (micro_is_5V) // Microcontroller runs off 5V
  {

    scaledX = mapf(rawX, 0, 1023, -scale, scale); // 3.3/5 * 1023 =~ 675
    scaledY = mapf(rawY, 0, 1023, -scale, scale);
    scaledZ = mapf(rawZ, 0, 1023, -scale, scale);

  }
  else // Microcontroller runs off 3.3V
  {
    scaledX = mapf(rawX, 0, 675, -scale, scale);
    scaledY = mapf(rawY, 0, 675, -scale, scale);
    scaledZ = mapf(rawZ, 0, 675, -scale, scale);
  }

   String dataString = "";
   // Concatenate string
   dataString += String(scaledX);
   dataString += "\t\t";
   dataString += String(scaledY);
   dataString += "\t\t";
   dataString += String(scaledZ);
   dataString += "\t\t";
   saveSD();
}

// Same functionality as Arduino's standard map function, except using floats
float mapf(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void saveSD()
{
  // create file for writing
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  // if file is available
  if (dataFile) {
    // save the data
    dataFile.println(dataString);
    // close file
    dataFile.close();
  } else {
    // if file is unavailable
    Serial.println("Error opening datalog.txt");
  }
}
```
So in loop I open file, write to it and after that close it. When my file will be big enough there will be bottle neck.It will take a lot of time to read and write file.
How to deal with saving data to files on SD card?

**UPD:**
I measured the time of executing code like that:
```
  ...
  start_open_t=micros(); // time in milli seconds
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  delta_open_t=micros() - start_open_t ;
  // if file is available for writing
  if (dataFile) {
    // save the data
    start_write_t=micros(); // time in milli seconds
    dataFile.println(dataString);
    delta_write_t=micros() - start_write_t ;
    // close the file
    start_close_t=micros(); // time in milli seconds
    dataFile.close();
    delta_close_t=micros() - start_close_t ;
    ...

```
And there is the result:
```
Open time:
7656
Write time:
2176
Close time:
8076
```
The open time is increasing there is no surprise (with increasing the file size).
Write to file and close time is almost constant.
I thought to open file in setup() and initialize timer. Write to file in loop() and after some time interval to close the file, after that open new file and so on. But as can be seen the print operation ```dataFile.println(dataString);``` takes approximately 2 ms that is 500 Hz, and it is too slow. I need to register with 5 kHz.
If I print in serial the data is printed much faster but I can not  connect to usb because arduino is located to far (approx 30 meters).
May be there is the way to connect to serial with wifi or bluetooth or may be there are another methods to store the data fast?

body:
I can see it is safe to open/close the file every time, especially closing, as if the Arduino loses power, the entire file can be corrupted possibly.

However, I can find of some 'solutions':

 1. Backup battery

Open the file in `setup()`, and only close the file when the backup battery becomes active (instead of closing the file after every write). This will however need an external battery, and some implementation to check if it is active. Also, during the external battery is active, no data should be written.

 2. Using multiple files

More easier is to use multiple files, and write each time period (less than the  size of the file that cause problems) in a separate file. You can either close the file after each write, or when starting a new period, meaning when the Arduino loses power, you only lose the last time period.

  3. Using binary format

This can be used in combination with solution 1 and 2, and is to not write the files as text files but in binary format, reducing the size considerably.


message:
Library fails to compile

I want to try out this library:
https://github.com/connornishijima/arduino-volume3

I downloaded the zip file from github, renamed it, and included it as a library in the IDE.

So run one of the examples, `A4_440HZ`
This is its code:

    #include "Volume3.h"
    #define speakerPin 9

    uint16_t frequency = 440;

    void setup() {
      // Nothing neeeded here!
    }

    void loop() {
      for(uint16_t volume = 0; volume < 1023; volume++){
        vol.tone(speakerPin,frequency,volume);
        delay(1);
      }
      for(uint16_t volume = 1023; volume > 0; volume--){
        vol.tone(speakerPin,frequency,volume);
        delay(1);
      }
    }

And i get this error:

    Error Compiling
    A4_440Hz.cpp.o: In function `loop':
    /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
    collect2: error: ld returned 1 exit status

I have no idea what is to blame, or how to mitigate it.

This is the first time that an included example from a library does not play out of the box.

body:
This is kind of a weird situation. The library declares the object
`vol`, but fails to define it. On the ancient version of the Arduino IDE
you are using, compilation fails, understandably, because `vol` has
never been defined. What is weird is that, on a more recent version
(1.8.15 on Ubuntu here), compilation succeeds.

It is worth noting that `vol` belongs to the class `Volume`, which is an
empty class. As such, it only plays the role of a namespace for the
functions `vol.tone()` and `vol.noTone()`. Strictly speaking, as `vol`
has no data (its size is zero), the compiler should never need to access
it. My guess is that the newer Arduino manages to compile this only
because it uses different optimization settings than the ancient 1.0.5.

Anyhow, you have two options:

- upgrade your installation of the Arduino IDE

- declare `Volume vol;` near the top of the sketch.

**Edit**: I did some tests and it appears that, as I suspected, this is
related to [link-time optimization][lto] (LTO). Since version 1.5.7, the
Arduino IDE enables LTO, and when this is the case, the linker doesn't
complain about missing empty objects.

The library could be fixed by defining `vol` in Volume3.cpp, although
this would create a weird empty object in the BSS. Another option would
be to declare both methods as `static` within Volume3.h. This would make
the compiler know it doesn't actually need to reference the `vol` object
when one of its methods is called.

Would you submit a pull request with one of those fixes?

[lto]: https://en.wikipedia.org/wiki/Interprocedural_optimization


message:
Mildly accurate oscilloscope using Arduino Uno R3

I'm trying to make a mildly accurate oscilloscope using Arduino Uno R3 and I've done some research on the best method to do so. First of all I need to measure the voltage with a rather high sampling rate and then I'm going to transfer my data through the serial port and plot the data using Python or Matlab.

According to what I have read the `analogread()` function will cause some delay and therefore some inaccuracies and thus it is not suitable for my purpose.

I found on [**this**][1] website some good info about how I should write my code, but I have some questions:

1. I want my reference voltage to be 1.1 V so that by dividing it to 1023 parts I will have an accuracy of about 1 mV. How should I edit the mentioned code in order to do so?

2. The code in the `void loop()` setup is of no use to me (I prefer not to save the measured data on the Arduino and then send to my PC because of memory limitations). After deleting it will the data still be sent to the serial port?

3. Will sending the data through the serial port affect my sample rate/accuracy? I mean how does it effect my accuracy?

P.S: by mildly accurate this is what I mean: I want to measure voltage accurately with 1 mV precision for frequencies of max. 500 kHz (a bit less or more won't hurt).

  [1]: http://yaab-arduino.blogspot.com/2015/02/fast-sampling-from-analog-input.html

body:
> I want my reference voltatge to be 1.1v so that by dividing it to
> 1023 parts I will have the accuracy of about 1mv.

You will have a _resolution_ of about 1 mV. The accuracy will be
significantly worse than that due to the imperfections of the ADC
(offset error, gain error, non-linearity) and noise.

> how should I edit the mentioned code in order to do so?

The reference is configured by the bits `REFS0` and `REFS1` of the
`ADMUX` register. The internal 1.1 V reference is selected by
setting both bits, as shown in table 24-3 of [the
datasheet][datasheet]. You can then patch the original code like this:

```diff
@@ -8,7 +8,7 @@
   ADCSRA = 0;             // clear ADCSRA register
   ADCSRB = 0;             // clear ADCSRB register
   ADMUX |= (0 & 0x07);    // set A0 analog input pin
-  ADMUX |= (1 << REFS0);  // set reference voltage
+  ADMUX |= (1 << REFS0) | (1 << REFS1);  // set reference voltage
   ADMUX |= (1 << ADLAR);  // left align ADC value to 8 bits from ADCH register

   // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
```

> the code in the `void loop()` setup is of no use for me (I prefer not
> to save the measured data on the arduino and then send to my pc
> because of memory limitations). after deleting it will the data still
> be sent to the serial port?

In the linked code, `loop()` is the only function sending anything to
the serial port. If you remove it, nothing will be sent. You could
`Serial.write()` in the ISR though, in which case an empty `loop()`
would be fine.

Note that writing to `Serial` from within an ISR is generally
discouraged. Your situation though (an oscilloscope code) is one of the
very few cases where it does make sense to do so.

> will sending the data through the serial port affect my sample
> rate/accuracy?

It can certainly affect your sampling rate. `Serial.write()` is usually
non-blocking, as all it does is write the data to the RAM-based transmit
buffer. If the buffer fills up, however, `Serial.write()` will block
waiting for the serial port to actually send the data, and make enough
room in the buffer.

This means that, in order for the oscilloscope to not miss samples, you
have to make sure that the serial port can send the data at least as
fast as the ADC is acquiring it.

**Example calculation**: If you clock the ADC at 1 MHz, you get one
sample every 13 µs. You can follow the example given in the code
you linked to, and discard the last two bits in order to transmit only
8 bits of the sample. Transmitting those in plain binary will take
10 “bits” worth of the serial port bandwidth (one start bit,
8 data bits and one stop bit). Each bit should then take less than
1.3 µs, which translates to a baud rate of 769,231 bits per
second. You will probably have no other choice than configuring the
serial port for 1 Mb/s.

If you want to transmit the whole 10 bits of the ADC readings, you
will have to lower the sampling rate by a factor two.

At this point you may notice that the serial port, rather than the ADC,
is the bottleneck for the performance of your oscilloscope. If this is
too limiting, you may consider building a scope that works by bursts: it
stores a burst of samples in memory, then sends it at a leisurely rate
through the serial port.

[datasheet]: https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738867


message:
Does an 5V 2.1 A will fit for this Led Schema?

Hello I would like to create an Arduino protoype with Led WS2182B.
I currently have
Arduino NANO (not UNO, like in this schema)
65 Led WS2182B = Which gives me 3.9 Amp of suply for full brighness (65*60mAmp)
Power supply of a movil charge wich have 5V 2.1 A

I am currently working with this schema from this [website][1]

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

I have a few questions
1) Does this battery will work for this schema replacing the usb conector?
2) Can I use the 68 leds at a medium energy, to make it suitable wih the power supply? Can this damage any device (Because in theory I believe it needs more than 2.1 Amps)
3)If this battery will not be appropiate to this schema. What could I do?

Thank you very much!

  [1]: https://core-electronics.com.au/guides/ws2812-addressable-leds-arduino-quickstart-guide/
  [2]: https://i.stack.imgur.com/rsZ5o.png

body:
You are using a standard USB power bank. It should be possible to power your project as long as you stay below the current limit (2.1A). Probably you should keep the intensity small enough to not exceed 1.9A in normal operation. That should be enough for about half intensity. You really don't want to exceed the current limit. And you should measure the actual current draw and then approach your own current limit (like 1.9A) from below. Calculations are good, but when operating like this you should look at the real values.

If you exceed the current limit of the power bank it depends on the implementation of the power bank what will happen. Most likely the power bank will cut the power but still work. Though it is also possible, that you fry some electronics inside the power bank and kill it this way.

Note:
- While you experiment with your code you can use fewer LEDs, so that they would be able to light up at full intensity. That makes sure, that you don't damage anything from a small programming error. If you write your code in the correct way (for example defining the number of LEDs at exactly one code line and reusing that name everywhere), then it will be easy to increase the number of LEDs to the target and also be sure, that you are staying within your limits.
- You already have it in your wiring diagram, but nonetheless I want to emphasize, that you must not power the LEDs through the Arduino. You need to connect them directly to the USB cable to the power bank. The Arduino cannot withstand such currents.
- USB power banks often cut power, when not enough current is being drawn from them (and for mine the current of an Arduino Nano wasn't enough to hold it active). If in your project the LEDs get turned of at some time, while the Arduino should keep running, the power bank might cut the power, thus turning off the Arduino. In my experience the bigger, more expensive power banks will do that, while small, cheap ones will just keep outputting the power. If this scenario is relevant for you, you need to test this yourself with your specific power bank.

> If this battery will not be appropiate to this schema. What could I do?

You could use multiple of these power banks, each of them powering its own part of the LED strip. One of them can also power the Arduino. Just make sure to connect all grounds together.


message:
Can I make an Arduino Uno Rev3 pretend to be a joystick?

I want to create a joystick for my flight simulator and I need to make an Arduino Uno Rev3 pretend to be a joystick when I plug it to my computer.

body:
The Uno doesn't have native USB capabilities. It uses an additional microcontroller (the Atmega16u2) as an USB to Serial adapter. In the default configuration this microcontroller is only programmed for providing a serial interface over USB, not a joystick interface. You can hack your Uno and reprogram the Atmega16u2 for providing a joystick interface (and there are tutorials for how to reprogram the Atmega16u2 online). (Note, that you need a genuine Arduino for this to work, since the cheap clones often only have CH430 chips as USB to Serial adapter)

But I would suggest going the easier way and buying an Arduino board, which itself has USB capabilities without the need of hacking the board, like the Arduino Micro. Then you can simply use one of the joystick libraries on it. This way will be a lot easier for a beginner than doing it with an Uno.


message:
Teensy 4.1 / 4.0 When to use FlexPWM vs QuadTimer pins to strobe LEDs

I want to strobe 3 LEDs (at independent frequencies and duty cycles) via mosfets with a duty cycle of 0.05%-1% at a frequency range of 24-100 hz. I would like to hold 1% or better accuracy for both duty cycle and frequency.

The Teensy 4.x seems perfect with its amazing PWM frequency and resolution controls, and generous number of independent PWM timers.

 1. For the purposes of my application, should I use pins with FlexPWM or QuadTimer? Does it matter?
 2. I see that the numbering convention is X.Y, is there any functional significance when X numbers are in common (IE FlexPWM 1.0 and FLexPWM 1.1)?

[See "Frequency" section of this page][1]

  [1]: https://www.pjrc.com/teensy/td_pulse.html

body:
I had cross-posted, and Paul Stoffregen answered [in the Teensy Forum][1].
Pasting Paul's great answer here for posterity:

> 1: Really doesn't matter for 0.05% accuracy.
>
> 2:See "PWM Frequency" on [this page.][2]
>
> The 3 pins identified as "FlexPWM1.0" (1, 44, 45) will always run at
> the same frequency. If you want different PWM frequency, you would
> need to choose pins from different groups.
>
> More detail on how the hardware actually works can be found in the
> reference manual. But usually that ends of being far too much
> information. The timers are packed with a mind boggling number of
> advanced features, which makes a steep learning curve if you want to
> dive into how the hardware really works.
>
> Most applications work fine by simply using analogWrite,
> analogWriteResolution and analogWriteFrequency. Everything you've said
> sounds like a pretty simple application that can be done easily with
> these 3 functions. You're only looking for 9 bit resolution from
> hardware than is natively 15 or 16 bits. Just use the easy functions
> do the low-level work for you.

  [1]: https://forum.pjrc.com/threads/70530-Teensy-4-1-4-0-When-to-use-FlexPWM-vs-QuadTimer-to-strobe-LEDs?p=308324#post308324
  [2]: https://www.pjrc.com/teensy/td_pulse.html


message:
Uploading sketch to multiple Arduinos connected in series

I'm currently working on a project where you essentially will have multiple Arduinos (1 Uno, multiple Nanos) daisy-chained, only connected through 2 digital pins and one wire for Serial communication (RX Pin -> TX Pin). (The first one is connected via USB to the PC.)

I figured the serial communication between the first Arduino and PC would also be forwarded through the RX and TX pins, but that doesn't seem to be the case.

As it's fairly tedious to update one at a time, is there a way of updating all of them at once, using only the one-way serial communication wire?

EDIT: Yeh so like imma just add a USB Port to every single component to the chain to update separately, and update every single one of them separately.

body:
Try connecting only the RX and reset pins. Serial programming is done by the bootloader, but it needs to be switched into programming mode first, which is done by resetting the chip and then sending a special code to the RX pin within a certain time period. When you program through the serial port (as you are doing with the Uno) the FTDI chip drives this pin for you, but you'll need to cascade that reset signal through to the other chips as well. This still isn't guarenteed to work 100%, because it depends on a number of other factors as well, but at least you'll have a chance.

When I've done stuff like this commercially I've programmed via the ICSP connector instead and made programming rigs out of spring-loaded pin connectors that the target boards simply clip onto. If you're planning on doing this with any degree of frequency then I'd recommend investing a bit of time into doing this yourself.

UPDATE: ok, I can see now why this isn't working. The Nano's CH340 usb-to-serial chip is pulling RX low, preventing the data stream from being read. Would work fine with standalone chips, obviously doesn't on the Nano.

I think your best option is to use ICSP. It's an extra pin, but if you breadboard then it shouldn't make any difference. Plus there are a number of advantages to doing so, including faster programming, the ability to upload/replace the bootloader and the ability to change fuses (e.g. to protect your firmware or disable the bootloader altogether to give you app more Flash space etc).

If you don't already know how to do this then the layout is:

 - Connect Uno SCLK(D13)/MOSI(D11)/GND pins to all the corresponding Nano pins.
 - Connect Uno D10 to all the Nano's RESET pins.
 - Connect Uno MISO(D12) to only the first Nano's MISO pin.
 - Connect Uno VIN to all the Nano VINs (you don't want all the Nanos being driven from the Uno's regulator)

Should wind up looking something like this:

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

Prepare the Uno for programming:

   - Set your IDE board type to Uno
   - Set IDE programmer type to "AVR ISP"
   - Upload IDE ArduinoISP sketch to the Uno

And now you're ready to program the Nanos:

   - Set your IDE board type to Nano
   - Set IDE programmer type to "Arduino as ISP"
   - Upload your Nano sketch using "Upload Using Programmer"

Just tried it now with the two Nanos in the photo, worked fine.

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


body:
There is a two-way protocol used by the bootloader which I describe [here](https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader/15937#15937).

You could conceivably connect all the Rx wires together, and use the Tx wire from the first one (so it responds appropriately), and discard the responses from the other units. If they program at exactly the same rate, and reset at exactly the same moment, that might work.

You might be better off just uploading using a device designed to do that, as I describe [on my forum](http://gammon.com.au/forum/?id=11638). The Atmega328P programmed using that method can be reprogrammed in about one second (so the time to hook up the wires is the long part). Using the ICSP interface on the chips, and a suitable plug, could make that very quick, and easy.

There are also stand-alone devices, for example [the Crossroads standalone programmer](http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html) which uses the techniques described in my forum post. You can use that in the field because it doesn't require a monitor or PC. You just hook it up via the ICSP port, select what file you want to upload, and hit the "program" button.


message:
How to display only specific data in the serial monitoring?

I got the following data as shown in the figure from imu razor which is connected to Arduino Mega 2560 in the serial monitoring and I want to get only the data that starts with "#A-R= "

Can any one provide me with code to do this?

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

This is my code:

    #define BUFF_SIZE 40
    char buffer[BUFF_SIZE];
    String header ;
    char Bufferheader[4] ;

    void setup(){
    Serial.begin(57600);
    Serial2.begin(57600);
    Serial2.write("#osct");
    }

    void loop() {

    int i = 0;
    while(Serial2.available()) {
    buffer[i++] = Serial2.read();
    if(i == BUFF_SIZE) break;
    }

    for(int j = 0; j < i; j++) {
    Serial.print(buffer[j]);

    }
    }

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

body:
Your code is doing literally nothing except reading from one serial port and passing it to another.

You need to throw away pretty much all that code and do some actual processing of the data.

You need to:

1. Read the incoming data a line at a time (that is, read everything up to the line ending into a buffer)
2. Examine the start of that buffer
3. Output whatever data from the buffer your examinations deem appropriate.

I can't go into detail here about how to do it, but there are tutorials covering all those topics available on the web. For the serial reading I have [a tutorial](https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27) that you may find helpful.


body:
The method outlined by Majenko is the general way of dealing with this
kind of requirement, and also probably the “cleanest” way. If, however,
you are confident that the incoming data always follows the pattern you
are showing, then you can “cheat” and cut some corners.

Consider this: in the sample you show, the character `'A'` only ever
appears as the second character in a line, and always as part of the
sequence `"#A-R="`. If you are confident that this is always the case,
then you can apply the following algorithm:

- the program processes one input character at a time, and decides
  whether to print it to its output or not
- it has two possible states: either it is printing every character it
  reads (because it believes the character belongs to a “#A-R” line), or
  it is not
- if it is printing and it reads an end of line, it prints that end of
  line, and then stops printing
- if it is not printing and it reads an `'A'`, it outputs `"#A"`, then
  starts printing all its input.

In code:

```c++
void loop() {
    static bool printing = false;  // are we printing what we read?
    if (Serial2.available()) {
        char c = Serial2.read();
        if (printing) {
            Serial.write(c);
            if (c == '\n')  // on end of line, stop printing
                printing = false;
        } else if (c == 'A') {  // on 'A', start printing
            Serial.print("#A");
            printing = true;
        }
    }
}
```

This code assumes your device uses ASCII LF (`'\n'`) as end-of-line
indicator. You will have to replace `'\n'` by `'\r'` if it uses ASCII CR
instead.


message:
Suggested pullup resistor values for 1-wire network

I'm attempting to connect 6 DS18B20 temperature sensors to an Arduino GPIO pin in a topology that looks something like this:

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

Conceptually, it's a star network with two star subnets.

The GPIO pin on the Arduino is connected to point "E" through a 4-inch wire, a JST connector, and another 4-inch wire.

The 3 wires (shown in green) connecting sensors "A", "B", and "C" to point "D" are approximately 3 feet long (and are, in fact, the original ~1-meter wires that came pre-attached to the sensors when I bought them). Segment ED is ~4 feet long.

The 3 wires (shown in blue) connecting sensors "G", "H", and "I" to point "F" are approximately 20-30 feet long (including the original 3-foot wires attached to the sensors when I bought them). Segment EF is ~8 feet long.

No parasitic power is involved. Every DS18b20 has 3 wires... +5v (probably closer to 4.5v by the time it gets to G/H/I), ground, and 1-wire data.

#### So... where would YOU recommend putting resistors (feel free to describe points besides the ones I labeled with letters), and what values would you use?

And... would it actually be any *better* to take advantage of the fourth (presently unused) wire in the cables I have connecting G, H, and I to F as a 'return wire' to turn it into a much longer daisy chain (E to F, F to G, G back to F, F to H, H back to F, F to I), or something even more radical (say, ED, DA, AD, DB, BD, DC, CD, DE, then continuing the daisy chain with EF as described previously)?

For what it's worth, I presently have a single 4.7k pullup resistor sitting at point "E", and it seems to work... but after reading Maxim's AppNote about ["Building reliable long 1-wire networks" (Appnote 148)][2], I'm feeling like it *shouldn't* work, and that I really *ought* to do something more sophisticated for the sake of long-term reliability.

  [1]: https://i.stack.imgur.com/o0JZE.png
  [2]: https://pdfserv.maximintegrated.com/en/an/AN148.pdf

body:
I have a linear network with three thermos at roughly 5', 20', and 40-50' from the micro (a 5v '328p), as well as being parasitically powered. The physical bus is a twisted pair from a Cat-5 cable. The pullup is 4.7KOhm on the processor board.

I've tested this network using a 3.3v '328p and it wasn't as reliable, but reducing the pullup to 2.2K (IIRC) fixed it.

I find Maxim's App Note 148, "[Guidelines for Reliable 1-Wire Networks][1]" to be very helpful and is my go-to for 1-wire network questions.

  [1]: https://pdfserv.maximintegrated.com/en/an/AN148.pdf


message:
Using an I2C barometer

When buying a barometer for my current project at work, I chose the MikroElektronika click 3 barometer. However, as it turns out, the library for it doesn't exist for Arduino.
I know it uses I2C communication, so I tried connecting the board to my Arduino UNO R3 as follows:

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

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

<!-- End schematic -->

However, I do not know how to use the output of the sensor. Is there a way to access the raw data measured by the sensor and post-process it myself, or is a library needed?

Thanks for your help

body:
I have found MikroElektronika library for the barometer 3. You can get basic idea how to communicate with the sensor.
[MikroElektronika c libraray][1]

  [1]: https://github.com/MikroElektronika/mikrosdk_click_v2/tree/master/clicks/barometer3

You can develop your own library based on that one for Arduino or you can read the data sheet of the sensor for more details.


message:
`noInterrupts()` causes the arduino to no longer appear in ports

Minimal working example:
```
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  noInterrupts();
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
```

When uploaded to my Arduino Nano 3.3v BLE from my M1 Mac, this causes the Nano to no longer appear in the ports menu. In order to get it to appear again, I have to double press the reset button on the Nano so that it resets to a default script. After doing this, the Nano is available in the ports menu again.

I also cannot see the Nano via `cat /dev/cu.<TAB>` when this script is uploaded to it.

Does anyone know why this happens? Or alternatively (if this is intended behaviour) why it is not documented in [`interrupts()`](https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts) or [`noInterrupts`](https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts)?

I've looked through some other posts, but I don't think they're duplicates of this one:
- [What functions are disabled with noInterrupts()?](https://arduino.stackexchange.com/questions/61567/what-functions-are-disabled-with-nointerrupts): doesn't highlight the behaviour I've seen in the MWE.
- [Trying to understand interaction of interrupts, noInterrupts and delays](https://arduino.stackexchange.com/questions/35358/trying-to-understand-interaction-of-interrupts-nointerrupts-and-delays): Gives interesting techniques for interrupts and embedded programming, but doesn't mention the behaviour I've seen

#### Edits in response to answers

So the MWE wasn't quite descriptive enough of my problem and some of the answers got caught up on that (which is my fault). I've included a more detailed description of what I'm doing below to describe what I'm actually doing, but I've also accepted the answer which I think answers the heart of the question "why do interrupts cause the Nano to not appear in port?".

What I'm actually doing is I've got two Arduino Nanos (call them primary and secondary) connected via I2C and `Wire.h`. Each Arduino nano is reading 15 analog inputs (via a multiplexer). The secondary Nano is then sending its 15 analog readings to the primary over I2C. But I'm getting a lot of noise in the analog readings of the primary Nano, but no noise in the secondary. This noise disappears when I disconnect I2C. So my theory was that digital SCL and SDA wires were causing noise in the analog sensor wires, but I observed the noise would only occur for ~2ms every ~10ms. I thought I'd disable interrupts (and therefor disable `Wire.h` from pulsing SCL/SDA) while I was reading the primary's analog sensors, and enable interrupts afterwards. This caused the Nano to not appear in the Ports tab, and the rest is the result of this post.

I now think I didn't include the 4.7Ohm pull-up resistor on SDA and SCL which seems to only be included on the official Arduino examples, and never on any random internet examples.

body:
I'm not really an expert on the Nano 3.3v BLE, however it appears that it is directly connected to the USB port and thus disabling interrupts will also disable its ability to respond to USB handshakes, thus it will appear to the host that it has been unplugged.

The original Nano had a separate chip (FT232RL) which handled the USB interface, and thus disabling interrupts on that Arduino would not drop the USB connection.

>  Or alternatively (if this is intended behaviour) why it is not documented in interrupts() or noInterrupts?

Probably the documentation has not kept up-to-date with later product releases. It is not uncommon for documentation to lag behind what the released products actually do.

As timemage points out in another answer, your attempts to blink LEDs with interrupts turned off will not succeed. In fact, turning interrupts off should only be done for milliseconds, not permanently. I assume that is a demonstration sketch, but still ... if you turn interrupts off only briefly the problem should go away.