body:
I am trying to communicate arduino uno with CAN bus using MCP2515 shield.
Data sending and receiving both things are done.
Whatever data received is displayed on LCD.
CAN bus receive is done using interrupt of timer1 and LCD updating using interrupt of timer2.
I think LCD does not get enough time for updating hence garbage data appears on LCD.
So please suggest me solution so that I can get Both CAN communication and LCD updation.
I am posting my code for your reference.

```cpp
#include <Wire.h>
#include <CAN.h>
#include <Adafruit_ADS1015.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

 Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */

 int timer2_counter;
 int timer1_counter;
 uint16_t adc0;
 uint8_t adch,adcl;
 char receive;
 uint8_t dlc = 0;
 int addr = 0;
 long sensorValue = 0;         // the sensor value
 float rpm;
 uint16_t count = 0;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

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

  // initialize timer1
  noInterrupts();           // disable all interrupts

  //---------------------TIMER_1---------------------------------------//
  TCCR1A = 0;
  TCCR1B = 0;

  //timer1_counter = 64930;   // preload timer 65536-16MHz/256/100Hz   10ms 64911
  //timer1_counter = 64911;   // preload timer 65536-16MHz/256/100Hz
  timer1_counter = 64286;   // preload timer 65536-16MHz/256/50Hz
 // timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
 //timer1_counter = 62411;   // preload timer 65536-16MHz/256/20Hz   100msec

  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

   //Setup Timer2 to fire every 1ms
  TCCR2B = 0x00;        //Disbale Timer2 while we set it up
  TCNT2  = 130;         //Reset Timer Count to 130 out of 255
  TIFR2  = 0x00;        //Timer2 INT Flag Reg: Clear Timer Overflow Flag
  TIMSK2 = 0x01;        //Timer2 INT Reg: Timer2 Overflow Interrupt Enable
  TCCR2A = 0x00;        //Timer2 Control Reg A: Wave Gen Mode normal
  TCCR2B = 0x05;        //Timer2 Control Reg B: Timer Prescaler set to 128

  interrupts();             // enable all interrupts

  Serial.println("CAN Sender");
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("DYNALEC CONTROLS");

  ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  ads.begin();
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

}

ISR(TIMER2_OVF_vect)
{

  TCNT2 = timer2_counter;   // preload time
  count++;
  if(count >= 20000)
  {
     Serial.println("LCD");
    lcd_write();
    count = 0;
  }
}

ISR(TIMER1_OVF_vect)        // interrupt service routine
{
  TCNT1 = timer1_counter;   // preload time

  if(dlc == 1)
  {
    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);
    dlc = 0;
    CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
    CAN.write(0x00);
    CAN.write(adch);
    CAN.write(adcl);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.endPacket();
    Serial.println(" ");
  }
   else{
  CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
  CAN.write(0xFF);
  CAN.write(adch);
  CAN.write(adcl);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.endPacket();
  Serial.println(" ");
  }

}
//------------------------------------while_loop-------------------------------------------//
void loop(void)
{
  //lcd_write();
  read_ads();
  read_can();
  calibration();
}
// ------------------------------lcd_write---------------------------------------------------//
void lcd_write(void)
{
  noInterrupts();

  //Serial.println("LCD");
  lcd.setCursor(0, 1);
  delay(10);
  lcd.print("RPM: ");
  lcd.print(rpm);
  delay(10);
  interrupts();

}
//--------------------------ads_read--------------------------------------------------------//
void read_ads(void)
{
  adc0 = ads.readADC_SingleEnded(0);// 10v = 64255 = 8031.875 max value speed. adjust 10v = 32127 counts.
  adc0 = adc0 * 2;
  sensorValue = adc0 - offset;
  sensorValue = sensorValue * slope;
  sensorValue = sensorValue / 10000;
  Serial.println(sensorValue);
  rpm = sensorValue * 0.125;
  Serial.println("RPM:");
  Serial.println(rpm);

  /*adch = adc0 >> 8;
  adcl = adc0 & 0x00FF;
  Serial.print("AIN0: "); Serial.println(adc0);
  Serial.println(adch);
  Serial.println(adcl);*/
}
//--------------------------------------can_read-----------------------------------------------------//
void read_can(void)
{
   // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print(CAN.read(),HEX);
      }
      Serial.println();
    }
    if((CAN.packetDlc() == 3) && (CAN.packetId() == 0x3AEF))
    {
      dlc = 1;
    }

    Serial.println();
  }
}
```

title: CAN bus communication and LCD updation

Answers: 0


body:
I have a domain. It is hosted by GoDaddy. I need to connect that server and receive some data by executing PHP files.

I am not sure about the components.

Tutorials on internet describes how to control esp8266 from web server which is i do not want.

Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is '**retired**'.

So do you recommend any component for this task or should i go with arduino uno wifi?

title: Connecting Web Server in GoDaddy Hosting

Answers: 1

body:
> I have a domain.

Congratulations.

> It is hosted by GoDaddy.

You have my deepest sympathies.

> I need to connect that server and receive some data by executing PHP files.
>
> I am not sure about the components.
>
> Tutorials on internet describes how to control esp8266 from web server which is i do not want.

"Controlling" an ESP8266 from a web server is nothing more than making a request to a web server and responding to something the web server sends back.

If you don't want to respond to what is sent back you don't have to. You just have to make the request. That request can contain whatever you want in the way of data and sensor values.

> Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.

Yes. It's been replaced with the Arduino WiFi Rev 2, which is a more modern AVR MCU coupled with an ESP32 based WiFi interface.

It's pretty wasteful really, since the WiFi interface is considerably more powerful than the AVR that it's connected to.

> So do you recommend any component for this task or should i go with arduino uno wifi?

I'd recommend an ESP32 based board. They're cheap, have direct connection to WiFi, very very powerful, plenty of inbuilt peripherals (unlike the ESP8266), and above all have great software support, examples and tutorials.


body:
I need to use a ESP32 WROVER B based MCU board with a standard (cheap) one-channel 5 V relay (e.g. to switch on a mains-power appliance).

Attempted removal of excess solder around the headers permanently disabled the 5 V power output line from the board (to power a relay or other modules), but other pins functional/board boots up correctly.

So at present, there is only a 3.3 V power source and 3.3 V GPIO pins (and others such as for external microphone and speaker).

I assume it is safe to connect a 3.3 V GPIO from the MCU to IN and external 5 V power source to VCC ad GND of the relay and connect the grounds of the MCU and relay together to complete the circuit.

The relay only needs to switch the appliance on when triggered (for example a lamp) and switch off when triggered again. I have a 3.3 ↔ 5 V bidirectional level shifter, but don't think it is suitable here (unless it can be incorporated directly). An alternative maybe is to use an Arduino Uno to connect with the relay, itself triggered by the ESP32 and more complex circuitry (bearing in mind the ESP32's GPIO is 3.3 V and the Arduino's is 5 V).

title: Connect 5V relay to ESP32 WROVER B board

Answers: 2

body:
Assuming a relay *module*: check if it is OK to drive it with 3.3 V logic when it is on a 5 V power supply, or show the specs for us to look at.

Driving a relay module with 3.3 V logic is unlikely to harm the ESP32, but it may not drive the relay properly if the relay module expects 5 V logic.

Generally, I would even prefer using an external power supply rather than the 5 V pin on a microcontroller board to power a relay module.

As long as you connect everything as you describe, it should work just fine (if the relay module accepts 3.3 V logic).

body: These "digital relay" modules are available in 3.3V and 5V versions. Simply buy one of the 3V models. Here is one, for example: https://www.dfrobot.com/product-1572.html


body:
I have a function:

    void Epd::SendData(unsigned char data) {
      digitalWrite(dc_pin, HIGH);
      SpiTransfer(data);
    }

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:

    SendData(0x03);
    SendData(0x1f);

To get those two values (`0x03` and `0x1f`) I am converting the decimal value of `799` to binary: `1100011111` and then adding `0` at the beginning to make sure my binary result is 16 digits long: `0000 0011 0001 1111`. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the `SendData` function.

I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the `SendData` function:

    void Epd::SendDecAsData(int dec) {
      int binary[16];
      for (int i = 0; i < 16; i++) {
        binary[i] = dec % 2;
        dec = dec / 2;
      }

      int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
      int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
      int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
      int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

      String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
      String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

      SendData(val1); // error because I'm sending `String` instead of `unsigned char`
      SendData(val2);
    }

I need help converting those strings (`val1`, `val2`) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to `String`).

title: Converting 8 bit binary to a hexadecimal pair as unsigned char

Answers: 1

body:
As [StarCat suggested][1], I can just send decimal values using the same function `SendData` I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.

This is the function I used to send decimal data in 8-bit pairs:

    void Epd::SendDecAsData(int dec) {
      if (dec == 0) {
        SendData(0);
        SendData(0);
      } else {
        SendData((dec-1) / 256);
        SendData((dec-1) % 256);
      }
    }

  [1]: https://arduino.stackexchange.com/questions/79606/converting-8-bit-binary-to-a-hexadecimal-pair-as-unsigned-char/79658#comment177213_79606


body: I'm wondering if it would be somehow possibly to have easy communication with a computer for Arduinos that don't have USB like the pro mini. That would make an easy way of having two-way communication with a computer. The computer could just play or record audio using software written specifically for this purpose. Would something like this require any special circuitry or would it just be a matter of connecting the right wires?

title: Communicate from Arudino to computer over 3.5mm port

Answers: 1

body:
I didn't read the all page, but it seems it can be achieved, see [David Awehr's blog][1] (this one is conected to a android phone instead to a PC tho) and this [Hackaday][2] page where they seems to it, but the PC's audio input normally use 44,1kHz or 96kHz, so if you wanna go for the higher Serial speed (let's say just 115200bauds) you should think about it this.

  [1]: https://davidawehr.com/blog/audioserial/
  [2]: https://hackaday.com/2014/11/04/using-a-headphone-jack-as-a-uart/


body:
Hi I'm trying to get my Arduino Uno code to work with a in a specific way where if I push a button, the Arduino will read the raw potentiometer value once and if I don't push it nothing happens.

  <https://i.stack.imgur.com/uCHkR.jpg>

    int switchState = 0
    int switchPin = 2
    int potPin = A0;

    void setup() {
    pinMode (potPin, OUTPUT);
    pinMode (switchPin, INPUT);
    Serial.begin (9600);

    }

    void loop() {
    switchState = digitalRead(2);
    if (switchState == High) {
    Potval = analogRead(potPin);
    Serial.print("potval:");
    Serial.Println(Potval);
    delay(200);
    }

    else {
    (switchState == LOW);
    while (Potval);
    }
    }

title: Can anyone help be get readings off of my potentiometer with a push of a button?

Answers: 2

body:
I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:
[![enter image description here][1]][1]

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

or you can simply change the button initialization to INPUT_PULLUP.

body:
There were several issues with your code:
 - It would not compile due to some missing semi-colons (lines 1 & 2);
 - The 'else' clause in your loop() function didn't do anything useful;
 - If your code didn't get trapped in the loop within the 'else' clause (it probably would!), it would print repeatedly as long as you were NOT pressing the button, since you wired the button to read LOW when pressed (which is perfectly fine, buy your code has to take that into account).
 - Buttons appear to bounce (electrically) when you press or release them. They don't switch once and stay that way. They switch multiple times before they settle down, due to the rough contact surfaces sliding over one another. The code has to allow for this as well.
- An analog pin has to not be set to OUTPUT if you want to read analog with it.

Here is a revised version of your code, compiled and tested. You'll find notations in the comments where I made changes:

    int switchState = 0;   // (';' was missing)
    int switchPin = 2;   // (';' was missing)
    int potPin = A0;
    int Potval = 0;    // (this declaration was missing)
    bool didPrint = false;  // true if we printed on this button-push
    // prevents multi-printing while button stays high

    void getSwitch();    // declare the new function

    void setup() {
      //  pinMode (potPin, OUTPUT);  // not OUTPUT for analog read
      pinMode (switchPin, INPUT_PULLUP);  // needs pullup or reads may be unreliable
      pinMode (13, OUTPUT); digitalWrite(13, LOW); //DEBUG
      Serial.begin (9600);

    }

    void loop() {
      getSwitch();
      if (switchState == LOW ) {  // pressed == LOW the way you've wired it

        if (!didPrint) {
          Potval = analogRead(potPin);
          Serial.print("potval:");
          Serial.println(Potval);

          didPrint = true;  // prevent printing again til button has been released
        }
      }
      else if  (switchState == HIGH) {
        didPrint = false;  // printing allowed on next button push
      }
    }

    void getSwitch() {
      switchState = digitalRead(switchPin);
      delay(30);    // waits for button to settle - may need to tweak this
    }


body:
Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]

Arduino:
```
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}
```
Python code:
```
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')
```

title: How can I send and receive data from an Arduino MEGA 2560 and Python?

Answers: 2

body:
Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like ```dat.write(b'1')``` and then receive it on the Arduino using ```Serial.readString()```. I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The easiest way is to,Arduino IDE)"
If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.

body: try with Firmata, it is a protocol that establishes serial communication between the computer with Arduino. All you have to do is have the Firmata on Arduino Board, and pyFirmata plugin available to talk with Arduino from Python on your machine.


body:
[![enter image description here][1]][1][![enter image description here][2]][2]Hi everyone I have an issue with getting these LEDs to cooperate.

I'm using a 470ohm resistor on the data port and a capacitor for the power. I complied and uploaded the "strandtest"(I changed the variables NUM_LED & LED_PIN) and this occurs [10s Video: https://drive.google.com/file/d/1xabkHW1xgFo9kh3YnGwIsaS5tSfFCsrb/view?usp=sharing]
This happens to all code in a loop. If I send no signals (aka put an empty pin and run) then the lights that were last on stay lit. If I try to clear the LED nothing happens. If I try to set a specific LED to a specific color/brightness nothing happens.

I'm at my wit's end; help a brother out!

LEDs Used:https://www.amazon.com/gp/product/B00ZHB9M6A/ref=ppx_yo_dt_b_asin_title_o02_s01?ie=UTF8&th=1
AC to DC 5V 5A: https://www.amazon.com/ALITOVE-Converter-5-5x2-1mm-100V-240V-Security/dp/B078RT3ZPS/ref=pd_bxgy_img_2/143-9706163-2199558?_encoding=UTF8&pd_rd_i=B078RT3ZPS&pd_rd_r=4133e781-45a6-4112-a571-c311f45e0720&pd_rd_w=t0bs4&pd_rd_wg=TIEcS&pf_rd_p=f325d01c-4658-4593-be83-3e12ca663f0e&pf_rd_r=PPCEVPJVY8N6XFTY1AD4&psc=1&refRID=PPCEVPJVY8N6XFTY1AD4

    #include <FastLED.h>

    // How many leds in your strip?
    #define NUM_LEDS 150

    // For led chips like WS2812, which have a data line, ground, and power, you just
    // need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
    // ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
    // Clock pin only needed for SPI based chipsets when not using hardware SPI
    #define DATA_PIN 3
    #define CLOCK_PIN 13

    // Define the array of leds
    CRGB leds[NUM_LEDS];

    void setup() {
        // Uncomment/edit one of the following lines for your leds arrangement.
        // ## Clockless types ##
        //FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);  // GRB ordering is assumed
        // FastLED.addLeds<SM16703, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<TM1829, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<TM1812, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<UCS1904, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<UCS2903, DATA_PIN, RGB>(leds, NUM_LEDS);
         //FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
        // FastLED.addLeds<WS2852, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

      FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

        // FastLED.addLeds<GS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<SK6812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
        // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<APA106, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<PL9823, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<WS2813, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<WS2811_400, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<GE8822, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<LPD1886, DATA_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<LPD1886_8BIT, DATA_PIN, RGB>(leds, NUM_LEDS);
        // ## Clocked (SPI) types ##
        // FastLED.addLeds<LPD6803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
        // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
        // FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<WS2803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
        // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
        // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
        // FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
        // FastLED.addLeds<SK9822, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    }

    void loop() {
      // Turn the LED on, then pause
      leds[0] = CRGB::Red;
      FastLED.show();
      delay(500);
      // Now turn the LED off, then pause
      leds[0] = CRGB::Black;
      FastLED.show();
      delay(500);
    }

  [1]: https://i.stack.imgur.com/ceF3z.jpg
  [2]: https://i.stack.imgur.com/7kvPr.png

title: Adafruit Neopixel Individual Addressable LEDs issue - Any and every code make LEDs go "crazy"

Answers: 1

body: Don't use the Neopixel library. for LEDs that have WS2812B the FastLED is the best option. I also had issues with the LEDs flashing on and off randomly but using this library and then changing the driver to W2812B made it work. Your power supply is plenty strong.


body:
the point of my code is to turn on a LED when the humidity level reaches a certain amount. However it reads the amount of humidity but the LED is not turning on. Why isn't it working??

```
#include <SimpleDHT.h>

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11;

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  }

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");

  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  if (humidity > 70 ) {
     digitalWrite(9, HIGH);
  }
  else if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

```

title: DHT11 not working with LED in arduino

Answers: 1

body:
Your code does not work because in fact error statement reads the value of temperature and humidity sensor.

You set the `humidity` and `temperature` variables to 0. If statement compares this variables to 70, before actually reading sensor data.

I haven't tested but this should work.

    #include <SimpleDHT.h>

    int pinDHT11 = 2;
    SimpleDHT11 dht11;

    void setup()
    {
        Serial.begin(9600);
        pinMode(9, OUTPUT);
    }

    void loop()
    {
        // start working...
        Serial.println("=================================");
        Serial.println("Sample DHT11...");

        // read without samples.
        byte temperature = 0;
        byte humidity = 0;

        int err = SimpleDHTErrSuccess;
        if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL))
            != SimpleDHTErrSuccess)
        {
            Serial.print("Read DHT11 failed, err=");
            Serial.println(err);
            delay(1000);
            return;
        }

        Serial.print("Sample OK: ");
        Serial.print((int)temperature);
        Serial.print(" *C, ");
        Serial.print((int)humidity);
        Serial.println(" H");

        if (humidity > 70 )
        {
            Serial.println("Humidity is above 70%");
            digitalWrite(9, HIGH);
        }
        else
        {
            Serial.println("Humidity is below 70%");
        }
        // DHT11 sampling rate is 1HZ.
        delay(1500);
    }


body:
I'm very new to the Arduino world so bare with me.
I would like to plot live data that I receive from my arduino. I use the Serial Monitor to read user input, show text, etc.

The only way I found to plot data from the arduino is by printing the data out in the serial monitor
I would rather prefer the data not to be shown in the serial monitor at all (just from a visual standpoint) but I guess there is no way around it.

Anyways, I would like to read and plot the data only when the user makes a specific input into the Serial Monitor.

Let's say the user types in: "start"
now the arduino prints out the values that needs to be plotted.

But every plotting tutorial on plotting with the arduino that I could find always prints out the data right from the start. I want to start the plotting with the specific user input.

I hope I could explain my question well enough.
Thank you in advance for your help.

Luca

title: Plotting data from Arduino and using the serial monitor in parallel

Answers: 2

body: Is using the Serial Monitor a requirement, or are you just looking for a good way to get and plot the data?  If the latter, you may be interested in the open-source DaqPort sketch. <https://www.daqarta.com/dw_rraa.htm>  This was created to use the Arduino as a peripheral for data acquisition, as opposed to the more typical case of the Arduino being the central device.  With DaqPort you can program in any language you like on the host computer, and use it to plot data from the Arduino. The Daqarta software package that includes DaqPort has several examples that use Daqarta's macro language to implement a multi-channel chart recorder, high-speed multi-function oscilloscope, timers, signal generator, etc.  You can use these for free, forever, even after Daqarta's 30-day trial ends.  Since Daqarta already has plotting, you may find it simpler to use than rolling your own, perhaps by modifying one of the examples.

body: You can also use the Serial Plotter in the Arduino IDE. If you use ```Serial.println(<some number>)``` and then open the Serial Plotter(Tools-Serial Plotter), you will see a live graph. Based on your baud rate, the update speed will change. It is very powerful.


body:
I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each.
Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44).
By debugging the code, I found out that endTransmission does not return.
Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?

Thanks!

    #include <Wire.h>

    void setup() {
      Serial.begin (115200);
      // Leonardo: wait for serial port to connect
      while (!Serial)
        {
        }
      Serial.println ();
      Serial.println ("I2C scanner. Scanning ...");
      byte count = 0;
      Wire.begin();
    }  // end of setup

    void loop() {
      byte count = 0;
      for (byte i = 1; i < 120; i++)
      {
        Serial.println(i);
        Wire.beginTransmission (i);
        Wire.endTransmission ();
        delay(10);
      }
    }

title: Pro micro Wire.endTransmission() does not return

Answers: 1

body: Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines


body:
I have a small project I am working on that accepts power from either a 5v DC power source or a USB power source.

Now, I know that both of the power sources are effectively 5v. I have measured the power on both with my meter and can see that the USB supply is at 5.4 and the DC supply is at 5.01v.

I would like to be able to build something that switches over to the USB supply when the cable is connected. However, I have never done this before. I have taken a look around on Google already and have read some things about P Channel MosFETs and PowerPath controllers - but I am a little confused as to whether the two incoming voltages I have are suitable for this?

Would someone be able to give me a little advice on this at all?

Cheers,

Rafa

title: switching power sources

Answers: 1

body:
Consider copying the [Arduino Uno reference design][1].  This is part of that schematic showing the MOSFET used to turn on / off the USB power when the barrel jack power source is active:

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

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://i.stack.imgur.com/ypgzv.jpg


body:
My task is to find the amount of current a light bulb uses, with that motive I used ACS712 current sensor of 30A connected all the connections properly as shown in the circuit diagram below

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

I tried all different codes available to calculate current...

**Arduino Code :**

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

    void loop(){
      int rVal = 0;
      int sampleDuration = 100;       // 100ms
      int sampleCount = 0;
      unsigned long rSquaredSum = 0;
      int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

      uint32_t startTime = millis();  // take samples for 100ms
      while((millis()-startTime) < sampleDuration)
      {
        rVal = analogRead(A0) - rZero;
        rSquaredSum += rVal * rVal;
        sampleCount++;
      }

      double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

      // x 1000 to convert volts to millivolts
      // divide by the number of millivolts per amp to determine amps measured
      // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
      double ampsRMS = voltRMS * 10.0;
      Serial.println(ampsRMS);
      Serial.println(analogRead(A0));
    }

**Output**

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

The output remains the same, even when the bulb is still lighting up.

Thank You in advance :)

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

title: Current Sensor ACS712 not changing its value even when connected bulb is lit

Answers: 1

body:
In a comment about `rZero = 511;`, you wrote:
> For illustrative purposes only - should be measured to calibrate
> sensor.

This may well be the cause of your problem. If, instead of 511, the
“zero” of your measurement is around 445, then you end up measuring a
non-existing DC current of about 3.23 A. When you turn on the light
bulb, you add roughly 435 mA (100 W / 230 V) of AC
current. The total RMS current you see is then:

√(3.232 + 0.4352) ≈ 3.26 A

Barely visible at the resolution at which you are printing the result.
And this is assuming you are using a 100 W bulb, as shown in the
diagram. These bulbs are getting hard to come by. If you are using
anything less powerful, you may not see any change in the displayed
value.

As a quick and dirty fix, you may replace `511` by `445`. A better
solution would be to compute the quadratic average of the AC part of the
signal alone. In other words, compute:

√(average(current2) − average(current)2)


body: I'm working on a project that have two separate setups for Arduino, each Arduino read sensors and send data to smartphone. how to connect two Arduino then send all data to smartphone over Bluetooth?

title: How to connect two arduinos with smartphone wirelessly

Answers: 0


body:
I am running out of intelligence trying to control a Lolin 2.4 Inch TFT shield.
I connected the shield via the official TFT connector to a Lolin D32 Pro. I am using the ILI9341 libary from Adafruit. With the libary it is no porblem controlling the display.
Unfortunately, as soon as I put the esp32 into Deep Sleep, the display goes white but the background illumination stays on.
Does someone know, how I can trun off the background illumination?
As far as I understood, the background light is not controlled via the ILI9341. Instead I tried putting the GPIO32 on Low, since accoring to the schema of the Lolin TFT cable it is responsible for the TFT_Led [![enter image description here][1]][1]
Unfortunately that does not work either

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

title: ESP32 with Lolin 2.4 inch TFT Shield Power control

Answers: 1

body:
The backlight of this shield is ON as long as there's power on the 3.3V pin, unless you make GPIO 32 an output and pull it low.

In deep sleep, however, GPIO 32 will stop acting as a pulled down output pin but the esp32 keeps its 3.3V output pin powered, so the backlight will switch ON.

You could power the display over a mosfet, controlled by a GPIO.


body:
I have installed the library of **[TimerInterrupt_Generic][1]** for ArduinoSTM32 module via Arduino IDE, so i have tried to test the example of library as you can see below:

[![enter image description here][2]][2]
and i have gotten this error:

```

TimerInterruptLEDDemo:45:4: error: #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
   #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
    ^
In file included from /home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/examples/STM32/TimerInterruptLEDDemo/TimerInterruptLEDDemo.ino:64:0:
/home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/src/TimerInterrupt_Generic.h:86:4: error: #error Unsupported Board! Please check your Tools->Board setting.
   #error Unsupported Board! Please check your Tools->Board setting.
    ^
exit status 1
#error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.

```
Also, This question is asked here:

https://github.com/khoih-prog/TimerInterrupt_Generic/issues/2

  [1]: https://github.com/khoih-prog/TimerInterrupt_Generic/
  [2]: https://i.stack.imgur.com/lS38R.jpg

title: Timer STM32 #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting

Answers: 1

body:
The [**Roger Clark's STM32 core**](https://github.com/rogerclarkmelbourne/Arduino_STM32)  you're using is not currently supported. I don't know in the future if I can add that core into the supported list.

You have to use this [**Arduino_Core_STM32**](https://github.com/stm32duino/Arduino_Core_STM32).

Convert to new core by following the intructions in [**Getting Started**](https://github.com/stm32duino/Arduino_Core_STM32#getting-started)


body:
I’ve spent the past few days trying researching communication protocols and I have a few issues. With sewable electronics, you need to work with cables with a fairly high resistance that are constantly moving. That means unreliable and noisy communication. Furthermore relying on multiple data lanes increases the needed number of stitches and the chances of failure.

Adafruit Neopixels use a good system that allows them to only use 1 data pin for a large number of individually controlled addressed devices with a total of 3 connections between each device. Disconnecting the devices while in use doesn’t cause them to crash most of the time, and there’s a lot of expandability. Best of all, the circuit design is incredibly simple because most of the hardware is on board the IC. The problem is that the communication type they use seems to be specifically designed for use on those circuits only, and to my knowledge there is no version of the logic circuit that isn’t coupled with the SMD RGB LED component, and even if there was there’s no way to directly adapt it to other components.

I’ve looked into I2C, SPI, UART, FTDI, USB, CAN-bus, and a bit of DMX and I’m still fairly certain none would work. All I need is to exchange bytes of data between two microcontrollers without them constantly crashing. I’m willing to try the most exotic solutions imaginable.

title: What’s the most stable digital communication protocol for sewable electronics?

Answers: 0


body:
I have a curiosity. What is the difference between adding a header file directly on the arduino IDE and the header file inside another h-file.
For example:

```
#include "MPU6050_6Axis_MotionApps20.h"
void setup()
{
}
void loop()
{

}
```
This last didn't give me any problem, but when I create a h-file and add inside that h-file that library, it gave me an error:

ARDUINO:
```
#include "Prueba.h"
void setup()
{
}
void loop()
{

}
```
Prueba.h

```
//#ifndef Prueba_H
//#define Prueba_H
//#define LIBRARY_VERSION 1.0.0

#include "MPU6050_6Axis_MotionApps20.h"
class Prueba
{
  public:
  Prueba();
};
//#endif
```
Part of the error code is:

```
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: implicit this pointer type mismatch
 uint8_t MPU6050::getIntStatus() {
         ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.h:438:7: note: type 'struct MPU6050' itself violates the C++ One Definition Rule
 class MPU6050 {
       ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src/MPU6050.h:438:7: note: the incompatible type is defined here
 class MPU6050 {
       ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: 'getIntStatus' was previously declared here
 uint8_t MPU6050::getIntStatus() {
         ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: code may be misoptimized unless -fno-strict-aliasing is used
collect2.exe: error: ld returned 1 exit status
exit status 1
```
Can someone explain me this?

Thanks in advance.

title: Problemm with the MPU6050 library

Answers: 1

body:
Well I don't know exactly why this work, but base on this question [this][1]. To solve this I should add 'inline' keyword in every method definition on the MPU6050_6Axis_MotionApps20.h
Like this:

```
inline uint8_t MPU6050::dmpInitialize() {
 // reset device
 DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
 reset();
 delay(30); // wait after reset

 // disable sleep mode
 setSleepEnabled(false);

 // get MPU hardware revision
 setMemoryBank(0x10, true, true);
 setMemoryStartAddress(0x06);
 Serial.println(F("Checking hardware revision..."));
 Serial.print(F("Revision @ user[16][6] = "));
 Serial.println(readMemoryByte(), HEX);
 Serial.println(F("Resetting memory bank selection to 0..."));
 setMemoryBank(0, false, false);

 // check OTP bank valid
 DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
 DEBUG_PRINT(F("OTP bank is "));
 DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

 // setup weird slave stuff (?)
 DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
 setSlaveAddress(0, 0x7F);
 DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
 setI2CMasterModeEnabled(false);
 DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
 setSlaveAddress(0, 0x68);
 DEBUG_PRINTLN(F("Resetting I2C Master control..."));
 resetI2CMaster();
 delay(20);
 DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
 setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

 DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
 setIntEnabled(1<<MPU6050_INTERRUPT_FIFO_OFLOW_BIT|1<<MPU6050_INTERRUPT_DMP_INT_BIT);

 DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
 setRate(4); // 1khz / (1 + 4) = 200 Hz

 DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
 setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

 DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
 setDLPFMode(MPU6050_DLPF_BW_42);

 DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
 setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

 // load DMP code into memory banks
 DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
 DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
 DEBUG_PRINTLN(F(" bytes)"));
 if (!writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) return 1; // Failed
 DEBUG_PRINTLN(F("Success! DMP code written and verified."));

 // Set the FIFO Rate Divisor int the DMP Firmware Memory
 unsigned char dmpUpdate[] = {0x00, MPU6050_DMP_FIFO_RATE_DIVISOR};
 writeMemoryBlock(dmpUpdate, 0x02, 0x02, 0x16); // Lets write the dmpUpdate data to the Firmware image, we have 2 bytes to write in bank 0x02 with the Offset 0x16

 //write start address MSB into register
 setDMPConfig1(0x03);
 //write start address LSB into register
 setDMPConfig2(0x00);

 DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
 setOTPBankValid(false);

 DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
 setMotionDetectionThreshold(2);

 DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
 setZeroMotionDetectionThreshold(156);

 DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
 setMotionDetectionDuration(80);

 DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
 setZeroMotionDetectionDuration(0);
 DEBUG_PRINTLN(F("Enabling FIFO..."));
 setFIFOEnabled(true);

 DEBUG_PRINTLN(F("Resetting DMP..."));
 resetDMP();

 DEBUG_PRINTLN(F("DMP is good to go! Finally."));

 DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
 setDMPEnabled(false);

 DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
 dmpPacketSize = 42;

 DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
 resetFIFO();
 getIntStatus();

 return 0; // success
}
inline bool MPU6050::dmpPacketAvailable() {
    return getFIFOCount() >= dmpGetFIFOPacketSize();
}
inline uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[28] << 24) | ((uint32_t)packet[29] << 16) | ((uint32_t)packet[30] << 8) | packet[31]);
    data[1] = (((uint32_t)packet[32] << 24) | ((uint32_t)packet[33] << 16) | ((uint32_t)packet[34] << 8) | packet[35]);
    data[2] = (((uint32_t)packet[36] << 24) | ((uint32_t)packet[37] << 16) | ((uint32_t)packet[38] << 8) | packet[39]);
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[28] << 8) | packet[29];
    data[1] = (packet[32] << 8) | packet[33];
    data[2] = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[28] << 8) | packet[29];
    v -> y = (packet[32] << 8) | packet[33];
    v -> z = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[0] << 24) | ((uint32_t)packet[1] << 16) | ((uint32_t)packet[2] << 8) | packet[3]);
    data[1] = (((uint32_t)packet[4] << 24) | ((uint32_t)packet[5] << 16) | ((uint32_t)packet[6] << 8) | packet[7]);
    data[2] = (((uint32_t)packet[8] << 24) | ((uint32_t)packet[9] << 16) | ((uint32_t)packet[10] << 8) | packet[11]);
    data[3] = (((uint32_t)packet[12] << 24) | ((uint32_t)packet[13] << 16) | ((uint32_t)packet[14] << 8) | packet[15]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = ((packet[0] << 8) | packet[1]);
    data[1] = ((packet[4] << 8) | packet[5]);
    data[2] = ((packet[8] << 8) | packet[9]);
    data[3] = ((packet[12] << 8) | packet[13]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    if (status == 0) {
        q -> w = (float)qI[0] / 16384.0f;
        q -> x = (float)qI[1] / 16384.0f;
        q -> y = (float)qI[2] / 16384.0f;
        q -> z = (float)qI[3] / 16384.0f;
        return 0;
    }
    return status; // int16 return value, indicates error if this line is reached
}
inline uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[16] << 24) | ((uint32_t)packet[17] << 16) | ((uint32_t)packet[18] << 8) | packet[19]);
    data[1] = (((uint32_t)packet[20] << 24) | ((uint32_t)packet[21] << 16) | ((uint32_t)packet[22] << 8) | packet[23]);
    data[2] = (((uint32_t)packet[24] << 24) | ((uint32_t)packet[25] << 16) | ((uint32_t)packet[26] << 8) | packet[27]);
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[16] << 8) | packet[17];
    data[1] = (packet[20] << 8) | packet[21];
    data[2] = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[16] << 8) | packet[17];
    v -> y = (packet[20] << 8) | packet[21];
    v -> z = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
    // get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
    v -> x = vRaw -> x - gravity -> x*8192;
    v -> y = vRaw -> y - gravity -> y*8192;
    v -> z = vRaw -> z - gravity -> z*8192;
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
    // rotate measured 3D acceleration vector into original state
    // frame of reference based on orientation quaternion
    memcpy(v, vReal, sizeof(VectorInt16));
    v -> rotate(q);
    return 0;
}
inline uint8_t MPU6050::dmpGetGravity(int16_t *data, const uint8_t* packet) {
    /* +1g corresponds to +8192, sensitivity is 2g. */
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    data[0] = ((int32_t)qI[1] * qI[3] - (int32_t)qI[0] * qI[2]) / 16384;
    data[1] = ((int32_t)qI[0] * qI[1] + (int32_t)qI[2] * qI[3]) / 16384;
    data[2] = ((int32_t)qI[0] * qI[0] - (int32_t)qI[1] * qI[1]
        - (int32_t)qI[2] * qI[2] + (int32_t)qI[3] * qI[3]) / (2 * 16384);
    return status;
}
inline uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
    v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
    v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
    v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
    return 0;
}
inline uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);   // psi
    data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y);                              // theta
    data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1);   // phi
    return 0;
}

#ifdef USE_OLD_DMPGETYAWPITCHROLL
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
    return 0;
}
#else
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan2(gravity -> x , sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan2(gravity -> y , gravity -> z);
    if (gravity -> z < 0) {
        if(data[1] > 0) {
            data[1] = PI - data[1];
        } else {
            data[1] = -PI - data[1];
        }
    }
    return 0;
}
#endif

inline uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
    return 0;
}

inline uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
    uint8_t status;
    uint8_t buf[dmpPacketSize];
    for (uint8_t i = 0; i < numPackets; i++) {
        // read packet from FIFO
        getFIFOBytes(buf, dmpPacketSize);

        // process packet
        if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;

        // increment external process count variable, if supplied
        if (processed != 0) (*processed)++;
    }
    return 0;
}

inline uint16_t MPU6050::dmpGetFIFOPacketSize() {
    return dmpPacketSize;
}
#endif
```
I don't know why the guys that made this library didn't add this. Maybe I'm missing something.

  [1]: https://arduino.stackexchange.com/questions/79644/multiple-definition-class-in-arduino


body:
Help me out here. I don't know what I'm missing.
I have this code in my arduino IDE

```
#include "Foo2.h"
void setup() {
  // put your setup code here, to run once:

}
void loop() {
  // put your main code here, to run repeatedly:
}
```
And I have five files: Foo.h, Foo.cpp, Foo2.h, Foo3.cpp and Foo.h

**Foo.h**
```
#ifndef Foo_H
#define Foo_H

class Foo
{
 public:
 Foo();

 public:
 bool Fooa();
 bool Foob();
};
#endif
```
**Foo.cpp**
```
#include "Foo.h"

Foo::Foo()
{

}

bool Foo::Foob()
{
 return true;
}
```

**Foo2.h**
```
#ifndef Foo2_H
#define Foo2_H
#define LIBRARY_VERSION 1.0.0
#include "Foo.h"

bool Foo::Fooa()
{
 return true;
}
#endif
```

**Foo3.h**
```
#ifndef Foo3_H
#define Foo3_H
#include "Foo2.h"

class Foo3
{
 public:
  Foo3();
  Foo _foo;
};
#endif
```
**Foo3.cpp**
```
#include "Foo3.h"

Foo3::Foo3()
{
}
```
And it is give me an error:
```
libraries\Foo\Foo3.cpp.o (symbol from plugin): In function `Foo::Fooa()':
(.text+0x0): multiple definition of `Foo::Fooa()'
sketch\kk2.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
```

what i'm doing wrong

regards,

title: Multiple definition class in arduino

Answers: 1

body:
If you want `Fooa()` to be defined in a header that can be included in more than one .cpp file, you would need to declare it as an inline function like so:

```cpp
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    inline bool Fooa();
    bool Foob();
};
#endif
```

Alternately, you can provide the function definition directly inside class definition; this also makes the function `inline` despite not requiring the `inline` keyword.

Or if you want to keep `Fooa` as a non-inline function, you'd need to move the definition out of the header and into a .cpp file as you did with `Foob()`.

Making a function inline has a second effect beyond implying that you want a function's code to be generated at the call site; it informs the compiler (or more accurately the linker) to expect to see multiple definitions (that are required to be identical) of the code for the function.  Without that advanced noticed, you will get the `multiple definition of` error when a function definition is inserted into multiple .cpp file by way of an `#include`.

As a side note: `#include` is an automated form of copy-and-paste.  It logically plants the contents of another file (and all of its reachable `#include` uses transitively) into place where the `#include` directive appeared.  It does not behave the same way that many similar looking directives in other languages do.  E.g. `#include` does not behave like the `import` keyword does in say Java or python for example.


body:
I can't quite understand this when I run arduino yun disk expander sketch with a sd card plugged in I get the the following message. You do not have enough flash memory need 1mb. I ssh into my arduino and I get this

```
Filesystem                Size      Used Available Use% Mounted on
rootfs                    6.9M    632.0K      6.3M   9% /
/dev/root                 7.5M      7.5M         0 100% /rom
tmpfs                     29.8M    148.0K     29.7M   0% /tmp
tmpfs                     512.0K       0    512.0K   0% /dev
/dev/mtdblock3            6.9M    632.0K      6.3M   9% /overlay
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /
/dev/sda1                29.7G      2.4M     29.7G   0% /mnt/sda1
```

The only thing that is full is the /dev/root but the reading I have done through the posts here and online say that's fine. Why may this be I am quite confused???

title: Arduino Yun Disk Expander low memory but it looks like my memory is fine

Answers: 1

body:
I don't have a YUN or a lot of experience with OpenWRT, so I'm not sure I'm going to be of much help but, I'm guessing the error you're seeing is from [this line][1] of the sketch.

Excerpting that here:

```cpp
Process awk;

awk.runShellCommand(F("df / | awk '/overlay/ {print $4}'"));
int output = awk.parseInt();
if (output < 1000) {
  Serial.println(F("\nYou don't have enough disk space to install the utility software. You need to free at least 1MB of Flash memory.\nRetry!"));
  halt();
}
```

So, it appears they are executing `df / | awk '/overlay/ {print $4}'` on the YUN.

They're using [awk][2] to extract the fourth column (`$4`) of the line containing overlay (`/overlay/`), which by the way is awfully hackish.

Given that they expect the result of `awk.parseInt()` to compare less than `1000` to mean you have less than 1 Mbyte available, it's fairly clear they expected this column to be reported in kilobytes.  And yet in your own df listing

```none
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /
```

the fourth column is `6.3M` and the rest are choosing different units, what is sometimes called "human" output.  So, we know what they care about is the overlay mount point.  And that at the time someone tested this code it either they didn't try an SDCard of any size or the output of df was different back then, which is why parsing something like df isn't a good idea.

And that's about as far as *I* can take you with any real confidence.  I don't know how overlay is set up on a YUN.

I guess, if you wanted to "fix" the code with a minimal change, it would be to add `-k` to the df command-line to force kilobyte based output, assuming `-k` works on whatever df comes with YUN.  If you wanted to go a step further, I suppose you could use `-P` to get POSIX output from df, again assuming that's supported, and change the expected units in the sketch accordingly.  But if this is **just** for you, and you **know** overlay has more than 1 MB free, you could just as easily change the function so it **cannot** fail:

```cpp
void haltIfInternalFlashIsFull() {
}
```

All that said, I wouldn't be surprised if you run into another problem just like this in another part of the sketch.

  [1]: https://github.com/arduino/yun-go-updater/blob/1.3/YunDiskSpaceExpander/YunDiskSpaceExpander.ino#L156
  [2]: https://en.wikipedia.org/wiki/AWK


body:
this is not my code this is what i found on makersguide i tried to use the same but it doesn't work

    #include <Servo.h>

    // Define Trig and Echo pin:
    #define trigPin 10
    #define echoPin 9
    // Define variables:
    long duration;
    int distance;
    void setup() {
    // Define inputs and outputs:
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(9600);
    }
    void loop() {
    // Clear the trigPin by setting it LOW:
    digitalWrite(trigPin, LOW);
    delayMicroseconds(5);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Read the echoPin, pulseIn() returns the duration (length of the pulse) in
    microseconds:
    duration = pulseIn(echoPin, HIGH);
    // Calculate the distance:
    distance = duration * 0.034 / 2;
    // Print the distance on the Serial Monitor (Ctrl+Shift+M):
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(50);
    }

    // Include the servo library:
    #include <Servo.h>
    // Create a new servo object:
    Servo myservo;
    // Define the servo pin:
    #define servoPin 9
    // Create a variable to store the servo position:
    int angle = 0;
    voidsetup() {
    // Attach the Servo variable to a pin:
    myservo.attach(servoPin);
    }
      void loop(){
      myservo.write(90);
      delay(1000);
      myservo.write(180);
      delay(1000);
      myservo.write(0);
      delay(1000);
      // Sweep from 0 to 180 degrees:
      for (angle = 0; angle <= 180; angle += 1) {
      myservo.write(angle);
      delay(0);
      }
      for (angle = 180; angle <= 0; angle -= 1) {
        myservo.write(angle);
        delay(0);

      }
      delay(1000);
     }

title: can anyone help me debug this code my delay microseconds is not working and my servo write for 180 as well

Answers: 1

body:
Your code has two "loop" functions in it. You cannot have two functions of the same name (and with the same argument list, in your case with no arguments) in the one compilation unit (piece of code).

It looks very much like you have combined two pieces of code you found into one and then tried to compile that. You can't do that. Choose one or the other. In the second "half" you incorrectly have "voidsetup" which should be "void setup".

Next time you post a question, and if the question is about an error message, please **copy and paste the error message**. We aren't mind readers. You can see what is on your screen, we can't.

See: [How do I ask a good question about the Arduino?](https://arduino.meta.stackexchange.com/questions/2523/how-to-ask-a-good-question-for-arduino-stack-exchange)


body:
I am trying to connect MFRC522 using nodeMCU and send a simple code to scan the tags but the IDE brings the following error:
```
Multiple libraries were found for "MFRC522.h"
 Used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/rfid-master
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522-spi-i2c-uart-async
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
```
What do I do to rectify this error?

Answers: 0


body:
For the last days, I am trying to establish serial communication between nodemcu and Arduino Uno but I failed to do this. Currently, I am working on a Home Automation project. I receive data from nodemcu and send it to Arduino Uno, but some dummy data also receive with original data. Please help.

Nodemcu code:

    #include <ESP8266WiFi.h>
    #include "Adafruit_MQTT.h"
    #include "Adafruit_MQTT_Client.h"

    #define Automated   D0
    #define Led         D1
    #define Fan         D2

    #define WLAN_SSID       "JioFi2_1EAFF8"
    #define WLAN_PASS       "Ode9c@,1S1ja$1xANkeL"

    #define AIO_SERVER      "io.adafruit.com"
    #define AIO_SERVERPORT  1883
    #define AIO_USERNAME    "_inishu"
    #define AIO_KEY        "aio_HZUG00TupkcsC2dvraQM7HLHrCd4"

    WiFiClient client;
    Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

    Adafruit_MQTT_Subscribe speed = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Fan");
    Adafruit_MQTT_Subscribe inten = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Led");
    Adafruit_MQTT_Subscribe autom = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Automate");

    void MQTT_connect();
    void datatransfer(int);

    int on_off;
    int sliderval1;
    int sliderval2;
    void setup(){
        Serial.begin(9600);
        pinMode(Automated, OUTPUT);
        pinMode(Led, OUTPUT);
        pinMode(Fan, OUTPUT);

        WiFi.begin(WLAN_SSID, WLAN_PASS);
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
        }

        mqtt.subscribe(&autom);
        mqtt.subscribe(&speed);
        mqtt.subscribe(&inten);
    }

    void loop (){
        MQTT_connect();

        Adafruit_MQTT_Subscribe *subscription;
        while ((subscription = mqtt.readSubscription(5000))){
            if (subscription == &autom){
                on_off = atoi((char *)autom.lastread);
                if (on_off == 1)   digitalWrite(Automated,HIGH);
                if (on_off == 0)   digitalWrite(Automated,LOW);
            }

            if (subscription == &speed){
                sliderval1 = atoi((char *)speed.lastread);
                analogWrite(Fan, sliderval1);
            }

            if (subscription == &inten){
                sliderval2 = atoi((char *)inten.lastread);
                analogWrite(Led, sliderval2);
            }
        }
        datatransfer(on_off);
        datatransfer(sliderval1);
        datatransfer(sliderval2);
    }

    void MQTT_connect() {
        if (mqtt.connected()) {
             return;
        }

        while (mqtt.connect() != 0) {
            mqtt.disconnect();
            delay(2000);
        }
    }

    void datatransfer(int value){
        Serial.println(value);
        delay(500);
    }

Arduino Uno code:

    int x = A0, y = A1, z = 1;
    int fan = 11, led = 10;
    float temp, lux;
    int autom = 1;
    int inten = 0;
    int speed = 0;
    int fanspeed, light;

    int datareceive(){
        int receiver = 0;
        while(Serial.available()==0 );
        String s = Serial.readStringUntil('\r');
        receiver = s.toInt();
        Serial.println(receiver);
        delay(1000);
        return receiver;
    }

    void setup(){
        Serial.begin(9600);
        pinMode(fan,OUTPUT);
        pinMode(led,OUTPUT);
        pinMode(x,INPUT);
        pinMode(y,INPUT);
        pinMode(z,INPUT);
    }

    void loop(){
        autom = datareceive();
        speed = datareceive();
        inten = datareceive();
        if(autom == 1){
            fanspeed = 255 - speed;
            light = 255 - inten;
            analogWrite(fan,fanspeed);
            analogWrite(led,light);
        }
        else {
            temp = analogRead(x);
            if (temp >= 52 && temp <= 104){
                int fanspeed = -4.90384615*temp + 510;
                analogWrite(fan, fanspeed);
            }
            else if(temp > 104)  digitalWrite(fan,LOW);
            else digitalWrite(fan,HIGH);
            lux = analogRead(y);
            if (lux >= 430 && lux <= 594){
                int light = 1.342657*lux-577.342657;
                analogWrite(led,light);
            }
            else if (lux < 430) digitalWrite(led, LOW);
            else digitalWrite(led,HIGH);
        }
    }

title: Serial communication between nodemcu and Arduino Uno

Answers: 1

body: Arduino UNO is 5v logic and esp8266 is 3.3v logic.  You need a level shifter for them to be able to have bidirectional serial link. Alternatively you can just use a voltage divider between Arduino Tx and ESP Rx pin to protect the rx pin of the esp.


body:
For one of my projects, I would like to transfer a camera image with the best possible resolution and as many FPS as possible with the ESP32Cam.
For this I successfully used the code from
[https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/][1]

A grayscale image would be enough for further processing, if it allows a higher speed.

Problem is, if I set the format to PIXFORMAT_GRAYSCALE, the ESP only outputs "Camera capture failed".

Are there any other settings to do?

  [1]: https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/

title: Capture GRAYSCALE image with ESP32 Cam

Answers: 2

body: I just tried this with my ESP32Cam with no problems.  I would check that you are supplying enough power; I've definitely seen the 'Camera capture failed' when I had power issues.  Also, I would try a more recent tutorial on the ESP32Cam; the latest Expressif ESP32 Arduino libraries have AI Thinker ESP32Cam as a device choice.  I would try the `CameraWebServer` example in the ESP32 library and see if you still have the problem.

body:
I guess that 1 year later you shouldn't work on this anymore, but for every one that need the grayscale too, here my solution.

For reference I've found [here][1] that we can set  : s->set_special_effect(s, 2);
Where 2 is grayscale effect.

0 - No Effect
1 - Negative
2 - Grayscale
3 - Red Tint
4 - Green Tint
5 - Blue Tint
6 - Sepia

      // Camera init
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        return;
      }

      sensor_t * s = esp_camera_sensor_get();
      s->set_special_effect(s, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)

  [1]: https://randomnerdtutorials.com/esp32-cam-ov2640-camera-settings/


body:
I just found the alpha version of Arduino Pro IDE and I was wondering why this project is not open source as the classic IDE.

I didn't found anything about that online.

title: Why Arduino Pro IDE is not open source?

Answers: 0


body:
I want to calculate THD. SO how do I isolate the fundamental frequency from a signal with harmonics?
I have a signal V which is a sum of V1, V2 and V3. V1=A1*sin(w1*t+phi1), V2=A2*sin(w2*t+phi2) and V3=A3*sin(w3*t+phi3). I want to find out the magnitude/amplitude of a known frequency w1 in the signal. How do I proceed? Should I use the FFT library? If yes then how?

title: How to separate a specific frequency signal from a summation of a few signals?

Answers: 1

body:
What exactly are you trying to do?  If you want to measure THD from an external signal, an Arduino is probably not the best choice.  It only has 10-bit ADCs and they are DC-coupled. You can build a simple circuit (<https://www.daqarta.com/dw_rrll.htm>) to shift an AC-coupled input to DC for the Arduino, but you will still have only 10-bit resolution.  I haven't looked deep enough into the library that chrisl mentions to see how big an FFT it can perform in the limited RAM of an Arduino, but I suspect the spectral resolution would be so poor as to be unhelpful for real-world THD measurements.

The way you describe the signal makes me think that this is an academic exercise, not a real-world problem.  If so, you don't need an Arduino or any other hardware, just run the FFT on your main computer.   If you *do* need to make real-world measurements, an ordinary sound card on your computer is a better way to go.  See <https://www.daqarta.com/dw_0d0t.htm> for an example.  The sound card approach has the added advantage that it can generate a low-distortion test signal to drive the device whose distortion you are trying to measure.  That allows a "trick" (called "Spectral Line Lock" in the example) to get even better resolution, by making the test signal synchronous with the sample rate so you don't need window functions.

If you really want to measure THD with an Arduino, consider an approach used in what used to be called a "wave analyzer".  The block diagram is shown here:
<https://www.daqarta.com/dw_0h0p.htm>.  This is essentially a one-spectral-line analyzer, which actually can be more selective than an FFT.  You basically multiply the input signal by the sine and cosine of the reference frequency (the fundamental) and then rectify and filter the results, and combine RMS-wise.  That gives you the fundamental value (or any individual harmonic you tune the reference to), so to get THD you divide by the RMS of the overall input signal.


body:
    #define trigPin 10
    #define echoPin 9
    #define buzzer 12
    long duration;
    int distance;

    void setup() {
    pinMode(trigPin,OUTPUT);
    pinMode(echoPin,INPUT);
    Serial.begin(9600);
    pinMode(buzzer,OUTPUT);
    }

     void loop() {
     digitalWrite(trigPin,LOW);
     delayMicroseconds(2);
     digitalWrite(trigPin,HIGH);
     delayMicroseconds(10);
     digitalWrite(trigPin,LOW);
     duration=pulseIn(echoPin,HIGH);
     distance=duration*0.034/2;
     Serial.print("DISTANCE=");
     Serial.println(distance);
     if (distance<=15){
     tone(buzzer,450);
     delay (500);
     noTone(buzzer);
     }
     else{
     noTone(buzzer);
     }
     }

this is the error code

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

    sketch_nov27a:9:15: error: stray '\342' in program

     void setup() {

                   ^

    sketch_nov27a:9:16: error: stray '\200' in program

     void setup() {

                    ^

    sketch_nov27a:9:17: error: stray '\213' in program

     void setup() {

                     ^

    sketch_nov27a:9:18: error: stray '\342' in program

     void setup() {

                      ^

    sketch_nov27a:9:19: error: stray '\200' in program

     void setup() {

                       ^

    sketch_nov27a:9:20: error: stray '\213' in program

     void setup() {

                        ^

    sketch_nov27a:14:2: error: stray '\342' in program

     }

      ^

    sketch_nov27a:14:3: error: stray '\200' in program

     }

       ^

    sketch_nov27a:14:4: error: stray '\213' in program

     }

        ^

    sketch_nov27a:14:5: error: stray '\342' in program

     }

         ^

    sketch_nov27a:14:6: error: stray '\200' in program

     }

          ^

    sketch_nov27a:14:7: error: stray '\213' in program

     }

           ^

    sketch_nov27a:18:14: error: stray '\342' in program

     void loop() {

                  ^

    sketch_nov27a:18:15: error: stray '\200' in program

     void loop() {

                   ^

    sketch_nov27a:18:16: error: stray '\213' in program

     void loop() {

                    ^

    sketch_nov27a:18:17: error: stray '\342' in program

     void loop() {

                     ^

    sketch_nov27a:18:18: error: stray '\200' in program

     void loop() {

                      ^

    sketch_nov27a:18:19: error: stray '\213' in program

     void loop() {

                       ^

    sketch_nov27a:28:19: error: stray '\342' in program

     if (distance<=15){

                       ^

    sketch_nov27a:28:20: error: stray '\200' in program

     if (distance<=15){

                        ^

    sketch_nov27a:28:21: error: stray '\213' in program

     if (distance<=15){

                         ^

    sketch_nov27a:28:22: error: stray '\342' in program

     if (distance<=15){

                          ^

    sketch_nov27a:28:23: error: stray '\200' in program

     if (distance<=15){

                           ^

    sketch_nov27a:28:24: error: stray '\213' in program

     if (distance<=15){

                            ^

    sketch_nov27a:32:2: error: stray '\342' in program

     }

      ^

    sketch_nov27a:32:3: error: stray '\200' in program

     }

       ^

    sketch_nov27a:32:4: error: stray '\213' in program

     }

        ^

    sketch_nov27a:32:5: error: stray '\342' in program

     }

         ^

    sketch_nov27a:32:6: error: stray '\200' in program

     }

          ^

    sketch_nov27a:32:7: error: stray '\213' in program

     }

           ^

    sketch_nov27a:33:6: error: stray '\342' in program

     else{

          ^

    sketch_nov27a:33:7: error: stray '\200' in program

     else{

           ^

    sketch_nov27a:33:8: error: stray '\213' in program

     else{

            ^

    sketch_nov27a:33:9: error: stray '\342' in program

     else{

             ^

    sketch_nov27a:33:10: error: stray '\200' in program

     else{

              ^

    sketch_nov27a:33:11: error: stray '\213' in program

     else{

               ^

    sketch_nov27a:36:1: error: stray '\342' in program

     }

     ^

    sketch_nov27a:36:2: error: stray '\200' in program

     }

      ^

    sketch_nov27a:36:3: error: stray '\213' in program

     }

       ^

    sketch_nov27a:36:4: error: stray '\342' in program

     }

        ^

    sketch_nov27a:36:5: error: stray '\200' in program

     }

         ^

    sketch_nov27a:36:6: error: stray '\213' in program

     }

          ^

    sketch_nov27a:36:8: error: stray '\342' in program

     }

            ^

    sketch_nov27a:36:9: error: stray '\200' in program

     }

             ^

    sketch_nov27a:36:10: error: stray '\213' in program

     }

              ^

    sketch_nov27a:36:11: error: stray '\342' in program

     }

               ^

    sketch_nov27a:36:12: error: stray '\200' in program

     }

                ^

    sketch_nov27a:36:13: error: stray '\213' in program

     }

                 ^

    exit status 1

    stray '\342' in program

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

title: trying to do a security motion sensor using the peizer and hc-sr04 but i am not able to find the errors the error code is all the way down

Answers: 1

body:
Nice error there. I copied your code into my Arduino IDE and also got many errors with "stray X in program".

Then I looked at the file in the text editor vim and made all non-printable characters visible (that are characters, that cannot be seen, like control characters). Here is the result (as image, so that you can see the unprintable characters)

[![Code listing in vim text editor][1]][1]

As you see, you have some extra characters marked as `<200b>`. Google gives me the description for it as

> zero width space

so a space character, that has zero width and is thus not visible.

The compiler doesn't know, how to interpret these characters. I removed them and the compilation succeeded. Here again your code as text without the unprintable characters (and autoformatted to make it easier to read):

    #define trigPin 10
    #define echoPin 9
    #define buzzer 12
    long duration;
    int distance;

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      Serial.begin(9600);
      pinMode(buzzer, OUTPUT);
    }

    void loop() {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = duration * 0.034 / 2;
      Serial.print("DISTANCE=");
      Serial.println(distance);
      if (distance <= 15) {
        tone(buzzer, 450);
        delay (500);
        noTone(buzzer);
      }
      else {
        noTone(buzzer);
      }
    }

How these unprintable characters got into your code can only be guessed. Maybe you have copied parts of it from some website, which had these extra characters in it. Maybe you inserted them with some kind of text editor by accident.

---

For reference: The used FAQ section of vim with the commands to display non-printable characters [here][2]:

> 11.5. How do I highlight all the non-printable characters in a file?
>
>You can use the following commands and search pattern to highlight all the
>non-printable characters in a file:
>
>    :set hlsearch
>    /\(\p\|$\)\@!.
>
>For more information, read
>
>    :help /\p
>
>    :help /bar
>
>    :help /$
>
>    :help /\(
>
>    :help /\@!
>
>    :help 'hlsearch'

  [1]: https://i.stack.imgur.com/eTkj4.png
  [2]: http://vimdoc.sourceforge.net/htmldoc/vimfaq.html#11.5


body:
Good afternoon!
I create a human movement alarm.
I am signaling atmega328. I receive a signal from the sensor and if there is a signal, then using the "tone" I generate a sound.
[![enter image description here][1]][1]
I am using a motion sensor. I want that if one movement was noticed for a short time, then turn on a short melody, and if the movement continues longer than a certain time, then play a long melody.

I wrote the code to play a short melody. How can you track that the input from the sensor is at a high logical level for a long time and play a long melody in this case?

    unsigned long timing; // Variable to store the starting point
    int T = 15; // Signal playback time!
    int S0 = PIND0; // With Doppler Probe

    int S1 = PIND1; // Food
    int S2 = PIND2; // Audio

    void setup ()
    {

      // Port control via registers:
      DDRD = B00000110; // Set the output pin (the first and second pins of register D as output pins, the rest (0.3-7) are set as input pins)
      // 76543210
      pinMode (PIND0, INPUT);
      pinMode (PIND1, OUTPUT); // Power for the audio amplifier
      pinMode (PIND2, OUTPUT); // Audio
    }
    void loop ()
    {
      if (digitalRead (PIND0))
      {
        sendSignal ();
      }

      if (digitalRead (PIND0) == 0)
      {
        digitalWrite (PIND1, LOW); // Food
        digitalWrite (PIND2, LOW); // Sound
      }
    }

    void sendSignal ()
    {
      digitalWrite (PIND1, HIGH); // Food
      for (int n = 0; n <4; n ++)
      {
        for (int i = 4800; i <5800; i ++)
        {
          tone (PIND2, i, 10); // tone (port, frequency in Hz, duration in ms) 600 - 6 sec.
        }
      }
    }

And yes, if my code can be optimized, tell me how!

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

title: Recognition of the signal duration from the sensor

Answers: 1

body:
I don't see where you are even attempting to detect the long condition in your code.

First of all you need determine what constitutes a long vs. a short detection.  My recommendation is to write your code to do the following:

 1. Initial detection.
 2. Wait for your "short" interval.  If the detection is gone, then you know it was a "short" one and you can play your short music.
 3. If the detection is still there, wait for the remainder of the time for your "long" detection.
 4. If the detection is gone you know it was a "short" one since it didn't make it to the "long" state.  So play your "short" song.
 5. Play your "long" music since the detection lasted for the duration of the long interval.

I'll leave the actual coding of that to you.  I'll also add that doing it this way, that is using the built-in delay() function is probably not the best approach overall.  The issue is that delay() blocks your loop() function and prevents you from doing anything else while it's delaying.

A better approach is to implement this as a state-machine coupled with an timer-driven interrupt.  That will give you much better control over your detections and also allow you do handle other inputs or set other outputs while you are waiting for detections to occur.

There are many resources online that discuss how to configure and handle AVR timers and their interrupts and there are also many resources discussing state machines and programming them in C.


body:
I am trying to program an Arduino Nano (with an ATmega328P) from an ESP32 that is attached to its UART and the reset pin. I have to do this via the ESP, because the Arduino is supposed to run on its own, detached from a PC (where I could use an existing programmer for it). But its program should be changable, hence, it is attached to the ESP, which is accessible from a web server via Wifi, so that the Arduino can be reprogrammed on request. I almost got the whole setup figured out: The server is running, files can be sent to the ESP, and the ESP can talk with the Arduino Bootloader. The only problem is that I cannot get the Arduino to execute new programs.

The whole procedure goes like this: The server communicates with the ESP, sends the HEX file of the Arduino sketch (which is successfully verified by a checksum, so this part is working properly). Then, the ESP pulls the reset pin of the Arduino and waits for a while before it attempts to talk to its bootloader. Then, it basically does the same sequence of STK500 commands as avrdude.

I really just copied the commands from the avrdude log after executing

    avrdude -c arduino -vvvvv -p m328p -b 57600 -P /dev/ttyUSB0 -U flash:w:sketch.hex:i

and skipping query commands like which firmware version it uses etc. So, basically: enter programming mode, erase chip, re-enter programming mode, write the hex file to flash, starting from address 0, moving in steps of 128 bytes (using 1's to pad the last message to the full size of 128 bytes). Then afterwards reading back the file from the Arduino and veryfing that all bytes match (which they do!) and leaving the programming mode (which is the very last thing that happens in the avrdude log). Afterwards, I trigger the reset. I am using exactly the same type of file which I gave to avrdude, and all the responses of the Arduino bootloader exactly match the values from the avrdude log.

But whereas the Arduino just starts executing the sketch after this procedure when using avrdude, in my own implementation it just blinks its LED in a regular interval (when the test sketch should make it blink short, long, short, long etc.). I don't get what's going wrong here. I thought that the blinking might represent an error code, but I couldn't find any documentation about that. I feel like I've searched the whole Internet (including arduino stackexchange), and I even looked at the avrdude source code to check if there's something else done after the last STK500 command, that is not listed in its log. I feel (hope) that I'm very close to having it work and this whole thing just needs like a one-line fix, but I don't know what else to try anymore and would greatly appreciate a second opinion from someone more experienced.

title: How to program Arduino manually via STK500?

Answers: 1

body:
Okay, by comparing the data packets my implementation sends with those from the avrdude log for the same sketch, I finally found the cause of trouble. I was sending the hex file byte-by-byte exactly as it is read from storage. But of course, the metadata needs to be skipped (i.e. the addresses at the beginning of each line, the magic bytes at the end of each line, and the newline). I added this simple fix, and now it works fine.

EDIT: Here is the preprocessing code from my Python3 script:

    import codecs

    program = b''
    for line in open('sketch.hex', 'rb'):
        program += codecs.decode(line[9:-4], 'hex')


body:
    #include <AFMotor.h>
    #include <NewPing.h>
    #include <Servo.h>

    #define TRIG_PIN A0
    #define ECHO_PIN A1
    #define MAX_DISTANCE 200
    #define MAX_SPEED 190
    #define MAX_SPEED_OFFSET 20

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor2(2, MOTOR12_1KHZ);
    AF_DCMotor motor3(3, MOTOR34_1KHZ);
    AF_DCMotor motor4(4, MOTOR34_1KHZ);
    Servo myservo;

    boolean goesForward=false;
    int distance = 100;
    int speedSet = 0;

    void setup() {

    myservo.attach(10);
    myservo.write(115);
    delay(2000);
    distance = readPing();
    delay(100);
    distance = readPing();
    delay(100);
    distance = readPing();
    delay(100);
    distance = readPing();
    delay(100);
    }

    void loop() {
    int distanceR = 0;
    int distanceL = 0;
    delay(40);

    if(distance<=15)
    {
    moveStop();
    delay(100);
    moveBackward();
    delay(300);
    moveStop();
    delay(200);
    distanceR = lookRight();
    delay(200);
    distanceL = lookLeft();
    delay(200);

    if(distanceR>=distanceL)
    {
    turnRight();
    moveStop();
    }else
    {
    turnLeft();
    moveStop();
    }
    }else
    {
    moveForward();
    }
    distance = readPing();
    }

    int lookRight()
    {
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    }

    int lookLeft()
    {
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
    }

    int readPing() {
    delay(70);
    int cm = sonar.ping_cm();
    if(cm==0)
    {
    cm = 250;
    }
    return cm;
    }

    void moveStop() {
    motor1.run(RELEASE);
    motor2.run(RELEASE);
    motor3.run(RELEASE);
    motor4.run(RELEASE);
    }

    void moveForward() {

    if(!goesForward)
    {
    goesForward=true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
    {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
    }
    }
    }

    void moveBackward() {
    goesForward=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
    {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
    }
    }

    void turnRight() {
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    delay(500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    }

    void turnLeft() {
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    delay(500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    }

These are the error messages:

```#

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

sketch_nov27b:44:15: error: stray '\342' in program

 void setup() {

               ^

sketch_nov27b:44:16: error: stray '\200' in program

 void setup() {

                ^

sketch_nov27b:44:17: error: stray '\213' in program

 void setup() {

                 ^

sketch_nov27b:44:18: error: stray '\342' in program

 void setup() {

                  ^

sketch_nov27b:44:19: error: stray '\200' in program

 void setup() {

                   ^

sketch_nov27b:44:20: error: stray '\213' in program

 void setup() {

[ trimmed ]
                       ^

sketch_nov27b:199:24: error: stray '\342' in program

 void turnLeft() {

                        ^

sketch_nov27b:199:25: error: stray '\200' in program

 void turnLeft() {

                         ^

sketch_nov27b:199:26: error: stray '\213' in program

 void turnLeft() {

                          ^

sketch_nov27b:199:27: error: stray '\342' in program

 void turnLeft() {

                           ^

sketch_nov27b:199:28: error: stray '\200' in program

 void turnLeft() {

                            ^

sketch_nov27b:199:29: error: stray '\213' in program

 void turnLeft() {

                             ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

stray '\342' in program

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

```

title: I tried to make a obstacle avoiding car (OAB), but my code seems to have a lot of errors

Answers: 1

body:
You copied and pasted the code from a website that presents the code using typography, not code blocks.

You have lots of typographical special characters in your code from pasting it.

Instead of copying and pasting code you should read and understand code then *write your own*.


body:
So I started typing out this question, but in the process of taking screenshots and looking up sources for the question I figured out the answer :P

That said, this problem has been a snag for me for a while and I've asked multiple people about it with no solution. Because it seemed kind of daunting for me and I haven't seen many well explained reasons I figured I'd finish out the post here to help anyone that is running into this or will run into it in the future.

---
# The snag

I'm using vscode for my editor and I've had this snag for a while but it's finally driving me nuts enough to ask for help.

When in include certain libraries I get error squiggles under the include.

[![squiggle][1]][1]

In this case the squiggle is popping up because of the error:

> cannot open source file "WProgram.h" (dependency of "Adafruit_MPR121.h")C/C++(1696)

[![WProgram.h error][2]][2]

At first I though the snag was because my include path needed my arduino libraries directory so I added that for the project, but I still get the snag.

[![updating the include path][3]][3]

I did a computer wide search for the `WProgram.h` file but was not able to find it.

[![Unable to find header file][4]][4]

The thing is, all of my sketches still compile and upload fine so for the most part I'm just able to ignore it ... _but the squiggle!!!!!!_.

Any ideas of how I can resolve this?

  [1]: https://i.stack.imgur.com/N55Pj.png
  [2]: https://i.stack.imgur.com/fkb2p.png
  [3]: https://i.stack.imgur.com/PbI2e.png
  [4]: https://i.stack.imgur.com/UBd1l.png

title: cannot open source file "WProgram.h" in VSCode

Answers: 3

body:
# The answer

Like I said in the question, I found the answer after doing some searching while typing up the question itself and I want to explain it for future squiggle-haters :)

## WProgram.h vs Arduino.h

I did a bunch of searching to try to track down what's going on and I eventually found [this helpful (and depending on the veracity of the source, kind of sad) bit of history](https://forum.arduino.cc/index.php?topic=128597.0#msg967351):

> There is history of the arduino project not everyone was aware of or supposed to know. I only this much: this all started with some graduate student(s) that created the wiring platform and IDE, called wiring board and wiring "programming language". This project is still active with active users like the arduino project. Then the arduino folks decide to create the arduino project based on wiring project so they took the wiring IDE (which took from the original Processing IDE), including all the libraries etc. and created the first Arduino board (slightly different than wiring board, cheaper!) called it arduino. Arduino project has not very positively acknowledged the wiring project as the source of their project and wiring folks didn't take it very well.
>
> Now, that WProgram.h, is a definition file created by and for the wiring project and board. That's why it has a W on it. It has been in Arduino IDE since its beginning and was replaced by Arduino.h only recently when Arduino 1.0 was released. Now all Arduino 1.0+ IDE will use Arduino.h and not WProgram.h so if you have that plus some other old stuff, you will have to make changes to work with Arduino 1.0+ IDE.

## The temp fix

With that in mind I dove into the source file for the `Adafruit_MPR121.h` library and found where it includes the `WProgram.h` header file and commented it out.

[![adjusting the source code][1]][1]

It's also worth pointing out that the pre-compiler conditional here supports the renaming of the file in newer versions of Arduino.

[![pre-compiler conditional][2]][2]

I labeled this section of the answer as "The temp fix" because it involves modifying a 3rd party dependency which is normally not a great idea. Yeah it fixes it now, but as soon as I need to update this library that edit is going to get blown away and I'd need to manually do it again. In this case the update is pretty minimal so maybe that's no big deal, but if the fix was more involved, like a heavy edit, that would be a real big pain in the butt and could cause other unforeseen consequences (and I played half-life as a kid so I know that's not good).

# The better fix

Normally I would say the better fix for this would be to clone the source repository, make the fix there, and do a pull request so the dependency itself gets updated at the source (if someone approves and merges the PR).

But this is a bit different, the conditional in there is actually fine as it adds backwards compatibility. It's there so that the library can support both pre-1.0 and post-1.0 arduino IDE versions. If we did a PR to cut out the `WProgram.h` reference we'd add in breaking code for anyone on the older versions.

So, the better solution is to appease my local compiler.

We know that the `Arduino.h` header for all intents and purposes is the same as the `WProgram.h`, so a almost-full-proof solution would be to fake out the `WProgram.h` file on my computer to appease the compiler.

[![Faking WProgram.h][3]][3]

An important part to note here is that to make sure I faked it out correctly I went to the arduino repository, scrolled back through the tags, found the last tag before they switched to 1.0+, and found the WProgram.h file. Once there I grabbed the same pre-compiler check and definition for the WProgram header so I could be sure I did the correct `define` for the WProgram name.

[![Correct WProgram define string][4]][4]

This feels like a bit of overkill because it protects me from other headers being included with the same string defined, but if that happened it would be because I _have_ the WProgram file anyway, but I figured if I was going to fake it out I'd do it right.

This could backfire if I include a library that _only_ includes `WProgram.h` and *not* the `Arduino.h` in that arduino version check conditional, but this would 100% be the case for a correction and pull request for that library.

# Summary

So now I know that the `Arduino.h` file is the reason I'm able to compile everything correctly even with the red squiggle, I have a faked out `WProgram.h` so that my compiler can find something when looking for the file and, _most importantly_, I no longer need to look at those red squiggles under the includes :)

[![no squiggles!][5]][5]

Next step, figure out the same thing for `Sam.h` :P

  [1]: https://i.stack.imgur.com/UbGwH.gif
  [2]: https://i.stack.imgur.com/CDN9J.png
  [3]: https://i.stack.imgur.com/qehQC.jpg
  [4]: https://i.stack.imgur.com/iKkQR.png
  [5]: https://i.stack.imgur.com/FipL6.jpg

body:
I landed here in the same position as you, and after researching the comments mentioning `-DARDUINO=10813` and some more googling I found: https://github.com/microsoft/vscode-arduino/issues/1148

This led me to adding one more line to `defines` in my `c_cpp_properties.json`

and this also removed the squiggly!

```
{
    "configurations": [
        {

            ...

            "defines": [
                "USBCON",
                "ARDUINO=10813"
            ],

            ...

        }
    ],

}```

body:
I recently figured out, it's way too simple.
Just tap F1 and look for this then select the configuration for "Arduino".
[![enter image description here][1]][1]

(Pardon my Grammer)

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