message:
Error 'exec: "python": executable file not found in $PATH Error compiling for board AI Thinker ESP32-CAM.' in Arduino IDE 1.8.12

I am trying to upload a sketch to the ESP32-CAM board using Arduino IDE 1.8.12 and I get an error message:

    exec: "python": executable file not found in $PATH
    Error compiling for board AI Thinker ESP32-CAM.

My OS is Ubuntu 18.04.4.LTS.

When I type python in the console, it does open python:

    $ python
    Python 2.7.17 (default, Nov  7 2019, 10:07:09)
    [GCC 7.4.0] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    KeyboardInterrupt
    >>>

Also python is in one of the directories referenced by PATH:

    $ which python
    /usr/bin/python
    $ echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

I added an additional URL referring to the ESP32 boards on the Espressif website:

    Arduino IDE > File > Preferences > Settings > Additional Boards Manager URLs: > https://dl.espressif.com/dl/package_esp32_index.json

Then I added the libraries for all ESP32 boards:

    Arduino IDE > Tools > Board > Boards Manager > esp32 version 1.0.4

(I tried with version 1.0.3 and it didn't change anything...)

I selected my board in the interface:

    Arduino IDE > Tools > Board > AI Tinker ESP32-CAM

I granted all permissions to the USB port:

    sudo chmod a+rwx /dev/ttyUSB0
    ls -la /dev/ttyUSB0
    crwxrwxrwx 1 root dialout 188, 0 Mar  4 21:25 /dev/ttyUSB0

My sketch is really simple:

    void setup() {
    }

    void loop() {
    }

I get the same error for any example sketch and for any ESP32 board.

Any idea how this could be fixed ?

body:
All right so I was able to fix the problem. The Arduino IDE I was using had been installed from the Ubuntu Software Center. I uninstalled it.

Then I reinstalled the Arduino IDE by downloading it from the www.arduino.cc website and doing a manual install in /opt. Now it works awesome.


sender: user

sender: assistant

body:
This was an issue with the old Arduino IDE snap on Ubuntu. You can easily fix this by installing the new [arduino snap](https://snapcraft.io/arduino):

```
snap install arduino
```

Then add your user to the `dailout` group:

```shell
sudo usermod -a -G dialout $USER
```

After this, **reboot your device** and open Arduino IDE.

## Installing additional libraries

The Arduino IDE snap runs inside of a sandbox for security and stability reasons. This means it cannot access the Python libraries on your device. The snap bundles Python 3 and the `serial` library. If you need any other Python dependencies, you can install them inside of the sandbox using the `arduino.pip` command.

```
arduino.pip install <package-name>
```

*Note: do not use `sudo` for this command*


message:
Getting wdt reset + reboots every 5 seconds on simple button/relay code that has worked previously, now it does not and I changed nothing

I have some arduino code I adapted from a simple 2 button 2 relay code I found online. I just multiplied everything so I could have 5 buttons/5relays. I am using a NodeMCU (ESP-12E) for this.

I have not changed anything, and now trying to upload it to other boards, and the same existing board I used before. Same results every time.

I have verified arduino is updated, the board manager link is up to date, and verified the code. Drivers re-installed. I have tried using different boards such as nodemcu 0.9, generic esp8266 module etc.
Code is verified, no error messages upon upload.

But every single time I get this error in the serial monitor over and over:

```

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

wdt reset
load 0x4010f000, len 1392, room 16
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld
```

And here is the code I am using:
(But please keep in mind this WORKS and has worked before)

```
//Buttons

int button1 = 4;
int button2 = 13;
int button3 = 12;
int button4 = 15;
int button5 = 10;

//Relays
int rl1 = 5;
int rl2 = 0;
int rl3 = 14;
int rl4 = 16;
int r15 = 9;

//States for Relay and Button (1)

int state1 = HIGH;      // the current state of the output pin
int reading1;           // the current reading from the input pin
int previous1 = LOW;    // the previous reading from the input pin

//States for Relay and Button (2)

int state2 = HIGH;      // the current state of the output pin
int reading2;           // the current reading from the input pin
int previous2 = LOW;    // the previous reading from the input pin

//States for Relay and Button (3)

int state3 = HIGH;      // the current state of the output pin
int reading3;           // the current reading from the input pin
int previous3 = LOW;    // the previous reading from the input pin

//States for Relay and Button (4)

int state4 = HIGH;      // the current state of the output pin
int reading4;           // the current reading from the input pin
int previous4 = LOW;    // the previous reading from the input pin

//States for Relay and Button (5)

int state5 = HIGH;      // the current state of the output pin
int reading5;           // the current reading from the input pin
int previous5 = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time1 = 0;          // the last time the output pin was toggled
long time2 = 0;
long time3 = 0;
long time4 = 0;
long time5 = 0;

long debounce1 = 60;   // the debounce time, increase if the output flickers
long debounce2 = 60;
long debounce3 = 60;
long debounce4 = 60;
long debounce5 = 60;

void setup()
{
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);
  pinMode(button5, INPUT);

  pinMode(rl1, OUTPUT);
  pinMode(rl2, OUTPUT);
  pinMode(rl3, OUTPUT);
  pinMode(rl4, OUTPUT);
  pinMode(r15, OUTPUT);

}

void loop() {

  reading1 = digitalRead(button1);
  reading2 = digitalRead(button2);
  reading3 = digitalRead(button3);
  reading4 = digitalRead(button4);
  reading5 = digitalRead(button5);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  //Condition Relay 1
  if (reading1 == HIGH && previous1 == LOW && millis() - time1 > debounce1) {
    if (state1 == HIGH)
      state1 = LOW;
    else
      state1 = HIGH;

    time1 = millis();
  }

  //Condition Relay 2
    if (reading2 == HIGH && previous2 == LOW && millis() - time2 > debounce2) {
    if (state2 == HIGH)
      state2 = LOW;
    else
      state2 = HIGH;

    time2 = millis();
  }

  //Condition Relay 3
    if (reading3 == HIGH && previous3 == LOW && millis() - time3 > debounce3) {
    if (state3 == HIGH)
      state3 = LOW;
    else
      state3 = HIGH;

    time3 = millis();
  }

  //Condition Relay 4
    if (reading4 == HIGH && previous4 == LOW && millis() - time4 > debounce4) {
    if (state4 == HIGH)
      state4 = LOW;
    else
      state4 = HIGH;

    time4 = millis();
  }

  //Condition Relay 5
    if (reading5 == HIGH && previous5 == LOW && millis() - time5 > debounce5) {
    if (state5 == HIGH)
      state5 = LOW;
    else
      state5 = HIGH;

    time5 = millis();
  }

  digitalWrite(rl1, state1);
  digitalWrite(rl2, state2);
  digitalWrite(rl3, state3);
  digitalWrite(rl4, state4);
  digitalWrite(r15, state5);

  previous1 = reading1;
  previous2 = reading2;
  previous3 = reading3;
  previous4 = reading4;
  previous5 = reading5;
}
```

If I google this error I get a myriad of results that so far have not helped me. Any help or insight on how I can better understand this error, where to start, and what I need to do to get this "simple" sketch working would be awesome.  I'm at my wits end and all I want is a simple lighting panel to work.

body:
First thing to realize for you is that the externally set status of three of the GPIO pins [determine the boot mode for the ESP8266][1] used on your NodeMCU. So you must take care to check that your external wiring will not interfere with the boot mode:

  * GPIO15/D8 must be LOW on boot (i.e. no external pull-up resistors may be connected between D8 and 3.3V)
  * GPIO2/D4 must be HIGH on boot (i.e. no external pull-down resistors may be connected between D4 and GND)
  * GPIO0/D3 must be free of pull-up/down resistors so that the USB-to-serial chip can switch between RUN and FLASH mode.

Also, holding GPIO16/D0 LOW for an extended amount of time while running [may have unintended side effects like triggering the watchdog][2], especially if the board manufacturer decided to add the deep sleep wakeup resistor between D0 and RST (you most certainly have a NodeMCU clone, so this might actually be possible).

So it might very well be that you need to reverse the button logic on GPIO15/D8 (i.e. connect the button between D8 and 3.3V). It also might be that the pin numbering on your NodeMCU is confusing; better [use the D0-D10 constants][3].

Depending on the type of your relays, your relays may act as a pull-up/down resistor, too, further adding to the confusion.

I'd try this sketch without anything connected (no buttons, no relays) and when it works, I'd add buttons and relays one by one until you find the culprit. Sometimes it might be sufficient to swap a relay and a button, sometimes you need to reverse the logic on a button.

I would say that using any ESP8266 with that many input/output lines requires very careful consideration on where to connect what. The GPIO pins on an Arduino Nano are not involved in boot mode nor watchdog, so at least there you'd not get any interference.

  [1]: https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes
  [2]: https://github.com/esp8266/Arduino/issues/1490
  [3]: https://github.com/esp8266/Arduino/issues/584#issuecomment-123715951


body:
According to [Esp8266 documentation][1] this is a software reset.
After a fast peek, I didn't find delay() or yield() in your code.
The esp8266 needs to attend some time to WiFi related background tasks, and it is does when your arduino code delays or yields the processor.

  [1]: https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf&ved=2ahUKEwjzp-zX04PoAhVms4sKHUrrDoYQFjAAegQIAhAB&usg=AOvVaw0ibtWPtwCjhMowy9Yuz7Ac&cshid=1583422506199


body: For anyone that has a similar issue, I figured it out. GPIO 9 could not be used for a relay/output for whatever reason. Wish I knew why.  Switched it to GPIO2 (D4) and the reboots stopped.


message:
Passing a NeoPixel object reference to a custom library

I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.

Here is my current project code:
```
#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}
```

And here is the library I tried to create:
```
/*
 Youkai's Artificery NeoPixel cycle library.
 A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
 public:
  YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
  void tryStep();
 private:
  Adafruit_NeoPixel& _neoPixel;
  unsigned int _ledHue = 0;
  int _saturation;
  int _brightness;
  int _hueStep;
};

#endif
```

```
/*
 Youkai's Artificery timer library.
 Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
 _neoPixel = neoPixel;
 _saturation = saturation;
 _brightness = brightness;
 _hueStep = hueStep;
 _neoPixel.begin();
 _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
 _ledHue += _hueStep;
 _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
 _neoPixel.show();
}
```

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.

After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL_PIN and LED_COUNT as variables to the library with `YaNeoPixelCycle(..., int controlPin, int ledCount)` so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.

This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

body:
You call `_neoPixel.begin()` and `_neoPixel.show()` in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   `begin()` functions are used. Add a `begin()` function to your class and call `cycle.begin()` in `setup()`.

    void YaNeoPixelCycle::begin() {
      _neoPixel.begin();
      _neoPixel.show();
    }

Of course remove the `_neoPixel.begin()` and `_neoPixel.show()` from the constructor.


message:
How far can a HC-SR04 can stand from the microcontroller?

I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

body:
The signal of an HC-SR04 is the pulse on the "Echo" wire. The length of that pulse is directly proportionate to the distance from the object.

Since cable length does not affect the duration of that pulse, measurement accuracy isn't affected either.


body:
I have a couple measuring the liquid level of two tanks.

The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.

Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.

That's the longest I needed, so I haven't tested beyond that.


body:
this problem consists of 2 things :

 1. supply level drop (this one has severe effect)
 2. signal level drop (a little more forgiving)

as the signals on the cables don't have high frequencies, the problem narrows down to just voltage level drop due to cable resistance.

supply level drop: the datasheet for SR04 says a maximum active current of 20mA is required for device to work properly. the supply voltage is 4.5~5.5v. so if you provide a 5v power for it, the cable must not drop it under 4.5v. the maximum resistance for the cable is calculated

> R=V/I => R = (0.5/20)*10^3 = 25 Ohms

. you can use this value to find out maximum cable length using resistance tables provided by cable makers. e.g. if you have bought a 5ohms/meter cable, the maximum length should be under 5 meters to ensure a good power delivery.

the signals on the other hand, have very little current going between them. as the MCU/Module pins have a very high input impedance. so they are not as severe as the supply drop.

using a 100uF cap near SR04's supply pins would be great.


message:
Self made ATMega32U4 board first programming

I'm stepping into Arduino world and decided to build a small board to implement a gamepad. Prior designing the board I tested my firmware on a *Arduino Pro Micro USB* so I decided to make something similar. My board use an **ATMEGA32U4-AU** instead  **ATMEGA32U4-MU** because it's simpler to solder. Connecting the board to my PC I noticed a new device named *ATmega32U4* appear between Windows devices this sounds like the board is working.
Now the problem is how to program it with the correct bootloader (?) and make it a *real* **Arduino** board.
I found some spurious articles about how to make it but I have not a clean idea. Someone can help me?
I can share everything you need to focus on the board.

UPDATE ---------------------------------------------------------------------

Before installing Arduino bootloader I tried programming a sample firmware on the board trough Atmel FLIP (successfully). After that I never been able to program the board again (neither trough FLIP or other means)

I connected my board to Arduino ISP and since Windows seems unable to find the correct driver I had to install it manually, after that I tried to install the bootloader trough **Install bootloader** option of Arduino IDE (selecting Arduino ISP as programmer) but I had no success:
This's the log:

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\tux\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : usb
             Using Programmer              : arduinoisp
    avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : USBtiny
             Description     : Arduino ISP Programmer
    avrdude: programmer operation not supported

    avrdude: Using SCK period of 10 usec
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

    Error during bootloader writing.

----

I can clearly see that my firmware is not running when I start the booloader process (probably because it reset the board).
From the log it seems that everything is going correctly until:
*programmer operation not supported*

What does it means? Is the programmer unable to program such chip? How can I fix this?
If I reset my board prior trying to burn again a new firmware over it will it work or I just have to put a brand new micro on it?

Best regards,
 Mike

body: The problem was a wrong MISO connection given by a bugged ATMega32U4 footprint.


message:
Set SPI MOSI pin to idle low on a Due?

I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?

[Here](https://arduino.stackexchange.com/a/62492/13327)'s a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

body: I have managed to set MOSI to low by setting bit 26 in `PIOA->PIO_PER`, `PIOA->PIO_OER` and  `PIOA->PIO_CODR` registers. To use SPI again, bit 26 in `PIOA->PIO_PDR` has to be set (this cancels the effect of `PIOA->PIO_PER`).


message:
Keep 5V on while sleep with LowPower library

Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?

I'm trying to use this HAT:

https://spellfoundry.com/product/sleepy-pi-2-usb-c/

to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

body: If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).


message:
Convert float to char array on ATtiny85

I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.

I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.

The master expects 31 bytes from the slave when data is sent to it.

When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.

```
    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);
```

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.

When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.

```
  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);
```

What am I missing? Any ideas?

Thanks

body:
The reason is that the library which implements `snprintf` and `sprintf` can be dependent on the compiler used for your MCU, so in your case it's not supported.

If you always need the form `%2.32f` why not put it in directly, like:

    int i = int(3.877 * 1000.0); // Assuming f of form a.bcd, i will be 3877
    char str[6];
    str[0] = (i / 1000) % 10;
    str[1] = '.';
    str[2] = (i / 100) % 10;
    str[3] = (i /  10) % 10;
    str[4] = (i      ) % 10;
    str[5] = '0';

It will be much faster too.


body:
Just to complement Michel Keijzers’ answer: `sprintf()` or `snprintf()`
are normally the right solution. On the AVR platform, however, float
conversions are left out of their default implementation, because they
take quite a lot of flash space, even when not used. On the other hand,
the avr-libc provides the non-standard function [`dtostrf()`][dtostrf]
for doing this conversion. The program

```c++
void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}
```

outputs

```text
3.877
```

[dtostrf]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42


message:
First time arduino attempt. 4 switch inputs controlling 8 LED outputs

This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.

Here is more info on the scheme I am looking for.

Switch 1 on turns on LED groups 1 and 2

Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8

Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.

Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.

Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino

body:
Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here


body:
First of all, you need to have an overview over the whole project because you need to know what components you are going to use, how many digital/analog pins do you need, then check the official Arduino website to see if the board fulfills your needs.

If there is no special need, like more EEPROM or more analog inputs, almost most of the board will work for you (because most of them have the same microcontroller: ATMEGA328P), so it is up to what form factor you prefer more.

Personally, I would like to go with the Micro board because it has microusb connector, it is breadboard friendly (which is a big plus when you are prototyping) and it can be recognised as a mouse or keyboard.


message:
How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"?

#include <Wire.h>

    long aX,aY,aZ,gX,gY,gZ;
    float rtX,rtY,rtZ,gfX,gfY,gfZ;

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

    void loop()
    {
      recordAccelregisters();
      recordGyroregisters();
      printData();
      delay(100);
    }

    void setupMPU()
    {

      Wire.beginTransmission(0b1101000);
      Wire.write(0x6B);
      Wire.write(0b00000000);
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000);
      Wire.write(0x1B);
      Wire.write(0b00000000);
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000);
      Wire.write(0x1C);
      Wire.write(0b00000000);
      Wire.endTransmission();
    }

    void recordAccelregisters()
    {
      Wire.beginTransmission(0b1101000);
      Wire.write(0x3B);
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6);
      while(Wire.available()<6)
      {
        aX = Wire.read()<<8|Wire.read();
        aY= Wire.read()<<8|Wire.read();
        aZ = Wire.read()<<8|Wire.read();
        processAData();
      }
    }

    void processAData()
    {
      gfX= aX/16384.0;
      gfY = aY/16384.0;
      gfZ = aZ/16384.0;
    }

    void recordGyroregisters()
    {
      Wire.beginTransmission(0b1101000);
      Wire.write(0x43);
      Wire.endTransmission();
      Wire.requestFrom(0b110100,6);
      while(Wire.available()>6)
      {
        gX = Wire.read()<<8|Wire.read();
        gY = Wire.read()<<8|Wire.read();
        gZ = Wire.read()<<8|Wire.read();
        processGdata();
      }

    }

    void processGdata()
    {
      rtX= gX/131.0;
      rtY = gY/131.0;
      rtZ= gZ /131.0;
    }

    void printData()
    {
      Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
      Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
      Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
    }

this is a code of mpu6050.  Why am I getting this error and How Can I resolve it?

body:
These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the `+` operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.

In other high level languages a string literal (characters enclosed by `"` in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the `+` operator for adding a float number in human readable form. This complex type in the Arduino world is the `String` type. You can convert the float variable into a `String` and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about [The Evils of Arduino Strings][1] for more information.

Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:

    Serial.print("Gyro degree(x)= ");
    Serial.print(rtX);
    Serial.print(" ");

It does exactly, what your code does. But it will not produce an error, since the `Serial.print()` method is also implemented for using float arguments.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


message:
Flow control between ESP32 and RS323 device

I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

body:
You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).

In the sample below, you just have to:
- assign `UART_CLIENT_RTS` and `UART_CLIENT_CTS` to the pins of your need
- change `uart_config_t` to whichever parameters are relevant for your RS232 device
- set `flow_ctrl` to `UART_HW_FLOWCTRL_RTS`, `UART_HW_FLOWCTRL_CTS`, `UART_HW_FLOWCTRL_CTS_RTS` or `UART_HW_FLOWCTRL_MAX`

```
    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);
```

Communication can be done with the various `uart_write_*` and `uart_read_*` methods as defined in the [documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html).


message:
Problem with PWM pins on Arduino uno

I am working on an Arduino Uno Project of a car with two motors. The motor driver board is an L9110 H-Bridge. Here is how everything is connected:

[![Schematic][1]][1]

And here is the code I am trying to run:

```lang-c

//Define all the pins for the motors
#define motorPinA1 3  //A pin right motor
#define motorPinB1 5  //B pin right motor
#define motorPinA2 6 //A pin left motor
#define motorPinB2 9 //B pin left motor

//Movement functions
void stopCar();
void frwrd(int motorSpdRight, int motorSpdLeft);
void back(int motorSpdRight, int motorSpdLeft);

//Global Variables
int motorSpeedRight = 0;  //The speed of the right motor
int motorSpeedLeft = 0;   //The speed of the left motor

void setup() {
  //Movement
  pinMode(motorPinA1, OUTPUT);
  pinMode(motorPinB1, OUTPUT);
  pinMode(motorPinA2, OUTPUT);
  pinMode(motorPinB2, OUTPUT);

  //Serial Monitor for debugging
  Serial.begin(9600);

  motorSpeedLeft = 100;
  motorSpeedRight = 100;

  frwrd(100, 100);
  delay(2000);
  stopCar();
  delay(1000);

  back(100, 100);
  delay(2000);
  stopCar();
  delay(1000);
}

void loop() {

  Serial.print("Forward");
  Serial.print("\n");

  frwrd(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

  back(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

}

// functions we need to make the code run
void stopCar(){
    Serial.print("Stoping Car\n");
    // Put motor 1 in halt
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, 0);

    // Put motor 2 in halt
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, 0);
}

// For the farward direction A pins will be high
void frwrd(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in forward motion with speed = motor_spd
    analogWrite(motorPinA1, motorSpdRight);
    analogWrite(motorPinB1, 0);

    // Put motor 2 (Left) in forward motion with speed = motor_spd
    analogWrite(motorPinA2, motorSpdLeft);
    analogWrite(motorPinB2, 0);

    /*
    // Put motor 1 (Right) in forward motion
    digitalWrite(motorPinA1, HIGH);
    digitalWrite(motorPinB1, LOW);

    // Put motor 2 (Left) in forward motion
    digitalWrite(motorPinA2, HIGH);
    analogWrite(motorPinB2, LOW);
    */
}

// For the backward direction B pins will be high
void back(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in backward motion with speed = motor_spd
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, motorSpdRight);

    // Put motor 2 (Left) in backward motion with speed = motor_spd
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, motorSpdLeft);

    /*
    // Put motor 1 (Right) in backward motion
    digitalWrite(motorPinA1, LOW);
    digitalWrite(motorPinB1, HIGH);

    // Put motor 2 (Left) in backward motion
    digitalWrite(motorPinA2, LOW);
    digitalWrite(motorPinB2, HIGH);
    */
}
```
Pins 3, 5, 6 and 9 are PWM so I can `alalogWrite()` to them and control the speed of the motors. Code uploads fine but although both motors move forward normally motor 1 (on pins 3, 5) doesn't move backward. The strange thing is that if I use `digitalWrite` (the commented code in the two functions) instead everything works normally but the motors move in full speed so it's not usable for my project. I have tested all the pins in other projects and everything worked fine so I know my board is not faulty.

I have also taken some measurements with a multimeter while the code was running. In the forward motion, both pairs of pins measured 1.95V. In the backward motion, the problematic pins measured 0V.

Any help would be appreciated!!

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

body:
Try different pins than 5 and 6, because those PWM generators share the timer with `delay()`, which I'd interpret as: You use `analogWrite()` to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call `delay(1000)`, which sets that same timer to fire in one second to continue the program.

Pins 10 and 11 do use a different timer, so try these.

Reference: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

> "The PWM outputs generated on pins 5 and 6 will have
> higher-than-expected duty cycles. This is because of interactions with
> the millis() and delay() functions, which share the same internal
> timer used to generate those PWM outputs."


message:
Displaying when Button has been pressed for LED and returning 1

I've just started using Arduino and I'm having trouble getting my code right.

Here is the task I need to do.

 "Create a button read function
  Hint: the function header should be `int checkbutton ( void )`
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."

There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!

Thanks!

    int Button = 15; //LED and output are on the same pin

    int last = 0;

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

    int button() {
      pinMode(Button, INPUT);

      int current = digitalRead(Button);

      if (current and not last) {
        delay(5);

        pinMode(Button, OUTPUT);

        Serial.print("Hey");
        return 1;
      }

      else {
        pinMode(Button, OUTPUT);

        current == last;

        return 0;
      }
    }

    void loop() {
      if (button >=0)
      {
        button();
      }

      else
      {
        ;
      }
    }

body: Your problem may only be that you are not calling the button function. Try changing `if (button >=0)` to `if (button() >=0)`.


body:
In your button() function, the line

    if (current and not last) {

is less common syntax. The more common equivalent is:

    if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)

This line:

    current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.

I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call `button()` the next time. So you would need to set “last” to the current button state, like this:

    last = current;

The next time you call `button()`, “last” contains the previous button state, so your comparison to the current button state will work.

And I think your button detection code would work better if you set `last = current` each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:

    int button() {
      pinMode(Button, INPUT);

      int current = digitalRead(Button);

      if (current &&  !last) {
        ...
        ...

        Serial.print("Hey");
        last = current; // Insert here
        return 1;
      }

      else {
        pinMode(Button, OUTPUT);
        ...

(This has not been tested but should give you a general idea).


message:
First time working with arduino, need help adapting project from UNO to NANO

This is my first time working with an arduino and I'm having some issues when trying to copy a program I found online on my Nano.

Basically, my project consists in a pulse sensor that sends the pulse information to the arduino and then to the hc-05 Bluetooth module so my phone can receive this information in real-time.

On my nano: D2 receives the output of the sensor, D8 and D9 are connected to pins RX/RT on HC05 and D13 has a LED connected to it.

Now here's the thing, I really don't know much about this and the code I found uses different pins from the ones I'm using.

The LED keeps blinking and isn't synchronized with the sensor output, when the led blinks I receive a response in the Bluetooth serial app but I would like to synchronize the heart sensor with the led so than I can receive the pulses on my phone. I've been trying to solve this but I still can't find a solution.

Full code can be found at
<https://www.instructables.com/id/Pulse-Sensor-With-Bluetooth-and-Arduino/>

Here's part of my code

```
//bluetooth
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(8, 9); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

//  Variables
int pulsePin = 2;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// Regards Serial OutPut  -- Set This Up to your needs
static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

void setup(){
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
   // UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
   // AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);
Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

//  Where the Magic Happens
void loop(){

    serialOutput() ;

  if (QS == true){     //  A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.
        QS = false;                      // reset the Quantified Self flag for next time
       }
      else {

      digitalWrite(blinkPin,LOW);            // There is not beat, turn off pin 13 LED
      }

   ledFadeToBeat();                      // Makes the LED Fade Effect Happen
  if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D12 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D12 Off ! ");
  }
}
  delay(20);                             //  take a break
}```

body:
First: There is no need to change pin assingments, when changing from Uno to Nano. They use the same microcontroller and have the same pins.

You have set `pulsePin` to 2, which corresponds to pin D2. But the pulse sensor gives you an analog signal. D2 is not capable of measuring analog voltages, it can only measure digital voltages. Meaning you need to use one of the analog pins, A0 to A7, so use one of these pins in the declaration of `pulsePin`.

The reason for this is, that the microcontroller uses an extra peripheral device included in it for measuring analog voltages: the ADC (Analog to Digital Converter). It can only be connected to a limited number of pins (internally via a multiplexer). That also means, that you can only measure the analog voltage at one pin at a time.


message:
Run servo when image is capture

I am trying to create a program when the camera capture the servo will rotate in 90 degrees continously, but my code will stop in `print output 2` any idea to run the servo continously?

Here's the Code

    import numpy as np
    import cv2
    import serial
    import struct
    import time

    ser = serial.Serial('COM11',9600)

    x=0

    while(True):

     # Capture frame-by-frame
        cap = cv2.VideoCapture(0)
        #framerate = cap.get(5)
        ret, frame = cap.read()
        cap.release()
        # Our operations on the frame come here

        filename = 'C:/Users/DELVO/Desktop/tryTest/bruises/main/images' +  str(int(x)) + ".png"
        x=x+1
        cv2.imwrite(filename, frame)
        print(ser.write(x))
        time.sleep(5)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

Arduino Code

    #include <Servo.h>
    int data_x = 0;
    int data_y = 0;
    int data[1];
    Servo myservo_x;
    Servo myservo_y;// create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin(9600);
      myservo_x.attach(7);  // attaches the servo on pin 9 to the servo object
      myservo_y.attach(10);
      myservo_x.write(90);
      myservo_y.write(90);
    }

    void loop() {
      while (Serial.available() >= 2) {
        //    data_x=Serial.read();
        //    data_y=Serial.read();
        for (int i = 0; i < 2; i++) {
          data[i] = Serial.read();
        }

        myservo_x.write(data[0]);
        myservo_y.write(data[1]);

        Serial.println(data[0]);
        Serial.println(data[1]);
      }

    }

body:
is the arduino code giving error because you have initialized the array data with length of 1 (```int data[1];```) and in the for loop the length is exceeding the allocated length of the string: ```for (int i = 0; i < 2; i++) {
  data[i] = Serial.read();
                       }```


message:
Arduino Nano 33 battery power/charging

I have a project with an [Arduino Nano 33 BLE Sense](https://store.arduino.cc/arduino-nano-33-ble-sense-with-headers). My project is working great, but I need to transition it to battery power, and I'm having a bit of confusion about exactly what's required.

I have a small 3.7V Li-ion battery I'd like to use (similar to [this one](https://www.sparkfun.com/products/13853) {0}) if possible.

I have read what seems to be some conflicting information, so I'd like to see which of the following are true:

* I can power the Arduino directly from the 3.3v pin? I'm suspicious of this advice since on the datasheet the 3.3v pin is marked output only. There's a note on the product page that says:

> Note: for ultra low-power functionality, you should cut the 3V3 jumper on the back of the board, and use an external battery at 3V3.

Is this something I should do? It seems difficult to reverse, I'm worried I might break my project.

* I can power the Arduino directly from the VIN pin? This again seems to contradict the datasheet, which says the VIN pin can only handle 4.5 - 21V. 3.7V is less than this.

* I could use a Step-up DC-DC transformer - like [this](https://www.ebay.co.uk/itm/Mini-3V-3-3V-3-7V-5V-9V-to-12V-Step-Up-Boost-Converter-Module-Voltage-Regulator/274297023384?hash=item3fdd606b98:g:pe4AAOSwD39eYUDV) {1}? I'd rather not wait for shipping from China.

Furthermore, I'd like to be able to charge the battery, so if I use a charging board like [this one](https://www.ebay.co.uk/itm/4-2V-5V-1A-Micro-USB-Li-ion-Battery-Charger-TP4056-Protection-Chip-Lithium-ion/192956632451?hash=item2ced1c8d83:m:m6FPVNrEa1Qnj21RHGsyZ7g) {2}, would that just work?

I don't want to connect the battery anywhere it might not be welcome for the risk of frying anything. Any help would be appreciated.

<hr>

Link references (in case ebay listings go away):

0: Lithium Ion Battery - 110mAh

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

1: Mini 3V 3.3V 3.7V 5V 9V to 12V Step Up Boost Converter Module Voltage Regulator

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

2: 4.2V 5V 1A Micro USB Li-ion Battery Charger TP4056 Protection Chip Lithium-ion

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

  [1]: https://i.stack.imgur.com/wpYl7.jpg
  [2]: https://i.stack.imgur.com/P6wLz.jpg
  [3]: https://i.stack.imgur.com/ASvKx.jpg

body:
The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.

You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.

Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).

You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

* Nina-B3 series module will run at down to 1.7V.
* The APDS-9960 will operate down to 2.4V.
* The HTS221 will run at down to 1.7V.
* MP34DT06J can go as low as 1.6V.
* LSM9DS1 can run from 1.9V.
* LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


message:
How to switch between multiple BMP180 sensors?

I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?

body:
The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.

So know you have 2 ways to go:

- You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.

- You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)


body: If you have n-MOSFETs available, a simple multiplex solution would be: SCL directly from master to all slaves. SDA from master to Source of MOSFET (for each slave one MOSFET), Drain of MOSFET with pull-up resistor (e.g. 4.7k) will be the SDA signal. Gate of MOSFET to select slaves (active <-> Gate=high level). Make sure your MOSFET turns on based on your used voltage levels.


message:
On compiling I get #endif without #if error. Here is the code. Please help!

#include <Arduino.h>
    #endif
    #include <ESP8266WiFi.h>
    #define watersensor D2
    const char* ssid = "pooja";
    const char* password = "ranip2780@";
    WiFiServer server(301);
    IPAddress ip(192, 168, 43, 67);
    IPAddress gateway(192, 168, 43, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress dns(192, 168, 43, 1);
    void setup() {
      Serial.begin(115200);
      delay(10);

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.config(ip, dns, gateway, subnet);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      server.begin();
      Serial.println("Server started");

      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }

    void loop()
    {
      // Check if a client has connected
      < WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while (!client.available()) {
        //    delay(1);
        client.setNoDelay(1);
      }

      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("");
      client.println("");
      client.println("");
      client.println("<meta http-equiv='refresh' content='20'>");
      client.println("<title>WATER OVERFLOW ALARM WITH ONLINE UPDATES</title>");
      client.println("");
      client.println("");
      client.println("

");
      client.println("
");
      client.println("
");
      client.println("WATER OVERFLOW ALARM WITH ONLINE UPDATES
");
      client.println("USING NODEMCU 1.0 BOARD");
      client.println("
	");
      client.println("
");

      if (digitalRead(watersensor) == LOW)
      {
        client.println("<button style='background-color:red;width:200px;height:100px'>FULL LEVEL ALERT</button>
");
      }
      else
      {
        client.println("<button style='background-color:gray;width:200px;height:100px'NOT FULL</button>
");
      }

      client.println("
	");
      client.println("
");
      client.println("

");
      client.println("");
      client.println("
");
      client.println("

");
      client.println("LEGENDS:  <button style='background-color:gray;width:100px;height:50px'><font color='white'NOT FULL</button>");
      client.println("WATER LEVEL IS BELOW SENSOR.
");
      client.println("
<button style='background-color:red;width:100px;height:50px'>FULL LEVEL ALERT</button> WATER LEVEL IS ALREADY FULL.");
      client.println("

");
      client.println("");
      client.println("");
      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");
      delay(500);
    }

body:
The Arduino IDE gives you a massive clue

    Arduino: 1.8.12 (Windows 10), Board: "Arduino Uno"

    sketchX:2:2: error: #endif without #if

     #endif

      ^~~~~

    sketchX:3:10: fatal error: ESP8266WiFi.h: No such file or directory

     #include <ESP8266WiFi.h>

              ^~~~~~~~~~~~~~~

    compilation terminated.

    exit status 1
    #endif without #if

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

That's pointing at lines #2 & #3 in the sketch as having the error. So we fix those and try again

    //#endif

I'll also install the ESP8266 stuff since that's missing on my new laptop.

    Arduino: 1.8.12 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new
    can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz,
    DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower
    Memory, Disabled, None, Only Sketch, 115200"

    C:\Users\winuser\Arduino\sketchX\sketchX.ino: In function 'void loop()':

    sketchX:42:3: error: expected primary-expression before '<' token

       < WiFiClient client = server.available();

       ^

    sketchX:42:16: error: expected primary-expression before 'client'

       < WiFiClient client = server.available();

                    ^

    sketchX:42:16: error: expected ';' before 'client'

    sketchX:43:8: error: 'client' was not declared in this scope

       if (!client) {

            ^

    sketchX:49:11: error: 'client' was not declared in this scope

       while (!client.available()) {

               ^

    sketchX:54:20: error: 'client' was not declared in this scope

       String request = client.readStringUntil('\r');

                        ^

    sketchX:4:21: error: 'D2' was not declared in this scope

     #define watersensor D2

                         ^

    C:\Users\winuser\Arduino\sketchX\sketchX.ino:79:19: note: in expansion of
    macro 'watersensor'

       if (digitalRead(watersensor) == LOW)

                       ^

    exit status 1
    expected primary-expression before '<' token

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

So all in all it's simple to use the messages that the IDE gives you to find your error and correct them, working from top to bottom in your sketch. It's not something that needs to be posted on StackExchange until you've corrected the basics.


message:
Reading data from an Ohaus Defender 3000 with a RS-232 shield

I have a project where we have to read the weight from an Ohaus Defender 3000 by using an Arudino Mega 2560 and a RS-232 shield. Right now we have the RX of the Arduino to the TX of the shield, and the TX of the Arduino to the RX of the shield. In our code, we get both the RX and the TX lights of the shield to light up but we can't receive data from the scale into the Arduino. Could someone help me understand what is going on or am I doing something wrong. This is the following code that I used for the Arduino. I found this code at: https://arduino.stackexchange.com/questions/48969/reading-arduino-serial-input. Thank you for the help in advance.

    #define HWSERIAL Serial1

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

    void loop() {
      int incomingByte;

      if (Serial.available() > 0) {
        incomingByte = Serial.read();
        Serial.print("USB received: ");
        Serial.println(incomingByte, DEC);
        //HWSERIAL.print("USB received:");
        //HWSERIAL.println(incomingByte, DEC);
      }
      if (HWSERIAL.available() > 0) {
        incomingByte = HWSERIAL.read();
        Serial.print("UART received: ");
        Serial.println(incomingByte);
        //HWSERIAL.print("UART received:");
        //HWSERIAL.println(incomingByte);
      }
    }

body:
Can you provide a photo of your hardware setup, and the full code for your project?  Please use the "code sample" formatting widget (the "{}" icon) to surround the code section, and look at the preview to make sure the code is formatted correctly.

Just a guess, but you may have the TX/RX lines to the scale connected to 'Serial' on the Mega instead of 'Serial1'. That would definitely cause problems


message:
I2C and softwareserial

Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.

If "Adafruit_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?

    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #define OLED_RESET     -1
    #define SCREEN_WIDTH 128
    #define SCREEN_HEIGHT 64
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(8, 9);
    Adafruit_GPS GPS(&mySerial);

    void setup() {
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        for(;;);
      }
      display.display();
      delay(2000);
      display.clearDisplay();
      display.drawPixel(10, 10, SSD1306_WHITE);
      display.display();
      delay(2000);
      testdrawchar();
    }

    void loop() {
    }

    void testdrawchar(void) {
      display.clearDisplay();

      display.setTextSize(1);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(0, 0);
      display.cp437(true);

      for(int16_t i=0; i<256; i++) {
        if(i == '\n') display.write(' ');
        else          display.write(i);
      }

      display.display();
      delay(2000);
    }

body: The problem was indeed running out of memory (as suggested by Juraj). After finding smaller libraries I was able to get it to work together just fine.


message:
Matching incoming data with a variable

I have a system where an RFID tag can be checked and Its individual 4byte UID will be printed. My task is to check if subsequent tags have the same UID and if not, print “access denied”. I'm assuming i need to use `const char` but I'm not sure. I get an error at `if (myrfid.serNum[i] == ID)` saying comparison between pointers and integers are forbidden.
Any sort of clarity would be appreciated, thanks!

(Code is only a section from the for loop)

```c++
void loop()
{
    int i;
    const char ID[] = "111 11 11 11";

    cardpresent = myrfid.isCard();

    if (cardpresent && ! lastcardpresent)
    {
        if (myrfid.readCardSerial())
        {
            for (i = 0; i < 4; i++)
            {
                if (myrfid.serNum[i] == ID)
                {
                    Serial.print("Acess granted ");
                }
                else
                {
                    Serial.print("Acess not granted ");
                }
            }
        }
        Serial.printf("= ", myrfid.serNum[i]);
    }
    Serial.print("\n");

    // ...
}
```

body:
The accepted way to initialize an array in C follows this example:

    const char ID [] = {111, 11, 11, 11};

You can read more about it [here][1].

You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.

  [1]: https://www.programiz.com/c-programming/c-arrays


message:
Multiple data packets with CIPSEND, associate each with pathway

When using a CIPSEND from an Arduino Uno to a ESP8266 connected to the Uno is there a way to associate the data packet sent with a pathway so it can be retrieved at said pathway from the browser?

For example ESP8266WebServer.h has a command like this:

    server.on(“/specificArgs”, handleSpecificArg);   //Associate the handler function to the path

where the first argument is the path/filename - what's the equivalent of this using using CIPSEND?

body:
Your "CIPSEND" is already associated with a path.

The sequence is generally:

1. You configure the ESP8266 as a server, including turning on multiple connections
2. You browse to the IP
3. The browser sends a HTTP request including a path. This has a "channel" number associated with it.
4. You generate a HTTP response and send it to the channel given in 3 using `AT+CIPSEND`.

The fact that you're sending the response to the browser through the channel that the request came in through "associates" the response with the request.

To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly.


message:
Arduino Firebase connection refused error

I am making a project for school where I have to send data from a sensor to a webpage. After doing some research I decided to use a Real-Time Firebase database. Security is not really important and I want to focus on other aspects of the project, so this seemed like an easy and quick option. I am using a d1 mini (esp8266) and a DHT11 humidity and temp sensor. For libraries I am using DHT, FirebaseArduino and ESP8266WiFi. The code is:
```
#include <ESP8266WiFi.h>                                                    // esp8266 library
#include <FirebaseArduino.h>                                                // firebase library
#include <DHT.h>                                                            // dht11 temperature and humidity sensor library

#define FIREBASE_HOST "xx"                   // the project name address from firebase id
#define FIREBASE_AUTH "xx"            // the secret key generated from firebase

#define WIFI_SSID "xx"                                             // input your home or public wifi name
#define WIFI_PASSWORD "xx"                                        //password of wifi ssid

#define DHTPIN D5                                                           // what digital pin we're connected to
#define DHTTYPE DHT11                                                       // select dht type as DHT 11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  delay(1000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                     //try to connect with wifi
  Serial.print("Connecting to ");
  Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                            //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                              // connect to firebase
  dht.begin();                                                               //Start reading dht sensor
}

void loop() {
  float h = dht.readHumidity();                                              // Reading temperature or humidity takes about 250 milliseconds!
  float t = dht.readTemperature();                                           // Read temperature as Celsius (the default)

  if (isnan(h) || isnan(t)) {                                                // Check if any reads failed and exit early (to try again).
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print("Humidity: ");  Serial.print(h);
  String fireHumid = String(h) + String("%");                                         //convert integer humidity to string humidity
  Serial.print("%  Temperature: ");  Serial.print(t);  Serial.println("°C ");
  String fireTemp = String(t) + String("°C");                                                     //convert integer temperature to string temperature
  delay(4000);

  Firebase.pushString("Humidity/", fireHumid);                                       //setup path and send readings
  Firebase.pushString("Temperature/", fireTemp);                                //setup path and send readings

}
```

replaced some 'sensitive' information with "xx". When running this code, it connects to my wifi connection and shows data from the DHT11 in the serial monitor. However NOTHING changes in Firebase. After enabling the feature to display extensive feedback/errors in the serial monitor, I noticed it's displaying this:
```
[HTTP-Client][begin] host: https://testtesttest-bd679.firebaseio.com/ port: 443 url: /Temperature/.json?auth=xxxx httpsFingerprint: 03 D6 42 23 03 D1 0C 06 73 F7 E2 BD 29 47 13 C3 22 71 37 1B
[HTTP-Client][sendRequest] type: 'POST' redirCount: 0
[HTTP-Client] failed connect to https://xxx-xxx.firebaseio.com/:443
[HTTP-Client][returnError] error(-1): connection refused
[HTTP-Client][returnError] error(-4): not connected
[HTTP-Client][end] tcp is closed
Humidity: 43.00%  Temperature: 22.50°C
```

I have tried the following things:

* Using a different version of the FirebaseArduino library (5.13.x (still using this one))
* Manually updating the fingerprint of the FirebaseArduino library (see current fingerprint in 2nd code section above)
* Using different versions of the Arduino IDE, using 1.8.12 now

And some other minor changes like creating a new Firebase Database or using something different from pushString to add data to the database.

None of this helped and I am running out of time for my project, hope someone here knows what's wrong and can help me out! :)

body:
You added a `/` to the end of the Humidity and Temperature collections.
e.g
    Firebase.pushString("Humidity/", fireHumid);
    Firebase.pushString("Temperature/", fireTemp);

The firebase API translates it to an address

    https://testtesttest-bd679.firebaseio.com/Temperature/.json?auth=xxxx`

as we can see in the output.

I'm pretty sure the correct address is `...Temperature.json...` and not `...Temperature/.json...`.

Please try to remove the slashes from the end of the collection names in the `pushString` statements..

    Firebase.pushString("Humidity", fireHumid);
    Firebase.pushString("Temperature", fireTemp);

If this does not help, it is possibly a problem with the auth string or the Host name. e.g trailing or leading space characters or something like that.


message:
Continue playing sound during interrupt routine

I'm trying to play a tone (on an Arduino Mega through the tone library) and have the tone not be interrupted if an interrupt routine is called while the tone is playing. I'm not sure it's possible. The code block is below. Relevant functionality is:

-A while loop runs indefinitely until Button S1 is pressed. Pressing Button S1 triggers an interrupt routine in which interruptFlag_s1 is set to 1.

-This starts a tone playing for 300ms.

-There's a possibility that another button press interrupt is triggered during the 300ms tone. This interrupts the tone for about 0.5ms, enough to make a perceptible break in the tone that I'd like to avoid.

-Ideal scenario is that the audible tone isn't interrupted by the interrupt routine.

```
    while (restart == 0) {
      if (interruptFlag_s1 == 1 || interruptFlag_s2 == 1) {
        if (interruptFlag_s1 == 1) {
          primary_sensor = 1;
          interruptFlag_s1 = 0;
          rBot = false;
          gBot = true;
          bBot = false;
        } else if (interruptFlag_s2 == 1) {
          primary_sensor = 2;
          interruptFlag_s2 = 0;
          rBot = false;
          gBot = false;
          bBot = true;
        }

        interruptFlag_rtc = 0;
        finish_id = 0;
        button_flag = 0;
        time_diff = 0.00;
        alt_finish_time = 0.00;
        tone(speakerPin, 3000, 300); // Start tone
        restart = 1;
      }
    }
```

body:
The sound is itself generated by an interrupt routine. Since only one interrupt routine can happen at a time, if your own interrupt routine takes too long, then you will get interruption in the sound.

There is nothing you can do about that other than making your interrupt routine short enough that it doesn't cause any interruption in the sound.


message:
5V on HIGH Digital Pins, Only While Using USB Power

So I have a small problem with my Arduino Pro Mini here. May be worth noting that it is a clone, but otherwise this is still some weird functionality. I have done some experimenting so I'll just set the scene for you. I have everything that requires power connected to the + and - lines on my breadboard, that way I can avoid drawing more than about 20mA across any individual pins. I currently have my Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. It actually is currently outputting 5.36V.

I have made sure all my pins I'm using for output are indeed set as output, the problem only arises when I attempt to power the device from something OTHER than USB power. I tested the output from my wall adapter connected to RAW and to a random VCC pin, both have the same effect.

When powering the device via USB (USB to Deek-Robot ASP, then to Pro Mini), if I set my digital output pin to HIGH, I get 5v. This is enough to turn on a 5v relay that then supplies power from the supply to a small water pump. However, if I use the regulated wall-power, I get about 3.7 to MAYBE 4.15v, which sadly is not enough to switch the relay to the NO position.

I have tested the voltage coming from the USB ASP as well, it is 4.95v.

EDIT: The wall-plug voltage drops from 5.36 with no load except the meter to 4.7v with the Arduino and a couple LEDs attached, if that means anything.

body: Power supply was dropping to 3.8 volts under basic load, once it turned on some LEDs it was just too low to activate the relay switch. Crappy Chinese parts.


body:
"Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. "

That is the problem. RAW pin expects more like 6V to 6.5V for the regulator to output 5V.

If you are supplying 5V, connect to the 5V, or VCC and GND pins.

If you are connecting to USB via an  FTDI Basic or equivalent, and the 5V supply at the same time, then the computer may not like having the USB 5V line back driven from an external source (mine complains about a "power surge" and shuts down the USB port). Make up a breakout cable between the FTDI and the Promini and either disconnect the 5V line, or put a diode in series so the Promini can't supply 5V back thru the FTDI and into the USB port.  That way the FTDI chip is powered from USB, but the Promini is not, and all the hardware is happy.

Make sure to use series resistors with LEDs to avoid overcurrent from the Promini output pin, which will either damage the IO pin, possibly damaging the 328P, or damaging the LED from overheating from excess current.  (5.36V - 2.2V)/.02A = 156 ohm. A 180 ohm, 220, 270, 330, some value in that range will do. 1K will probably be fine, LEDs these days can be quite bright even at lower current; 20mA can be blindingly/annoyingly bright.


message:
How does the ssd1306 handle different screen sizes?

I noticed that if I have two SSD1306 displays, the 128x32 display will lose every other row if written in x64 mode, and the 128x64 display will show blank horizontal lines if written in x32 mode. How does this physically work, and can I expect this to be a reliable feature?

I would have thought that half the screen would get cut off somehow, but it appears that it must interlace the data instead (which seems a lot more complicated). Yet there's also some sort of configuration to the driver chip to make it do this (It seems to be the 0xDA command, but I'm not clear how/why it has these options).

Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior? I was planning to use it to help the user detect what screen they have.

body:
The SSD1306 does not handle different sizes, it's ever only handling it's maximum size 128x64. But one can decide to only use less pins of the driver for a smaller display.

The SSD1306 has 128 segment pins, which activate the current column, so that the states of the 64 common signal pins will be used by the display for that column. For smaller display sizes there are just some pins of the SSD1306 left unconnected. They get set like all the other pins, but they are not connected to anything, thus the information gets lost.

For accommodating that, the library sets the pixel according to the size by not using every second row (aka common signal) for half size displays. That's why you get horizontal black lines, when using a 128x64 display with the library in 128x32 mode. The library thinks, that every second row is not connected either way and thus sets these pixels to black. The 128x32 display is loosing every second row when used with the library in 128x64 mode, because every second row is not connected.

Note, that nor the library neither the SSD1306 know about how the display is connected. You need to tell the library this, by setting the mode, and it will control the SSD1306 accordingly. So there is no feedback about the display, that you could use.

> Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior?

Yes and no. The library handles it this way, because it is the common way to leave out every second pin for displays of half size. But it comes down to the manufacturer to decide this. We cannot guarantee, that nobody will ever connect the SSD1306 in a different way to a display.

For most manufacturers you will be good. If you simply plan to provide the displays for your user, so that they can change them their selves, you can be sure. If the user should be able to use her/his own display, purchased anywhere else, you might run into problems (though rarely).


message:
How to create large progmem arrays and not annoy the linker

I have a rather complex project (PlatformIO, but I've also had this happen in the vanilla IDE) with several nested includes.
Let's say that there are three files and a main sketch.
The main sketch includes #2 and #3.
File #3 includes file #1 and file #2.

If file #2 is a .h file containing something like a font, of the format:
```
const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};
```
Then I get linker errors of **multiple definitions of 'foo'** in both #3 and main.

Weirdly, the default fonts included in my OLED library are placed in a header file, EXACTLY like how I did it, and yet multiple files including that library (or files that themselves included it) do not cause this issue with the library's header file.

Yes, I do have a working include guard. For some reason it doesn't ever seem to help.

I have been using `extern` to solve this issue, but it's annoying and I'm not sure that it's proper behavior, either...

Could it have something to do with `#include <font.h>` vs `#include "font.h"`? What is the difference? My reference said they mean the same thing, but now I'm not so sure.

body:
Include Guards only protect against inclusion of a header file multiple times within the same *translation unit*.  This is important.  If you include a header file (1) in a source file, then include another header file (2) in the same source file, said header file also including the previous header file (1), then the include guard will perform its function.

If you have two source files and you include the same header in both, then the include guard will do nothing.

If you have a variable or function defined in a header file and you include that header into two different source files, when you link those source files together you will get a multiple definition error, since you have two translation units that have the same thing in them, and the linker doesn't like that.

The only time you should ever define variables or functions in a header file are if they are *simple constant* types, like a `const int` or a `const char` - something where the compiler can replace it verbatim in the code and optimize out the symbol completely (arrays of any kind are not *simple*), or if the symbol is declared "static", where it will be forced to remain "within" the translation unit and not get exported for linking.

Normally you will only declare your *complex* constants in the header file, and define them once and once only in a single source file. That way there is only one instance of the symbol in one translation unit.

For example, in the header file you would declare your constant:

    extern const char foo[] PROGMEM;

And in your source file define the constant:

    #include "foo.h"
    const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};

And in answer to the question "what's the difference between `#include <...>` and `#include "..."` - when it comes to Arduino, nothing whatsoever.

Officially it denotes a separation between "system" and "local" headers. That is, headers that are installed in the OS as part of the compiler, and headers that are contained within the project.  However there isn't that distinction with Arduino, and the two mean the same thing - just a header.

And finally a note on terminology - a glossary if you will:

* *Translation unit* - One compilable source file (and any included headers) that forms a single file of object code to be linked.
* *Declaration (Declare)* - The indicating of a symbol's type and any attributes, but not the content of that symbol
* *Definition (Define)* - Associating a symbol, whilst declaring it, with the content of that symbol.
* *Symbol* - the name of any variable, function, class, etc.


message:
This code gives the wrong output. Why?

void setup()
    {
      int calc(9,2);
      Serial.begin(9600);
    }

    void loop()
    {}

    int calc(int val1, int val2)
    {
      Serial.print(val1 + val2);
    }

It's not syntax error, i am getting output as 1, i should get 11.

body:
A function's name should tell what it does.

Something called calc() should not mainly print (except for debug purposes))

    void setup() {
      Serial.begin(9600);
      printSum(9,2);
    }
    void loop() {}

    void printSum(int val1, int val2) {
      Serial.print(val1 + val2);
    }

The other good approach is to really define a function returning a result.

    int calc(int a, int b) {
       return a+b;
    }
    void setup() {
       Serial.begin(9600);
       Serial.println(calc(9,2));
    }
    void loop() {}


body:
If your goal is to call your function with `int calc(9,2);`, you might want to change it to `calc(9,2);`, this is the way to call functions, no type declarator needed if you arent creating said function (or in a declaration, wich has nothing to do in the setup)
If you want to declare your functions, it must be done at the very top of your code, out of the setup function, and with arduino 1.8.9 on my end, this is not mandatory.

Also, you are calling your printing function before the `Serial.begin()`, one good practice may be to `Serial.begin()` at the very top of your setup, so you don't make mistakes on why your debug is not showing.

As on why you have a 1 printed, if that's all your code, i don't really know, i have no output when i try your code on my end

tl;dr;

    void setup() {
      Serial.begin(9600);
      calc(9,2);
    }


message:
How is this code working?? val3 is defined as constant

const int val3 = 7;
    void setup(){
      Serial.begin(9600);
      int val3 = 8;
      int val4 = 4;
      Serial.print(calc(val3,val4));
    }

    void loop()
    {}

    int calc(int val1, int val2)
    {
      return val1 + val2;
    }

this code gives output as 12.

body:
You have declared val3 two times: One time as constant int and another time as int (in setup loop). Replace the statement `int val3=8 by val3 = 8`. You will know the difference.

The first declaration is of no use in this case. As a try, you may first declare val3 as int and in the second declaration you may declare val3 as const int.

Just try and note the difference. Happy coding!


body:
In your code, the `const int val3 = 7;` definition, is outside of any functions so it defines a **global** constant/variable (available in every part of your code).

The `int val3 = 8;` definition is inside your `setup ()` function, so it acts as a **local** variable only within that function. This overrides the `val3` constant defined outside of the `setup ()` function. I.e. the global `val3` constant and the local `val3` variable inside of `setup ()` are not the same variable, which will inevitably lead to confusion (as in your case).

It’s valid syntax but I don’t consider it good coding practice. It’s good to know why it works that way though.


message:
How can I declare custom pins when using with ESP8266 in MPU9250 library

I want to declare SCL and SCK pins like   `Wire.begin(sda_pin, scl_pin);` to use with ESP8266 to integrate a MPU 9250/6500 sensor.
I can't figure out a way to declare that in this code exaample provided by [https://github.com/bolderflight/MPU9250][1]

in the example of the above it has just passed as **Wire** to and created object like `MPU9250 IMU(Wire,0x68);` which was meant to be used with UNO boards(as I think)

And in any case if any of you have seen a library that can be used with the ESP8266 for the MPU 9250/6500 point me on that direction please (I'm trying to get the roll, pitch, yaw)

  [1]: https://github.com/bolderflight/MPU9250

body:
You can use `Wire.pins(sda, scl);` before `IMU.begin();`.
`IMU.begin()` then calls `Wire.begin()` without parameters.


message:
MIDI Keyboard control

I am relatively new to Arduino and I am looking to implement a simple system that uses a MIDI keyboard to

(i) detect key presses (via MIDI messages) from the keyboard

(ii) store the information of the MIDI messages (note pressed, velocity)

(iii) Light up LEDS on the keyboard based on what key was pressed

I am currently in the planning stage and I am considering using an Arduino Mega. I have two issues I am not sure about:

(i) My keyboard only has a Male USB A to Male USB B connection with the former connecting to the computer and the latter to the keyboard. So far in my search, I have seen that all Arduino-MIDI projects require a 5 pin MIDI cable to interface with the Arduino using the circuit in this webpage (https://www.instructables.com/id/Send-and-Receive-MIDI-with-Arduino/). Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?

(ii) Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.

One way I thought of avoiding these problems is to use MATLAB MIDI package (https://uk.mathworks.com/help/audio/ug/midi-device-interface.html#mw_80dc54f4-867c-43c0-a159-e56ee62ec4ab) to interface with the MIDI device and use the MATLAB Arduino package to control the Arduino. I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.

This is my first question in Arduino StackExchange (or any StackExchange site), so I appreciate the answers and feedback on my question.

body:
> Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?

You could probably do it with a "USB Host Shield", though I have no experience of them and don't know if they can handle MIDI - you'll have to research this.

> Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.

Highly unlikely. You'd have to be doing something very wrong to make it so slow to respond that you'd see any delay.

> I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.

I cannot comment, I have never used MATLAB. If you don't use a USB Host Shield then you will certainly require something that runs on a PC to forward the MIDI information over serial.  Whether you create that in MATLAB or some other programming language is neither here nor there as far as the Arduino is concerned - you'll still need to program the Arduino itself, and that can be done in the IDE and still use MATLAB for the PC portion of your setup.


body:
- I don't have experience with USB MIDI, but I'm (almost) sure it should work with a shield (as Majenko already writes).
- I have experience with the following library. I used it for normal (DIN5) MIDI, not via USB, but it seems to support USB too: https://github.com/FortySevenEffects/arduino_midi_library
This library is interrupt based, try to keep the interrupts as short as possible, you can do the processing of the MIDI messages in the main function, together with driving the LEDs.
- I created a (temporary) USB merger which worked quite well, so yes, with a Mega it's easy to use 3 (or 4) MIDI channels, using DIN5. It's more than fast enough. MIDI is just 31.250 baud.
- I found it was very annoying to use the only UART of an Arduino Uno to use for both MIDI and debugging/uploading, so it's easier to use 3 UARTs from the Mega, and when your program works, use the main RX/TX for MIDI too (make it flexible).
- In case you think about use the software serial: forget about it, at least for reading MIDI.


message:
Function pointers that call one function

I'm reading a library file `timer.h` for STM core library that I just installed in Arduino hardware folder.

Of course, there has to be a lot of questions for me as a beginner about many approaches/stratgegies that programmers rule in writing the code.

One thing is that calling a function with a function pointer that only call one function, but the difference is that the function pointer is declared/defined as an inline function.

********************************************************************************
Edit: I deleted the code and posted a link for it in github.

[stm32/timer header file][1]

OK, the part that I started to think about starts from line 595.

It's functions declarations.

In line 598, it's a declaration for a function that receiver a pointer to a function.

In later lines, starting from line 634, these functions have only one line to execute. So my question is why to develop a function to only execute one line ?

Why they didn't just put that line directly instead of putting it inside function ?

  [1]: https://github.com/rogerclarkmelbourne/Arduino_STM32/blob/master/STM32F1/system/libmaple/include/libmaple/timer.h#L595

body:
`bb_perip` is a function that returns a pointer to a bit from a register that is related to a specific timer peripheral (there's more than one).  That pointer is then dereferenced with the `*` operator to make `*bb_perip(...)`.

What `bb_perip` returns is dependent on what timer you are using and what value you are interested in.

`bb_perip` is not a pointer to a function, it is a normal function that happens to return a pointer.


message:
Displaying multiple effects in Fast LED

I want to implement three effects which display every 5 seconds. I know that using `delay()` is not a good method so I want to use `milis()`. Duration times of the effects are different from each other. How can I assure "non-freezing" or displaying 2 or 3 effects at the same time? Should I measure the time of display of every effect and on its base adjust intervals or is there another solution? What do you think?

EDIT:

Here is my code:

```
void loop() {
   unsigned long currentMillis = millis();

   if(currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;
     i++;

    switch (i){
      case 1:
        meteorRain(0xff,0xff,0xff,10, 64, true, 30); // efekt spadającej gwiazdy
        Serial.print("meteorrain: ");
        Serial.print(previousMillis);
        Serial.print("\n");
        break;

      case 2:
         colorWipe(0x90,0x90,0x90, 50);
         colorWipe(0x00,0x00,0x00, 50);
         Serial.print("colorwipe: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;

      case 3:
         MyEffect();
         Serial.print("My effect: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;
    }
    if (i>3) i=0;
    }
}
```

I've ommited the code of effects (it doesn't matter, I think).

body:
I'd take a look at [Mark Kriegsmans FastLED example "DemoReel100"][1]. This example shows how to delegate to multiple functions.

First, I'll explain that example a bit: You set up an array of function pointers plus a variable for the current index.
```
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };
uint8_t gCurrentPatternNumber = 0;
```
All the functions (`rainbow`, `juggle`, etc) just need to work on your `leds[]` array that you gave to `FastLED.addLeds()` in your `setup()` -- I assume that your functions already fulfill that requirement. But: All functions must have the same argument list (in this case: they must be defined like `void rainbow() { leds[x] = CHSV(a,b,c); }`), so you might need to wrap them in another function.

Then, in your loop, you call your effect functions like this while calling `nextPattern()` every 10 seconds:
```
void loop()
{
  // Call the current pattern function once, updating the 'leds' array
  gPatterns[gCurrentPatternNumber]();

  // send the 'leds' array out to the actual LED strip
  FastLED.show();
  // insert a delay to keep the framerate modest
  FastLED.delay(1000/FRAMES_PER_SECOND);

  // do some periodic updates
  EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
}

#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
void nextPattern()
{
  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
}
```
`EVERY_N_SECONDS` is a macro defined in the FastLED library; it basically does what you did with `currentMillis`, `previousMillis` and `interval` (There's also `EVERY_N_MILLISECONDS` and some other related macros).

That's the example so far, now we need to work with differing "effect switch times".

The easiest method in code would be to find the greatest common factor of all switch times -- let's say you want the `rainbow()` effect to last for 10 seconds, the `juggle()` effect for 15 and the `bpm()` effect for 5 seconds. All those switch times are a multiple of 5, so we put that as the switch delay: `EVERY_N_SECONDS(5)`. Now, to get higher runtimes, we just put those functions multiple times into the array:
```
SimplePatternList gPatterns = { rainbow, rainbow, juggle, juggle, juggle, bpm };
```

There's another way, which gives you the option of setting the effect durations directly. First, we need an array of durations of the same length than our effect function array and a variable to remember where we are in the durations:
```
SimplePatternList gPatterns = { rainbow, juggle, bpm };
int[] gPatternDurations = { 10, 13, 73 };
int effectDurationLeft = gPatternDurations[0];
```
Then, we reduce the "effect switch resolution" down to 1 second and put a bit of logic around the `nextPattern()` call:
```
  EVERY_N_SECONDS( 1 ) {
    if( effectDurationLeft == 0 ) {
      nextPattern();
      effectDurationLeft = gPatternDurations[gCurrentPatternNumber];
    } else {
      effectDurationLeft -= 1;
    }
  }
```
Now you could set your pattern durations by editing the `gPatternDurations` array.

Please be aware that I did not test the code above. Syntax Errors may occur :)

  [1]: https://github.com/FastLED/FastLED/blob/master/examples/DemoReel100/DemoReel100.ino


message:
Where to find the attribution name for a certain board?

I'm working on lcd128x64 spi library. And was working with my Arduino Atmega328p chip.

Now I want to run the code with my maple mini board too.
So I have to specify the name on the pins for each chip board.
But I want to learn the basics of how to write these statements.

Could you tell me where to find the attributions for each board ?

For now I want to define the pin names for the Atmega328p and maple mini. This is my intention:

 #if defined(__AVR_ATmega328P__)
  #define CS_PIN     10
  #define MOSI_PIN    11
  #define CLK_PIN     13
 #elif defined(STM32_SERIES_F1)
  #define CS_PIN     PB12
  #define MOSI_PIN    PB15
  #define CLK_PIN     PB13
 #endif

I don't think that's 0 correct, but I'm pretty sure that it's not the correct names of boards.

body:
The Arduino defines to identify a board are in form of `ARDUINO_<board>`, where `<board>` is the value from `<x>.build.board` from boards.txt for board `<x>`

For example for Arduino AVR boards, in the boards.txt file is `uno.build.board=AVR_UNO` so the define is `ARDUINO_AVR_UNO`.

And Arduino has ['architecture' identification define][1] too. This has form of `ARDUINO_ARCH_<arch.name>`. The `<arch.name>` is the uppercase version of the folder name with the boards package version. For example AVR for packages/arduino/hardware/avr/1.6.21.

  [1]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#working-with-multiple-architectures


body:
If you are working on Maple Mini, you may look in [this folder][1], you will found the pin mapping between STM32 and Arduino nomenclature.

  [1]: https://github.com/rogerclarkmelbourne/Arduino_STM32/tree/master/STM32F1/variants/maple_mini


message:
How can I make my Arduino Esplora program start on the press of a button and then continue to run without me having to hold the button down?

I am trying to create a program where the main code starts on the press of a button.
I am using an Arduino Esplora, and I want to have the built-in LED be blue when I plug in the power until I press Switch 1 (or any of them), upon which the program starts.
I have had no problem in making the main part of my program, but I would like to find a way to have my program by just pressing the button once, as currently it only works while I am holding the button down continuously - something that is not possible in the situation I am using it for. I can't use any components apart from the Esplora itself, which rules out the option of using switches, etc. which probably would have made my life easier .
I would appreciate any suggestions. I'm pretty new to Arduino, so I'm sorry if I ask any dumb questions, or don't understand some of the concepts you are talking about, but I'll try my best. Thank you!

body:
You could simulate the switch with the button by using a state variable that hold the state of the "switch". I don't know your code, so I can only give you an example on how to do that:

    // the includes are here, if you need any

    int flagActive = -1;

    // ...

    setup()
    {
       // ... set the internal LED to blue
    }

    loop()
    {
       if ( < switch pressed > )
       {
         flagActive = 1;
       }

       if ( flagActive > 0 )
       {
         // .... your program
       }
    }

You could also toggle the flag if you intend to deactivate you program by pressing the button again.

       if ( < switch pressed > )
       {
         flagActive = flagActive * -1;
       }


message:
Serial.print array displays nothing

I tried Serial.print an array I had made, but the Arduino displays nothing in the monitor.

I tried doing Serial.print("Hehehe"); as a test, but it just displayed "h?h?h?".

The monitor works fine with other sketches than this one.

Anyone knows why?

    int my_array[10];

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

      for (int i = 0; i < 10; i++){
        my_array[i] = i * 5;

      }
    }

    void loop() {
      // put your main code here, to run repeatedly:
        for (int i = 0; i < 10; i++){
          Serial.print(my_array[i]);
          Serial.print(" ");
        }
        Serial.println();
        delay(1000);
    }

body: Test on my Arduino Uno, your code works fine with a simple copy-paste. Remember to set the proper baud rate.