message:
File download from SD card hangs up my ESP-12E

I'm using ESP8266 Arduino for compiling and uploading my code to NodeMCU 1.0 (ESP-12E Module).
Flash Size: 4M (3M SPIFFS)
CPU frequency: 80 MHz
Upload Speed: 115200

I'm using portable arduino-1.6.9-windows extracted in my D: drive. I'm using the latest ESP8266 Arduino image [brought by git command][1].

I've written this basic code to download 'datalog.txt' file (stored in the root of my SD card).

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

    const int chipSelect = 4;

    const char *ssid = "tiny-esp";
    const char *password = "password";

    ESP8266WebServer server(80);

    String home = "
Hello! from ESP8266!
"
                    "
<button>Download</button>";

    void handleRoot() {
        server.send(200, "text/html", home);
    }

    void handleDownload() {

        File dataFile = SD.open("datalog.txt");
        int fsizeDisk = dataFile.size();
        Serial.print("fsizeDisk: ");
        Serial.println(fsizeDisk);

        size_t fsizeSent = server.streamFile(dataFile,"text/plain");

        Serial.print("fsizeSent: ");
        Serial.println(fsizeSent);

        dataFile.close();
    }

    void setup() {
        delay(500);
        Serial.begin(115200);
        Serial.println();

        WiFi.softAP(ssid, password);

        IPAddress apip = WiFi.softAPIP();
        Serial.print("Please visit: \n");
        Serial.println(apip);

        // see if the card is present and can be initialized:
        if (!SD.begin(chipSelect)) {
            Serial.println("\nCard failed, or not present");
            // don't do anything more:
            return;
        }
        Serial.println("\nCard Initialized.");

        server.on("/", handleRoot);
        server.on("/down", handleDownload);
        server.begin();
        Serial.println("HTTP server started");
    }

    void loop() {
        server.handleClient();
    }

But, when I press the 'Download' button, the ESP hangs, dumps some errors and then restarts as displayed below (from my Serial Monitor):

 Please visit:
 192.168.4.1

 Card Initialized.
 HTTP server started
 fsizeDisk: 28600

 Panic D:\arduino-1.6.9-windows\arduino-1.6.9\hardware\esp8266com\esp8266\cores\esp8266\core_esp8266_main.cpp:98 __yield

 ctx: sys
 sp: 3ffffc80 end: 3fffffb0 offset: 01b0

 >>>stack>>>
 3ffffe30:  3ffefdf4 000003b9 000003b9 4010020c
 3ffffe40:  00000000 3ffe9645 00000001 4020815d
 3ffffe50:  3ffefdf4 00000481 3fff0d50 402077e5
 3ffffe60:  3fff337c 00000b68 00000000 40207823
 3ffffe70:  3fff3a74 3fff1480 3fff3a74 3fff1474
 3ffffe80:  3fff337c 00000b68 3fff307c 40202a57
 3ffffe90:  3fff3a74 00000b68 3fff2cfc 40202c07
 3ffffea0:  00000000 3ffe9704 3fff337c 3fff1474
 3ffffeb0:  3fff337c 3fff147c 3fff2cfc 40202d34
 3ffffec0:  3ffeead0 0883f900 3fff1478 40202d54
 3ffffed0:  3fff337c 3fff147c 3fff1478 4022670d
 3ffffee0:  00000000 0104a8c0 00000010 00000000
 3ffffef0:  00000000 00000010 3ffefe40 40221001
 3fffff00:  40210000 00000000 0000007d 3fff151c
 3fffff10:  3ffebae4 3fff1520 3fff3434 40224b39
 3fffff20:  3fff1370 3fff1fac 3fff1fac 4021547e
 3fffff30:  40215972 3ffed310 3ffebabc 3fff1fac
 3fffff40:  3ffebad6 00000000 3fff3434 40223f35
 3fffff50:  0204a8c0 3ffee318 02a93dee 00000000
 3fffff60:  40104b62 02a93dee 3ffeead0 60000600
 3fffff70:  4022d230 3ffeeaa8 3ffeead0 0884220c
 3fffff80:  4022d256 3fffdab0 00000000 3fff2004
 3fffff90:  3fffdc90 00000000 3fff3434 4022ce8b
 3fffffa0:  40000f49 3fffdab0 3fffdab0 40000f49
 <<<stack<<<

  ets Jan  8 2013,rst cause:2, boot mode:(3,7)

 load 0x4010f000, len 1384, room 16
 tail 8
 chksum 0x2d
 csum 0x2d
 v00000000
 ~ld

 Please visit:
 192.168.4.1

 Card Initialized.
 HTTP server started

I tried updating the code by writing custom "server.streamFile()" function and adding

    "Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";
to the header to allow downloading the txt file as an attachment.

The modified code is [Only handleDownload() function has been changed]:

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

    const int chipSelect = 4;

    const char *ssid = "tiny-esp";
    const char *password = "password";

    ESP8266WebServer server(80);

    String home = "
Hello! from ESP8266!
"
                    "
<button>Download</button>";

    void handleRoot() {
        server.send(200, "text/html", home);
    }

    void handleDownload() {

        int32_t time = millis();
        File dataFile = SD.open("datalog.txt");
        int fsizeDisk = dataFile.size();
        Serial.print("fsizeDisk: "); Serial.println(fsizeDisk);

        String WebString = "";
        WebString += "HTTP/1.1 200 OK\r\n";
        WebString += "Content-Type: text/plain\r\n";
        WebString += "Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";
        WebString += "Content-Length: " + String(fsizeDisk) + "\r\n";
        WebString += "\r\n";
        server.sendContent(WebString);

        char buf[1024];
        int siz = dataFile.size();
        while(siz > 0) {
            size_t len = std::min((int)(sizeof(buf) - 1), siz);
            dataFile.read((uint8_t *)buf, len);
            server.client().write((const char*)buf, len);
            siz -= len;
        }
        Serial.print(siz);
        Serial.println(" Bytes left!");

        dataFile.close();
        time = millis() - time;
        Serial.print(time); Serial.println(" ms elapsed");
    }

    void setup() {
        delay(500);
        Serial.begin(115200);
        Serial.println();

        WiFi.softAP(ssid, password);

        IPAddress apip = WiFi.softAPIP();
        Serial.print("Please visit: \n");
        Serial.println(apip);

        // see if the card is present and can be initialized:
        if (!SD.begin(chipSelect)) {
            Serial.println("\nCard failed, or not present");
            // don't do anything more:
            return;
        }
        Serial.println("\nCard Initialized.");

        server.on("/", handleRoot);
        server.on("/down", handleDownload);
        server.begin();
        Serial.println("HTTP server started");
    }

    void loop() {
        server.handleClient();
    }

Now, when I press the Download button, a popup opens up in browser displaying "datalog.txt" has started downloading. But after about 20-30 seconds it says "Download failed". The esp freezes after printing the 'fsizeDisk'.

Meanwhile, the serial monitor reads:

 Please visit:
 192.168.4.1

 Card Initialized.
 HTTP server started
 fsizeDisk: 28600

I don't understand what am I doing wrong. Please help!

**EDIT:** I added delay(2) and a Serial.println(cnt++) inside *while(siz > 0)* in handleDownload() for debugging:

 int cnt=1;
 delay(10);
 while(siz > 0) {
  delay(2);
  Serial.println(cnt++);
        size_t len = std::min((int)(sizeof(buf) - 1), siz);
        dataFile.read((uint8_t *)buf, len);
        server.client().write((const char*)buf, len);
        siz -= len;
    }

What happens now is, I get

 Please visit:
 192.168.4.1

 Card Initialized.
 HTTP server started
 fsizeDisk: 28600
 1
 2
 3
 4
 5
 6
 7
 8

The loop may hang up at any count(e.g. 10, 15, 17, 23, etc). Also, in my browser, it reads as 28% downloaded (for cnt=8) or so. So, file starts downloading but hangs up midway. I've tried increasing the delay upto 10 ms, but there has been no progress.

  [1]: https://github.com/esp8266/Arduino#using-git-version

body:
try to add a yield() command in to your wihle-loop.
With yield() the ESP hast time to do his background jobs.


sender: user

message:
Need to turn on project twice in order for screen to work!

This problem is really stumping me. I made a simple printed circuit board with an ATtiny85, a 128x64 I2C OLED display, and a Sharp IR analog distance sensor. You can view the circuit here: [circuits.io][1].

If I turn the system on using the simple 3-pin slide switch that I put on the board, the screen does not turn on. I can see that the system is powered though, because I can see a little bit of red light escaping from the IR sensor where some of the IR light borders on the visible end of the spectrum. If I turn the board off then immediately turn it back on, the display powers up just fine. If I upload a new program to the board and use the programmer's 3.3v power I don't need to do it twice - the screen works first time.

I'm using a 3.7v LiPo battery, so I know power is not an issue (everything is 3-5v tolerant, and the LiPo battery can deliver plenty of current). Why do I need to turn it on twice in order for the screen to work? Thanks!

  [1]: https://circuits.io/circuits/3184178-attiny85-counter-with-oled-screen-rev-2#pcb

sender: assistant

body: Adding a 100ms delay before calling `oled.init(0x3c); oled.clear(); oled.startScreen();` made this problem go away.


message:
Why do I get a compiler error when I'm pretty sure I have such method?

Code
-
*(I've omitted much of the code, and left just the outline and code probably relating to the error.)*

`SelfDrivingCar.ino`

    #include "JKMain.h"
    void setup() { JKMain::setup(); }
    void loop() { JKMain::loop(); }

`JKMain.h`

    #include "JKMotors.h"
    class JKMain
    {
      static JKMotors motors;
    public:
      static void setup();
      static void loop();
    };

`JKMain.cpp`

    #include "JKMain.h"
    #include "JKPin.h"
    const int leftMotorStraightSpeed = 100;
    const int rightMotorStraightSpeed = 100;
    const int leftMotorTurnSpeed = 150;
    const int rightMotorTurnSpeed = 150;
    const int turn90Time = 700;
    void JKMain::loop() { }
    void JKMain::setup()
    {
      motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
        JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
        leftMotorStraightSpeed, rightMotorStraightSpeed,
        leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
    }

`JKMotors.h`

    class JKMotors
    {
    private:
      const int leftMotorSpeedPin;
      const int leftMotorDirectionBit1Pin;
      const int leftMotorDirectionBit2Pin;
      const int rightMotorSpeedPin;
      const int rightMotorDirectionBit1Pin;
      const int rightMotorDirectionBit2Pin;
      const int leftMotorStraightSpeed;
      const int rightMotorStraightSpeed;
      const int leftMotorTurnSpeed;
      const int rightMotorTurnSpeed;
      const int turn90Time;
      void setSideDirection(JKDirection _side, JKDirection _direction);
    public:
      JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
        const int rmsp, const int rmdb1p, const int rmdb2p,
        const int lmss, const int rmss, const int lmts, const int rmts, const int t90t);
    };

`JKMotors.cpp`

    #include "JKMotors.h"
    #include "Arduino.h"
    JKMotors::JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
        const int rmsp, const int rmdb1p, const int rmdb2p,
        const int lmss, const int rmss, const int lmts, const int rmts, const int t90t):
          leftMotorSpeedPin(lmsp), leftMotorDirectionBit1Pin(lmdb1p), leftMotorDirectionBit2Pin(lmdb2p),
          rightMotorSpeedPin(rmsp), rightMotorDirectionBit1Pin(rmdb1p), rightMotorDirectionBit2Pin(rmdb2p),
          leftMotorStraightSpeed(lmss), rightMotorStraightSpeed(rmss), leftMotorTurnSpeed(lmts), rightMotorTurnSpeed(rmts), turn90Time(t90t)
    {
      pinMode(leftMotorSpeedPin, OUTPUT);
      pinMode(leftMotorDirectionBit1Pin, OUTPUT);
      pinMode(leftMotorDirectionBit2Pin, OUTPUT);
      pinMode(rightMotorSpeedPin, OUTPUT);
      pinMode(rightMotorDirectionBit1Pin, OUTPUT);
      pinMode(rightMotorDirectionBit2Pin, OUTPUT);
    }

`JKPin.h`

    #include "Arduino.h"
    struct JKPin
    {
      // Ultrasonic
      static const int UltrasonicEcho = A4;
      static const int UltrasonicTrig = A5;

      // Servo
      static const int ServoSignal = 10;

      // Motor
      static const int LeftMotorSpeed = 5;
      static const int LeftMotorDirectionBit1 = 7;
      static const int LeftMotorDirectionBit2 = 6;
      static const int RightMotorSpeed = 3;
      static const int RightMotorDirectionBit1 = 8;
      static const int RightMotorDirectionBit2 = 9;
    };

**Notes**

I wouldn't worry too much about the `SelfDrivingCar.ino` file. I had it "encapsulated" with `JKMain.h`. Also, don't concentrate on `JKPins.h`, as it is mostly "factual" information likely unrelated to the problem.

---

Error
-

> sketch/JKMain.cpp: In static member function 'static void JKMain::setup()':

>JKMain.cpp:19: error: no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'
     leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);

>exit status 1

>no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'

---

Request
-

As far as I see, I do indeed have the constructor that the error claims I lack. **What's wrong with my code?**

---

Update
-

*(reply to jantje)*

I when removing `static` from `motors`, I receive a new error:

In file included from sketch/JKMain.cpp:1:0:

>sketch/JKMain.h: In static member function 'static void JKMain::setup()':

>JKMain.h:10: error: invalid use of member 'JKMain::motors' in static member function

>JKMotors motors;

>JKMain.cpp:16: error: from this location

> motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,

>exit status 1

>invalid use of member 'JKMain::motors' in static member function

body:
I think the problem is related to the fact motors is declared as a static member which makes it a global variable. This means the constructor can not be in the setup method.
I'm not 100% sure about the format but you need something like

    #include "JKMain.h"
    #include "JKPin.h"
    const int leftMotorStraightSpeed = 100;
    const int rightMotorStraightSpeed = 100;
    const int leftMotorTurnSpeed = 150;
    const int rightMotorTurnSpeed = 150;
    const int turn90Time = 700;
      JKMain::motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
        JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
        leftMotorStraightSpeed, rightMotorStraightSpeed,
        leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
    void JKMain::loop() { }
    void JKMain::setup()
    {

    }


body:
>     void JKMain::setup()
>
    {
      motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
        JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
        leftMotorStraightSpeed, rightMotorStraightSpeed,
        leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
    }

You can't call a constructor like that. A constructor is either implicitly called, eg. if `foo` is a class:

    foo bar;   // constructor for foo called

Or:

    foo bar (1, 2, 3, 4);  // pass arguments to the constructor

Or even as some people do:

    foo bar = foo (1, 2, 3, 4);

The last example creates a temporary instance of foo that is then copied into bar.

But what you **can't** do is this:

    foo bar;   // make an instance of the class
    bar (1, 2, 3, 4);  // call the constructor later

It's too late! The instance already exists. In your case `motors` is the instance of the class `JKMotors`. You can't call the constructor later on in the code. It doesn't make sense.


body:
The idea to embed both `setup()` and `loop()` with an OOP instance is good, but why not pushing the use of `class JKMotors` and `class JKMain` deeper by removing `static` variables and functions.

**Step1** - use a `JKMotors *` in a non-static `class JKMain`:

> The default constructor `JKMain()` is just used to initialize
> `motors`.

    class JKMain
    {
      JKMotors *motors;
    public:
     JKMain() { motors = NULL; };
      void setup();
      void loop();
    };

**Step2** - create the `motors` instance in the `void JKMain::setup()` as proposed by **@Mikael Patel**

> But now, the `JKMotors *motors;` is accessible from the non-static
> `void JKMain::setup()`.

    void JKMain::loop() { }
    void JKMain::setup()
    {
      motors = new JKMotors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
        JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
        leftMotorStraightSpeed, rightMotorStraightSpeed,
     leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
    }

**Step3** - declare a global `JKMain` instance and call `setup/loop` method from static `setup/loop` functions.

> The `JKMotors *motors;` is now accessible from both `JKMain::setup()`
> and `JKMain::loop()`functions.

    JKMain glbMain;

    void setup() { glbMain.setup(); }
    void loop() { glbMain.loop(); }


message:
millis() vs creating a "long" variable

I think my issue is not fully understanding how the `millis()` function works;

I am wondering the difference between simply creating a variable such as

    long fake_millis  ++ ;

vs using `millis()`?

body:
`millis()` returns the **ACTUAL** time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, `millis()` will still return the right time.

The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.

I short, just use `millis()`. It is easy to use and works great.

P.S. Use an `unsigned long` instead of a `long`.


message:
Implementing interrupts and timers on an Arduino Uno board

I am trying to implement interrupts on an Arduino Uno board.  My goal is to synthesize waves and play them via a 3.5 mm jack.  This is what I have so far, based on some code I was provided.  I have stripped it down to a somewhat barebones version in order to isolate what is wrong.  I have the audio jack plugged in to pin 9, which is what I was told is the PWM pin for this board.  However, nothing plays out of the audio jack at all.  I would really appreciate any advice or help! :)

    #include "avr/pgmspace.h"
    #define NUM_OSC 1    // number of oscillators
    #define MAXVOL 255   // maximum volume of each oscillator

    const byte sine256[256] PROGMEM = {
      128,131,134,137,140,143,146,149,152,156,159,162,165,168,171,174,
      176,179,182,185,188,191,193,196,199,201,204,206,209,211,213,216,
      218,220,222,224,226,228,230,232,234,236,237,239,240,242,243,245,
      246,247,248,249,250,251,252,252,253,254,254,255,255,255,255,255,
      255,255,255,255,255,255,254,254,253,252,252,251,250,249,248,247,
      246,245,243,242,240,239,237,236,234,232,230,228,226,224,222,220,
      218,216,213,211,209,206,204,201,199,196,193,191,188,185,182,179,
      176,174,171,168,165,162,159,156,152,149,146,143,140,137,134,131,
      128,124,121,118,115,112,109,106,103,99, 96, 93, 90, 87, 84, 81,
      79, 76, 73, 70, 67, 64, 62, 59, 56, 54, 51, 49, 46, 44, 42, 39,
      37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 18, 16, 15, 13, 12, 10,
      9,  8,  7,  6,  5,  4,  3,  3,  2,  1,  1,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  1,  1,  2,  3,  3,  4,  5,  6,  7,  8,
      9,  10, 12, 13, 15, 16, 18, 19, 21, 23, 25, 27, 29, 31, 33, 35,
      37, 39, 42, 44, 46, 49, 51, 54, 56, 59, 62, 64, 67, 70, 73, 76,
      79, 81, 84, 87, 90, 93, 96, 99, 103,106,109,112,115,118,121,124
      };

    const byte square256[256] PROGMEM = {
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
      255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255
      };

    const byte* const wave_table[] = {sine256, square256, triangle256, sawtooth256};

    // information about the current state of a single oscillator
    struct OscillatorState
    {
       unsigned int phaseStep;  // frequency of this oscillator
       unsigned int volume;     // volume multiplier for this oscillator
       unsigned int phaseAccu;  // accumulator that steps through this oscillator
                                // high byte = current sample index
       const byte* waveform;    // which waveform
    };

    volatile OscillatorState oscillators;
    volatile byte valOut;

    //********* interrupt routines ******

    // set up timer 1 to do phase correct PCM at a nominal frequency of 31372.549
    void setupTimer()
    {
    // Timer1 Clock Prescaler to : 1, set WGM22 to zero, and WGM12,13 for phase     correct PCM
      TCCR1B = (TCCR1B & 0b11100000) | 0b00001;

    // set it to clear compare match mode on both pins, and phase correct PCM     (WGM21 and WGM20)
      TCCR1A = (TCCR1A &0b00001100)| 0b10100001;

    // set overflow interrupts enabled for timer 1
      TIMSK1 |= (1<<TOIE1);

      Serial.println("hello");
    }

    // each timer 1 overflow, set the next sample value for the PWMs
    ISR(TIMER1_OVF_vect)
    {

      oscillators.phaseAccu += oscillators.phaseStep;
      valOut = highByte(pgm_read_byte(oscillators.waveform +     highByte(oscillators.phaseAccu)) * oscillators.volume);

      OCR1A = valOut; // replaced ... = valOut[0];  // write to pin 9
    }

    unsigned int hzToPhaseStep(float frequency)
    {
      float phaseStep = frequency * 2.0886902978652881446683197032183;    // (pow(2,16) * frequency) / 31376.6
      return (unsigned int)phaseStep;
    }

    void setup()
    {
      delay(1000);
      Serial.begin(9600);
      OCR1A = 0;
      oscillators.waveform = wave_table[2];
      oscillators.phaseAccu = 0;
      setupTimer();
      oscillators.volume = 200;
      oscillators.phaseStep = hzToPhaseStep(440.00);
    }

    void loop()
    {

    }

body:
>  I have the audio jack plugged in to pin 9 ... However, nothing plays out of the audio jack at all.

As you are relying on the timer changing the pin you need to make pin 9 output in `setup`:

     pinMode (9, OUTPUT);

When I did that I heard stuff - I wouldn't exactly call it pretty but I heard stuff.


message:
How do I read data from Parallel port DB25 over my Arduino?

I am using this program. However, I am getting garbage values only.
Do revert as to how can I get proper values over my arduino.

    /*****************************************************************************/
    * PrinterCapturePoll.ino
    * ------------------
    * Monitor a parallel port printer output and capture each character. Output the
    * character on the USB serial port so it can be captured in a terminal program.
    *
    * By............: Paul Jewell
    * Date..........: 29th January 2015
    * Version.......: 0.1a
    *-------------------------------------------------------------------------- -     ----
    * Wiring Layout
    * ------------ -
    *
    * Parallel Port Output               Arduino Input
    * --------------------               ------------ -
    * Name      Dir.   Pin                Name    Pin
    * ----             -- -                ----    -- -
    * nSTROBE    >       1..........................2
    * DATA BYTE  >     2 - 9.......................3 - 10
    * nACK       <      10.........................11
    * BUSY       <      11.........................12
    * OutofPaper <      12................GND
    * Selected   <      13.................5v
    * GND        <>  18 - 25................GND
    *------------------------------------------------------------------------------ -
    ******************************************************************************** /

    int nStrobe = 2;
    int Data0   = 3;
    int Data1   = 4;
    int Data2   = 5;
    int Data3   = 6;
    int Data4   = 7;
    int Data5   = 8;
    int Data6   = 9;
    int Data7   = 10;
    int nAck    = 11;
    int Busy    = 12;
    int led     = 13; // use as status led

    void setup() {
      // Configure pins
      pinMode(nStrobe, INPUT_PULLUP);
      for (int n = Data0; n < (Data7 + 1); n++)
        pinMode(n, INPUT_PULLUP);
      pinMode(nAck, OUTPUT);
      pinMode(Busy, OUTPUT);
      pinMode(led, OUTPUT);
      Serial.begin(9600);
      while (!Serial) {
        Serial.println("Waiting to Initialise");
      }
      //State = READY;
      delay(1000);
      Serial.println("Initialised");
      delay(1000);
    }

    void loop() {
      while (digitalRead(nStrobe) == HIGH) {
        digitalWrite(Busy, LOW);
        digitalWrite(nAck, HIGH);
        digitalWrite(led, HIGH);
        ProcessChar();
      }
      digitalWrite(Busy, HIGH);
      digitalWrite(led, LOW);
      digitalWrite(nAck, LOW);
      delay(5); //milliseconds. Specification minimum = 5 us
    }

    void ProcessChar() {
      byte Char;
      Char = digitalRead(Data0) +
             (digitalRead(Data1) << 1) +
             (digitalRead(Data2) << 2) +
             (digitalRead(Data3) << 3) +
             (digitalRead(Data4) << 4) +
             (digitalRead(Data5) << 5) +
             (digitalRead(Data6) << 6) +
             (digitalRead(Data7) << 7);
      Serial.print(char(Char));
    }

body:
Do you know the printer is working properly?

You are trying to fix more than one thing at once and that's never a good idea.  What I suggest you do is get a breadboard and make your own printer simulator.  You need to connect and LED up to every output pin and a button to every input pin.

Then you can simulate data from the printer, i.e. just pressing the button for pin 3 and you should see 1 coming out on the serial monitor.  OK I agree this "simulator" is rubbish, but you probably have the bits to knock it up now.

If you are still seeing 'junk' values then have a look and see if there is a pattern to the data.  This would be helped by printing the values in hex.

Of course if the Arduino side works then the issue is that the printer is sending data that you are not expecting.  It might help stick LEDs on every pin, both directions, it will help you see what is being sent.

Its possible that you are expecting 1 to indicate the bit is set and the printer is using 0.


body:
I think I can see the problem - although I have no way to test it.

According to [Wikipedia][1]:
> When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.

Here's my attempt at your loop() which I hope will at least get you started:

    void loop()
    {
        // Wait for strobe to go LOW, indicating a character is ready
        while (digitalRead(nStrobe) == LOW) {
            delay(1)
        };

        // Strobe is now LOW - a character is ready.
        // Pull BUSY to high
        // (NB: I don't know what you're doing with nAct and led)
        digitalWrite(Busy, HIGH);
        digitalWrite(led, LOW);
        digitalWrite(nAck,LOW);

        // Print the character
        ProcessChar();

        // Return BUSY to low again
        // (NB: I don't know what you're doing with nAct and led)
        digitalWrite(Busy, LOW);
        digitalWrite(led, HIGH);
        digitalWrite(nAck,HIGH);

        // Wait for the strobe to go HIGH again
        while (digitalRead(nStrobe) == LOW) {
            delay(1)
        };
    }

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state.  I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.

  [1]: https://en.wikipedia.org/wiki/Parallel_port


message:
IDE avoiding math operation

I have no idea why this has been happening:

    byte potenciometro = 0;int redpin=9;

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

    void loop() {
    int valor=analogRead(potenciometro);  delay(50);
    Serial.println();
    Serial.print(valor, DEC);

    analogWrite(redpin,valor);   }

This code above has been working just fine. However, i understand the LEDs will work properly with intensities that range from 1 to 255, so i replaced this line

    Serial.print(valor, DEC);

for this
    Serial.print((valor/700)*255, DEC);

and all that the IDE has been returning since then is 0 as console output.

i tried also just

    Serial.print(valor/700, DEC);
and i get nothing but 0s

anyone?

my arduino is the UNO version.

body:
Using `Serial.print (xx,DEC)` will give you a number on decimal base (round number). That's why your first code works

To solve this, you just simply change to

    Serial.print((valor*255/700),4) //4 digits behind comma


body:
In the C family of programming languages, the division operator (`/`),
when used with integer arguments, provides an _integer division_. You
get the integer quotient, and you can use `%` to get the remainder.

If you want a floating point division, then at least one of the
arguments should be a floating point number. E.g.:

    Serial.print(valor / 700.0 * 255);

(the `DEC` argument is redundant). The final result is then truncated to
an integer before being passed to `Serial.print()`.

A better option, which is outlined in dhimaspw's answer, is to do the
multiplication before the division. This way you avoid costly floating
point operations. If you do that, however, you should be careful about
overflows: `valor*255` can be as big as 1023 × 255
= 260865, which is larger than the maximum value an `int` can store
(215−1 = 32767). You should then write

    Serial.print(valor * 255L / 700);

where the `L` suffix forces the operation to be carried using long
integers.

The simplest solution, however, is to use the Arduino function `map()`,
which does essentially the same as above:

    Serial.print(map(valor, 0, 700, 0, 255));


message:
RF24Mesh master-base node communication delay

I'm trying to build a mesh network using 4 nRF24L01 modules directly connected with Arduino Uno where 1 module is master node and the rest are base nodes.

The workflow is exactly as follows

I'm sending a command in the Arduino IDE serial monitor. The master node receives this command and send it to other base nodes. There's no problem receiving the command on the base node side (from master node) as well as sending the command on the master node side (to base nodes). Upon receiving the command from the master node, base nodes successfully able to read the command and send the response. No problem at all.

But when the master node receives the response status from the base node(s), there's the problem. Master node is not receiving the data immediately. I have to send the command from the Arduino serial monitor repeatedly and on the 10th time, the master node is able to read the response status from the base node(s). Exactly on the 10th times every time.

Here's the source.

**master node**

    // global variables
    int dat2;
    String temp1 = "";
    boolean actualDataSent = false;

    // get input from arduino serial monitor

     while (Serial.available() > 0) {
          // my command
          String temp1 = Serial.readString();
    }

    // write block
    if (actualDataSent == false && temp1 != "") {

        // send this data to the base node one by one char
        for (int j = 0; j < mesh.addrListTop; j++)
        {
          for (int k = 0; k < temp1.length(); k++) {
            char ch = (char)temp1.charAt(k);
            Serial.print("NodeID: ");
            Serial.print(mesh.addrList[j].nodeID);
            Serial.print(" RF24Network Address: 0");
            Serial.println(mesh.addrList[j].address, OCT);
            RF24NetworkHeader header(mesh.addrList[j].address, OCT);
            Serial.println( network.write(header, &ch, sizeof(ch)) == 1 ? F("Send OK") : F("Send Fail"));
          }
          actualDataSent = true;
        }
        temp1 = "";
      }

    // read block
    else if (network.available() && actualDataSent == true) {
        RF24NetworkHeader header;
        network.peek(header);

        switch (header.type) {
          case 'M':
            network.read(header, &dat2, sizeof(dat2));
            Serial.print("Got: ");
            Serial.print(dat2);
            Serial.print(" from RF24Network address 0");
            Serial.println(header.from_node, OCT);
            actualDataSent = false;
            break;
          default: network.read(header, 0, 0); Serial.print("Not M case"); Serial.println(header.type); actualDataSent = false; break;
        }
      }

**base node**:

    //global variables

    String mypayload = "";
    int res1;

    // receive command from master
    while (network.available()) {
        RF24NetworkHeader header;
        network.read(header, &payload, sizeof(payload));
        mypayload.concat(payload);
      }
      if (mypayload != "")
      {
        Serial.print("Received data: ");
        Serial.println(mypayload);
        if ((mypayload == "100%"))
        {
          res1 = 1;
          Serial.println("Turn ON");
          if (!mesh.write(&res1, 'M', sizeof(res1))) {
          if ( ! mesh.checkConnection() ) {
            Serial.println("Renewing Address");
            mesh.renewAddress();
          } else {
            Serial.println("Send fail, Test OK");
          }
        } else {
          Serial.print("Send OK: "); Serial.println(res1);
        }
        }
        else if (mypayload == "0%")
        {
          res1 = '1';
          Serial.println("Turn OFF");
          if (!mesh.write(&res1, 'M', sizeof(res1))) {
          if ( ! mesh.checkConnection() ) {
            Serial.println("Renewing Address");
            mesh.renewAddress();
          } else {
            Serial.println("Send fail, Test OK");
          }
        } else {
          Serial.print("Send OK: "); Serial.println(res1);
        }
        }
        mypayload = "";
      }

body: The nRF24L01 "ACK_PAYLOAD" feature allows for two-way data transfer in a single radio transaction.  This is more complicated to set up but plenty of tutorials can be found online, on arduino stackexchange and of course another very helpful source is the nRF24L01 data sheet.  This should solve your problem by ensuring the master/slave radio messages are sent in the same, rather than independent, radio transactions.


message:
Using an Arduino for a Diorama Controller

Kind of new to the whole DIY electronics scene.

I'm building a diorama for my son.  It will include a length of track, a station, some other buildings, and scenery.  It will be HO scale.  The buildings came with these cool little LED lights and I've bought additional ones as well.  I want it to be of the period of the late 1800s to early 1900s.  So the additional LEDs I bought give off a more "yellow" light to simulate candle/lantern light.  The track is not a circuit and is not powered.  It is just "static" to sit a train so it appears to be at the station.

I have the following questions:

 1. Could I hook up the LEDs to a Arduino and have the different buildings (or floors within a building) be controlled separately?
 2. Could I make the LEDs "flicker" to simulate candle/lantern light?
 3. Could I maybe hook up a little speaker inside the train station to give off train noises, whistles, conductor calls, etc?
 4. Could this setup (Arduino with LEDs/speaker) be run off of batter power (not a custom battery, just off the shelf AAs, AAAs, or Cs, etc.)?
 5. Is an Arduino instead the appropriate controller for this kind of project?

I think this is a great opportunity to teach my kids not only modeling but also electronics (myself as well on the electronics).

Thanks in advance for any help/suggestions.

**EDIT:**

A little more about the setup.  The LEDs are made specifically for this type of application (model buildings/railroads).  Hence, they already have an 1800 ohm resistor attached to the input side of the LED.  There will indeed be multiple LEDs per building (even per floor).  I would like to at least isolate the circuits by building and even better if I could isolate them by floor.  I think it would be cool to have the software cycle the buildings/floors on and off at different times.

A smaller form factor for the Arduino would be ideal as it will have to fit into one of the scale buildings.  I've never really worked with the Arduino so I don't know all my options.  I've done a little with the Raspberry Pi and originally posted this question there and was told the Raspberry Pi would be overkill for this type of application.

body:
First, since you didn't mention any kind of Arduino, my answer is based on using Arduino Uno/Nano (I think its the most common)
 1. Yes you can. You use 1 transistor per building as switch (if there are many LEDs in the building) to gives optimal current and prevent your Arduino pin. The value of R2 -- Rx is depend the LED colour. You can control each group with one Arduino pin.

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

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

<!-- End schematic -->

 2. Yes you can, one in my mind is using PWM feature, like [this][1] project
 3. Yes you can. But maybe the generated sound is not up to your expectation. Here is one of the [simple example][2] and [this][3] maybe a bit challenging.
 4. The battery is up to your setup. More output (such as led and speaker) requires power source that can provide greater current. Arduino Uno voltage limit is 6v-20v
 5. In my opinion, yes.

As for the form factor, I think Arduino Nano is small enough to hide in the building, while Arduino Uno size is just slightly less than a Raspberry Pi.

Good luck for your project :)

  [1]: https://www.youtube.com/watch?v=uX9YMCLgK9A
  [2]: https://www.arduino.cc/en/Tutorial/toneMelody
  [3]: https://diyhacking.com/arduino-audio-player/


message:
Getting different results from function. How to retrieve values correctly?

Trying to implement PI controller in function.
Already worked for one controller.
However, for more than one controller, the results are shifting.
Suppose to get same values in the following code.
Any help I appreciate it.

    float r_in_1 = 10.00;
    float y_out_1 = 5.00;

    float r_in_2 = 10.00;
    float y_out_2 = 5.00;

    float r_o_1;
    float y_o_1;

    float r_o_2;
    float y_o_2;

    float vi_1 = 0;
    float vi_2 = 0;

    void setup() {

     Serial.begin(9600);

      // put your setup code here, to run once:

    }

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

    r_o_1 = pow_2(r_in_1);

    r_o_2 = pow_2(r_in_2);

    y_o_1 = pow_2(y_out_1);

    y_o_2 = pow_2(y_out_2);

    vi_1 = PI_1(r_o_1, y_o_1);
    vi_2 = PI_1(r_o_2, y_o_2);

    Serial.print(vi_1);
    Serial.print(',');
    Serial.println(vi_2);
    delay(1000);

    }

    float pow_2(float x){

    float z;

    z = x*x;

    return z;

    }

    float PI_1(float r, float y){

    float e;
    static float sum_e=0;
    float vi;
    float kp=2.00;
    float ki=10.00;

    e = r - y;
    sum_e =  sum_e + e;
    vi = kp * e + ki * sum_e;

    return vi;
    }

body:
The problem is you declare `static float sum_e` in PI_1 function. The value of will increase everytime PI_1 function is called. In 1 loop, you call PI_1 two times, resulting first call always smaller than second call because of the value of `sum_e`. Sum of error should be declared as global variable, and each controller has its own "sum" variable.
**Declare as global :**

    float sum_e[100]; //for 100 controller.

**Your function**

    float PI_1(float r, float y,int number){

    float e;
    float vi;
    float kp=2.00;
    float ki=10.00;

    e = r - y;
    sum_e[number] =  sum_e[number] + e;    //integrator for controller number
    vi = kp * e + ki * sum_e[number];

    return vi;
        }

**function call**

    vi_1 = PI_1(r_o_1, y_o_1,1);
    vi_2 = PI_1(r_o_2, y_o_2,2);

Here is the rough example. There are lot more efficient ways than this, but this should gives you some idea. You can reduce the code yourself since the values should be correct already.


body:
A PI controller has “state”: it has to remember the sum of all the
previous errors. If you want several controllers you have to
independently store the state of each one.

The traditional solution used by C programmers is to write a controller
function that takes an extra parameter which is a pointer to the state.
In C++ you can use a reference instead:

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

    // PI controller.
    float PIController(float &sum, float r, float y)
    {
        const float kp = 2.00;
        const float ki = 10.00;

        float e = r - y;  // error
        sum += e;         // integral of error
        return kp * e + ki * sum;
    }

You would use it like this:

    void loop()
    {
        static float sum_1, sum_2;  // State of the controllers.
        // ...
        vi_1 = PIController(sum_1, r_o_1, y_o_1);
        vi_2 = PIController(sum_2, r_o_1, y_o_1);
    }

The C++ language provides a nicer way of writing the same thing: you can
use a class to wrap the state and the controlling method together under
the same name:

    // PI controller.
    class PIController {
    public:
        PIController() : sum(0) {}
        float operator()(float r, float y);
    private:
        float sum;
    };

    float PIController::operator()(float r, float y)
    {
        const float kp = 2.00;
        const float ki = 10.00;

        float e = r - y;  // error
        sum += e;         // integral of error
        return kp * e + ki * sum;
    }

Which you would use like this:

    void loop()
    {
        static PIController pi_1, pi_2;  // Controller instances.
        // ...
        vi_1 = pi_1(r_o_1, y_o_1);
        vi_2 = pi_2(r_o_1, y_o_1);
    }

The generated assembly should not be much different. Note that in both
cases the static variables of `loop()` could be globals if you prefer.


message:
Very strange power supply problem

So, I've put together my Christmas tree lights - a string of WS2811s driven by my Uno board. They are 12 volt WS2811s, so I have rigged a 12 volt supply to them and just using the Uno for the data channel, powered, initially by the USB port of the PC. So far, so good.

Then I take the whole arrangement to the tree and try to power the Uno from a USB charger - but that's where it all goes wrong! The LEDS start to flash madly, nothing like the pattern that I've programmed.

I've tried various USB chargers and various USB cables to no avail, I've tried powering with 6 volts to the DC in socket - same thing. When I go back to the PC and pick up the Uno power from the USB cable, all is good! I have no idea what can be causing this, please help!

body:
The Arduino Uno barrel jack input connects to a linear 5 volt regulator.  These types of regulators require a several volt difference between the input and output.  So you need to supply 5 volts + several more volts or at least 7 volts at the barrel jack.

From the [Arduino Uno web page][1]:

> The board can operate on an external supply from 6 to 20 volts. If
> supplied with less than 7V, however, the 5V pin may supply less than
> five volts and the board may become unstable. If using more than 12V,
> the voltage regulator may overheat and damage the board. The
> recommended range is 7 to 12 volts.

  [1]: http://htthttps://www.arduino.cc/en/Main/ArduinoBoardUnop://


body:
[Turning my comment and other peoples replies into an answer to make it easier to read]

You are using two different power supplies? (PC + 12V or USB Charger + 12V) Have you connected the grounds from the two power supplies?

I have a limited understanding of why, but I know that unless the two power supplies have a common ground level the values for 0V and 5V may not be the same across the two feeds and you get odd and unpredictable behaviour.

Gerban explained that the reason it works on your PC is that most PC Power supplies reference Gnd from the Earth.  If you 12V supply is an ex-PC PSU, or similar, that will be doing the same which is why that setup works, they share a common ground via the mains earth.  The 5V phone charge probably has a plastic earth pin, which means it doesn't do this and therefore the Gnds are not tied to each other.

Majenko's blog will provide a more detailed, less hand wavey explanation:
https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/


message:
Update custom library

I've recently made a custom library. Then, I've imported the library into the IDE via the `add .zip library`. Once I tried to compile the code, I've realised that I made a small typo. Once I changed the error and then retried to compile the code, the error still appeirs and I'm **quite** sure that I've changed it.

So my guess is that the library is not updating. I've tried to go to manage library and then seeing if there is an other version of the library. There wasn't any.

So is there an easy fix to this solution that doesn't involve updating or downgrading the IDE?

body:
Text from [here][1] says this:

> In Arduino v16 and earlier, libraries were stored in the
> ArduinoInstallDirectory/hardware/libraries folder, which also
> contained all the built-in libraries (like Wire and Serial).
>
> In v17 and up, the user libraries are now stored in the
> ArduinoSketchDirectory/libraries folder.

Check your version of the Arduino SDK and then look in the appropriate directory for your library source code.  Then change it there.

The Arduino SDK is fairly simple and often compiles everything to avoid problems like this.  The installing from a zip file feature (unless it has changed) is more for convenience when downloading a single zip file.  I have often developed & edited custom library source code where the SDK expects to find it.

  [1]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/arduino-libraries


body:
[I actually found this answer on Stack Overflow.][1]

>In the Arduino GUI on windows, if I click on Sketch --> Import Library, at the bottom of the menu there is a section called "Contributed".
>
>Unfortunately, I had misclicked and added a library I did not want to that list.
>
>**How can I remove it from that list?**
>
>The help page only mentions that "If a sketch no longer needs a library, simply delete its #include statements from the top of your code" but it does not mention how to remove the library from the list of contributed libraries.

By : @merlin2011 from *Stack Overflow*.

  [1]: https://stackoverflow.com/questions/16752806/how-do-i-remove-a-library-from-the-arduino-environment


message:
Interfacing IMU and GPS with Arduino

I am using an Arduino UNO board and trying to interface IMU sensor (GY-521) and GPS sensor (Ublox Neo-6M) at the same time. The connections of the IMU and GPS are as follows

IMU to Arduino:
Vcc --> 5V
Gnd --> Gnd
SDA --> A4
SCL --> A5
INT --> D2

GPS to Arduino:
Vcc --> 5V
Gnd --> Gnd
Tx --> Rx
Rx --> Tx

Now when I used the IMU sensor alone and tested it with the Jeff Rowberg library, it was working fine. But as soon as I make the connections with the GPS and upload a program, the IDE gives the following error:

    Arduino: 1.7.10 (Windows 7), Board: "Arduino Uno"

    Build options changed, rebuilding all

    Sketch uses 3,970 bytes (12%) of program storage space. Maximum is 32,256 bytes.

    Global variables use 313 bytes (15%) of dynamic memory, leaving 1,735 bytes for local variables. Maximum is 2,048 bytes.

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa5

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa5

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

I can't seem to spot the problem. Kindly help me out as I am new to the Arduino development. Thanks.

body:
Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.

Cheers!


body:
Not enough to comment yet, but to add Mikael Patel's answer, using [Software Serial][1]  might help here to take the gps off the Arduino's serial lines

  [1]: https://www.arduino.cc/en/Reference/softwareSerial


message:
Arduino USB Host Shield with joystick

I'm building my own quadcopter and going to use an Arduino for this. An Arduino Micro for the quadcopter and an Arduino UNO for the controller. I want to use an USB host shield with a Logitech Extreme 3D Pro to control the quadcopter.

I have the joystick already working with de example from the USB host shield example, but I can't get the values to my `void loop()`. There is not much information on the internet about this.

The link to the library and example I'm using: https://github.com/felis/USB_Host_Shield_2.0/tree/master/examples/HID/le3dp

.INO file:

    /* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

    #include <hid.h>
    #include <hiduniversal.h>
    #include <usbhub.h>

    #include "le3dp_rptparser.h"

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB                                             Usb;
    USBHub                                          Hub(&Usb);
    HIDUniversal                                    Hid(&Usb);
    JoystickEvents                                  JoyEvents;
    JoystickReportParser                            Joy(&JoyEvents);

    void setup()
    {
      Serial.begin( 115200 );
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      Serial.println("Start");

      if (Usb.Init() == -1)
          Serial.println("OSC did not start.");

      delay( 200 );

      if (!Hid.SetReportParser(0, &Joy))
          ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
    }

    void loop()
    {
        Usb.Task();
    }

.cpp file:

    #include "le3dp_rptparser.h"

    JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
     joyEvents(evt)
    {}

    void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
    {
     bool match = true;

     // Checking if there are changes in report since the method was last called
     for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
      if( buf[i] != oldPad[i] ) {
       match = false;
       break;
      }
      }
       // Calling Game Pad event handler
     if (!match && joyEvents) {
      joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

      for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
     }
    }

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
     Serial.print("X: ");
     PrintHex<uint16_t>(evt->x, 0x80);
     Serial.print(" Y: ");
     PrintHex<uint16_t>(evt->y, 0x80);
     Serial.print(" Hat Switch: ");
     PrintHex<uint8_t>(evt->hat, 0x80);
     Serial.print(" Twist: ");
     PrintHex<uint8_t>(evt->twist, 0x80);
     Serial.print(" Slider: ");
     PrintHex<uint8_t>(evt->slider, 0x80);
        Serial.print(" Buttons A: ");
     PrintHex<uint8_t>(evt->buttons_a, 0x80);
     Serial.print(" Buttons B: ");
     PrintHex<uint8_t>(evt->buttons_b, 0x80);
     Serial.println("");
    }

.h file:

    #if !defined(__HIDJOYSTICKRPTPARSER_H__)
    #define __HIDJOYSTICKRPTPARSER_H__

    #include <hid.h>

    struct GamePadEventData
    {
      union { //axes and hut switch
        uint32_t axes;
        struct {
          uint32_t x : 10;
          uint32_t y : 10;
          uint32_t hat : 4;
          uint32_t twist : 8;
        };
      };
      uint8_t buttons_a;
      uint8_t slider;
      uint8_t buttons_b;
    };

    class JoystickEvents
    {
    public:
     virtual void OnGamePadChanged(const GamePadEventData *evt);
    };

    #define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

    class JoystickReportParser : public HIDReportParser
    {
     JoystickEvents  *joyEvents;

      uint8_t oldPad[RPT_GAMEPAD_LEN];

    public:
     JoystickReportParser(JoystickEvents *evt);

     virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    };

    #endif // __HIDJOYSTICKRPTPARSER_H__

So I hope that someone can give me a solution how I can get the value out of the code below (I changed the code a bit, so that I get decimal values) into the void loop().

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
     Serial.print("X: ");
     Serial.print(evt->x);
     Serial.print("\t Y: ");
     Serial.print(evt->y);
     Serial.print("\t Hat Switch: ");
     Serial.print(evt->hat);
     Serial.print("\t Twist: ");
     Serial.print(evt->twist);
     Serial.print("\t Slider: ");
     Serial.print(evt->slider);
        Serial.print("\t Buttons A: ");
     Serial.print(evt->buttons_a);
     Serial.print("\t Buttons B: ");
     Serial.print(evt->buttons_b);
     Serial.println("");
    }

I've some experience with Arduino programming but not much.

Please ask me if you need more information.

body:
The following assumes you are seeing `OnGamePadChanged` being called.

One way you could get the values you want (`GamePadEventData *evt`) into the `loop()` would be to add a member variable to the `JoystickEvents` class, so that class would become something like

    class JoystickEvents
    {
    public:
     virtual void OnGamePadChanged(const GamePadEventData *evt);
        static GamePadEventData mostRecentEvent;
    };

In `OnGamePadChanged`, make a copy of `evt`:

    GamePadEventData JoystickEvents::mostRecentEvent;
    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
        mostReventEvent = *evt;
    }

Now you can read it from `loop()` using something like

    Serial.print("X: ");
    Serial.print(JoystickEvents::mostReventEvent.x);

A significant limitation of this method is that it will only keep the most recent event.  Maybe that's OK for your purpose.

It's probably not quite what the author of that code had in mind: he probably expected you to do the work in `OnGamePadChanged`: his implementation of that method looks like an example so you can see how it works.


body:
After trying some other things I came up with the following idea:

I moved this piece of code from the .cpp file to the .INO file:

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
     Serial.print("X: ");
     PrintHex<uint16_t>(evt->x, 0x80);
     Serial.print(" Y: ");
     PrintHex<uint16_t>(evt->y, 0x80);
     Serial.print(" Hat Switch: ");
     PrintHex<uint8_t>(evt->hat, 0x80);
     Serial.print(" Twist: ");
     PrintHex<uint8_t>(evt->twist, 0x80);
     Serial.print(" Slider: ");
     PrintHex<uint8_t>(evt->slider, 0x80);
        Serial.print(" Buttons A: ");
     PrintHex<uint8_t>(evt->buttons_a, 0x80);
     Serial.print(" Buttons B: ");
     PrintHex<uint8_t>(evt->buttons_b, 0x80);
     Serial.println("");
    }

After I changed some of the code in the .INO file the code looks like this:

    /* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

    #include <hid.h>
    #include <hiduniversal.h>
    #include <usbhub.h>

    #include "le3dp_rptparser.h"

    int joyX = 512;       // min: 0 | max: 1023 | center: 512
    int joyY = 512;       // min: 0 | max: 1023 | center: 512
    int joyHat = 8;       // up: 0 | right-up: 1 | right: 2 | right-down: 3 | down: 4 | left-down: 5 | left: 6 | left-up: 7 | center: 8
    int joyTwist = 128;   // min: 0 | max: 255 | center: 128
    int joySlider = 0;    // min: 0 | max: 255
    int joyButtonsA = 0;
    int joyButtonsB = 0;

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB                                             Usb;
    USBHub                                          Hub(&Usb);
    HIDUniversal                                    Hid(&Usb);
    JoystickEvents                                  JoyEvents;
    JoystickReportParser                            Joy(&JoyEvents);

    void setup()
    {
      Serial.begin( 115200 );
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      Serial.println("Start");

      if (Usb.Init() == -1)
          Serial.println("OSC did not start.");

      delay( 200 );

      if (!Hid.SetReportParser(0, &Joy))
          ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
    }

    void loop()
    {
        //Print all the values into the serial monitor:
        Usb.Task();
        Serial.print("X: ");
        Serial.print(joyX);
        Serial.print("\t Y: ");
        Serial.print(joyY);
        Serial.print("\t Hat: ");
        Serial.print(joyHat);
        Serial.print("\t Twist: ");
        Serial.print(joyTwist);
        Serial.print("\t Slider: ");
        Serial.print(joySlider);
        Serial.print("\t Buttons A: ");
        Serial.print(joyButtonsA);
        Serial.print("\t Buttons B: ");
        Serial.println(joyButtonsB);
    }

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
      //Put the values from the joystick in another variable:
      joyX = evt->x;
      joyY = evt->y;
      joyHat = evt->hat;
      joyTwist = evt->twist;
      joySlider = evt->slider;
      joyButtonsA = evt->buttons_a;
      joyButtonsB = evt->buttons_b;
    }

It works very good for me and I'm now able to send the values to another Arduino with the nRF24L01+.


message:
Arduino Uno: how to increase distance of serial communication to PC

Does Arduino Uno's serial communication to  PC has the same distance as USB communication? (if I'm not mistaken 5m) If it is, what are the options for me to be able to communicate from Arduino Uno to PC with a longer distance? Thank you for any help!

body:
There are many options of varying complexities, pros, cons and prices.

The simplest method is to use powered USB hubs to extend the range. It's 5m per run of cable between powered hubs, so if you have access to power at 5m intervals (or can provide power at 5m intervals) you can chain hubs together to increase your distance. That rapidly becomes unwieldy and expensive though.

Assuming you want to keep the ability to directly program your Arduino from the PC without having to mess with swapping cables around, etc, other options include:

* USB over CAT5 adapters (up to 100m length)
* Bypass the USB altogether and use RS-232 (MAX-232 chips, about 15m length)

There are also some bluetooth adaptors that allow programming of the Arduino, but that gets a bit tricky.

If you're not too worried about programming there are far more options:

* Radio options, such as using XBees, nRF24L01 modules, etc.
* Networking - connect to an Ethernet or WiFi network
* GSM modem
* RS-485 / RS-422 - similar to RS-232 but longer distance, and without the signals needed for rebooting the Arduino for programming

The "distance" of the fully networked options is, literally, global. Once on a network you have the option of arranging access from anywhere on the globe with an internet connection

It all depends, really, on what you want to be able to do over the connection.

<sub>(I am sure there are many more options I have forgotten - feel free to suggest them in comments, or even go ahead and edit this answer to add them if you like.)</sub>


message:
How to use potentiometer data from slave to master Arduino?

I'm trying to make a game where i can use one Arduino as a controller (the controller is a potentiometer) and the other Arduino sending the signals to the computer. Im trying to figure out communication with two Arduino's so i would like to use two instead of one although using one would be logical and easier. Ive tried looking into I2C but cant seem to figure it out.

body:
Start by reading the potentiometer. Add a Wire [request service function][1] and that makes the Slave:

    #include <Wire.h>

    const uint8_t controllerAddress = 8;
    const int controllerPin = A0;
    volatile int controllerValue = 0;

    void setup() {
      Wire.begin(controllerAddress);
      Wire.onRequest(requestEvent);
    }

    void loop() {
      int value = analogRead(controllerPin);
      noInterrupts();
        controllerValue = value;
      interrupts();
    }

    void requestEvent() {
      Wire.write((const uint8_t*) &controllerValue, sizeof(controllerValue));
    }

This is minor update of the [Arduino Wire Master Reader][2] tutorial. The sketch for the Master is left as an exercise.

Cheers!

  [1]: https://www.arduino.cc/en/Reference/WireOnRequest
  [2]: https://www.arduino.cc/en/Tutorial/MasterReader


message:
Voltage on analog pin arduino when arduino turned off

So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

body:
All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

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

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

<!-- End schematic -->

The internals of the ATMega chip can be visualised for this purpose as a small resistor:

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

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

<!-- End schematic -->

If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

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

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

<!-- End schematic -->

That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.

It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.


message:
How to interpret accelerometer data to get decimals from -255 to 255

I'm using gy-521 module and I'm wondering how can i get useful readings from it so that i could work with the data that I'm receiving.

I want for AcX and AcY variable values to be from -255 to 255.
How to make this work.

sample data that I'm getting right now

    X = 16380 Y = -64
    X = 8116 Y = 3520
    X = 12564 Y = 8728
    X = -12652 Y = 1296
    X = -17732 Y = -2420
    X = -14576 Y = -2264

;

    #include<Wire.h>
    const int MPU_addr=0x68;
    int16_t AcX,AcY;
    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop(){
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);
      AcX=Wire.read()<<8|Wire.read();
      AcY=Wire.read()<<8|Wire.read();

      Serial.print("X = "); Serial.print(AcX);
      Serial.print(" Y = "); Serial.println(AcY);

      delay(333);
    }

body:
Use this code:

<!-- language-all: lang-cpp -->

    AcX = map(AcX, -32768, 32767, -255, 255);
    AcY = map(AcY, -32768, 32767, -255, 255);

Of course, you won't be able to store the resulting value in `int8_t` since its range is from -128 to 127.

[Here][1] you can read more about Arduino `map()` function.

  [1]: https://www.arduino.cc/en/Reference/Map


message:
delete or free on object causes Arduino to hand or reboot

I've read a lot about dynamic allocation for strings or buffers, but that's not my case.

I plan to implement much blinkers types as classes, all inheriting from a base `Action` class.

I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :

    Action** actions = new Action*[10];

In the code, I will do something like :

    int i = GetFreeActionID();
    actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

Then the loop will call a method of the object and it works fine.

When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :

    if (actions[i]->Do() != 0)
    {
      delete(actions[i]);
      actions[i] == 0;
    }

Howerver, I see in the serial console that when it comes to the `delete` instruction, the Arduino just reboots itself ...

Tryed also `free` instead of `delete` with same result.

How could I safely free the object when it's not used anymore ?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.

body:
>       actions[i] == 0;

That statement has no useful effect. Perhaps you mean:

    actions[i] = 0;


message:
What is the principle of scanner

I find a 2.4GHz scanner in this [web][1] . I want to do same thing in 433 Mhz with SI4463. But I fail to understand it's principle. Who can explain it ? Thanks.

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

  [1]: https://arduino-info.wikispaces.com/Nrf24L01-Poor+Man's+2.4+GHz+Scanner
  [2]: https://i.stack.imgur.com/1N6S9.png

body:
> I find a 2.4GHz scanner in this web . I want to do same thing in 433
> Mhz with SI4463. But I fail to understand it's principle. Who can
> explain it ?

The scanner you found loops through the channels looking for activity. The channels are defined by the NRF24L01. And activity is received signal within the channel above threshold (RSSI). For this device this is a single bit.

Other devices define RSSI as the signal quality/level for the latest received package. This is the case for the SI4463.

Cheers!


message:
How to use this Arduino code to control multiple different LEDs?

I am making an Android-controlled LED system over Bluetooth but I need to use 4 LEDs. I have done Android app but I am not able to figure out this Arduino code. Can some please help me get this done?

    char command;
    String string;
    boolean ledon = false;
    #define led 5

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

    void loop() {
      if (Serial.available() > 0) {
        string = "";
      }

      while(Serial.available() > 0) {
        command = ((byte)Serial.read());
        if(command == ':') {
          break;
        } else {
          string += command;
        }
        delay(1);
      }

      if(string == "TO") {
        ledOn();
        ledon = true;
      }

      if(string =="TF") {
        ledOff();
        ledon = false;
        Serial.println(string);
      }

      if ((string.toInt()>=0)&&(string.toInt()<=255)) {
        if (ledon==true) {
          analogWrite(led, string.toInt());
          Serial.println(string);
          delay(10);
        }
      }
    }

    void ledOn() {
      analogWrite(led, 255);
      delay(10);
    }

    void ledOff() {
      analogWrite(led, 0);
      delay(10);
    }

body:
Its better if you use SoftwareSerial for Bluetooth, so the native serial port can be used to debugging. But in case you doesn't need them:

    uint8_t led[4] = {5,6,7,8}; // pin for LED 1,2,3,4
    char command1,command2;
    String string;
      void setup()
      {
        Serial.begin(9600);
        for (int i=0; i<4; i++)
            pinMode(led[i], OUTPUT); //set all LED pin as OUTPUT
      }

      void loop()
      {
        if (Serial.available() > 1) //run if 1 bit or more data received
        {
        string = "";
            command1 = Serial.read();
            command2 = Serial.read();
            switchled(command1-'0',command2-'0');
        string = command1+command2;
        }
        delay(1);
      }
    void switchled(char pinLED,char statusLED)
    {
        if (statusLED == 0 || statusLED == 1)
        digitalWrite(led[pinLED-1],statusLED);
        else
        digitalWrite(led[pinLED-1],!digitalRead(led[pinLED-1]));

        Serial.print("LED ");
        Serial.print(pinLED);
        Serial.print(" = ");
        Serial.print(digitalRead(pinLED));
    }

The code reads 2 byte of data, so if your phone sent "11" the 1st led will turned on, and "10" will turn the 1st led off. The first digit is the LED index (1/2/3/4) and the second digit is the LED state (0/1), other than that, the LED on selected index will be toggled;


message:
getHostByName always failing to find a valid ip

I'm using an arduino Uno and a CC3000 wifi shield. I installed Adafruit library in arduino to get access to Wifi network. I'm currently trying to run some samples that comes with the library. It successfully connects to Wifi network and returns

IP Addr: 192.168.137.101
Netmask: 255.255.255.0
Gateway: 192.168.137.10
DHCPsrv: 0.0.0.0
DNSserv: 8.8.8.8
localhost -> 172.217.22.46

Pinging 172.217.22.46...0 replies

But when it tries to connects to a remote service like "www.adafruit.com" or "www.google.com" it assigns ip to 0 which means the host ip unknown. My wifi-hotspot is capable of providing internet connection. Can anyone please tell me what can I do to access remote web site through Wifi from this configuration. Setup method of one of the sample codes that I tried is mentioned below.

    void setup(void)
    {
      Serial.begin(115200);
      Serial.println(F("Hello, CC3000!\n"));

      displayDriverMode();
      Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

      /* Initialise the module */
      Serial.println(F("\nInitialising the CC3000 ..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
        while(1);
      }

      uint16_t firmware = checkFirmwareVersion();
      if (firmware < 0x113) {
        Serial.println(F("Wrong firmware version!"));
        for(;;);
      }

      displayMACAddress();

      /* Optional: Get the SSID list (not available in 'tiny' mode) */
    #ifndef CC3000_TINY_DRIVER
      listSSIDResults();
    #endif

      /* Delete any old connection data on the module */
      Serial.println(F("\nDeleting old connection profiles"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Failed!"));
        while(1);
      }

      char *ssid = WLAN_SSID;             /* Max 32 chars */
      Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      /* Wait for DHCP to complete */
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      while (! displayConnectionDetails()) {
        delay(1000);
      }

    #ifndef CC3000_TINY_DRIVER
      /* Try looking up www.adafruit.com */
      uint32_t ip = 0;
      Serial.print(F("www.adafruit.com -> "));
      while  (ip  ==  0)  {
        if  (!  cc3000.getHostByName("www.adafruit.com", &ip))  {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }
      cc3000.printIPdotsRev(ip);
      Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
      uint8_t replies = cc3000.ping(ip, 5);
      Serial.print(replies); Serial.println(F(" replies"));
      if (replies)
        Serial.println(F("Ping successful!"));
    #endif
      Serial.println(F("\n\nClosing the connection"));
      cc3000.disconnect();
    }

body: My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.


message:
ESP8266 NodeMCU first WS2812 LED lights up green

I'm trying to power some WS2812 LEDs from my ESP8266 ESP-12E NodeMCU board [(circuit here)](https://arduining.files.wordpress.com/2015/08/nodemcudevkit_v1-0_io.jpg). I'm simply trying to use the [NeoPixel Strandtest](https://raw.githubusercontent.com/adafruit/Adafruit_NeoPixel/master/examples/strandtest/strandtest.ino) which works perfectly on my Arduino UNO with the same LED strip, but when I change the `#define pin 6` to `#define pin D4` (or `12` as GPIO) only the first LED lights up and it's green. I did throw in a 470 ohm resistor between data and DIN, but that didn't do anything different.

When I use one of the other pins, nothing seems to light up, even if I disconnect all pins and hit reset. Here is my wiring:

<img src="https://i.stack.imgur.com/lIuPH.jpg" />

Don't mind the actual `3v -> 5v`. It works fine with 3v. I have also tried powering it off externally. I have tried all other pins from D0 to D7 (I saw many people say "STAY AWAY FROM PIN D8"). Could my ESP8266 be dead on arrival?

body:
Please read and understand [the manual][1]

You say it works on an Arduino, a big difference between the Uno and ESP8266 is the voltage (and voltage regulators).

Another difference is the chip/architecture itself.

So that leads to having to debug these two factors.

**Debug the power/circuit/voltage**

Please check if the 3V pin of your particular dev board can supply the current for the 3 LED's.
Alternatively you can try by using another 5V power supply, or the 5V from your USB or (Arduino, since that did work) to try and power the LED's.

Another problem may be that the voltage [will slowly go down][2] over the length of the strip. Your strip is small, though you also power it from 3V, increasing the effect. You can try to power it on multiple points, or from the middle.

Try [using a logic level shifter][3] to increase the logic output pin from 3V to 5V, it may not be sufficient to transmit the data. This usually isn't a problem, but you should exclude this possibility.

The guide also shows some [peculiar things][4] regarding the wiring. They say you should use a capacitor between the + and - lines. I don't see how that can fail, but you may as well try.

Also doublecheck the wiring, maybe some connector is a little loose. I've also had problems with LED strips that have been bent, the copper may come loose from the strip, or the strip may get teared a little.

You should also check with another piece of LED strip, just to be sure.

**Debug the controller**

It works on the Arduino, but not the ESP8266, and we have checked that it's not due to the voltages/power.

The NeoPixels have pretty strict timing, I would actually advise anyone to NOT use them. Since you can't write to the strip "pixel by pixel", you'll have to put the whole strip in memory, and then send it all at once.

Other SPI based LED strips can receive the pixels one by one, like streaming. So you can simply make a loop that sets a color and sends it (while slowly increasing color, to make an virtually infinite rainbow effect). The cool thing is that it even doesn't block interrupts from happening. (Neopixels disable interrupts, need 3 bytes per pixel, and can't do calculations between sending)

If you still want to use NeoPixels, there may be a timing issue. You can check at which clock speed you've set the ESP8266.

Also are you using ESP show with the right "is800KHz" option? `espShow(pin, pixels, numBytes, is800KHz);`

You may also try another ESP8266 from another manufacturer, to be sure that it's not the board. They may have used a crystal that isn't as accurate as it should be.

  [1]: https://learn.adafruit.com/adafruit-neopixel-uberguide/the-magic-of-neopixels
  [2]: https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels#distributing-power
  [3]: https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels#driving-5v-neopixels-from-3-dot-3v-microcontrollers
  [4]: https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices#improper-use-can-damage-your-neopixels-before-diving-in-be-aware-of-the-following


body:
So here comes my solution: I was playing around with [NeoPixelBus by Makuna](https://github.com/Makuna/NeoPixelBus) and the examples. I noticed in one of his examples, it said:

>// You can also use one of these for Esp8266,
>
>// each having their own restrictions
>
>//
>
>// These two are the same as above as the DMA method is the default
>
>// NOTE: These will ignore the PIN and use GPI03 pin
>
>//NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);

So I tried outcommenting that line and used that instead, and then it worked! I've always used `Neo800KbpsMethod` whenever I saw NeoPixelBus being used, because that was what other people did. Notice it also said:

>These will ignore the PIN and use GPI03 pin

That pin is the RX pin on my board. No other example I have seen, has used the RX pin on the board.

After 6+ hours of constant troubleshooting, I can finally power on my strip and control each LED!


body:
Ok i got it working after banging my head for couple of days, i was using a Node MCU Board V3, the pin number on board were D1 D2 D3 D4 etc all other library when data was connected to D4 in code where we specify the pin number we use to write D4.

However for FASTLED codes tbe code you need to write is just 4 without the letter D and when i did the same it just worked like magic


body:
Ok, I am using WS2812B with nodemcu and Fastled. Now all folks out there reading this need not worry about voltages if your led is not blinking at all. It was not working at D0, it worked for me when I changed to D1, I am not aware of issue though. Need to check that.
I did not use any other component and connected directly to nodemcu.
Below is the simple code for first led to blink.

    #define FASTLED_ESP8266_RAW_PIN_ORDER
    #include <FastLED.h>
    // How many leds in your strip?
    #define NUM_LEDS 3

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

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

    void setup() {
        Serial.begin(9600);
        // Uncomment/edit one of the following lines for your leds arrangement.
        // ## Clockless types ##
        FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
        Serial.println("Setup");
    }

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


message:
GSM shield 2 - Fully erase memory buffer

I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.

### What I'd like to do
My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem[1].

> I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the `sms.flush()` function. This function is available from the `GSM.h` library, which is [bundled with the Arduino IDE](http://www.arduino.org/learning/reference/gsm2) by default.

- and here comes the first glitch: the `flush()`function [reference page](https://www.arduino.cc/en/Reference/GSMSMSFlush) states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that `flush()` would only work for outgoing messages...
- ...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use `flush()` to delete received SMS.

So for me, `flush()` really works both for outgoing and received SMS. Am I right?

### What I did
Here is how the program works:

1. The arduino receives a SMS and is asked to light a LED
2. It does as instructed
3. then sends a SMS back saying that the LED is ON.
4. The DeleteSMS function is triggered

Here is the code:

    void DeleteSMS(){
  int MessageQtt = 0;
  Serial.print(F("["));
  do{
   sms.flush();
   MessageQtt++;
  } while (sms.available() > 0);
  Serial.print(MessageQtt);
  Serial.print(F(" message(s)"));
  Serial.println(F(" have been deleted]\n"));
    }

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also *any SMS received in the mean time*.

But it doesn't work and I can't really find out why.

### My devices

- Arduino UNO
- GSM Shield 2
- local (France) provider SIM card

Thanks all in advance for your input...

(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

----------
[^1]: _From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the **memory buffer**, but I can't really retrieve my source on that one_.

body:
Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.

So, the bottom line: never try to use the shield without a good powering system.


message:
How to run 50 IR LEDs off an Arduino UNO?

Hi I have 50 camera devices I want to program. Luckily the camera devices have a param.xml file I can import. I have already loaded the param.xml file on each of the camera devices however, now I need to import the param.xml file.

 The devices work on IR waves, Usually I would have to import the params on each individual device with a remote but I decided to try and create a neat project where I would attempt to program all of the devices at once using an Arduino.

I would like to buy 50 IR LEDs, make small booster circuits for each LED and then point each one too the receiving module on the camera devices. All the Signal wires would be connected to Arduino pin 3.

I am mostly concerned about all the signal wires connected to Arduino pin 3. is there perhaps some kind of circuit I can use on pin 3 to ensure that this project will work perhaps someone Knows of a better way or has some advice?

Any suggestions will be appreciated.

I am not worried about power because I will connect the IR LEDs + & - to an external Power supply with adjustable current and voltage.

Booster Circuit:

[Link To IR Led Datasheet][1]

[Link To Transister Datasheet][2]

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

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

<!-- End schematic -->

This is the code I am using with an Arduino Uno and I have tested it with the IR booster circuit and it does work.

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 3; i++) {
            irsend.sendNEC(0x1067E21D, 32); // Login
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 1
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 2
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 3
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 4
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 5
            delay(1000);
            irsend.sendNEC(0x106722DD, 32); // Password Digit 6
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x10678877, 32); // Right Arrow
            delay(1000);
            irsend.sendNEC(0x10676897, 32); // Down Arrow
            delay(1000);
            irsend.sendNEC(0x1067A857, 32); // Enter
            delay(1000);
            irsend.sendNEC(0x1067A857, 32); // Enter
            delay(1000);
            irsend.sendNEC(0x10678877, 32); // Right Arrow
            delay(1000);
            irsend.sendNEC(0x1067A857, 32); // Enter
            delay(1000);
        }
        delay(5000); //5 second delay between each signal burst
    }

  [1]: http://www.communica.co.za/Content/Catalog/Documents/D4112255518.pdf
  [2]: http://web.mit.edu/6.101/www/reference/2N2222A.pdf

body:
You should put a current-limiting resistor in series with _each_ LED.
You could then try to drive all of those LEDs from a beefy transistor, like
a power MOSFET or a Darlington. Alternatively, you can use a small
transistor for each LED, and then drive all of them from a PNP transistor,
like this:

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

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

<!-- End schematic -->

This way, if you want to drive some of the LEDs independently, you can just
connect an Arduino pin to its R2.

Beware that the PNP reverses the logic: pin `LOW` turns the LEDs ON.


message:
ard-reset-arduino resetting Leonardo/Micro via USB works on OSX, fails on Ubuntu

I'm trying to program a Leonardo (actually a Micro ATmega32U4) via the command line using USB.  Schematically, I'm doing `ard-reset-arduino` followed by a `sleep 1` and an `avrdude` command.

This works reliably on my Mac (OSX 10.12.1, avrdude v6.3), but bombs out on Ubuntu (Ubuntu 5.2.1-22ubuntu2, avrdude v6.1) with the message:

    .avrdude: butterfly_recv(): programmer is not responding

Update: I believe this is actually due to a failure to get the atmega32u4 into the bootloader.  See `update` at the bottom of this post...

Has anyone seen this?  Any suggestions for debugging strategies or things to try?

### Details on the Mac:

Here is the command line with results under OS X:

    $ ./ard-reset-arduino --verbose --caterina /dev/cu.usbmodem1411 && sleep 1 && /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -V -D -p atmega32u4 -C /Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -c avr109 -b 9600 -P /dev/cu.usbmodem1411 -U flash:w:./leds_test.ino.leonardo.hex:i
    Forcing reset using 1200bps open/close on port /dev/cu.usbmodem1411
    /dev/cu.usbmodem1411 has come back after reset

    Connecting to programmer: .
    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.
    Programmer supports the following devices:
        Device code: 0x44

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e9587 (probably m32u4)
    avrdude: reading input file "./leds_test.ino.leonardo.hex"
    avrdude: writing flash (9146 bytes):

    Writing | ################################################## | 100% 0.70s

    avrdude: 9146 bytes of flash written
    avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)
    avrdude done.  Thank you.

### Details on Ubuntu:

Here is the command line with results under Ubuntu.  Except for the pathnames, all of the options are the same as under OSX:

    $ /boot/ard-reset-arduino --verbose --caterina /dev/ttyACM0 && sleep 1 && /usr/share/arduino/hardware/tools/avr/../avrdude -V -D -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/../avrdude.conf -c avr109 -b 9600 -P /dev/ttyACM0 -U flash:w:/boot/leds_test.ino.leonardo.hex:i
    Forcing reset using 1200bps open/close on port /dev/ttyACM0
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    Waiting for /dev/ttyACM0 to come back
    /dev/ttyACM0 has come back after reset

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

### Postscript

Just to make sure I hadn't borked the bootloader somehow, I moved the Leonardo/Micro back to the OSX and re-ran the reset / programming sequence under OSX.  It worked without error, so I conclude that the resident bootloader is intact.

### Update

I believe the real problem is that under Ubuntu, `ard-reset-arduino` fails to put the Leonardo into the bootloader.

Here's why I believe this is the problem: the resident sketch makes the onboard LEDs blink.  On the Mac, running `ard-reset-arduino` makes the blinking stop for about 8 seconds.  On Ubuntu, the LEDs continue to blink without interruption after the `ard-reset-arduino` command returns.

### Update 2

Here's an even simpler Python program that resets the Leonardo under OSX but not under Ubuntu.

    #! /usr/bin/python
    import sys
    import serial

    ser = serial.Serial(sys.argv[1], 1200)
    ser.close()

body:
I'm somewhat embarrassed as to the source of the problem.  It wasn't an OSX vs Ubuntu issue.

Rather, on the Ubuntu system, there was an another application that was holding the USB port open, so attempts to reset the Leonardo were failing.

Rather than delete this post out of shame, I'm leaving it here in case someone else stumbles across the same problem.


message:
Use of struct and sizeof in C for Arduino

I am a newbie in C and I can not understand the point of using a structure in C. Could someone explain to me what is the point of defining a structure in C programming?

For example, this code(written in C for Arduino)

    struct books
    {
      char name[30];
      char author[30];
      int ID;
    } Mybook, Yourbook;

    void setup()
    {
      Serial.begin(9600);
      // put your setup code here, to run once:
      strcpy(Mybook.name, "Girl in the train");

      strcpy(Yourbook.name, "Gone");

      Serial.print("Name of the book is:");
      Serial.println(Mybook.name);
      Serial.println((long)&(Mybook.name));
      Serial.println((long)&(Mybook));
      Serial.println((long)&Mybook);
      Serial.println(sizeof(Mybook));

      Serial.print("Name of the book is:");
      Serial.println(Yourbook.name);
      Serial.println((long)&Yourbook);
      Serial.println(sizeof(Yourbook));
    }

 Would use the same amount of memory as defining

    char Mybookname[30];
    char Yourbookname[30];

And you should type the same amount of lines.
So what is the point?

I have another question:

Why I get 62 for the `sizeof(Mybook)`? I have not defined it anywhere. Is it set automatically?

body:
Consider the following:

    void printBook(const books &theBook)
    {
        Serial.println("Name of the book is: ");
        Serial.println(theBook.name);
        Serial.println("author is: ");
        Serial.println(theBook.author);
        Serial.println("ID is: ");
        Serial.println(theBook.ID);
    }

    void loop()
    {
        printBook(MyBook);
        printBook(YourBook);
    }

You should appreciate this avoids the code duplication you have in your
example.

> Why I get 62 for the sizeof(Mybook)?

* 30 bytes for `name[30]` (each char is one byte)
* 30 bytes for `author[30]`
* 2 bytes for `ID` (the AVRs have 16-bit ints)

No padding between the members because this architecture has no
alignment constraints.


body:
Using Arrays-of-Parts (AoP) to represent a single item or "record" means that record's information is scattered among the AoP. When you need to do more than storing and listing 'N' records, that can get cumbersome and error-prone (as in: you miss one of the AoP when writing one of your routines). It also limits how you can allocate memory for the set of records.

Using an Array-of-Structs (AoS) only requires you to manipulate the one struct as a unit. If you move a record, all of its parts go with it. If you delete it, all of its parts get deleted. When you need more space, you only need to re-declare one array instead each of the individual parts arrays.

And one step up from an AoS is a Linked List of Structs (LLoS). Each record will contains one or more pointers (links) to some other record(s). Sorting then requires nothing more than writing some record's address into this record's link, and you've established a precedence. LLoS really shine when the records get large; writing a couple of pointers is way faster than copying 100 or more bytes. Same with deleting a record (call it "me"): change my predecessor's link-to-me to instead link to my successor, and Bang, done! I'm out of the list, there's no hole left as there would be with AoS or AoP, and my memory can be de-allocated, or I can be linked onto a different list.

Bottom line, arrays can get cumbersome when the data-set is large and and the records are complex. Structs gather a whole record together and allow more flexible manipulation.