message:
I'm facing a problem with cap sense proximity

I've made use of the cap sense library in Arduino to make a touch less piano. I went according to my design and tried it out. Even after using a 10M ohm resistor, my program is only responding when I'm touching the electrodes. I want it to start detecting my finger from at least a few inches away.

I've posted the schematic and code for Arduino and Processing below.

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

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

Code for processing:

    import ddf.minim.*;
    import processing.serial.*;

    Minim minim;
    AudioPlayer song40;
    AudioPlayer song41;
    AudioPlayer song42;
    AudioPlayer song43;
    AudioPlayer song44;
    AudioPlayer song45;
    AudioPlayer song46;
    AudioPlayer song47;
    AudioPlayer song48;
    AudioPlayer song49;

    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port

    int r=0;
    int m=1;
    void setup()
    {
      minim = new Minim(this);
      song40 = minim.loadFile("40.wav");
      song41 = minim.loadFile("41.wav");
      song42 = minim.loadFile("42.wav");
      song43 = minim.loadFile("43.wav");
      song44 = minim.loadFile("44.wav");
      song45 = minim.loadFile("45.wav");
      song46 = minim.loadFile("46.wav");
      song47 = minim.loadFile("47.wav");
      song48 = minim.loadFile("48.wav");
      song49 = minim.loadFile("49.wav");

      String portName = "/dev/cu.usbmodem1411";                             //Change COM48 to the port number that your Arduino is connected, you can check the port number from arduino program.
      myPort = new Serial(this, portName, 115200);

      size(160, 160);
      background(0);
    }

    void draw()
    {
      if ( myPort.available() > 0 )
      {  // If data is available,
        val = myPort.readStringUntil('\n');
        if(val!=null)
        {
          print(val);
          if(val.charAt(0)=='a')
          {
            song40.rewind();
            song40.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("DO", 80, 90);
          }
          if(val.charAt(0)=='b')
          {
            song41.rewind();
            song41.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("DO#", 80, 90);
          }
          if(val.charAt(0)=='c')
          {
            song42.rewind();
            song42.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("RE", 80, 90);
          }
          if(val.charAt(0)=='d')
          {
            song43.rewind();
            song43.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("RE#", 80, 90);
          }
          if(val.charAt(0)=='e')
          {
            song44.rewind();
            song44.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("MI", 80, 90);
          }
          if(val.charAt(0)=='f')
          {
            song45.rewind();
            song45.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("FA", 80, 90);
          }
          if(val.charAt(0)=='g')
          {
            song46.rewind();
            song46.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("FA#", 80, 90);
          }
          if(val.charAt(0)=='h')
          {
            song47.rewind();
            song47.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("SOL", 80, 90);
          }
          if(val.charAt(0)=='i')
          {
            song48.rewind();
            song48.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("SOL#", 80, 90);
          }
          if(val.charAt(0)=='j')
          {
            song49.rewind();
            song49.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("LA", 80, 90);
          }
        }
      }

      if (mousePressed == true)
      {
        if(r==1)
        {
          myPort.write(' ');
          background(0);
        }
        r=0;
        m=1;
      }
    }

    public void stop()
    {
      minim.stop();
    }

And here's the Arduino Code:

    #include <SD.h>
    #include <CapacitiveSensor.h>

    #define total 30                   //define sensitivity, high value for decreases sensitivity, low value increases
    #define sensor 1                  //define number of samples Arduino takes, high value will increase stability while increasing response time
    #define replay 40                 //define debouncing, high value will increase stability while increasing response time

    int led = 13;
    int state = HIGH;

    boolean yes12;
    boolean previous12 = false;

    boolean yes11;
    boolean previous11 = false;

    boolean yes10;
    boolean previous10 = false;

    boolean yes9;
    boolean previous9 = false;

    boolean yes8;
    boolean previous8 = false;

    boolean yes7;
    boolean previous7 = false;

    boolean yes6;
    boolean previous6 = false;

    boolean yes5;
    boolean previous5 = false;

    boolean yes4;
    boolean previous4 = false;

    boolean yes3;
    boolean previous3 = false;

    CapacitiveSensor   cs_2_12 = CapacitiveSensor(2,12);        // 2.2M resistor between pins 2 & 12, pin 2 is send pin, pin 12 is sensor pin
    CapacitiveSensor   cs_2_11 = CapacitiveSensor(2,11);        // 2.2M resistor between pins 2 & 11, pin 2 is send pin, pin 11 is sensor pin
    CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);        // 2.2M resistor between pins 2 & 10, pin 2 is send pin, pin 10 is sensor pin
    CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
    CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
    CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
    CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
    CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
    CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
    CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);

    void setup()
    {
      cs_2_12.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
      cs_2_11.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_9.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_8.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_5.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);
      pinMode(led, OUTPUT);
      Serial.begin(115200);
    }

    short int a=1,a1=0,b=1,b1=0,c=1,c1=0,d=1,d1=0,e=1,e1=0,f=1,f1=0,g=1,g1=0,h=1,h1=0,i=1,i1=0,j=1,j1=0;  //for debounce purpose

    void loop()
    {
      long total112 =  cs_2_12.capacitiveSensor(sensor);
      long total111 =  cs_2_11.capacitiveSensor(sensor);
      long total110 =  cs_2_10.capacitiveSensor(sensor);
      long total19 =  cs_2_9.capacitiveSensor(sensor);
      long total18 =  cs_2_8.capacitiveSensor(sensor);
      long total17 =  cs_2_7.capacitiveSensor(sensor);
      long total16 =  cs_2_6.capacitiveSensor(sensor);
      long total15 =  cs_2_5.capacitiveSensor(sensor);
      long total14 =  cs_2_4.capacitiveSensor(sensor);
      long total13 =  cs_2_3.capacitiveSensor(sensor);

      if (total112 > total){yes12 = true;}
      else {yes12 = false;}

      if (total111 > total){yes11 = true;}
      else {yes11 = false;}

      if (total110 > total){yes10 = true;}
      else {yes10 = false;}

      if (total19 > total){yes9 = true;}
      else {yes9 = false;}

      if (total18 > total){yes8 = true;}
      else {yes8 = false;}

      if (total17 > total){yes7 = true;}
      else {yes7 = false;}

      if (total16 > total){yes6 = true;}
      else {yes6 = false;}

      if (total15 > total){yes5 = true;}
      else {yes5 = false;}

      if (total14 > total){yes4 = true;}
      else {yes4 = false;}

      if (total13 > total){yes3 = true;}
      else {yes3 = false;}

      if(yes12 == true && previous12  == false && a)
      {
          if(state == LOW) {
            state = HIGH;
          }
          else
            state = LOW;
          a = 0;
          a1 = 0;
          Serial.println('a');
      }
      if(yes12 == false && previous12  == false)
        a1++;
      else
        a1=0;
      if(a1==replay)
      {
        a=1;
        a1=0;
      }
      if(yes11 == true && previous11  == false && b)
      {
        if(state == LOW) {
          state = HIGH;
        }
        else
          state = LOW;
        b = 0;
        b1 = 0;
        Serial.println('b');
      }
      if(yes11 == false && previous11  == false)
        b1++;
      else
        b1=0;
      if(b1==replay)
      {
        b=1;
        b1=0;
      }
      if(yes10 == true && previous10  == false && c)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
          state = LOW;
        c = 0;
        c1 = 0;
        Serial.println('c');
      }
      if(yes10== false && previous10  == false)
        c1++;
      else
        c1=0;
      if(c1==replay)
      {
        c=1;
        c1=0;
      }
      if(yes9 == true && previous9  == false && d)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        d = 0;
        d1 = 0;
        Serial.println('d');
      }
      if(yes9== false && previous9  == false)
        d1++;
      else
        d1=0;
      if(d1==replay)
      {
        d=1;
        d1=0;
      }
      if(yes8 == true && previous8  == false && e)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        e = 0;
        e1 = 0;
        Serial.println('e');
      }
      if(yes8== false && previous8  == false)
        e1++;
      else
        e1=0;
      if(e1==replay)
      {
        e=1;
        e1=0;
      }
      if(yes7 == true && previous7  == false && f)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        f = 0;
        f1 = 0;
        Serial.println('f');
      }
      if(yes7== false && previous7  == false)
        f1++;
      else
        f1=0;
      if(f1==replay)
      {
        f=1;
        f1=0;
      }
      if(yes6 == true && previous6  == false && g)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        g = 0;
        g1 = 0;
        Serial.println('g');
      }
      if(yes6== false && previous6  == false)
        g1++;
      else
        g1=0;
      if(g1==replay)
      {
        g=1;
        g1=0;
      }
      if(yes5 == true && previous5  == false && h)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        h = 0;
        h1 = 0;
        Serial.println('h');
      }
      if(yes5== false && previous5  == false)
        h1++;
      else
        h1=0;
      if(h1==replay)
      {
        h=1;
        h1=0;
      }
      if(yes4 == true && previous4  == false && i)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        i = 0;
        i1 = 0;
        Serial.println('i');
      }
      if(yes4== false && previous4  == false)
        i1++;
      else
        i1=0;
      if(i1==replay)
      {
        i=1;
        i1=0;
      }
      if(yes3 == true && previous3  == false && j)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        j = 0;
        j1 = 0;
        Serial.println('j');
      }
      if(yes3== false && previous3  == false)
      j1++;
      else
      j1=0;
      if(j1==replay)
      {
        j=1;
        j1=0;
      }

      digitalWrite(led, state);
      previous12 = yes12;
      previous11 = yes11;
      previous10 = yes10;
      previous9 = yes9;
      previous8 = yes8;
      previous7 = yes7;
      previous6 = yes6;
      previous5 = yes5;
      previous4 = yes4;
      previous3 = yes3;

      delay(2);
    }

Thank you in Advance. :)

body:
Cap sensing is quite sensitive to the sense pad design. Generally you want thee pad to sufficiently big. I haven't seen a single wire design as you are using here.

I would play with one wire first and adjust your code to make it work before taking on more pads.


sender: user

sender: assistant

body:
## About your actual question

You have to realize that you are trying to measure **tiny**
capacitances, which is not completely trivial. Detecting your finger
“from at least a few inches away” is probably impossible with this
setup, as we are talking about fractions of a picofarad.

There are a few things you can do to increase the sensitivity though:

* make sure both you and the Arduino are properly grounded

* make the pads as big as practically possible

* increase the series resistance

* lower the detection threshold (your `total` constant) until you are at
  the verge of seeing spurious detections.

## About your Arduino code

This is not directly related to your question, but it addresses the
criticism you received for posting too large a program.

Looking at your code, it appears to be quite simple. It is too big only
because almost every statement is repeated ten times (once per piano
key). The simple thing you could have done is to remove all but one (or
maybe two) keys. This would have made the program easily digestible for
anyone trying to help you. What I strongly recommend is that you learn
about **using loops and arrays** in C++. This will allow you to avoid
repetition by instead looping through the arrays. Here is for example
how you could rewrite your `setup()` function based on an array of
sensors:

    const size_t SENSOR_COUNT = 10;

    CapacitiveSensor sensors[SENSOR_COUNT] = {
        CapacitiveSensor(2, 12),
        CapacitiveSensor(2, 11),
        CapacitiveSensor(2, 10),
        CapacitiveSensor(2, 9),
        CapacitiveSensor(2, 8),
        CapacitiveSensor(2, 7),
        CapacitiveSensor(2, 6),
        CapacitiveSensor(2, 5),
        CapacitiveSensor(2, 4),
        CapacitiveSensor(2, 3)
    };

    void setup()
    {
        for (size_t i = 0; i < SENSOR_COUNT; i++)
            sensors[i].set_CS_AutocaL_Millis(-1);
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.begin(115200);
    }

As you can see here, the sensor initialization
(`set_CS_AutocaL_Millis()`) is only written once, and the Arduino is
instructed by the `for` loop to repeat the same thing on every sensor,
one after the other. If you then do the same for `loop()`, you will end
up with a program that is almost ten times shorter, and a _whole lot_
easier to read, modify and debug. For that, you would need to also
replace your `yesXX`, `previousXX`, `a`, `a1`, `b`, `b1`, `c`, `c1`...
variables with arrays.

At this point you have a collection of arrays. The next level in
modularization is to replace the collection of arrays by an array of
collections: you put all the data relevant to one piano key inside an
object, and then you have just one array of such objects.

I tried rewriting your program with this approach, and I am posting the
result here. Beware that I did not test it. I realize this may be a
little bit above your current level, but I hope it will at least give
you an idea of how the language allows you to abstract things: the whole
logic about detecting whether a key was hit lives in the
`PianoKey::hit()` method, and then the `loop()` becomes short and
simple.

    #include <CapacitiveSensor.h>

    class PianoKey : private CapacitiveSensor
    {
        public:
            PianoKey(byte sendPin, byte receivePin, char _note)
                : CapacitiveSensor(sendPin, receivePin), note(_note),
                  last_state(false), last_toggle(0)
                { set_CS_AutocaL_Millis(-1); }
            bool hit();
            char note;
        private:
            static const byte SAMPLES = 1;     // number of samples to average
            static const long THRESHOLD = 30;  // detection threshold
            static const short DEBOUNCE = 50;  // debounce time (ms)
            bool last_state;
            uint32_t last_toggle;
    };

    // Returns true once per hit on the key.
    bool PianoKey::hit()
    {
        uint32_t now = millis();
        if (now - last_toggle < DEBOUNCE)
            return false;
        bool state = capacitiveSensor(SAMPLES) > THRESHOLD;
        bool was_hit = state && !last_state;
        if (state != last_state) {
            last_state = state;
            last_toggle = now;
        }
        return was_hit;
    }

    const size_t KEY_COUNT = 10;

    PianoKey keys[KEY_COUNT] = {
        PianoKey(2, 12, 'a'),
        PianoKey(2, 11, 'b'),
        PianoKey(2, 10, 'c'),
        PianoKey(2,  9, 'd'),
        PianoKey(2,  8, 'e'),
        PianoKey(2,  7, 'f'),
        PianoKey(2,  6, 'g'),
        PianoKey(2,  5, 'h'),
        PianoKey(2,  4, 'i'),
        PianoKey(2,  3, 'j'),
    };

    void setup()
    {
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.begin(115200);
    }

    void loop()
    {
        static int led_state = HIGH;
        for (size_t i = 0; i < KEY_COUNT; i++) {
            if (keys[i].hit()) {
                led_state = !led_state;  // toggle LED
                Serial.println(keys[i].note);
            }
        }
        digitalWrite(LED_BUILTIN, led_state);
    }

A couple of final notes:

* The line `class PianoKey : private CapacitiveSensor` says a piano key
  _is_ a capacitive sensor with some extra functionality. Another valid
  option would be to say that the key _has_ a sensor, i.e. to store a
  `CapacitiveSensor` inside the object.

* <s>I do not know whether it's safe to call `set_CS_AutocaL_Millis()`
  before the low-level initialization of the Arduino. That's why it's
  done in a `begin()` method to be called by `setup()`.</s> I checked
  the source code of the CapacitiveSensor library, and it appears that
  `set_CS_AutocaL_Millis()` does nothing but set a private member of the
  object. This means it is safe to call it from a global constructor,
  before the hardware initialization of the Arduino.
  Had this not been the case, one would need to defer this call until
  `setup()`, as done in [a previous version of this
  answer](https://arduino.stackexchange.com/revisions/34677/2).

* The `PianoKey::hit()` method uses time-based rather than
  loop-count-based debouncing. This should be more consistent if you
  change the program in a manner that changes the time it takes to loop.
  It does pure debouncing: you may want to change that to an algorithm
  that combines debouncing with deglitching.


message:
A coding problem or improper interrupt usage?

As I should expect(?), the PIR on pin#2 should trigger the trigsensor state at any time the board is running. However, I may get one trigger then nothing else. I have a GSM shield on top of a UNO. I know that I still have some tweaking to do, but I'm trying to solve one issue at a time. Thanks for any insight. The other functions seem to perform correctly. When I enter an incorrect code, the alarms operates properly. When the interrupt is triggered, the alarm response should be the same.

    ///////////////////////// initialize & includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;

    boolean started = true;
    int PIR_SensorPin = 2;
    int Alarm_OutPin = 11; //green
    int Light_OutPin = 12; //red
    int alarm_count;
    boolean volatile trigsensor = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; // four rows
    const byte COLS = 4; // four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("GSM Shield testing."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = READY");
        digitalWrite (Alarm_OutPin, HIGH);
        // PIR as interrupt
        attachInterrupt (digitalPinToInterrupt (2), trigger, RISING);
        //attachInterrupt ((0), trigger, RISING);
      }
      //  started = false; //////////////////////////////////////////////////////////////
      Serial.println ("System Ready, at the keypad loop!");
    }

    //////////////////////////////// void loop ///////////////////////////////////
    void loop() {
      readKeypad();
    }

    ////////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      trigsensor = true;
      started = true;
    }

    //////////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
      Serial.println (started); Serial.println (trigsensor);
      //  digitalWrite (trigsensor, LOW);
      Serial.println("at Alarm");
      // while ((timedelay - time) > 0); Serial.println (time);  time++;
      if ((started == true) && (trigsensor == true)) {
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
        for (alarm_count = 0; alarm_count < 5; alarm_count++) { // Cycle outputs if triggered
          digitalWrite (Alarm_OutPin, HIGH); delay (2000); // On/Off/On/Off/Off
          digitalWrite (Alarm_OutPin, LOW);
          digitalWrite (Light_OutPin, HIGH); delay (2000);
          digitalWrite (Light_OutPin, LOW); // End by turning off light
        }
        digitalWrite (Alarm_OutPin, HIGH);
      }
      else { }
      readKeypad();
    }

    //////////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              Serial.print(key_input[i]);
            }
            Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    //////////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();
      }
      else {
        incorrectPIN();
      }
    }

    //////////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      started = false;
      digitalWrite (Alarm_OutPin, HIGH);
      readKeypad();
    }

    ///////////////////////////// incorrect PIN ///////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
      Serial.println ("@ incorrect PIN ");
      started = true;
      // add time delay before alarm, via keypad??
      alarm();
    }

body: None of the code you posted ever sets trigsensor to false, besides the initial value.


message:
Controlling 4 LED strips

I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?

EDIT:
So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?

EDIT2:
Take a look at my setup. Is that OK?
[![enter image description here][1]][1]

Thanks

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

body:
You will need several things.

First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.

Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).

You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.

Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the [TSOP382](https://www.sparkfun.com/products/10266) or any other) and the proper decoding. A lot of remote controllers are already mapped in the library [IRremote](https://github.com/z3t0/Arduino-IRremote); you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.

This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.


message:
Insert Variables In AT commandes

I'am trying to apply USSD operation with variable codes, for example this piece of code return my account balance:

                 gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
i want to change "*100#" to variable so gsm.SimpleWrite uses what the variable contains. I want to find how to make it work like this:

                 gsm.SimpleWriteln("AT+CUSD=1,\"Variable\"");

EDIT: here is my code to give you a better view. it return balance in serial monitor.

    #include "SIM900.h"

      void setup()
        {
       Serial.begin(9600);
        Serial.println("GSM Shield testing.");
           if (gsm.begin(9600))
                Serial.println("\nstatus=READY");
          else Serial.println("\nstatus=IDLE");

             gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
          delay(10000);
                 char msg[200];
                 gsm.read(msg, 200);
                Serial.print("resp: ");
                Serial.println(msg);
     }
        void loop()
         {

        }

body:
I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.

Just split your string into chunks, like you would with any serial device:

    gsm.SimpleWrite("AT+CUSD=1,\"");
    gsm.SimpleWrite(command);
    gsm.SimpleWriteln("\"");

Where `command` is a suitable container for your data - say `const char *`.


message:
Battery level indicator

In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?

    int Batpin = A0;
    int Led1  = 12;
    int Led2  = 11;
    int Led3 = 10;

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

    }

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

    void volt(){
    int sensorVal = analogRead(Batpin);
    float voltage = sensorVal * (5.0/1023.0);

     Serial.print(" volt: ");
     Serial.println(voltage);
     if (voltage < 3.80){
         digitalWrite(Led1,HIGH);
      }

       if (voltage > 3.80 && voltage <= 4)
       {
          digitalWrite(Led1,LOW);
          digitalWrite(Led2,HIGH);
       }

       if (voltage > 4)
       {
          digitalWrite(Led1,LOW);
          digitalWrite(Led2,LOW);
          digitalWrite(Led3,HIGH);
       }
       delay (1000);
    }

body:
What you could do with for this is *[hysteresis](https://en.wikipedia.org/wiki/Hysteresis)*.

Instead of simple threshold ranges (0 < A < B < C < 5) you instead need to watch the voltage over time and decide what it is doing compared with what it has done in the past.

You need to keep a record of what state the voltage is in at any one time - That is, is it in band A, B or C in the thresholds above. You then need a second set of thresholds, A1, B1 and C1.

The two thresholds overlap:

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

If, for example, the voltage rises from between A and B to between B1 and C1 then you switch states to the BC state.

If it falls from between B1 and C1 to between A and B then you switch to the AB state.

Basically, if the voltage rises, it needs to transition between the lower set of thresholds to the upper set of thresholds to register as a change. If it drops it has to transition between the upper set of thresholds and the lower set of thresholds to register as a change.

So, in pseudocode,

    if (State == 0A && Voltage > A1 && Voltage < B1)
        State = AB
        Turn on LED 1

    if (State == AB && Voltage > B1 && Voltage < C1)
        State = BC
        Turn on LED 2

    if (State == BC && Voltage > C1)
        State = C5
        Turn on LED 3

    if (State == BC && Voltage < B && Voltage > A)
        State = AB
        Turn on LED 2

    if (State == AB && Voltage < A)
        State = 0A
        Turn on LED 1

    if (State == C5 && Voltage < C && Voltage > B)
        State = BC
        Turn off all LEDs

It's up to you to decide what a good level of separation is suitable for your system.

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


message:
Simple example multiplexer usage

I'm new at multiplexing with arduino (I use arduino from some years), and -as title says- I'd like to learn. I'm trying to build an expandible system with 3 sensors, and I'd like to use a 74hc595b1 to link them, leaving some pins free. My first question is: is It possible? And second, can you kindly link me a simple -but very simple- example about multiplexers in arduino? Thankyou!

body:
For connecting 8 analog devices to an Arduino, using only 3 Arduino pins, look at say a 4051 multiplexer IC: [4051 example][1]

  [1]: https://electronics.stackexchange.com/questions/67004/how-do-i-extend-the-number-of-analog-input-pins-available-to-me


message:
How compact, small and smart a fluid detector need to be communicate with external systems?

I like to build a fluid(liquid) level detector using Arduino that can send 2 types of information:

 1. Status of the Fluid Container (Empty,Full or Below Required Level)

 2. Location of Fluid Container

Now I like to know how small and compact such a fluid detector can be so that it can be placed in vessels, containers, tanks, etc. without causing any contamination to the fluid.
In addition, how can I interface this fluid detector with external systems like a smartphone app or cloud based app, etc.

What Arduino would i be using for the said purpose and why?

body:
Your question should be broken into a minimum of two parts.

The first, regarding the sensor, can be addressed with at least one specific product, although there may be others of this nature. It is a teflon coated pressure sensitive strip placed into the holding container or tank. Teflon is a non-reactive plastic and will not contaminate the substance in the tank, unless you are measuring extraordinarily reactive chemical liquids. One example is
[Chemical eTape][1] which is available in lengths from 130mm to 800mm.

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

This particular product is offered in three different interface types, all of which are acceptable to a properly configured Arduino.

The second portion of your question regarding the smartphone and type of Arduino is going to depend on how you plan to use the data you'll collect with the sensor. This aspect of the question is also extremely broad, as there are many solutions, including Blynk, SMS, WiFi and others.

You will want to "start small," and create a local Arduino-only interface, to ensure that you can properly code the sensor to present the results you require.

Once you have the data, you would then explore the many options available for distribution and dissemination.

  [1]: http://milonetech.com/products/chemical-etape-assembly
  [2]: https://i.stack.imgur.com/32L74.jpg


message:
Understanding writing to input pins and pull up resistors

I am new to Arduino, and am trying to understand the following code.  The question is: Is my understanding correct, or if not, what is happening here?

I have to reverse engineer an existing undocumented project, based on Marlin firmware for 3D Printers.  The relevant lines from the source are:

    #define DIO87_PIN               PINE2
    #define DIO87_RPORT             PINE
    #define DIO87_WPORT             PORTE
    #define DIO87_DDR               DDRE
    #define DIO87_PWM               NULL

    #define MASK(PIN)  (1 << PIN)
    #define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)
    #define TOGGLE(IO)  _TOGGLE(IO)

    TOGGLE(87);

1) Reducing this code gives me:
``DI087_RPORT = 1 << DI087_PIN``

2) Which reduces further to:
``PINE = 1 << PINE2``
3) Which reduces further to:
``PINE = 00000100``

4) I understand this to mean that we are setting Pin 2 of the Inputs Register (of Port E) to "High". (and are setting the other 7 pins to low)

5) I understand this to mean, as we are writing to an "Input", that we are enabling the internal pull-up resistor on Port E Pin 2.
(EDIT: I have made a mistake here in point 5: to enable a pull-up resister, you write to a pins OUTPUT register, not it's INPUT register. (but you must write to it's output register when it is in "input mode")

**Questions:**

 1. Is my understanding and work-through above correct?
 2. If yes, does this also mean that we are **also** disabling the pull-up resistors to the other 7 Input Pins at the same time?

I am confused by the "TOGGLE" code given above - it seems that it is "destructive" in the sense that by "toggling" the input resistor on one pin, you also *disable* the resistors on all other pins?  Would it not make more sense to just toggle the one pin with a bitwise ``or``.
e.g:
``PINE = PINE | 1 << PINE2``

body:
As noted in the *I/O-Ports – Introduction* section of the ATmega2560 datasheet,

>... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.

Pullups are on for an input bit when the data bit is high *and* the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.

Regarding the macro code, your reduction looks right.  But note that use of `_TOGGLE` as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783) for discussion.


body:
The feature is well documented in the datasheetss.

Just be aware that it is not available on all across chips.
Atmega8 for example is a notable exception.


body:
Now that I have improved my understanding, I provide a full answer here for completeness.

 1. To enable (or disable) a pull up resister, you write a 1 (or 0) to
    the PORTxn (data) register.
 2. Writing a 1 to a PINxn (input)register, toggles (bitflips) whatever value is in the PORTxn data register.
 3. Writing a 0 to PINxn does nothing, ever.
 4. The structure of the Macro means it is hardcoded to **only** write to a PINxn register - it is impossible (with this code structure) to call "TOGGLE" on a PORTxn (Data) register.
 5. Thus, this TOGGLE macro will never cause any issues, as writing zero's to PINx causes no action.

Specifically the answer is in the following two lines of code:

    #define DIO87_RPORT             PINE
    #define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)

(TOGGLE is hardcoded to use "DIO_XX_**RPORT**" which is **PINx**)


message:
Servo motor with 9V battery

I'm using servo motor in my Arduino based project, I've tried to provide servo with external power supply, So I've used 9v battery with IC7805 to step down to 5v,  but the motor is not working, so what should I do? FYI: I used the same battery with IC7805 to power IR proximity sensor which works fine.

body:
A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.

Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.

Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.

A 7805 has a high dropout voltage and is out of place in a battery powered system.


message:
ESP01 flashing error

I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer.
I have removed the ATmega and grounded the RESET pin (quite useless without the uC though).
Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:

    python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

However, both ways give me the same output:

    A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.

I also followed esp8266 [official forum][1] advice to edit the Python script according to the following, but without success.

    Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
    Line 44 ESP RAM BLOCK = 0x400 //change this to 40

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

[![Wiring][2]][2]

  [1]: http://www.esp8266.com/viewtopic.php?f=6&t=442&start=16
  [2]: https://i.stack.imgur.com/LIZJ0.png

body:
Your wiring sounds wrong.

Tie CHPD to Vcc (3.3v) to enable the device.

Tie GPIO0 to ground as you power up, to put it into programming mode.

RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.

That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.


body:
An addition to Mark's answer, from https://arduino.stackexchange.com/questions/17571/uploading-sketch-to-esp8266

> Before download, pull both GPIO0 and RST to ground. Release the pull
> down on RST, but keep GPIO0 low. When the IDE has finished uploading,
> release GPIO0 from low.


message:
Can I safely power my UNO and DC motors with the 5v1A and 5v2.1A ports on a USB charger?

I have USB charger battery pack with two output ports ([Fremo C510][1]).  One is marked as 5 volts 1 amp, and the other as 5 volts 2 amps.

I'm building a toy robot and would like to run the UNO off of one of those ports, and the motors off of the other.

Can I safely do that?  I have two main concerns:

 - Can I safely power the arduino with that current?
 - If I power both the motors and the arduino from that source (two usb ports connected to the same battery), will I still have to worry about spikes from switching the motors on and off?  I don't know how those ports are wired to the actual battery inside.

  [1]: https://www.newegg.ca/Product/Product.aspx?Item=N82E16875790001

body:
You can power the Arduino from either side, since it will only draw what it needs, and most arduinos are powered from a .5 amp USB port. But you'll want to reserve the higher current side for the motors.

Make sure your motors' total draw (including starting current) doesn't exceed the 2 amps available.

Unless you can find out for sure that the two power ports are isolated from one another, you're better off to assume they are not and provide motor spike damping yourself.


message:
Problem sending data from arduino with ESP8266 to a local mysql database

i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.

Arduino Code:

    #include <ESP8266WiFi.h>

    const char* server = "192.168.1.106";
    const char* ssid = "DARUSALAM C8";
    const char* password = "asro4520";
    const char* SensorID = "ESP001";

    WiFiClient client;

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

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

      WiFi.begin(ssid, password);
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.print(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi Connected");
    }

    void loop() {
    float n = random(300);

    Serial.print("Random Number: ");
    Serial.println(n);

      if (client.connect(server,80)) {
        Serial.print("Posting data...");
        digitalWrite(BUILTIN_LED, LOW);
        Serial.println("Random Number: " + String(n));
        client.println("GET /log.php?n=" + String(n));
        client.println("HOST: ");
        client.println(server);
        client.println("Connection: close");
        client.println();

        client.stop();
        Serial.println();

        digitalWrite(BUILTIN_LED, HIGH);
      }

      delay(5000);
    }

PHP code:

    <?php

    $db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
    if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

    $n = $_REQUEST['n'];
    if (!empty($n) &&)
    {
      $s = "insert into data_random set value1='$n'";
      $r = mysqli_query($db_amb, $s);
      echo "OK";
    }
    else echo "ERR";
    ?>;

The database is named 'wemos', and the table where i intend to store the data is named 'data_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.

**EDIT** the problem i encountered is whenever i checked `http://localhost/log.php` this appears:

    Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

body:
The `HOST` should not have a newline after it, so you should have

    client.print("HOST: ");
    client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the `&`s here are left over from something you have removed, and causing syntax errors - just remove them

    if (!empty($n) &&)

I believe your `n` parameter is going to be in `_GET` (not `_REQUEST`).  Also, you should check whether it's there, not just assume it is, so:

    if isset ( $_GET["n"] )
    {
        $n = $_GET["n"];
        // Do your database stuff here
    }

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)


body:
Change this:

    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);

To this:

    client.print("GET /log.php?n=" + String(n));
    client.println( " HTTP/1.0" );
    client.print("Host: ");
    client.println(server);

This means you're sending the `Host:` header + value on one line, and you're correctly appending the ` HTTP/1.0\n` after your URL-request.


message:
I2C Arduino ESP8266 Bad Reading

I have a NodeMCU, which I program with the Arduino IDE. I have connected a VOC sensor to pins D1, D2, which are the SLC/SDA pins for NodeMCU. They have pull-up resistor at 4,3kohm to 3.3V.

First I used I2C scanner code, provided by Arduino, and got a response that I have the sensor connected at address 0x70, which is the correct address, indicated on the datasheet for the sensor.

After I tried to read values from the sensor with command 0b00001001 (provided in the datasheet also), I only get 0s as output! Probably something weird in the coding, perhaps someone could assist me in what I am doing wrong here?

In the code, I request 100 bytes just to make sure to get everything, but I receive only 32 back. The datasheet says it should be 6 bytes on address 0x9. And I have tried hex and dec form but that doesn't work. Binary is the proper way I assume.

My Output:

    Start
    Bytes Available: 32
    Data read: 00000000000000000000000000000000

Code:

    #include <Wire.h>

    int miscadr = 0b1110000;

    void setup() {
      Serial.begin(115200);
      Wire.begin();
      delay(100);
    }

    void loop() {
      Serial.println();
      Serial.print("Start");
      Serial.println();
      Wire.beginTransmission(miscadr); //Start bit
      Wire.write(0b00001001); //Asking for registry 9
      Wire.endTransmission();
      Wire.requestFrom(miscadr, 100);
      Serial.print("Bytes Available: ");
      while(Wire.available()==0);
      Serial.print(Wire.available());
      Serial.println();
      Serial.print("Data read: ");
      while(Wire.available()!=0) {
        Serial.print(Wire.read());
      }
      Serial.println();
      delay(2000);
    }

body:
Which VOC sensor is it ? I like to see the datasheet myself. My crystal ball tells me it is a MiCS-VZ-86/89. When the i2c scanner finds address 0x7, then you should use 0x7. In your sketch the miscadr is now 0x70.

The read and write bit is taken care of by the Wire library. You could print the return value of Wire.endTransmission and Wire.requestFrom. The Wire.endTransmission  returns an error and the Wire.requestFrom returns the number of read bytes. Those return values can tell if the I2C transaction was wrong.

There is no need for a while-loop to wait for data after the Wire.requestFrom. You can remove that first while statement.

You can not request 100 bytes. The Wire library has a buffer of 32 bytes.

When you use the term "address", please use "i2c address" or "register address".

The Wire.requestFrom reads bytes from the Slave (the VOC sensor), but the sensor can not stop the I2C transaction after 6 bytes. The Master (the ESP8266) should set the number of bytes to read. If you need only 6 bytes, then you should read only 6 bytes.


body:
If your ESP8266 device NodeMCU is not using the Arduino ESP8266 Library standard pins for I2C ( SDA=2, SCL=14) then you must change the Wire.begin() statement to Wire.begin(SDA, SCL) inserting your values for the SDA and SCL pins. See this note for another ESP breakout (Sparkfun) [Arduino ESP8266 Wire][1]

  [1]: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/using-the-arduino-addon


message:
Is my arduino board broken?

Last night I had my arduino connected to pc and mc connected to 9 volts in the same time then today I tried to connect my arduino to pc and i removed any connection i just wanted to display a string it i used this code

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

       void loop() {

        Serial.print("NO FORMAT");
         }

its not showing anything in serial montor I tried to blink led no output still

And  i have another arduino i used the same code it showing the message in serial monitor is my previous board broken ? thank you for help when i tried to click the reset button in arduino the orang led built in is not blinking

body:
I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.

If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.

Few ideas for voltage levels:

 1. Voltage on "main" ATMega328 (You can check it through ISP header)
 2. Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
 3. Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.

If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


message:
esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE

I've uploaded a sketch from the Arduino IDE to my (Amica) esp8266-12e board with the sketch data upload tool (ESP8266FS). This goes without any errors or problems. However, the code is never executed, it's like that the code isn't even on the board, it does nothing. I've tried flashing the firmware several times but this does not help. Depending on the installed firmware I get different messages on the serial monitor such as

    NodeMCU 0.9.5 build 20150318  powered by Lua 5.1.4
    lua: cannot open init.lua

or

    Ai-Thinker Technology Co.,Ltd.
    invalid

So installing different kinds of firmware is not the problem here. What did I do wrong which causes the board to 'ignore' the uploaded data sketch?

body:
It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: [ESP8266FS][1]

  [1]: https://github.com/esp8266/arduino-esp8266fs-plugin


message:
NodeMCU Light Sensor

I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).

I've successfully printed from a single light sensor but now I'd like to try three.

I'm curious to know what I'm missing.  Any guidance would be appreciated.

Code is as follows:

    const int photocellPin_0 = 16; // D0
    const int photocellPin_1 = 5; // D1
    const int photocellPin_2 = 4; // D2
    int photocellReading_0;
    int photocellReading_1;
    int photocellReading_2;

    void setup() {
      delay(4900);
      Serial.begin(115200);
      Serial.println("Startup");
      delay(100);
      pinMode(photocellPin_0, INPUT);
      pinMode(photocellPin_1, INPUT);
      pinMode(photocellPin_2, INPUT);
    }

    void loop() {
      delay(1000);
      photocellReading_0 = analogRead(photocellPin_0);
      photocellReading_1 = analogRead(photocellPin_1);
      photocellReading_2 = analogRead(photocellPin_2);
      Serial.println("-----NEW ON READING-----");
      Serial.print("Photo Sensor #1 = ");
      Serial.println(photocellReading_0); // the raw analog reading
      Serial.print("Photo Sensor #2 = ");
      Serial.println(photocellReading_1);
      Serial.print("Photo Sensor #3 = ");
      Serial.println(photocellReading_2);
      delay(5000);
    }

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.

body:
The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).

digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.

You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.

The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts


message:
How to send sensor data from Arduino through NRF24L01 to Raspberry Pi

>I am able to send text from the Arduino wirelessly to RPi.  I am now trying to send the sensor data I'm measuring to the Pi.  This is what I have below:

    int moisture = A0;
    int temp = 3;

    //Skipping the setup and reading of the values

    radio.write(&moisture);
    radio.write(&temp);

    //the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

body:
As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the `write()` method accepts (or requires) a second parameter, `len`, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.

Either of those cases could produce erratic results.

Instead of leaving off the second parameter, specify it.  For example:

    radio.write(&moisture, 2);
    radio.write(&temp, 2);


body:
I recommend you to choose a platform for communication. You don't need to deal with the low level communication.
I suggest you to try https://www.mysensors.org/ It helps to wire your sensors, gives you example codes for the chosen sensors for data transfer in the direction to your Pi. There is a well documented API you can build your application on.
On the Pi you can use a serial gateway or/and a controller installed. These controllers are written to communicate with your sensors and other nodes. They give graphical web interface to visualize your data and their history. For a controller I recommend to start with https://www.domoticz.com/ or Openhab I think Domoticz is the better choice to start with on Pi.


body: most likely is that your nrf24l01 library only allow text or string communcaiton, not nuermical data.  when you send your measured data, nrf24l01 treats it as text.  so what you read is text (text's unicode numbers).  I encountered the same problem.


body: I will suggest you to provide valid size of data with write function for eg radio.write(&moisture,sizeof(moisture)). hope this will work for further explanation of this method www.robofever.in


message:
How to concatenate strings

I am new to the Arduino platform so please bear with me. I have a program to display rolling text on a LED matrix which is for the Tinyduino platform

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

    #include "Charliplexing.h"
    #include "Font.h"
    #include "Arduino.h"

    void setup()
    {
      LedSign::Init();
    }

    static char test[]="HELLO";

    void loop()
    {
      for (int8_t x=DISPLAY_COLS, i=0;; x--) {
        LedSign::Clear();
        for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
          int8_t w = Font::Draw(test[i2], x2, 0);
          x2 += w, i2 = (i2+1)%strlen(test);
          if (x2 <= 0)  // off the display completely?
            x = x2, i = i2;
        }
        delay(80);
      }
    }

Then I have some code to read temperature and humidity data for the same Tinyduino platform

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

    #include <Wire.h>
    #include <SI7021.h>

    SI7021 sensor;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      Serial.print("Initializing sensor... ");
      if(!sensor.begin()){
        Serial.println("Sensor not found!");
        while(true);
      }
      Serial.println("Success!");
    }

    void loop()
    {
      int celcius=sensor.getCelsiusHundredths()/100;
      int relativeHumidity=sensor.getHumidityPercent();
      Serial.print(celcius);
      Serial.print(" deg Celsius\t");
      Serial.print(relativeHumidity);
      Serial.println("% relative humidity");

      delay(500);
    }

I am trying to integrate this together so that Arduino reads the temperature and humidity sensor data and then displays it on the LED matrix as text. I have some code that is integrated from the above two examples

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

    #include "Charliplexing.h"
    #include "Font.h"
    #include "Arduino.h"
    #include <Wire.h>
    #include <SI7021.h>

    SI7021 sensor;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      Serial.print("Initializing sensor... ");
      if(!sensor.begin()){
        Serial.println("Sensor not found!");
        while(true);
      }
      Serial.println("Success!");
      LedSign::Init();
    }

    static char test[100]="";

    void loop()
    {
      int celcius=sensor.getCelsiusHundredths()/100;
      int relativeHumidity=sensor.getHumidityPercent();
      test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

      for (int8_t x=DISPLAY_COLS, i=0;; x--) {
        LedSign::Clear();
        for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
          int8_t w = Font::Draw(test[i2], x2, 0);
          x2 += w, i2 = (i2+1)%strlen(test);
          if (x2 <= 0)  // off the display completely?
            x = x2, i = i2;
        }
        delay(80);
      }
      delay(500);
    }

Here is the error message that the IDE throws out

    test:28: error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

     test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";
                                 ^

    Using library LOL in folder: C:\Program Files (x86)\Arduino\libraries\LOL (legacy)
    Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
    Using library Temp in folder: C:\Program Files (x86)\Arduino\libraries\Temp (legacy)
    exit status 1
    invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Any suggestions on how to resolve this error is welcome.

body:
You cannot "add" character arrays like that. You may try to use a
`String` object instead, as these do support the `+` operator as a way
to concatenate them:

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

    String message = (String(celcius) + " deg Celcius, "
                   + relativeHumidity + " relative humidity");
    const char *c_message = message.c_str();

And then you use `c_message` in place of your `test` variable.
Note that only the first element (`celcius` here) needs to be explicitly
converted to a `String` object. The other conversions happen implicitly.

**Edit**: Updated the code to avoid using the internal state of a
(possibly destroyed) temporary object.


body:
You can use sprintf to format a string.

You have to change:

    test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

for

    sprintf(test,"%d deg celsius %d relative humidity",celcius,relativeHumidity);


message:
Powering Arduino Mega 2560 from a Raspberry Pi Usb

I have a Raspberry Pi B+ running 7x24. I have to connect an Arduino Mega 2560 to its USB. The Arduino has only one nRF24L01-PA-LNA powered from its 3V3.
Can I power the Arduino from the Pi's USB?

body:
If you are powering your RPi from power supply 5V/2A at least there should be no problem. USB hub on the RPi should not give more than 500mA to power Arduino. Also there is a fuse on Arduino's board to prevent any damage from USB power.

Check both Arduino and RPi schematics for more details about modules used there:

 - [Arduino]
 - [Raspberry]

[Arduino]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf
[Raspberry]: https://datasheets.raspberrypi.com/rpi3/raspberry-pi-3-b-reduced-schematics.pdf


body: raspberry pi can power ur mega board normally,but the 3v3 in the mega board is not stable and has noise,so it is better to use 3v3 supply source for ur NRF the simplest to use is just hooking a piece of 1117 to 5v of ur mega board


body: Yeah, as the others have mentioned you can power the Arduino form the raspberry pi's power supply, but you cannot transit data from the raspberry to the Arduino without a third party software.


message:
Arduino for push notifications to phone

I'm interested in using an Arduino for a project for taking information and sending it through a phone application. I was wondering what the cheapest option there is for an arduino with internet capabilities. From what I see, a lot of articles list they use UNOs with shields for wifi/ethernet. After looking these up, I noticed that they can get a little pricey. Is there any alternative options I may be overlooking? Thanks.

body: You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.


message:
Does Arduino sent output to TX pinout?

I am beginner at Arduino,i tried to read as much as i can but i am not sure if i am doing good.I would like to send a specific code for a (non PC) device through the TX pinout when i push the button which is wired to the Pin 2.I have writtem this small code to check it:

    int buttonUPpin = 2;
    int UpinStatus=LOW;

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

    }

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

    UpinStatus=digitalRead(buttonUPpin);

    if(LOW==UpinStatus)
    {
    Serial.print('A');
    digitalWrite(1,LOW);

    }

    }

When i push the button i can see at serial monitor the 'A' character but i am not sure if this character was also sent out to the TX pinout since the TX led is not blinking only the RX led.

body:
You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).

    #define buttonUPpin = 2;
    #define LedPin = 3;
    int UpinStatus = LOW;

    void setup()
    {
        Serial.begin(9600);
        pinMode(buttonUPpin, INPUT_PULLUP);
        pinMode(LedPin, OUTPUT);
        // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

    }

    void loop()
    {
        UpinStatus=digitalRead(buttonUPpin);
        if(LOW==UpinStatus)
        {
           Serial.print('A');
           digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
        }
    }


body:
If you start the `Serial` it takes over the `TX` and `RX` pins and it ignores pin mode settings (and `digitalWrite` too).

Btw `TX` and `RX` LEDs are driven by USB to Serial interface chip so you don't have any control of it either.


message:
Time displays on serial monitor but not my LCD

#include <TimeLib.h>
    #include <Wire.h>
    #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

    #define PIN_SCE   7
    #define PIN_RESET 6
    #define PIN_DC    5
    #define PIN_SDIN  11
    #define PIN_SCLK  13

    #define LCD_COMMAND    LOW
    #define LCD_DATA     HIGH

    #define LCD_X     84
    #define LCD_Y     48

    String now_time;
    char printTime;

    void gotoXY(int x, int y) {
      LCDWrite(0, 0x80 | x);  // Column.
      LCDWrite(0, 0x40 | y);  // Row.  ?
    }

    //This takes a large array of bits and sends them to the LCD
    void LCDBitmap(char my_array[]){
      for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
        LCDWrite(LCD_DATA, my_array[index]);
    }

    //This function takes in a character, looks it up in the font table/array
    //And writes it to the screen
    //Each character is 8 bits tall and 5 bits wide. We pad one blank column of
    //pixels on each side of the character for readability.
    void LCDCharacter(char character) {
      LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding

      for (int index = 0 ; index < 5 ; index++)
        LCDWrite(LCD_DATA, ASCII[character - 0x20][index]);
        //0x20 is the ASCII character for Space (' '). The font table starts with this character

      LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
    }

    //Given a string of characters, one by one is passed to the LCD
    void LCDString(char *characters) {
      while (*characters)
        LCDCharacter(*characters++);
    }

    //Clears the LCD by writing zeros to the entire screen
    void LCDClear(void) {
      for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
        LCDWrite(LCD_DATA, 0x00);

      gotoXY(0, 0); //After we clear the display, return to the home position
    }

    //This sends the magical commands to the PCD8544
    void LCDInit(void) {

      //Configure control pins
      pinMode(PIN_SCE, OUTPUT);
      pinMode(PIN_RESET, OUTPUT);
      pinMode(PIN_DC, OUTPUT);
      pinMode(PIN_SDIN, OUTPUT);
      pinMode(PIN_SCLK, OUTPUT);

      //Reset the LCD to a known state
      digitalWrite(PIN_RESET, LOW);
      digitalWrite(PIN_RESET, HIGH);

      LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
      LCDWrite(LCD_COMMAND, 0xAF); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
      LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
      LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14

      LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
      LCDWrite(LCD_COMMAND, 0x0C); //Set display control, normal mode. 0x0D for inverse
    }

    //There are two memory banks in the LCD, data/RAM and commands. This
    //function sets the DC pin high or low depending, and then sends
    //the data byte
    void LCDWrite(byte data_or_command, byte data) {
      digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command

      //Send the data
      digitalWrite(PIN_SCE, LOW);
      shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
      digitalWrite(PIN_SCE, HIGH);
    }

    void setup(void) {
       LCDInit();
       LCDClear();
       Serial.begin(9600);
       while (!Serial) ; // Needed for Leonardo only
       setSyncProvider(RTC.get);   // the function to get the time from the RTC
       if (timeStatus() != timeSet)
         Serial.println("Unable to sync with the RTC");
       else{
         Serial.println("RTC has set the system time");
          digitalClockDisplay();
       }
    }

    void loop(void) {
      if(timeStatus() == timeSet)
      {
        delay(1000);
        digitalClockDisplay();
      }
    }
    void digitalClockDisplay(){
      // digital clock display of the time
      if(minute() < 10)
      {
        now_time = String(hour()) + ":0" + String(minute());
      }
      else if(minute() >= 10){
        now_time = String(hour()) + ":" + String(minute());
      }
      Serial.println(now_time);
       LCDClear();
       LCDString("Time: ");
       for(int i = 0; i <= now_time.length()-1; i++)
       {
          printTime = now_time.charAt(i);
          LCDString(printTime);
       }

    }

    void printDigits(int digits){
      // utility function for digital clock display: prints preceding colon and leading 0
      LCDString(":");
      if(digits < 10)
        LCDString('0');
      LCDString(digits);
    }

When I run the code the time will display perfectly on the Serial Monitor but when I connect it to my Nokia LCD screen the words "Time: " will appear along with some random characters. Anyone know why this is?

body:
I assume you are writing now_time one Char at a time because the LCD library does not accept the String object as input? LCDString assumes you will pass a C-style string -- that is a pointer to an array of char. When you pass in one character, it's not a pointer to a C-style string, but the LCDString function is assuming that it's a pointer to some bit of memory elsewhere.

Try not sending one Char at a time, but:

    LCDString(now_time.c_str());


message:
Seven segment display multiplexing

I have written a code that displays a number into a seven segment display without manually setting the Arduino pins HIGH/LOW for each number. Now, my problem is how can I display a number larger than 9? This is my code and it works for only 1 digit number: (The seven segment display truth table is inverted because I'm using common anode 7seg)

    #define SEG_A 2
    #define SEG_B 3
    #define SEG_C 4
    #define SEG_D 5
    #define SEG_E 6
    #define SEG_F 7
    #define SEG_G 8
    #define DEC_P 12

    #define SET1 9 // [!][!][x]
    #define SET2 10// [!][x][!]
    #define SET3 11// [x][!][!]

    struct segmentmap {
      uint8_t num;
      const int segment[7];
    };

    const struct segmentmap segments[] = {
      // n   A  B  C  D  E  F  G
      {0, {0, 0, 0, 0, 0, 0, 1}},
      {1, {1, 0, 0, 1, 1, 1, 1}},
      {2, {0, 0, 1, 0, 0, 1, 0}},
      {3, {0, 0, 0, 0, 1, 1, 0}},
      {4, {1, 0, 0, 1, 1, 0, 0}},
      {5, {0, 1, 0, 0, 1, 0, 0}},
      {6, {0, 1, 0, 0, 0, 0, 0}},
      {7, {0, 0, 0, 1, 1, 1, 1}},
      {8, {0, 0, 0, 0, 0, 0, 0}},
      {9, {0, 0, 0, 1, 1, 0, 0}}
    };

    void setup() {
      Serial.begin(9600);
      for (int x = 2; x <= 8; x++) {
        pinMode(x, OUTPUT);
        Serial.print("Segment pin: ");
        Serial.print(x);
        Serial.println(" is set to OUTPUT mode.");
        digitalWrite(x, HIGH);
      }
      pinMode(DEC_P, OUTPUT);
      pinMode(SET1, OUTPUT);
      pinMode(SET2, OUTPUT);
      pinMode(SET3, OUTPUT);
      digitalWrite(SET1, 1);
    }
    int x = 0;
    void loop() {
      if (x > 9) {
        x = 0;
      }
      updateDisplay(x);
      delay(1000);
      x++;
    }

    void updateDisplay(int input) {
      for (int x = 0; x <= 9; x++) {
        //Serial.println(segments[x].num);
        if (segments[x].num == input) {
          Serial.println(segments[x].segment[0]);
          ////////////Simplify this part//////////////
          digitalWrite(SEG_A, segments[x].segment[0]);
          digitalWrite(SEG_B, segments[x].segment[1]);
          digitalWrite(SEG_C, segments[x].segment[2]);
          digitalWrite(SEG_D, segments[x].segment[3]);
          digitalWrite(SEG_E, segments[x].segment[4]);
          digitalWrite(SEG_F, segments[x].segment[5]);
          digitalWrite(SEG_G, segments[x].segment[6]);
          ////////////////////////////////////////////
          //Multiplex here?//
        }
      }
    }

body:
> my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.

your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.


body:
It looks like you are using a 3 digit common anode display.
If your code currently works, fixed to display something on digit 0, then you could get it working for all 3 digits by adding/updating the following:

    // globals:
    byte display_buffer[3] ;  // representation of the display which you can change in loop()
    byte anode_map[3] = { 9, 10, 11 } ;  // anode pins

    void loop() {
      if (millis() % 5 == 0 ) updateDisplay();  // every 5mS - better to use a timer
      if ( millis() % 1000 == 0) {  // every second
        if (x > 9) {
          x = 0;
        }
        display_buffer[0] = x ;  // just for testing
        display_buffer[1] = (x + 11) % 10 ;
        display_buffer[2] = (x + 12) % 10 ;
        x++;
      }
    }

    void updateDisplay() {
       // called every x Ms preferably with a timer
       // selects next item from display_buffer_ptr and displays it
       //
       static byte display_buffer_ptr ;
       display_buffer_ptr ++ ;
       if ( byte display_buffer_ptr > 2 ) display_buffer_ptr = 0 ;
       int input = display_buffer[display_buffer_ptr] ;
       for ( int i = 0 ; i < 3 ; i++ ) {
           digitalWrite( anode_map[i], ( i == display_buffer_ptr ) ) ;  set current anode HIGH, rest LOW
       }
       // rest of your code to display the value of input

    }

This is not the most elegant solution but involves minimal changes to your code.
It is more usual to use an array of byte for the mapping digits to segments.
You may have to optimise the switching of the anodes to stop ghosting.


message:
Ethernet Shield - Multiple simultaneous connections cause TCP reset

I have a very inconvenient problem with a web server I'm writing for a Arduino Mega 2560 with a W5100 Ethernet Shield (with the "official" Ethernet lib). I wrote the server code and it works like a charm, BUT there is a condition, when the server won't accept all the TCP handshakes and resets the TCP connections:
When I load a big webpage, the browser (Firefox and Chrome too) asks for the .htm first, then collects the links in the file and request them all simultaneously and that's when I got the problem:

The server gets multiple TCP connections but it only accepts the first, then dumps all the others (by TCP reset). After that the client sends them again and the problem starts again: the server accepts the first and drops the others. And so on, for example if the browser needs 3 files, it will take ~9 seconds, because of the retransmission delay. (3 + 6 seconds) Eventually the webpage will load, but a 10 second delay is not acceptable.
Is there any way to cache the requests on the Ethernet Shield or to tell the browser to wait a bit between requests or any other way, to wait a bit for the Arduino to finish the previous request?

Snippet for the server, Wireshark and Chrome network data: https://gist.github.com/anonymous/181f359b70d69e4470931204c4ec175c

Thanks for the help!

G.

body:
*I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.*

---

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page [Arduino Ethernet Shield 2](https://www.arduino.cc/en/Main/ArduinoEthernetShield) we learn:

> It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.

Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

I did a post about [a tiny web server for the Arduino](http://www.gammon.com.au/forum/?id=12942) which uses a state machine to handle incoming data without blocking.

---

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.

    Connection: keep-alive

That might stop the client opening new connections in quick succession.


message:
Buffering output stream

I'm looking to toggle a pin on and off in a fast and timing-sensitive manner, and I'm wondering if the Arduino Uno has any built in "buffers" that would be able to hold a set of values and send them sequentially to the output pin at high speed, separately from the rest of the loop. I could then refill the buffer with the next set to be outputted, and so on.
Is this even possible? If anyone has any documentation on what's involved, I'd really appreciate some links (or tips!) :) thanks

body:
The closest thing to what you describe is DMA (Direct Memory Access). The Arduino doesn't have DMA. More powerful microcontrollers often do, but not little 8 bit ones.

The closest you could do is to use a timer interrupt to run a small function periodically which reads the next value from an array and sets the pin to that state.

The [TimerOne or TimerThree](http://playground.arduino.cc/Code/Timer1) libraries can be of help to you here.


body:
For most Arduino devices, using the USART in SPI mode is about the most effective way to generate a hardware-timed stream of bits out of one pin.  For background, see §21, “USART in SPI Mode”, in the ATmega328 data sheet.  For some example code and exposition, see [ATmega Arduino USART in SPI Master Mode MSPIM,
Posted on February 17, 2015 by feilipu](https://feilipu.me/2015/02/17/avr-atmega-usart-spi-mspim/).

Ordinary SPI output on most Arduinos is single-buffered, hence subject to occasional delay if other interrupts get in the way of the SPIF-SPIE-SPDR interrupt handler.  However, the USART-in-SPI-mode method double-buffers output as well as input, allowing continuous data output.  That is, one can generate a continuous stream of bits clocked out at whatever rate one selects.

The [Arduino Due](https://www.arduino.cc/en/Main/arduinoBoardDue) is based on the Atmel SAM3X8E ARM Cortex-M3 CPU, a 32-bit ARM core microcontroller.  It supports DMA (direct memory access) and one can find webpages, eg [arduino.cc topic 219291](http://forum.arduino.cc/index.php?topic=219291.0), describing waveform generation using DMA and the 12-bit DAC (digital to analog converter) on the Due.  More notably, the Arduino software compatible [Teensy 3](https://www.pjrc.com/teensy/) series uses Cortex-M4 and M4F chips on boards running at 48, 72, 120, and 180 MHz, probably more suitable for elaborate waveform generation than are the Due or Zero.


message:
Using PROGMEM in constructor

Is it safe to use PROGMEM variable like dynamically allocated memory (a pointer to PROGMEM variable which is out of scope).

I need this so I can generate a variable size (before compilation), constant values, lookup array stored in flash.

Working example:

    class Ex_class {
      public:
        Ex_class(int table_size, int value_range) {
          int flash_table[table_size + 1] PROGMEM;
          _ex_table = flash_table;
          for (int i = 0; i <= table_size; i++) {
            _ex_table[i] = random(value_range);
          }
        }

        int get_value(int index) const { return _ex_table[index]; }

      private:
        int* _ex_table;
    };

    void setup() {
      randomSeed(analogRead(0));
      Serial.begin(9600);
      Ex_class ex_object(5, 50);
      for (int i = 0; i <= 5; i++) {
        Serial.print(i); Serial.print(": "); Serial.println(ex_object.get_value(i));
      }
    }

    void loop() {}

body:
The closest I could get to what you are trying to do is this:

    template <size_t table_size> struct Ex_class {
      int get_value(int index) const {
        return pgm_read_word(&_ex_table[index]);
      }
      int _ex_table[table_size];
    };

    void setup() {
      Serial.begin(9600);
      static PROGMEM const Ex_class<5> ex_object = {1, 2, 3, 4, 5};
      for (int i = 0; i < 5; i++) {
        Serial.print(i);
        Serial.print(": ");
        Serial.println(ex_object.get_value(i));
      }
    }

    void loop() {}

`avr-nm` and `avr-objdump` confirmed that the object lives indeed in the
text section of the program. Please note that:

* The object is `PROGMEM const`. It would make no sense to try to put in
  PROGMEM anything that is not constant.

* The object is allocated statically. It can be either a global or a
  static local, but not an automatic local like in your example.

* I am using [aggregate initialization][] here. I know no other way to
  statically initialize an array of variable length. If you have an
  idea, I would be interested to know though.

[aggregate initialization]: http://en.cppreference.com/w/cpp/language/aggregate_initialization


message:
Unable to connect Arduino Uno to Ubuntu 16.04

I've received an Arduino Uno today only. I have zero experience prior to Arduino boards or any other micro controller. I followed every step very carefully from the setting up guide for Linux based OS, but I still can't connect the board with my Ubuntu 16.04 PC. After googling the problem I found that the device must show up as `ttyACM*` but I don't see any such device in `/dev`. Its also not listed under the command `lsusb` but the LED's on the board are working properly. The ON LED is turned on when I connect it with my PC and the inbuilt LED starts to blink.

This is what the IDE displays:

[![Arduino IDE][1]][1]

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

body:
You may have to add yourself to the dialout group in Ubuntu so that your user account can access the serial ports.

Then, in the Arduino IDE, the Tools->Port menu should show you options. Right now, the screenshot you gave shows that it's set for COM1, which is a Windows-style serial port naming and definitely won't work on Ubuntu.


message:
Sending values from Matlab to arduino using serial communication

I want to send numeric value from matlab to arduino but code is not working.

Matlab code is as:

    doi = 3 ;
    arduino=serial('COM5','BaudRate',9600); % create serial communication object
    fopen(arduino); % initiate arduino communication
    fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
    fclose(arduino);

Arduino code is as:

      int solenoidPin = 13; //This is the output pin on the Arduino
    int doi;

    void setup()
    {
      Serial.begin(9600);
      //pinMode(13, OUTPUT);
      pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
    }
    void loop()
    {

      if(Serial.available()>0)
      {

        doi = Serial.read();
        //Serial.println(doi);
        //Serial.println("\n");
        //doi = doi - 48;
       if (doi == 1)
       {
        //Serial.println(1);
        digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
        delay(1000); //Wait .15 Second
         digitalWrite(solenoidPin, LOW);
        }
      else if (doi == 2)
        {
         //Serial.println(2);
        digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
        delay(2000); //Wait .165 Second
        digitalWrite(solenoidPin, LOW);
        }
      else
        {
          //Serial.println(3);
          digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
          delay(3000); //Wait .180 Second
          digitalWrite(solenoidPin, LOW);
        }

      }
    }

 I used str2num(doi) also instead of `fprintf(arduino, '%s', char(doi))` but no output.

Please give suggestion to correct this.

Thanks.

body:
You send a string of ASCII characters representing a number in human readable format.

You then read one of those characters that represents a single digit and then try and use it as if it were a number.

Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.


body:
fopen(arduino); takes some time to initialize the serial connection so you should use pause(2); after fopen(arduino); and in fprintf() send doi as interger i.e. fprintf(arduino, '%i', doi);. Suppose the doi is 1 then code would be as

    doi = 1;
    arduino=serial('COM5','BaudRate',9600); % create serial communication object
    fopen(arduino); % initiate arduino communication
    pause(2);
    fprintf(arduino, '%i', doi); % send answer variable content to arduino
    fclose(arduino);

Another modification required in arduino program as

    doi = doi - 48;

Uncomment this line inside if(Serial.available()>0) block.


message:
Carry out two consecutive tasks when a button is pressed

I'm building a project that has 2 motors. What I want to do is:
When button is pressed (hold down through RF controller) then:

1. Run motor A on pwm at 50 for 1 second
2. Run motor B on pwm at 255 for 1 second

After that first second

3. Run motor A on pwm at 255 until button is released
4. Stop motor B.

And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.

I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.

Here is my code:

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include <elapsedMillis.h>

    // Motor 1
    int dir1PinA = 4;
    int dir2PinA = 5;
    int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed

    // Motor 2
    int dir1PinB = 7;
    int dir2PinB = 8;
    int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed

    int msg[1];
    RF24 radio(9,10);
    const uint64_t pipe = 0xE8E8F0F0E1LL;

    unsigned long previousMillis = 0;
    long OnTime1 = 500;
    long OnTime2 = 10000;

    void setup(){
     Serial.begin(9600);
     radio.begin();
     radio.openReadingPipe(1,pipe);
     radio.startListening();

     pinMode(dir1PinA,OUTPUT);
     pinMode(dir2PinA,OUTPUT);
     pinMode(speedPinA,OUTPUT);

     pinMode(dir1PinB,OUTPUT);
     pinMode(dir2PinB,OUTPUT);
     pinMode(speedPinB,OUTPUT);

     }
     void CandPush()
     {
              analogWrite(speedPinA, 50);//Sets speed variable via PWM
              digitalWrite(dir1PinA, HIGH);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinB, LOW);
              digitalWrite(dir2PinB, HIGH);

     }
     void CandStop()
     {
              analogWrite(speedPinA, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinA, HIGH);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 0);//Sets speed variable via PWM
              digitalWrite(dir1PinB, LOW);
              digitalWrite(dir2PinB, LOW);

     }
     void Home()
     {
              analogWrite(speedPinA, 0);//Sets speed variable via PWM
              digitalWrite(dir1PinA, LOW);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinB, HIGH);
              digitalWrite(dir2PinB, LOW);

     }
     void loop(){

     if (radio.available()){
        bool done = false;
        while (!done){
        done = radio.read(msg, 1);
        Serial.println(msg[0]);
        if (msg[0] == 111)
        {
          unsigned long currentMillis = millis();
          CandPush();
          if(currentMillis - previousMillis >= OnTime1)
          {
            CandStop();
            previousMillis = currentMillis;
          }

        }
     }
     }

     else
     {
      Home();
      Serial.println("Nothing");
     }
     }

body:
I assume pressing the button results in msg[0] == 111 every time you do the radio.read (i.e. it will continue sending that while the button is held).  If so, the first issue I see is that after 500ms has elapsed, you will call CandStop(), and then it will loop back and immediately call CandPush(), essentially cancelling the second state.

I think you should create a state variable and state machine, so for example it does a different operation when/while the button is pressed depending on whether it is in the 'home', 'push', or 'stop' state.  In the first ('home') state it is waiting for the button to be pressed, in the second ('push') state it is waiting for the time to elapse, and in the third ('stop') state it is only waiting for the button to be released.  It would also allow you to avoid repeatedly calling CandPush() and Home() when it only needs to be called once (when the button is pressed).

EDIT:
I am adding the code below.  This hasn't been tested so there may be some bugs but it should give an idea of what I mean.  It could probably also be optimized somewhat, but I tried to make it do what I think you wanted it to do based on the code you attached.

There are parts in there that I doubt work as you wanted, aside from the button handling, for example how Home() is called whenever there is no radio available and how nothing appears to happen when the button is released.

Should the Home() call really set B to full output?  I added a call to StopAll which I assumed you would use to stop A and B when the button is released.

Also radio.read doesn't return anything, so done = radio.read(...) is pointless.

    // State machine states
    enum {
        STATE_INIT,
     STATE_HOME,
     STATE_PUSH,
     STATE_STOP
    };

    unsigned long previousMillis;
    bool buttonPressed = false;
    bool radioAvailable = false;
    int state = STATE_INIT;

    void loop()
    {
     //Check for new radio input every cycle
     if (radio.available()) {
      radio.read(msg, 1);
      buttonPressed = (bool) (msg[0] == 111);
      radioAvailable = true;
     } else {
      radioAvailable = false;
     }

     //State machine
     switch (state) {
     case STATE_INIT:
      //first cycle after boot-up, add any desired initialization
      //wait here until the first time the radio is available
      if (radioAvailable) {
       state = STATE_HOME;
      }
      break;

     case STATE_HOME:  //Wait for button to be pressed
      if (radioAvailable) {
       if (buttonPressed) {
        //button was pressed, reset timer and move to PUSH state
        previousMillis = millis();
        CandPush();
        Serial.println("STATE_PUSH");
        state = STATE_PUSH;
       }
      } else {
       //no radio input, go to HOME state
       Home();
       Serial.println("STATE_HOME");
       state = STATE_HOME;
      }
      break;

     case STATE_PUSH:  //Wait for timer to elapse
      if (millis() - previousMillis >= OnTime1) {
       //OnTime1 has elapsed, move to STOP state
       CandStop();
       Serial.println("STATE_STOP");
       state = STATE_STOP;
      }
      break;

     case STATE_STOP:  //Wait for button to be released
      if (radioAvailable) {
       if (!buttonPressed) {
        //button was released, stop all motors?
        StopAll();
        state = STATE_HOME;
       } //else still waiting for button to be released
      } else {
       //no radio input, go to HOME state
       Home();
       Serial.println("STATE_HOME");
       state = STATE_HOME;
      }
      break;
     }
    }


message:
Powering ESP8266EX with batteries and a voltage divider

So I recently bought a ESP8266 chip, it requires 3V3 and a large current( around 210mA max which is more than that can be supplied by an arduino uno at least). I managed to connect it to my arduino uno and got it to operate in standby mode, but Wifi mode wouldn't work because it requires more power.

After reading multiple online articles, I've decided to construct my own power supply. I'm planning on hooking 3 AAA batteries in series(4V5) and then use resistors(of small values to decrease power loss) to construct a voltage divide which powers the chip.

My concern is that I have not seen a single person doing this online and this seems like a straight forward thing to do, which makes me worried. Did I miss something? Is my plan feasible?

body:
There's a good reason why you can't do this.

When you power something like an ESP, the current it consumes will vary over time, as it does different things. For the purposes of current consumption, you could model the device as a resistor  whose resistance varies (greatly) over time. When it's in sleep mode with the radio off, it might be a 10k resistor. When it's active with the radio on full power, maybe a 30ohm resistor.

A potential divider divides voltage according to the ratio of the resistances. You are talking about putting your ESP in parallel with one of the resistors. Putting two resistors in parallel creates a new resistor with a resistance lower than either of the two.

If you want to calculate the resistance of two parallel resistors, it's R = (R1 x R2) / (R1 + R2).

What values would you choose for the resistors in the potential divider?  You'd have to go for values much lower than 15ohm in order for the 'resistance' of the ESP not to greatly affect the behavior of the divider - say 5ohm in total. This would mean your divider alone would draw a current of 1A from a 5v supply.

Fortunately, voltage regulators and buck converters are easily and very cheaply available. I recently bought a pack of five 3.3v regulator modules from China, delivered for less than £2.

Alternatively, you can create a reasonably stable supply from a reference voltage with just a single NPN transistor, but I don't know offhand whether it would be good enough for this application.


message:
Vin and Ground pins shorting only under specific conditions

So I have an Arduino Nano that I think might have gone bad. The Vin and ground pins are shorting (I'm checking continuity with a multimeter). But it only shorts when:

 - The Arduino has power
 - The red lead of the multimeter is on ground and the black is on Vin (not the other way around)

I've tried checking with the leads both ways (red to ground as well as red to vin) while both on and off, and with two different multimeters, one of which is brand new. Completely at a loss for words because this isn't really how physics is supposed to work (continuity shouldn't depend on lead orientation from the multimeter or whether the circuit is powered, right?). Any insight would be appreciated. Do I have a bad board?

body: It is not clear from your question what you are measuring with the multimeter (volts, ohms, amps etc.) but if you are using the ohms scale when your Nano device is not connected to the power, your multimeter charging capacitors on the board and reversing the leads will then cause a discharge through the multimeter, maybe giving a reading which leads you to believe there is a short circuit.


body:
Also if you have this setup and set it to measure Amp, then it will effectively shortcut the leads with as small resistace as mutltimeter can.

Also check, if those connectors (usually crocodiles) cannot touch something they should not (each other mainly)


body:
> But it only shorts when: The Arduino has power

You **must not** use a continuity checker or ohm meter on a powered circuit.

Not only will it not work, you risk damaging the meter.

It's also not necessarily safe to use such a meter on an unpowered active electronic circuit like an IC or eval board, as the meter must apply a small amount of power to the circuit to make a measurement - how much power varies between meters and settings, and how much a circuit can tolerate in an unintended way depends on things like polarity and the state of other parts of the circuit.  However, it is common practice to do so - especially for example when there's a fear that the device might already be damaged.