body:
I have an esp8266 and I cannot get the value to read HIGH when 3.3v is applied to directly to pin by hand. I have an Arduino Uno powering the esp8266. It connects to the WiFi like it should, and now all I want is to manually see that when I apply 3v that the state will change from 0 to 1. Does anyone know how I can do this.

When I apply 3 volts directly to pin 15 it outputs 0. Even if I try digitalWrite on the pin and set it to HIGH it still says 0 and i serialPrint. My end goal if to use the arduino uno to fire and ouput on pin 8. On the arduino UNO side I am using a super sonic sensor. When the sensor is triggered I want to turn pin 8 on. From there I want to take pin 8 to feed pin 15 on the 8266 as an input. Before I did that I just wanted to see that when you manually apply 3v that the pin would read 1 or HIGH but no matter I do it wont change value. Once I get that value as HIGH I can send  a second request to the server like im already but now I want to say  that there was an intruder. Im not sure why the value wont change but being a beginner with arduino Im trying to keep it simple and ideally would like to wire it in this manner.

    #include <SoftwareSerial.h>
    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

    const char* ssid = "********";
    const char* password = "********";

    HTTPClient http;

    static const uint8_t D8 = 15;
    int featherPin = D8;

    //int trigPin = 13;
    //int echoPin = 12;
    //int ledPin = 10;
    //int hornPin = 11;
    //
    //int spaceIntruded;
    //
    //long duration, cm, inches;

    void setup() {
      Serial.begin(115200);
      pinMode(featherPin,INPUT);

      WiFi.begin(ssid, password);

      while(WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Waiting for connection");
     }

    //  Serial.begin (9600);
    //  pinMode(trigPin, OUTPUT);
    //  pinMode(echoPin, INPUT);
    //  pinMode(ledPin, OUTPUT);
    //  pinMode(hornPin, OUTPUT);
    //  delay(5000);
    //  Serial.println("Armed...");

    }

    void loop() {

      if (WiFi.status() == WL_CONNECTED) {
        Serial.println("yay connect");

        http.begin("http://10.150.40.121:3000/");
        http.addHeader("Content-Type", "text/plain");

        int httpCode = http.POST("Message from ESP8266");
        String payload = http.getString();
        Serial.println(payload);
        http.end();

        } else {
          Serial.println("Error in Wifi connection");
        }
    //    digitalWrite(featherPin, HIGH);
        int sensorValue = digitalRead(featherPin);
        Serial.print(sensorValue);

    //    if (digitalRead(featherPin) == HIGH) {
    //      http.begin("http://10.150.40.121:3000/home");
    //      http.addHeader("Content-Type", "text/plain");
    //
    //      int httpCode = http.POST("Message from ESP8266");
    //      String payload = http.getString();
    //      Serial.println(payload);
    //      Serial.print("hi");
    //      http.end();
    //      } else {
    //        Serial.print(featherPin);
    //        Serial.println("I am not hot");
    //      }

    //  digitalWrite(trigPin, LOW);
    //  delayMicroseconds(1);
    //  digitalWrite(trigPin, HIGH);
    //  delayMicroseconds(2);
    //  digitalWrite(trigPin, LOW);
    //
    //  pinMode(echoPin, INPUT);
    //  duration = pulseIn(echoPin, HIGH);
    //
    //  inches = (duration / 2) / 74;
    //  Serial.println(inches);
    //
    //  spaceIntruded = inches;
    //
    //  if (spaceIntruded <= 50 || spaceIntruded >= 900){
    //      digitalWrite(ledPin, HIGH);
    //      digitalWrite(hornPin, HIGH);
    //      Serial.println("Intruder Detected!");
    //      Serial.println("Sending text Notification...");
    //      delay(500);
    //      Serial.println("Armed...");
    //  }
    //
    //  else{
    //    digitalWrite(hornPin, LOW);
    //    digitalWrite(ledPin, LOW);
    //  }
        delay(30000);

    }

title: Cannot get pins on esp 8266 adafruit wifi module to read HIGH on pin 15

Answers: 1

body:
Pin 15 is one of the boot configuration pins (0, 2, 15) and must be LOW at boot. To ensure it, dev boards with esp8266 have external pull-down on pin 15 (and pull-up on 0 and 2). To read the pin HIGH you must overcome the pull-down.

Adafruit Feather HUZZAH has 4.7kOhm resistor for the pull-down, so it is a 'strong' pull down. NodeMcu has 12kOhm resistor on io 15.

From schematics of Adafruit Feather HUZZAH

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

Note: setting pin as OUTPUT and HIGH doesn't make it read HIGH in code. Only INPUT pin state can be read with digitalRead (only on some MCUs digitalRead reads the same register set by digitalWrite).

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


body:
I just can't wrap my head around on how to properly work with multiple files. My code has been getting quite big so I decided to split all the classes into one file each. So I'm left with 6 files:

    dataHandler.cpp
    fileHandler.cpp
    header.cpp
    main.cpp
    request.cpp
    sensorData.cpp

*header.cpp includes all the header files, and main.cpp the setup() and loop() functions.*

Visual Studio Code shows me no errors while compiling. The includeguards have the name convention: CLASSNAME_INCG

So in my main.cpp for example I have something like:

    #ifndef HEADER_INCG
    #include "header.cpp"
    #define HEADER_INCG
    #endif

    #ifndef SENSORDATA_INCG
        #include "SensorData.cpp"
        #define SENSORDATA_INCG
    #endif

    #ifndef DATAHANDLER_INCG
        #include "DataHandler.cpp"
        #define DATAHANDLER_INCG
    #endif

    setup()
    {
        ...
    }

    ...

When going into a class-file I have it defined in the following way (fileHandler.cpp):

    #ifndef HEADER_INCG
    #include "header.cpp"
    #define HEADER_INCG
    #endif

    #ifndef FILEHANDLER_INCG
    #define FILEHANDLER_INCG

    class FileHandler{
        ...
    }

    #endif

**So in summary** I include the headerfile into every file, with includeguards arround. If I wouldn't include it I would get errors that crucial libaries like Serial etc. are missing. But when including the header into every file compiliing works just fine, but when it comes to linking the files togehter I get an error of multiple definitions.

*So how can I define the headerfile just once for all files albeit I need it in every file?*

title: Multiple definition error when linking firmware.elf

Answers: 1

body:
1. Rule #1:

Header file extension is ".h". Files with ".cpp" are ususally compiled as separate compilation units into the object file. If you have any function definition (= declaration + implementation) or any global variable in more object files, it'll fail to link.

 2. Rule #2:

No definitions in headers - variables and functions will cause this error if you include .h file into more .cpp files. If you need super global variable, you have to use declaration with extern modifier and you have to define it in one of the .cpp files. But only one! Also there can be only function prototypes (declarations) in header file. Implementation have to be only once in one of the ".cpp" files.

It's usually in the first chapter of books about learning C/C++.

Really short example:

    // myLib.h
    #ifndef _myLib_h_guard_
    #define _myLib_h_guard_

    void myFunction(); // function prototype (declaration)

    extern int mySuperGlobalVariable;  // variable declared as extern, there must be definition somewhere

    class MyClass {
    public:
      int someMethod(); // method declaration

      int anotherMethod() { return 1; }  // definition inside of class works, but sometimes is less readable
    };

    #endif

    // myLib.cpp
    #include "myLib.h"

    void myFunction() { // function implementation (definition)
      // do something...
    }

    int mySuperGlobalVariable; // definition

    int MyClass::someMethod() { return 2; } // method definition

    // main.cpp
    #include <myLib.h>

    int main() {

      mySuperGlobalVariable = 10;

      myFunction();

      MyClass instance;
      int first = instance.someMethod();
      int second = instance.anotherMethod();
    }


body:
I created the circuit in this schematic on protoboard,
[![schamatic][1]][1]

and the code,
https://github.com/elkayem/midi2cv

I use a dual opamp and a single dac, because i only need note and velocity.
The opto i use is, H11L1

It works but has a strange issue that i can not figure out.

The author says the code supports midi notes from 21 to 108.

When I send midi notes to test the device,

(Arduino powered with +12, TL082 Opamp powered with +15 to GND )

The notes <= 36 gives +15V in the output of the opamp.
The note 37 gives +3.43V
The note 38 gives +1.7V
.
.
.then it increments as expected until note 108 which gives +7.52 V

Also to add I have +1.5V DC offset on the both outputs of the opamp.
(This, i can live with but i would love it not to happen. )

I would be very happy if you help me on this, thank you.

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

title: Arduino Nano Midi to cv convertor interesting issue

Answers: 1

body:
I changed the opamp to LM358 and all problems solved it works perfectly!

If you have enough motivation and time please explain me why, but i will research and learn anyway.


body:
I got my Arduino kit a few days ago and I've been going through some of the tutorials.

I got to the 8 LEDs with a shift register tutorial, where I got stuck. Nothing would light up after I plugged everything in and uploaded the sketch.

[![arduino][1]][1]

This is the circuit I've attempted to recreate using Fritzing, and the following is the code I used, from the tutorial :
<!-- language-all: lang-cpp -->

    int tDelay = 100;
    int latchPin = 11;      // (11) ST_CP [RCK] on 74HC595
    int clockPin = 9;      // (9) SH_CP [SCK] on 74HC595
    int dataPin = 12;     // (12) DS [S1] on 74HC595

    byte leds = 0;

    void updateShiftRegister()
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, LSBFIRST, leds);
      digitalWrite(latchPin, HIGH);
    }

    void setup()
    {
      pinMode(latchPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
    }

    void loop()
    {
      leds = 0;
      updateShiftRegister();
      delay(tDelay);
      for (int i = 0; i < 8; i++)
      {
        bitSet(leds, i);
        updateShiftRegister();
        delay(tDelay);
      }
    }

I have also attempted to use an 8-segment digit display using the same shift register, also failing.

Is there something wrong that I am doing or could it be that the little chip is broken?

I accidentally discovered that when I swap the ground from pin 8 on the 595 to 5V, all the LEDs will light up.

Update : I got the same circuit in Tinkercad, some kind of Arduino simulator.
After dropping in the code and running the simulation, after it lights up the 5th LED, I get this warning :

[![warning][2]][2]

However, when I change the 220 ohm resistors to something like 500 ohm resistors, that pop-up is gone. Could this be another reason of why my chip could be possible broken at the moment?

  [1]: https://i.stack.imgur.com/bPD5g.png
  [2]: https://i.stack.imgur.com/3QOJs.png

title: 74HC595 shift register not working

Answers: 3

body:
One omission I see is that you don't have a bypass capacitor across Vcc and Gnd of the 74HC595. Without it you would have inconsistent operation.

But if you had the power reversed on the chip then that will be the major problem and I'm sure the chip is damaged.

What I would do is put leds on the clock, data, and latch lines. And then make your delay very long, 1 second, so that you can see what the lines are doing. Just to confirm that you are getting the output that you expect. But first put a bypass cap across the chip.

Also double check that your leds are in the right way.

body:
A few thoughts

Connecting 5v to pin 8 (=gnd) is not a good idea.  It may not cause any damage if pin 16(=vcc) is also connected to 5v but i would not rely on that. Generally reverse voltage will kill all electronics unless they are specifically protected against it.

For the LEDs I would use 1k to 10k ohm resistors.  This is giving still enough current to see them light up. Using 330ohms just takes more current and makes the leds extremely bright (3mA is enough).

For testing whether something simple is working, like a shiftregister, flipflop, or logic gate, I would not use a microcontroller at all. You can just use a couple of switches attached to the CLK and LATCH pins, with a slide switch attached to the DATA pin to select 1 or 0 input bit. This eliminates one point where stuff can go wrong.

Whether or not you put in a bypass cap will not make a difference if your supply is sufficiently capable and stable. I use the charger of my broken laptop that can deliver 5v at up to 2.5amps. In this setup I don't need any bypassing, although it's still best practise to include it.

Adding LEDs to the serial IN, latch, and shift clock, and serial output may also help nail down the problem.

Also make sure you don't have dodgy cables. If any of the wires is broken or has microscopic internal breaks this can lead to misbehaviour and is very difficult to find.

One thing I did when I tried if my chips worked was to first use a known good chip from a colleague to confirm the circuit was ok.

Depending on where you take your power from, adding a power LED is usually a good idea as well. If you power everything from a powerbank you may find that some of them just shutoff the outputs if there is less than a certain threshold current flowing out.  This can leads to effects like "the circuit worked for 30 seconds and then died. After disconnecting and waiting a couple of seconds and repluging the power it works again..."  For this reason I include a power LED in just about every project of mine.

body:
The only way i found to make this circuit to work
is by putting  8 pullup resistors (1k) from vcc
to each of the output pins of the 74hc595 whithout
them no leds light up ever.


body:
im trying to build a bit of test equipment that will talk to some software and it needs to send a fix string. when the voltage changes the string length does as well. i need to cap the results to 4 in length. (sorry for not knowing the correct terminology. this is the output i need -
<X_PCCCC_Y_PFFFF_Z_PTTTT>
Where,

    X = Flag CP Value
    _ = Space
    P = Polarity
    C = CP Received value
    Y = Flag Field Gradient
    F = Field Gradient Received value
    Z = Flag Contact CP
    T = Contact CP Received value

There is also a line feed and carriage return present at the end of each string.
The polarity indicator will only display a minus sign ‘-‘ if the received value is
negative otherwise no assignation will be transmitted. Although the overall string
length is constant the values for each measurement are right justified and hence a
space will be present should the value of the measurement not necessitate the
utilisation of all allocated character spaces.
Sample Outputs

    < X -89 Y -1989 Z -1096 >
    < X 1039 Y 8 Z 78 >

this is my code so far

    #include <Wire.h>
    #include <Adafruit_ADS1015.h>

    Adafruit_ADS1115 ads1(0x48);     // Use this for the 16-bit version
    Adafruit_ADS1115 ads2(0x49);

    void setup(void) {

      Serial.begin(9600);

      ads1.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV
      ads2.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV

      ads1.begin();
      ads2.begin();
    }

    void loop(void) {

      int16_t results01,results02,results03;

      results01 = ads1.readADC_Differential_0_1();
      results02 = ads1.readADC_Differential_2_3();
      results03 = ads2.readADC_Differential_0_1();

      Serial.print("X ");
      Serial.print(round(results01 * multiplier));

      Serial.print(" Y ");
      Serial.print(round(results02 * multiplier));

      Serial.print(" Z ");
      Serial.print(round(results03 * multiplier));

      Serial.println();              // send a cr/lf
      delay(500);
    }

Any help pointing me in the right direction would be Amazing.
Thanks in advance

Joe

title: Newbe needing help with fixed string length

Answers: 1

body:
The [printf() family of functions][printf] comes handy when you need
this kind of control over the formatted output:

    /*
     * Format a number as 5 characters.
     * Returns the string in a statically allocated buffer.
     */
    char * format5(int x)
    {
        static char buffer[6];  // 5 chars + terminating NUL
        snprintf(buffer, sizeof buffer, "]", x);
        return buffer;
    }

    void setup() {
        Serial.begin(9600);
        Serial.println(format5(15));
        Serial.println(format5(-15));
        Serial.println(format5(-1500));
        Serial.println(format5(1500));
    }

    void loop(){}

output:

       15
      -15
    -1500
     1500

[printf]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html


body:
So I have and arduino uno that is firing an output on pin 8. This code is not in this file just to be clear. From there Im taking that output and using it to fire pin 0 on the wifi module. Im using pin 0 because from what I understand all other pins have a pullup or pulldown resistor. When pin 0 is hot I want to print that value. Sometimes it works when I do it other times the analog values reads very low. I am using the 3.3v from the arduino uno and I plan to get a voltage regulator for the wifi module but would this cause this kind of issue? I am very very new to arduino so if anyone has any ideas I would appreciate a very dumbed down explanation. Thanks a lot. Also the reason why I have the delay turned down so low is because it seemed to make the analog signal pick up more often. Im not sure why this would matter but at a delay of 3000 it would almost never change analog value but when I turned the delay down to one the value came through much more consistently. Currently the code just outputs low analog numbers and occasionally pops up 1023 when voltage is applied but not consistently. And sometimes it just stops altogether until I keep trying for a while. I am getting voltage to the pin however so I know I have a complete circuit and power.

#include <SoftwareSerial.h>

    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

    const char* ssid = "ENDOWED Underwear";
    const char* password = "endowwear";

    HTTPClient http;

    static const uint8_t D0   = 16;
    static const uint8_t D1   = 5;
    static const uint8_t D2   = 4;
    static const uint8_t D3   = 0;
    static const uint8_t D4   = 2;
    static const uint8_t D5   = 14;
    static const uint8_t D6   = 12;
    static const uint8_t D7   = 13;
    static const uint8_t D8   = 15;
    static const uint8_t D9   = 3;
    static const uint8_t D10  = 1;

    int featherPin = D3;

    void setup() {
      Serial.begin(115200);
      pinMode(featherPin, INPUT);

      WiFi.begin(ssid, password);

      while(WiFi.status() != WL_CONNECTED) {
        delay(10);
        Serial.println("Waiting for connection");
      }
    }

    void loop() {
      int sensorValue = analogRead(featherPin);

      if (WiFi.status() == WL_CONNECTED) {
            Serial.println("yay connect");

            http.begin("http://10.150.40.121:3000/");
            http.addHeader("Content-Type", "text/plain");

            int httpCode = http.POST("Message from ESP8266");
            String payload = http.getString();
    //        Serial.println(payload);
            http.end();

        } else {
            Serial.println("Error in Wifi connection");
        }

        if (sensorValue > 850) {

          http.begin("http://10.150.40.121:3000/home");
          http.addHeader("Content-Type", "text/plain");

          int httpCode = http.POST("Message from ESP8266");
          String payload = http.getString();
          Serial.println(payload);
          Serial.print("hi");
          http.end();
          } else if (sensorValue < 850) {
            Serial.print(sensorValue);
    //        Serial.println("I am not hot");
          }

    //  digitalWrite(trigPin, LOW);
    //  delayMicroseconds(1);
    //  digitalWrite(trigPin, HIGH);
    //  delayMicroseconds(2);
    //  digitalWrite(trigPin, LOW);
    //
    //  pinMode(echoPin, INPUT);
    //  duration = pulseIn(echoPin, HIGH);
    //
    //  inches = (duration / 2) / 74;
    //  Serial.println(inches);
    //
    //  spaceIntruded = inches;
    //
    //  if (spaceIntruded <= 50 || spaceIntruded >= 900){
    //      digitalWrite(ledPin, HIGH);
    //      digitalWrite(hornPin, HIGH);
    //      Serial.println("Intruder Detected!");
    //      Serial.println("Sending text Notification...");
    //      delay(500);
    //      Serial.println("Armed...");
    //  }
    //
    //  else{
    //    digitalWrite(hornPin, LOW);
    //    digitalWrite(ledPin, LOW);
    //  }
        delay(1);

    }

title: Cannot get esp8266 - 12 wifi module to always read analogRead incoming voltage accurately

Answers: 1

body:
Analog to Digital conversion is one aspect1 where the ESP8266 is very poor. It has a single ADC pin which can read a maximum of 1V.

That pin is the only pin you can use with `analogRead()`. Any attempts to use any other pin just use that pin instead. The parameter (pin number) to `analogRead(pin)` is ignored and no matter what you do that one single ADC pin is what is being read. Also the pin cannot be used for anything else. None of the digital functions can be used with it since the pin doesn't have a GPIO number associated with it.

Some boards include a simple voltage divider on the ADC pin to allow higher voltages to be read, such as the NodeMCU:

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

If your board doesn't have such a divider you will have to implement it (or something similar) to be able to read the 3.3V incoming voltage.

----

1 The ESP8266 is great for WiFi but pretty poor for everything else. It is seriously starved of internal peripherals (it doesn't even have I²C). For a more feature-rich solution you might consider upgrading to the ESP32.

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


body:
Can you help me out to understand if this is possible with ESP8266 / 32 ?

I have a main binary that i upload to the chip, let's call it **A** - that's done from arduino.

**A** starts to work, but communicates every couple of minutes with central server polling for a *task*.

If there is a task - let's call it **B**

**A** downloads it and stores it on SPIFFS.

Now what should happen is that **A** uploads it, reboots and **B** starts to work.

When **B** finishes it loads up again **A** and the circle closes - this process goes on forever.

Questions:

1) Is it possible that a stored on SPIFFS binary file can be uploaded to the chip? Like OTA does via www.

2) Can i somehow store **A** onto the SPIFFS, so that when **B** finishes i reupload **A** ?

Thanks for any input into this

title: ESP8266 Switching firmware on the fly

Answers: 2

body:
The esp8266 Arduino package has 3 libraries for firmware update.

 - ArduinoOTA for upload from Arduino IDE
 - ESP8266HTTPUpdateServer for upload with web browser
 - **ESP8266httpUpdate library to check a web server for new version of the
   firmware**

body:
I think i've found an answer to my question here

https://www.esp8266.com/viewtopic.php?f=32&t=11324

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    #include "FS.h"

    void setup() {
      Serial.begin(115200);
      Serial.println();
      SPIFFS.begin();
      Dir dir = SPIFFS.openDir("/");

      pinMode(BUILTIN_LED, OUTPUT);
      digitalWrite(BUILTIN_LED, LOW);

      File file = SPIFFS.open("/blinkESP.bin", "r");

      uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
      if (!Update.begin(maxSketchSpace, U_FLASH)) { //start with max available size
        Update.printError(Serial);
        Serial.println("ERROR");
      }

      while (file.available()) {
        uint8_t ibuffer[128];
        file.read((uint8_t *)ibuffer, 128);
        Serial.println((char *)ibuffer);
        Update.write(ibuffer, sizeof(ibuffer));

      }

      Serial.print(Update.end(true));
      digitalWrite(BUILTIN_LED, HIGH);
      file.close();
    }

    void loop() {

    }

Will give it a try and revert back to confirm if it answers my question.


body:
Suppose I want to divide two integer variables and put the result into a float.
In order to prevent integer division do I have to program like this:

        int i = 6312;
        int j = 258;
        float f;
        f = i;
        f = i/j;

Or can I straightforward program like below and the compiler makes sure it is handled the 'proper' way:

        f = i/j;

title: Divide two integers resulting into a float

Answers: 2

body:
Cast the integers to float before doing the calculation.

    float f = float(i) / float(j);

or

    float f = (float) i / (float) j;

Always be clear how the calculation should be done, so the compiler will do what you want it to do.

body:
As Arduino is C++, you should *really* use a [static cast][1], to be technically accurate. However, for Arduino code it probably doesn't really matter.

So either

```
float f = static_cast< float >(i) / static_cast< float >(j);
```

or

```
float f = static_cast< float >(i) / j;
```

**Note**: Using a static cast on each operand, rather than just one, is  useful to quiet any warnings about the loss of precision with `int` to `float`, which typically needs to form a rounded `float` for large `int` values.

See [C++ int float casting][2] for more info.

---

Just to add to Jot's answer: Strictly speaking, it should be pointed out that `(float)` is C, whereas `float()` is C++.

---

Also, as you had meant to write in your question:

int i = 6312;
int j = 258;
float f;
f = i;
f = f/j;

Yes, that would work. However, even though it seems quite elegant, it could cause confusion later in time, when someone else examines the code - unless you added a comment explaining why.

it is probably best to keep the code simple and obvious (for debugging purposes) unless you are deliberately intending to obfuscate the code.

  [1]: https://stackoverflow.com/a/1255015/2628257
  [2]: https://stackoverflow.com/q/5456801/4424636


body:
I've searched quite a lot for this and tried to piece bits of code together but with no luck so far.

All i'm looking to do is have a command I can run in terminal/bash script on the Mac trigger some code to run on the Arduino (Leonardo)

It doesn't matter what data the Mac sends, I only have one command to run so it doesn't need to look like separate buttons or anything.

So far i've tried

    int incomingByte = 0;   // for incoming serial data
    void setup() {
    Serial.begin(9600);
    }

    void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
    //run commands
      }
        }

and then from terminal/script both

    echo "1" > /dev/tty.usbmodemHIDPC1 9600

and

    screen > /dev/tty.usbmodemHIDPC1 9600

I see the Arduino light flash when I run those two commands in terminal which would seem to suggest that its receiving the data, but nothing runs.

I have stripped out my code that is due to be run by the way for simplicity. I've got working keyboard presses ready to go to enter in the "run commands".

title: Have terminal bash script act as virtual "button" for Leonardo?

Answers: 0


body:
I am having a bit of trouble trying to read multiple Analog Input Pins (A0 and A3, in this instance). I am using a Pololu A-Star 32U4 LV Robot Controller (https://www.pololu.com/product/3116), and am using the Arduino IDE to program the board; it is recognized as a Arduino Leonardo. I am using the Joystick Library (https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-2.0) to have the controller be recognized by Windows as a Game Pad (irrelevant to the issue I am seeing, I believe).

I am simulating an Axis by using a potentiometer, with the data line running into the Analog Input, the 5V baseline coming from the board, and the Ground on the opposite of the Analog Input. This does indeed cause the values to change.

The issue that I am specifically running into is when I attempt to get the analog value for each pin that I am monitoring, it appears that the values of the other pins change at the same time. Because I am trying to use the Analog Pin values to drive an X/Y Axis, this issue manifests itself in an X/Y graph that appears linear with some sort of defined slope (with an X change leading to a Y change); rather than the expected X Horizontal only movement and Y Vertical only movement.

Further.. when I remove the second Axis (ie. only using X or only using Y), it appears to track as I expect, with the Pot moving the axis (changing the value of the Analog Input).

Here is where I check the pins in the loop:

      // Read the Analog Pins and update the controller
      for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
        checkAnalogAxisState(a, axisPins, axisPinVals);
        delay(10);
      }

And here is where I attempt to send the X/Y Axis changes based off of the readings coming from the Analog Pins:

    // Checks the Analog Pin for a value to be used as the Axis value. Only updates the state if it
    // has been found to have changed. Will update the Joystick Axis based on which pin it is currently
    // looking at
    void checkAnalogAxisState(uint8_t pinIndex, uint8_t analogPins[], int analogPinVals[]) {
        uint8_t analogPin = analogPins[pinIndex];

        // The trick when using multiple analog sensors is to read them twice, with a small delay after each read (10ms is good)
        // then discard the first reading. This is because the ADC multiplexer needs switching time and the voltage needs
        // time to stabilize after switching.
        int currentState = analogRead(analogPin);
        delay(10);
        currentState = analogRead(analogPin);
        delay(10);

        if(currentState <= analogPinVals[pinIndex] - 5 || currentState >= analogPinVals[pinIndex] + 5) {
            if(analogPin == X_AXIS_PIN) {
                Joystick.setXAxis(currentState - ANALOG_ADJUSTMENT);
            } else if(analogPin == Y_AXIS_PIN) {
                Joystick.setYAxis(currentState - ANALOG_ADJUSTMENT);
            }
            analogPinVals[pinIndex] = currentState;
        }
    }

I try to keep the Pin and the Value of that pin in an array, but even when I do this with 2 separate variable and function calls, I still see that the Analog values change at the same time.

Here is the full sketch, I can include the full contents of ControllerDefines.h and ControllerFunctions.h if they will be helpful, but I have pulled the relevant functions from each:

    #include <AStar32U4.h>
    #include <Joystick.h>
    #include "libraries/ControllerDefines.h"
    #include "libraries/ControllerFunctions.h"

    void setup() {
      // Setup pins for the Axis controls
      for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
        pinMode(axisPins[a], INPUT);
      }

      // Setup Joystick
      Joystick.begin();
      Joystick.setXAxisRange(-ANALOG_ADJUSTMENT, ANALOG_ADJUSTMENT);
      Joystick.setYAxisRange(-ANALOG_ADJUSTMENT, ANALOG_ADJUSTMENT);

      // Setup Serial Comm
      Serial.begin(9600);
    }

    void loop() {
      // Read all button states and update the controller
      for(uint8_t b = 0; b < TOTAL_BUTTONS; b++) {
        checkButtonState(b, buttons, buttonStates);
      }

      // Read the Analog Pins and update the controller
      for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
        checkAnalogAxisState(a, axisPins, axisPinVals);
        delay(10);
      }

      // Delay before polling buttons again
      delay(50);
    }

Edit:

I have taken a plot of the 2 Array values over time, as can be seen here. This is with the Pot hooked up to A3, which is `axisPinVals[0]`:
[![Plotted Values][1]][1]

Moving the Pot to A0 gives the following:
[![Plotted Values 2][2]][2]

Using the modified code below:

      // Read the Analog Pins and update the controller
      for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
        checkAnalogAxisState(a, axisPins, axisPinVals);
        delay(10);
      }

      // For the plotter
      Serial.print(axisPinVals[0]);
      Serial.print(",");
      Serial.println(axisPinVals[1]);

As you can see, the two values track together. This same behavior is not present in the buttons presses, and multiple buttons can be held at the same time with no issue.

I would expect each variable (line) to track independently of one another, when the Pot is moved from A0 to A3.

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

title: Reading Multiple Analog Input Pins

Answers: 2

body: Try reading each input twice in a row, and use the value from the 2nd read.  The input source may need additional time to charge up the sample & hold cap that is read by the ADC in the uC.

body:
I can't reproduce your problem. Your code is a bit lengthy to say for certain whether or not A0 and A3 clash when read in quick succession. Try this test code and see what results you get:

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

    void setup() {
     Serial.begin (115200);
     while (!Serial) {}  // wait for Serial

     Serial.println ("Starting");
    }

    void loop() {

    int a, b;

      a = analogRead (0);
      b = analogRead (3);

      Serial.print ("A0 = ");
      Serial.println (a);
      Serial.print ("A3 = ");
      Serial.println (b);
      delay (100);
    }

I found on my Micro (which has the same processor) that the two inputs were completely independent. For example changing A3:

    A0 = 0
    A3 = 195
    A0 = 0
    A3 = 453
    A0 = 0
    A3 = 680
    A0 = 0
    A3 = 879

And then changing A0:

    A3 = 0
    A0 = 64
    A3 = 0
    A0 = 292
    A3 = 0
    A0 = 427
    A3 = 0
    A0 = 474
    A3 = 0
    A0 = 294
    A3 = 0
    A0 = 48

This was with two potentiometers connected at all times. If you only had one you might get a "floating" input.

I suggest you try the code above and confirm whether or not you get similar results. If you do, then the problem is not "Reading Multiple Analog Input Pins" but something else entirely, like logic in your code.

Even when I changed the delay in my code to 10, the figures reported were still independent. That is, one pot did not influence the other at all.


body: Do Arduino Nano Atmega328p have the same pins as Arduino/Gizduino Uno Atmega328p?

title: Does UNO and Nano have the same pins?

Answers: 1

body: The '328P uC on the boards is the same die. The 328P in DIP has 4 fewer pins brought out (Vcc, Gnd, A6, A7) compared to the surface mount parts. The boards themselves then bring the pins out to edge connectors in physically different locations.


body:
Im using a 5v 1A power supply and connected to VIN pin on the NodeMCU. I also use 18650 battery to keep NodeMCU running in case the power supply shuts off due to power interruption.

I'm planning to use the 5V from power supply, convert it to 3.3V with voltage divider and connect it to the gpio to detect power interruption.

Is it possible? Can the NodeMCU handle the current from the power supply?

title: Detect power interruption on NodeMCU

Answers: 1

body: Yes, you can.  You need to convert the 5V down to 3.3V with a voltage divider. You also need to consider how you are going to operate the ESP8266 when there is no power.


body:
I am trying to get this code working:

    #include <Button.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <RTClib.h>

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 32 // OLED display height, in pixels

    // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
    RTC_DS1307 RTC;

    // when I remove this part it works...
    int mode = 1;
    const String periodicSystem[60] = {
        "H", "He", "Li", "Be", "B", "C", "N", "O",
        "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S",
        "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr",
        "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge",
        "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb",
        "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn",
        "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd"
    };
    /////////////////////////////////////////////////////////////////////

    Button button1(7);

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

      // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
        Serial.println(F("SSD1306 allocation failed"));
        for(;;); // Don't proceed, loop forever
      }

      RTC.begin();
      if (! RTC.isrunning()) {
        Serial.println("RTC is NOT running!");
        // This will reflect the time that your sketch was compiled
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }

      display.display();
    }

    void loop() {
      DateTime now = RTC.now();
      if(button1.pressed()) {
          display.clearDisplay();
          display.setTextSize(1); // Draw 2X-scale text
          display.setTextColor(WHITE);
          display.setCursor(10, 0);
          display.print(now.second());
          display.display();
      }
    }

Whenever I try to add the constant `periodicSystem`, I get the error `SSD1306 allocation failed` over Serial. The error also goes away when I remove the part with `button1.pressed()`. Basically I am not able to add the constant `periodicSystem` and read out a digital pin at the same time. To me it seems to be some sort of memory issue (I am only adding the constant, I am not doing anything else with it), but my IDE tells me I am only using 52% of the available storage. What am I doing wrong?

Here is my wiring (in reality I am using a 128x32 display, I didn't have the correct part for Fritzing; my display is labeled SDA, SCK, VCC, GND instead of SDA, SCK, VDD, GND; the RTC Module I am using is a DS1307 AT24C32 RTC Module):

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

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

title: SSD1306 allocation failed when adding a constant

Answers: 1

body:
Your display needs 624 bytes of RAM for its internal buffer (`128 * ((32 + 7) / 8)`). The `periodicSystem` array needs a massive 360 bytes of RAM just for the objects. That doesn't include the memory used to store the actual string data, which by my reckoning is 168 bytes.

So far we're up to 624+360+168 = 1152 bytes of a maximum of 2048.  Over half way and we haven't touched on the serial buffers or other objects that you're using.

An array (`const` or otherwise) of `String` objects is by far the least efficient way possible of storing constant string data on an Arduino. You're using 528 bytes of RAM to store what could be stored in 121 bytes of flash.

Personally I would store the data thus:

    const char periodicSystem[] PROGMEM = "H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNd";

Each symbol consists of exactly two bytes, and the `PROGMEM` forces it to stay in flash and never be copied to RAM.

You can get the two bytes of each symbol with:

    char b1 = pgm_read_byte(periodicSystem + (i * 2));
    char b2 = pgm_read_byte(periodicSystem + (i * 2) + 1);

Then either print them separately, or combine them into a C string:

    char symbol[3] = { b1, b2, 0 };

That will include the space character, of course. So you could remove that if you like:

    if (symbol[1] == ' ') symbol[1] = 0;

Theoretically you could also change the spaces in the original data to be character 0 if you like - depending on what you do with it, it shouldn't cause any issues:

    const char periodicSystem[] PROGMEM = "H\0HeLiBeB\0C\0N\0O\0F\0NeNaMgAlSiP\0S\0ClArK\0CaScTiV\0CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY\0ZrNbMoTcRuRhPdAgCdInSnSbTeI\0XeCsBaLaCePrNd";


body:
I am trying to program [mBot][1] using Arduino IDE. I am connected to the mBot using USB on `COM7`, I am able to upload a code created in [mBlock 3.4.11][2] fine, using "Arduino Mode" as the editing mode. I would like to proceed to more complex coding now and for this I want to be able to edit the source code directly. The source code seen in the MBlock application seems to be read only, there is a button which should allow editing the code, called "Edit with Arduino". When I press this button, the Arduino IDE opens and I am able to edit the code. The trouble is I seem to be unable to send the code edited this way into the mBot.

When I use the Arduino IDE Sketch/Upload menu item, the code is compiled, but when sending it, I always get following error:

> avrdude: stk500v2_ReceiveMessage(): timeout

Note: I was editing and uploading Arduino code before with both Ardino IDE and VisualStudio visualMicro (now [Arduino IDE for Visual Studio][3]) without any issues.

I do not know exactly how is the mBlock application handling the upload, but while doing so a folder with the project is created, which contains the following buildprefs.txt - perhaps this could help to understand what it is doing:

    build.arch = AVR
    build.board = AVR_UNO
    build.core = arduino
    build.core.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\cores\arduino
    build.extra_flags =
    build.f_cpu = 16000000L
    build.mcu = atmega328p
    build.path = X:\Users\UserName\AppData\Local\Temp\build3998294614124133332.tmp
    build.project_name = project_followLineAuto0_0.cpp
    build.source.path = X:\Users\UserName\AppData\Roaming\com.makeblock.Scratch3.4.11\Local Store\scratchTemp\project_followLineAuto0_0
    build.system.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\system
    build.usb_flags = -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
    build.usb_manufacturer = "Unknown"
    build.variant = standard
    build.variant.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\variants\standard
    build.verbose = true
    build.warn_data_percentage = 75
    compiler.S.extra_flags =
    compiler.S.flags = -c -g -x assembler-with-cpp
    compiler.ar.cmd = avr-ar
    compiler.ar.extra_flags =
    compiler.ar.flags = rcs
    compiler.c.cmd = avr-gcc
    compiler.c.elf.cmd = avr-gcc
    compiler.c.elf.extra_flags =
    compiler.c.elf.flags = {compiler.warning_flags} -Os -Wl,--gc-sections
    compiler.c.extra_flags =
    compiler.c.flags = -c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD
    compiler.cpp.cmd = avr-g++
    compiler.cpp.extra_flags =
    compiler.cpp.flags = -c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD
    compiler.elf2hex.cmd = avr-objcopy
    compiler.elf2hex.extra_flags =
    compiler.elf2hex.flags = -O ihex -R .eeprom
    compiler.ldflags =
    compiler.objcopy.cmd = avr-objcopy
    compiler.objcopy.eep.extra_flags =
    compiler.objcopy.eep.flags = -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
    compiler.path = {runtime.tools.avr-gcc.path}/bin/
    compiler.size.cmd = avr-size
    compiler.warning_flags = -w
    compiler.warning_flags.all = -Wall -Wextra
    compiler.warning_flags.default =
    compiler.warning_flags.more = -Wall
    compiler.warning_flags.none = -w

  [1]: https://www.makeblock.com/steam-kits/mbot
  [2]: http://www.mblock.cc/software-1/mblock/mblock3/
  [3]: https://www.visualmicro.com/

title: How to upload Arduino C code to mBot?

Answers: 1

body:
Be sure to select correct board (Arduino UNO) and port.

See this guide for details:
https://www.arduino.cc/en/Guide/ArduinoUno#toc5


body:
I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is < 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this?
I am new to Arduino and would appreciate any help.

    #include <Servo.h>
    Servo myservo;

    int dryValue = 1024; // max
    int wetValue = 0; // min

    int friendlyDryValue = 0; // %
    int friendlyWetValue = 100;

    int sensor = A0;
    int sensorValue;

    void setup() {

      Serial.begin(115200);

      pinMode(A0, INPUT);
      pinMode(D6, OUTPUT);
    }

    void loop() {

      int rawValue = analogRead(A0); // soil sensor

     Serial.print("Raw: ");
      Serial.print(rawValue);
      Serial.print (" | ");

       int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);

      Serial.print("Friendly: ");
      Serial.print(friendlyValue);
      Serial.println("%");

    if (friendlyValue <50)
    {
      myservo.write(9);
      }
      else
      {
        myservo.write(90);
        }
      }

title: Newbie question: Set servo at certain degrees when something happens

Answers: 1

body:
From your statement `pinMode(D6, OUTPUT);`, It looks you're using pin6 for the servo - ? If so, you need instead: `myservo.attach(6);` to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an [example program to drive a servo][1] using the servo library on the Arduino site.

Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.

There are a couple of things you can do about it:

 1. Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.

 2. Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.

 3. Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.

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


body:
This seems like an old, solved problem, but I can't find any simple answers.
I'm reading latitude and longitude data as Strings from a file (about 50 points), but they are really double float numbers.

First, I want to find the min/max ranges.   Then, later, I want to do some calculations on them.  I don't really want to keep reading the file, so I want to put them in an array.  But no matter what kind of array I use (3 examples below), the program crashes with stack errors.

    const char *latArray[ptsN];
    const char *lngArray[ptsN];
    //  or
    String      latArray[ptsN];
    String      lngArray[ptsN];
    //  or
    double      latArray[ptsN];
    double      lngArray[ptsN];

    while( myFile.available() ) {
      lineN++;
      String  latGet = myFile.readStringUntil(',');
      double dLat = StrngToDouble( latGet );
      if( dLat < minLat )  minLat = dLat;
      if( dLat > maxLat )  maxLat = dLat;

      latArray[lineN] = latGet;         //  put in String array
      //  or
      latArray[lineN] = latGet.c_str(); //  put in const char * array
      //  or
      latArray[lineN] = dLat;           //  put in double array

      String  lngGet = myFile.readStringUntil(',');
      double dLng = StrngToDouble( lngGet );
      if( dLng < minLng )  minLng = dLng;
      if( dLng > maxLng )  maxLng = dLng;

      lngArray[lineN] = lngGet;         //  put in String array
      //  or
      lngArray[lineN] = lngGet.c_str(); //  put in const char * array
      //  or
      lngArray[lineN] = dLng;           //  put in double array

      String  tmp = myFile.readStringUntil('\n');
    }

where

    double StrngToDouble( String dblString ) {
      double temp = strtod( dblString.c_str(), NULL );
      return temp;
    }

This can compile and work - EXCEPT for reading the arrays and calculating using the floats, no matter what type of arrays I try using.  It just crashes.  What's the best way to resolve this?
Thanks, Rick

title: How to store an array of doubles? As array of doubles, Strings or const char *? Then convert back to use?

Answers: 0


body:
I uploaded program MPU6050_DMP6_Multiple.ino (https://github.com/eadf/MPU6050_DMP6_Multiple/blob/master/MPU6050_DMP6_Multiple.ino) to Arduino Uno and it works fine.
When I upload the very same code to NodeMCU 1.0 board in Arduino IDE I have this message from the compiler :

Errors :

    Arduino: 1.8.5 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (3M SPIFFS), v2 Prebuilt (MSS=536), Disabled, None, 115200"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
    Using board 'nodemcuv2' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
    Using core 'esp8266' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
    Detecting libraries used...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev\I2Cdev.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire\Wire.cpp" -o "nul"
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master\MPU6050.cpp" -o "nul"
    Generating function prototypes...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp.o"
    In file included from C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/Arduino.h:244:0,

                 from C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp:1:

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: error: __c causes a section type conflict with __c

    #define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                                   ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

    #define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                            ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

    #define F(string_literal) (FPSTR(PSTR(string_literal)))

                                  ^

    C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino:225:20: note: in expansion of macro 'F'

     Serial.println(F("FIFO overflow!"));

                    ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: note: '__c' was declared here

    #define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                                   ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

    #define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                            ^

    C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

    #define F(string_literal) (FPSTR(PSTR(string_literal)))

                                  ^

    C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master/DeathTimer.h:45:22: note: in expansion of macro 'F'

         Serial.print(F("S:")); Serial.println(time % 60);

                      ^

    Using library I2Cdev in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev (legacy)
    Using library Wire at version 1.0 in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire
    Using library MPU6050_DMP6_Multiple-master in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master (legacy)
    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I am not so good in programming to understand what I can do to solve the problem !
I'd like to use NodeMCU with two MPU6050 and I need help !

title: The code is working fine with Arduino Uno but not with NodeMCU

Answers: 1

body:
It is [an issue][1] in esp8266 Arduino core. It is hard to explain, but here is a workaround for you:

In MPU6050_Wrapper.h change word `__FlashStringHelper` to `char` for function `halt` to be `void halt(const char* errMessage = NULL)`.

In DeathTimer.h remove `#include <Arduino.h>`.

In sketch add before includes `#define F(s) s` to hide the F macro.

  [1]: https://github.com/esp8266/Arduino/issues/2078


body:
I have this [relay module][1] that is attached to an ESP8266 ([Wemos D1 Mini][2]). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from [an external power supply][3]

The circuit diagram can be found [here][4].

The module works fine and all but I am wondering: is it okay to operate it like this ?

[![circuit diagram][5]][5]

  [1]: https://arduinomodules.info/ky-019-5v-relay-module/
  [2]: https://wiki.wemos.cc/products:d1:d1_mini
  [3]: https://eu.mouser.com/ProductDetail/MEAN-WELL/IRM-03-5?qs=NKmfXavxMazJdFbXlu0eDA==
  [4]: https://easyeda.com/stefanpruneanu/smart-switch
  [5]: https://i.stack.imgur.com/RdcgS.png

title: Is it okay to short IN and GND pins of relay module with controller ground?

Answers: 2

body:
You mean that you pull your Arduino relay control pin LOW, causing it to ground the pin? Yes, that sounds correct. (And you would set it HIGH to not energize the relay.) You might need a low value resistor between the relay's logic pin and the Arduino output if the relay is sinking too much current through the Arduino logic pin. A 100 ohm resistor would prevent sinking too much current through the Arduino logic pin. Try it and see if the relay still energizes.

## EDIT:

When I posted my answer the image wasn't loading, so I had to guess as to what you were describing. My guess was wrong, and thus my answer was wrong too.

Since you're driving the gate of a transistor you will need a current limiting resistor or you will overload the logic pin on your microcontroller. (As Jot says in their answer.)

There are 3.3v versions of these logic-driven relay modules readily available, and some even include optical isolation, so why not use one of those?

Take this one for example: https://www.adafruit.com/product/3191
(I don’t think that one has optical isolation.)

body:
It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.

The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "*5VDC to 12VDC (some boards may work with 3.3)*" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.

Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.

Could try to connect the collector only the IN pin? As in the schematic below.

[![schematic][1]][1]

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

----------

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.

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


body:
Still don't understand about char concatenation.

    void setup() {

      testCounter(3);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

    char testCounter(int countx){
      char a[10];
      strcpy(a, "COUNTER: ");
      strcat(a, printDigits(countx));
      return a;
    }

    char printDigits(int digits){
      char a[3];
      if(digits < 10) {
        strcpy(a, "0");
        sprintf(a,"%d",digits);
      } else {
        sprintf(a,"%d",digits);
      }
      return a;
    }

Error:  *invalid conversion from 'char' to 'const char*' [-fpermissive]* in `testCounter` line:

    strcat(a, printDigits(countx));

Don't understand this part of error.

`printDigits` function return char, so... `strcat` should be work. But why still error?

Please help...

title: strcat char concatenation trouble

Answers: 1

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

    char printDigits(int digits){

You are telling the compiler you will return **one** character.

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

     char a[3];

`a` is three characters. Thus the declaration doesn't match.

---

You could change the declaration to:

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

    char * printDigits(int digits){

But even that would be bad because `a` would go out of scope after the function returns.

---

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

     char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

---

The simplest way of doing what you seem to be wanting is:

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

    void setup() {
      Serial.begin (115200);
      testCounter(3);
    }

    void loop() {
    }

    char testCounter(int countx){
      char a[15];
      sprintf (a, "COUNTER: d", countx);
      Serial.println (a);
    }

---

Also, here:

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

      if(digits < 10) {
        strcpy(a, "0");
        sprintf(a,"%d",digits);
      } else {

That won't work because you are putting "0" into `a` and then **overwriting** it with `sprintf`.

---

> `printDigits` function return `char`, so... `strcat` should be work. But why still error?

Look at the prototype for `strcat`:

http://www.cplusplus.com/reference/cstring/strcat/

It expects `char *` not `char`. They are different things. One is a pointer, one isn't.


body:
For my project i need to measure accelerations up to 16g. My options are either digital accelerometers such as the MPU6050 or MPU9250 or an analog accelerometer such as the ADXL326.

What are any major pro's and con's of each. number of wires would be almost equal. the digital accelerometer is less pins on the board but i could easily use analog to digital convertors to bypass that. sampling rate is lower at 550Hz for the analog vs 4000Hz for the MPU9250. However i believe 550Hz would be more than adequate. And the biggest difference for me. £2 for an MPU9250 and £12 for the ADXL326!

Does anyone have any general advice on the main differences when choosing between analog and digital? I am measuring suspension motion on a motorcycle and need 5 of these accelerometers.

title: Analog vs Digital Accelerometers - pro's and con's?

Answers: 2

body:
The biggest difference is where the measurement (the conversion to digital) is done.  On the digital accelerometer, it is done in the accelerometer itself. On the analog one it is done at the MCU.

For simple arrangements where the accelerometer is near the MCU that makes no difference. However the analog one is more susceptible to noise. With longer wires / traces between the accelerometer and the MCU you can get less accurate results with an analog one since it picks up noise which you are then sampling and including in your results.

The digital one is more immune to that kind of interference - instead it is susceptible to digital noise - corruption of the data as it traverses long wires. But that is less of a problem since it takes far more induced voltage to corrupt a digital signal than an analog one.

One other main difference is that you are limited to the ADC that is in the digital accelerometer. If you want a different resolution you have to use a different accelerometer. With analog, since it has no inherent resolution, you sample at the resolution of your MCU's ADC.

Digital is also easier to interface in modern systems.  Many SoCs don't have analog inputs. So adding an analog accelerometer would mean adding an ADC chip as well - and you don't really want to do that in something like a mobile phone.

So in summary:

* Digital is the most convenient, reliable and suitable for current basic uses
* Analog is more of a niche product that is rarely used in consumer electronics

body:
The ADXL326 is only an accelerometer.
When you have one, you can measure the output of the sensor with a oscilloscope. For the final project a digital sensor is preferred as @Majenko has explained in his answer.

The MPU-9250 is an accelerometer, gyro and magnetometer. That makes it possible to use sensor fusion (combining the sensors with software calculations for a much improved result).

Are there vibrations involved? An accelerometer is sensitive for vibrations. I doubt if an accelerometer can be used to measure the suspension motion.

By the way, I'm ignoring the MPU-6050 and so should you. The MPU-9250 is less noisy.


body:
I have an Afafruit NRF52 board with SD 132 and 5.1 dual fw bootloader.
I implemented RTT logging and controlling (input) and the code is compiled using arduinoBuilder with RTT and debug level 3.
The device uses to control DALI lights but sometimes it hangs, I can see that it does not responses to input and light level never changes.

I want to debug it, maybe getting a stacktrace to see where it hangs, hoping it's a software issue.

Any leads on how to do that ?
Tutorial maybe ?

title: Debugging a Nordic MCU (feather NRF52) using Segger J-Link

Answers: 1

body:
I haven't tried this, but [OpenOCD](http://openocd.org/) supports both the nRF52 and the JLink.  Something like (on Linux):

    openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

might start OpenOCD.

You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).

You can find information about using gdb with OpenOCD [here](http://openocd.org/doc/html/GDB-and-OpenOCD.html) and [here](http://openocd.org/doc/html/General-Commands.html).


body:
I'm looking for two answer here.

 1. Is it possible to power a Leonardo to be always on, separate from the power from the USB host - I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that. I've bought a battery shield too which will be arriving soon.

 2. I want it be power-able via a switch with batteries so that I do a few things. For a start avoid it's boot up time and have it pressing a key as soon as the booted computer sees it (I'm running it as a keyboard/mouse via USB-HID) and also at one point I have the computer send serial data to have the Arduino run a different part of it's code...at this point the host computer reboots. Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

Do I need to change code, or libraries to achieve any of this?

With the theory intact answered, here is some of my actual code, i've stripped most of it out as it's just a bunch of keyboard presses

    #include <Keyboard.h>
    #include <Mouse.h>
    char returnKey = KEY_RETURN;
    char tabKey = KEY_TAB;
    void setup() {
    Keyboard.begin();
    Mouse.begin();
    // delay(60000); //Deploy Delay
    delay(3000); //Testing Delay
    // Keyboard commands
    Keyboard.write(returnKey);
    delay(14000);
    // Welcome Screen
    Mouse.click(MOUSE_LEFT);
    delay(100);
    }

    void loop() {
    }

title: Leonardo - always on power, status remains between computer reboots?

Answers: 2

body:
> Is it possible to power a Leonardo to be always on, separate from the power from the USB host

Yes, that is what the barrel jack is for.

> I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that.

Then your code is wrong. Are you using `while (!Serial);` or something similar near the top of your code?

> For a start avoid it's boot up time

The most certain way of doing that is to not use the bootloader. Instead program the board directly with a hardware programmer disabling (or erasing) the bootloader.

> Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

The Leonardo only reboots if you open the serial port at 1200 baud, or toggle the RESET pin / button.

> Do I need to change code, or libraries to achieve any of this?

It sounds like you may need to, yes - since it's not working at the moment when if the code were correct it should work.

----

**IMPORTANT**

**Most computers will not recognize the Leonardo until the operating system is fully booted. This means you cannot use the Leonardo to interact with the BIOS or boot menu. The Leonardo does not implement the "Boot Protocol" keyboard which is required to interact with the BIOS or other pre-boot environment.**

body:
It is possible to tell if the computer has opened or closed the serial port.

The serial port is located on the Arduino board.
By testing `if(Serial)` you can check if the serial port has been made active by the computer.
You could send keyboard and mouse events after it became active.

The fading in and out of the led at pin 13 is done by the bootloader. You could upload the sketch with a programmer to run without bootloader.

As far as I know, even without bootloader the serial port is still created.
The Teensy boards have a little more control over the USB interface.

To know what is going on and when a computer is connected, a mini linux computer is a lot easier. For example a Raspberry Pi.
The ATmega32u4 of the Arduino Leonardo has the possibilities and the information is available, but as far as I know, there are no libraries functions to use it.


body:
I am using an Arduino nano and an ESP8266. I have burnt an Arduino, but when I send a request to the Arduino LED, it takes some time to turn ON.

Here is my code:

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(2,3); //Pin 2 & 3 of Arduino as RX and TX. Connect TX and RX of ESP8266 respectively.
    #define DEBUG true
    #define led_pin 11 //LED is connected to Pin 11 of Arduino
    #define LED1 6
    #define LED2 7
    #define LED3 4
    #define LED4 5

    void setup()
      {
        pinMode(led_pin, OUTPUT);
        digitalWrite(led_pin, LOW);
         pinMode(LED1,OUTPUT);
     pinMode(LED2,OUTPUT);
     pinMode(LED3,OUTPUT);
     pinMode(LED4,OUTPUT);
        Serial.begin(115200);
        esp8266.begin(115200); //Baud rate for communicating with ESP8266. Your's might be different.
        esp8266Serial("AT+RST\r\n", 5000, DEBUG); // Reset the ESP8266
        esp8266Serial("AT+CWMODE=1\r\n", 5000, DEBUG); //Set station mode Operation
        esp8266Serial("AT+CWJAP=\"shubham\",\"shubh@1\"\r\n", 5000, DEBUG);//Enter your WiFi network's SSID and Password.

        //while(!esp8266.find("OK"))
        //{
         //}
        esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);
         esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);
          esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);//You will get the IP Address of the ESP8266 from this command.
        esp8266Serial("AT+CIPMUX=1\r\n", 5000, DEBUG);
        esp8266Serial("AT+CIPSERVER=1,80\r\n", 5000, DEBUG);
      }

    void loop()
      {
       String IncomingString="";
     boolean StringReady = false;

     while (esp8266.available()){
       IncomingString=esp8266.readString();
       StringReady= true;
      }

      if (StringReady){
        Serial.println("Received String: " + IncomingString);

      if (IncomingString.indexOf("LED1=ON") != -1) {
        digitalWrite(LED1,HIGH);

       }

      if (IncomingString.indexOf("LED1=OFF") != -1) {
        digitalWrite(LED1,LOW);

       }

         if (IncomingString.indexOf("LED2=ON") != -1) {
        digitalWrite(LED2,HIGH);
       }

      if (IncomingString.indexOf("LED2=OFF") != -1) {
        digitalWrite(LED2,LOW);
       }

         if (IncomingString.indexOf("LED3=ON") != -1) {
        digitalWrite(LED3,HIGH);
       }

      if (IncomingString.indexOf("LED3=OFF") != -1) {
        digitalWrite(LED3,LOW);
       }

      if (IncomingString.indexOf("LED4=ON") != -1) {
        digitalWrite(LED4,HIGH);
       }

      if (IncomingString.indexOf("LED4=OFF") != -1) {
        digitalWrite(LED4,LOW);
       }

      }
     }

    String esp8266Serial(String command, const int timeout, boolean debug)
      {
        String response = "";
        esp8266.print(command);
        long int time = millis();
        while ( (time + timeout) / millis())
          {
            while (esp8266.available())
              {
                char c = esp8266.read();
                response += c;
              }
          }
        if (debug)
          {
            Serial.print(response);
          }
        return response;
      }

title: LED turning on late

Answers: 0


body:
I want to run 5v and 12v strips and halos together, i read that with the 12v strips, give 12v to the strip but the data is always 5 volts, and tie the ground to the ground of the 5v controller?

I use SP105E bluetooth controllers off ebay, and i use a 10/20a 12v to 5v buck converter to get me to 5v as i use my lights in vehicle accessories so thats why i dont have a power supply or anything.

So would i just take the 12v strip, run the +12v to the +12v then data to the data wire and tie the 12v strip ground to the 5v ground on the controller/step down converter?

title: Running 5v and 12v strips together?

Answers: 0


body:
    int RlightPin=0;  //pin for right Photoresistor
    int LlightPin=1;  //pin for left Photoresistor
    int TranslateAnalogR=0;
    int TranslateAnalogL= 1;
    #include <Servo.h> //Servo library.
    int pos=90; //Declare and initialize the variable pos.
    int servoPin=9; //Servo connected to pin 9
    int servoDelay=10; //Time motor waits before working again.
    Servo myArms; //Servo object called myArms

    void setup() {
    Serial.begin(9600); //Start serial communication.
    pinMode(7,OUTPUT);
    pinMode(servoPin,OUTPUT);
    myArms.attach(servoPin);

    }

    void loop() {

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

    Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
    TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

    if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
    myArms.write(pos); // sets the servo position according to the scaled value
    delay(servoDelay);// waits for it to get to the position

    }

    if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
    for (pos=0; pos>=40; pos=pos+1)  {
      myArms.attach(servoPin);
      myArms.write(pos); //send servo to pos
      if(TranslateAnalogR=TranslateAnalogL){
      myArms.detach();}
    }
    }

    if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
    for (pos=0; pos>=40; pos=pos-1){
       myArms.attach(servoPin);
       myArms.write(pos); //send sevo to pos
       if(TranslateAnalogL=TranslateAnalogR){
       myArms.detach(); }

    }
    }

    }

title: (Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light

Answers: 1

body:
There are many issues with this code:

    pinMode(7,OUTPUT);

What is this pin for? Why do you set it to `OUTPUT` and then never
actually output anything? If the pin is in use, you should declare a
constant for it, like

    const int fooPin = 7;

and then use the constant instead of the bare number 7.

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

`analogRead()` is a slow function, and it is quite inefficient to do the
analog to digital conversion twice. You can instead

    TranslateAnalogR = analogRead(RlightPin);
    Serial.println(TranslateAnalogR);

As a matter of style, I would remove the comments. Commenting code is
generally considered a good practice, as long as the comments tell
something non obvious, like giving the “big picture” or the rationale
for doing something in a particular way. Paraphrasing in English what
the code already says in C++ is useless.

    Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
    //...
    Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

You won't know what value corresponds to the left and what value
corresponds to the right. I would instead do something like:

    Serial.print("L: ");
    Serial.print(TranslateAnalogL);
    Serial.print(", R: ");
    Serial.println(TranslateAnalogR);

Then:

    if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

You mean `==`.

    if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

The first test is redundant. If R>L, then obviously R≠L.

        for (pos=0; pos>=40; pos=pos+1)  {
            myArms.attach(servoPin);
            myArms.write(pos); //send servo to pos
            if(TranslateAnalogR=TranslateAnalogL){
                myArms.detach();
            }
        }

This is a very contrived way of searching the optimum. Normally you
attach the servo once and keep it attached all the time. Then you adjust
the position until you see the same illumination on both LDRs. This way
you keep track of the correct position and you need not redo the whole
angle scan every time. Also, this will not work for three reasons:

1. You mean `TranslateAnalogR==TranslateAnalogL` rather than
   `TranslateAnalogR=TranslateAnalogL`
2. `TranslateAnalogR` and `TranslateAnalogL` are not updated within the
   loop, you need to explicitly perform an analog read.
3. The loop will run too fast for the servos to follow the requested
   positions.

Later:

        for (pos=0; pos>=40; pos=pos-1){

The loop is backwards. You probably mean

        for (pos=40; pos>=0; pos=pos-1){

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

Here is my take at this, completely untested:

    #include <Servo.h>

    // Pinout.
    const int PIN_LDR_R = 0;  // right photoresistor
    const int PIN_LDR_L = 1;  // left photoresistor
    const int PIN_SERVO = 9;  // servo

    const int SERVO_DELAY = 20; // time motor waits before working again

    int pos = 90; // servo position in degrees
    Servo servo;  // servo object

    void setup() {
        Serial.begin(9600);
        pinMode(PIN_SERVO, OUTPUT);
        servo.attach(PIN_SERVO);
    }

    void loop() {
        // Read and report light levels.
        int level_L = analogRead(PIN_LDR_L);
        int level_R = analogRead(PIN_LDR_R);
        Serial.print("L: ");
        Serial.print(level_L);
        Serial.print(", R: ");
        Serial.println(level_R);

        // Adjust the servo position.
        if (level_R > level_L && pos < 180)
            ++pos;
        if (level_R < level_L && pos > 0)
            --pos;

        // Update the servo.
        servo.write(pos);
        delay(SERVO_DELAY);
    }

A few things worth noting:

* Constants are qualified as `const` (it helps the compiler optimize and
  catch bugs) and spelled in full caps (a common stylistic convention).
* The servo position is adjusted step by step, one degree per loop
  iteration. No need to perform a full scan every time.
* The program does not do anything special when the light levels are
  equal, because in that case there isn't actually much to do.
* I increased the delay between servo updates to 20 ms, as
  the serial communication alone can take close to 19 ms per
  iteration.
* You may want to add some hysteresis in order to avoid the servo
  jitter when it has found the optimum.