# Question
Title: 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.

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. :)

# Answer
> 0 votes
## 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.
* ~~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()`.~~ 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.
* 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.

# Answer
> 2 votes
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.

---
Tags: arduino-uno, serial, programming, arduino-ide, library
---


title: Insert Variables In AT commandes

text:
# Question
Title: 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()
     {

    }

```

# Answer
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 *`.
> 0 votes

---
Tags: arduino-uno, gsm
---


title: Battery level indicator

text:
# Question
Title: 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);
}

```

# Answer
> 4 votes
What you could do with for this is *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:

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.

---
Tags: arduino-uno
---


# Question
Title: Arduino Mega prototype analog timer interrupts: newbie question
I am currently using an Arduino Mega with a fast vibration sensor to trigger the components operation (force sensor, temperature sensor) and also toggle sleep mode.

I am very new at this and I have been doing some googling, but I just can't seem to understand it.

So, my questions are:

1. How would I toggle(on/off) sleep mode?
2. How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

I am currently working on a Mega, but I will eventually move on to the Arduino Mini Pro. I hope there are no exclusive problems later on.

I realize that this is not a professional question, but I find these tasks very challenging.

Please help me. An example link or perhaps example code to help me understand better.

Thank you very much.

# Answer
> How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

Thee best and most authoritative answer to that and all your other questions about the chip can be found in thee device data sheet and the compiler manual. Read them thoroughly and then write code to the data sheet to experiment.

Your can fire example have an analog interrupt where the chip constantly does ADC on the pin attached to the sensor and you can test the value of the ADC to see if certain trigger conditions are met and take appropriate actions.

The same with timers, etc. The data sheet is your best friend.
> -1 votes

---
Tags: arduino-mega, sensors, arduino-pro-mini, code-optimization, project
---


# Question
Title: 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?

# Answer
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 which is available in lengths from 130mm to 800mm.

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 votes

---
Tags: bluetooth, arduino-nano
---


title: Servo motor with 9V battery

text:
# Question
Title: 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.

# Answer
> 3 votes
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.

---
Tags: arduino-uno, servo, battery
---


# Question
Title: 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). 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.

# Answer
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.
> 1 votes

---
Tags: arduino-uno, power, motor
---


# Question
Title: Arduino add two spi slaves that has no slave select pin
I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.

How Can I solve this issue?

Sensor example

Thanks

# Answer
Ss or cs pin ISS not mandatory for SPI.

A few solutions.

1. Power on or off the devices. A group pin can do that.
2. Cut off mclk.
3. Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.
4. Software SPI.

...

I'm sure others will come up with more solutions.
> 1 votes

# Answer
Looking at the MS5540C specifications and assuming there are no other significant parts on the PCB you identified, there does not appear to be a SPI port available.

Neither "SPI" not "I2C" appear in the document. Please check your self to verify.

Instead there is a section on serial communication with the MS5540C part its self. In this section there are a number of diagrams. Here is one:

In the text we find this:

> Every communication starts with an instruction sequence at pin DIN. Fig. 6 shows the timing diagrams for the MS5540C.

Which is very nearly if not exactly how I2C works.

The text goes on to say:

> he device does not need a ‘Chip select’ signal. Instead there is a START sequence (3-Bit high) before each SETUP sequence and STOP sequence (3-Bit low) after each SETUP sequence. The SETUP sequence consists in 4-Bit that select a reading of pressure, temperature or calibration data. In case of pressure- (D1) or temperature- (D2) reading the module acknowledges the start of a conversion by a low to high transition at pin DOUT during the last bit of the STOP sequence.

Unfortunately, this design appears to prohibit using more than one identical device on the same serial bus.

Workarounds to this design flaw (if it truly exists) include blocking the SCLK or the DIN signal to the un-selected MS5540C.

In many other cases where multiple identical I2C devices are used on the same bus, vendors provide a pin on the device which can be used to alter the address of an individual device.
> 0 votes

---
Tags: arduino-uno, spi
---


title: Compiling is slow

text:
# Question
Title: Compiling is slow
Compilation of even the simplest program (like Blink) is extremely slow, the progress bar often hangs halfway for nearly half a minute.

Is this normal? I understand that not all computers are equally fast, but there's a huge difference between 3 seconds and 30 seconds

**edit**
It appears from the report that every time I switch programs they're built anew completely:

> Build options changed, rebuilding all

even when nothing has been changed. How can I avoid a complete rebuild?

# Answer
> 5 votes
I have found that this is a common issue across my development machines, however using Visual Micro for Visual Studio reduces this time by a significant factor.

I primarily use it for other Visual Studio features like Intellisense, refactoring, and solution management. Visual Micro has some compelling features of its own, like debugging tools, however I haven't used them.

I haven't personally tried, but I would expect that you can avoid the rebuild using the project/solution options in Visual Studio - I found that the compile time is fast enough in most cases with this environment for it to not matter.

# Answer
> 3 votes
If you find compilation slow then yes, it is probably recompiling things that it doesn't really need to recompile. This has always been a major failing of the Arduino environment, and is one of the major impetuses for the complete re-write of the whole compilation system in my IDE UECIDE.

That includes very aggressive caching of compiled library and core files as proper ".a" files which are stored away separate from your board selection and kept until something really does need compiling. That way the first time you compile something for a board it may take 30 seconds, 50 seconds, whatever. All subsequent compilations for that same board, even for different sketches (not including the compilation time of "fresh" libraries) would be around 2 seconds, even less.

That caching is especially important when you're running on a very slow system, such as a Raspberry Pi, when compiling can take many minutes without the caches in place, but only a few seconds on all subsequent compilations.

# Answer
> 3 votes
I had the same problem until today. Like many answers around the web, the problem seems to come from the anti-virus. My setup is Windows 10 x64 with a SSD and I use Windows Defender as the AV.

I tried by excluding the main arduino folder in "c:\program files (x86)\arduino", but it didn't improve the compilation time.

I checked the "verbose" option in the Arduino IDE and I've seen that it was calling the compiler from the AppData folder. So I add this folder to my AV exclusion list and it worked!

The compilation time improve by ten folds.

**TLDR;** In Windows 10, add the folder in %USERPROFILE%\AppData\Local\Arduino15 to the AV exclusion list.

# Answer
> 1 votes
This thread, Arduino IDE and ESET: Slow compilation, may be helpful if you use ESET (at least one user has reported that it helped), but it didn't help me since I'm using Comodo (and may be there are some other reasons).

Here's another thread, SLOW ARDUINO IDE regarding a solution which helped many users, since 2009 (the latest comment on the forum is dated year 2014).

Several useful posts here as well, Unbelievable slow compilation of simple sketches. Ok, I haven't tested all the solutions myself, but let me collect useful links here so that other guys can find them and I'll check them out, too.

# Answer
> 0 votes
I would download the non-install version and try compiling the blink sketch in it. This will let you know if it is a computer specific issue or something related to your install. I experienced something similar with a library that wasn't updated correctly between versions which caused all sorts of buggy behavior.

# Answer
> 0 votes
The occurrence of “Build options changed, rebuilding all” (as mentioned in edited question and shown in screen shot) probably is causing the large delay. My belief (correct or not) is that lots of libraries are being rebuilt when that message appears. Ordinarily, libraries should be rebuilt only upon initial install or when changing target board type.

An arduino.cc thread, “"Build options changed, rebuilding all" even when nothing changes ==\> very slow”, from 2014 treats the issue superficially, merely pointing out that Arduino 1.5.8 Beta is suitable for Yún and Arduino Due boards, not “regular Arduino” boards.

A 2011 Google code thread probably is mostly irrelevant, but it's worth trying some steps mentioned in posts #14 and 15 ‒ eg, starting arduino via a path with no spaces in names ‒ if your platform is MS Windows. If the Arduino IDE cannot find its options or preference files it probably assumes it is starting from scratch.

Note, please edit the question to specify how you started the Arduino IDE running, where the IDE is installed on your system, what your op system is, and what your computer is.

---
Tags: compile
---


# Question
Title: 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`

# Answer
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? for discussion.
> 1 votes

# Answer
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.
> 0 votes

# Answer
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**)
> 0 votes

---
Tags: programming, pins, avr, firmware, atmega2560
---


# Question
Title: ATmega168a Breadboard - can't load via Arduino IDE
I have ATmega168a on a breadboard. I am programming it via the Arduino IDE and a FT232RL USB adapter. When I select my board for 168 and upload, I get the following error:

```
stk500_getsync(): not in sync: resp=0x00

```

Normally this error means that either:

1. My wiring is not correct
2. I choose the wrong board

So to double check my wiring, I replace the 168 with a 328p. I am able to program the 328, so I think its the board selection.

I have tried `Ardiono Diecimila or Duemilanove w/ ATmega168` and I also have a custom board entry:

```
atmega168bb.name=ATmega168 breadboard (16 MHz internal clock)
atmega168bb.upload.protocol=stk500
atmega168bb.upload.maximum_size=14336
atmega168bb.upload.speed=57600

atmega168bb.bootloader.low_fuses=0x62
atmega168bb.bootloader.high_fuses=0xDF
atmega168bb.bootloader.extended_fuses=0xF9
atmega168bb.bootloader.path=arduino:atmega
atmega168bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_16MHz.hex
atmega168bb.bootloader.unlock_bits=0x3F
atmega168bb.bootloader.lock_bits=0x0F

atmega168bb.build.mcu=atmega168
atmega168bb.build.f_cpu=16000000L
atmega168bb.build.core=arduino:arduino
atmega168bb.build.variant=arduino:standard

```

Also, I am able to program the 168 via my AVR Programmer/Debugger. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Any suggestions I can try?

# Answer
Have you burned a bootloader? The standard Arduino IDE upload requires that you have a bootloader on the chip. You can burn a bootloader with the Arduino IDE and your AVR dragon
> 1 votes

# Answer
Try adding a 1k resistor on the TxD and RxD pins to your chip. And a 100nF capacitor like the schematic below. And a 10k Pull-up resistor to the reset pin.

```
Target processor                                 USB to Serial converter
(Atmega 168)
GND   ------------------------------------------ GND

5V    <----------------------------------------- 5V
RX    <--- 1K ---------------------------------- TX
TX    ---- 1K ---------------------------------> RX
RESET <----||----------------------------------- DTR_PIN
  |       100nF
 10K
  |
 5V

```

This will help stabalizing the signals.
> 0 votes

# Answer
There is another possibility, which I have had in the past.

My AVR was brand new, and it was set to use the internal resonator, at 1/8th speed, for a total of 1mhz. This was too slow to program using the default settings.

I had an USBASP, and it very conveniently had "SLOW SCK" jumper option, to slow down the programming. This was enough to program it, and if I'd wanted to use an external crystal clock (which I didn't, and 1mhz was fast enough for the specific project), I could have changed the fuses Check out http://www.engbedded.com/fusecalc/ to calculate new fuse settings. Be careful, I managed to set one chip to the wrong fuses, and am no longer able to change it.

P.S. - I used AVRDUDE to program the fuses. You should be able to read the current values, before you start - again, at slow speed. AVRDUDE has the '-B' option to slow down the programming, if you do not have the "SLOW SCK" jumper option, option -B10 should be plenty (default = -B1 I think).

When checking what the current fuse settings are, I think the main ones that slow down the clock are: CKSEL and SUT (the top dropdown list on the calculator website), and CKDIV8 - divide clock by 8; the second tickbox on the list. The defaults for these for AtMega 168 should be: Internal RC Oscillator: 8mhz, and the "Divide clock by 8" option selected.
> 0 votes

# Answer
> . If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Your dragon is an ISP so you don't have to unplug and replug it for programming.

I would check if your ftdi board an indeed function as a stk500.

Another alternative is to burn the bootloader and go down the regular Arduino route.
> 0 votes

# Answer
you should be selecting the Arduino NANO board as the original Arduino Nano board is equipped with the FT232RL, rest all have either atmega chip for usb to ttl conversion or CP2302 chip. So **select Arduino Nano** and try.
> -1 votes

---
Tags: programming, arduino-ide
---


title: Is my arduino board broken?

text:
# Question
Title: 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

# Answer
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.
> 2 votes

---
Tags: arduino-ide
---


title: Use all pins As digital I/O

text:
# Question
Title: Use all pins As digital I/O
**Increase the number of digital pins**

There are many post that explain how to use more than just the standard pins on the various arduinos but none of them explain the limitations and the proplems properly.

Arduino Uno:

**1.You can** use the analog pins

```
Pin 14 = Analog in 0
Pin 15 = Analog in 1
Pin 16 = Analog in 2
Pin 17 = Analog in 3
Pin 18 = Analog in 4
Pin 19 = Analog in 5

digitalWrite(14,HIGH);
or
digitalWrite(A0,HIGH);

```

**2.You can't** use both SDA , SCL & A4 , A5 as they are basically the same (18,19).

**3.You can** also use the TX/RX.

> "Don't do it, you break the serial communication..."
>
> "Never use pins 0 and 1"
>
> "you can't use the TX/Rx Pins"

**You can... but you need to take precautions. Which ones?**

It should have software serial over USB, right?

Or do i break the USB serial?

Are there internal Chip problems if i use TX/RX?

As i use those TX/RX pins in the code i probably should not use `Serial.print()`?

What happens if i forget to remove `Serial.print()` after uploading the code that use pins 0,1?

How to hardware reset the arduino/bootloader if something goes wrong?

As there are various other Arduino's that use different chips, is the above valid for all Atmel chips?

**So, what shuold i know before using those TX/RX or also maybe the other analog pins?**

> There are cheap shiftregisters, pwm drivers, led drivers, spi, i2c and more ic's to expand your I/O

---

But if there are not to big problems it means that the arduino has 20 I/O pins...

*You could theoretically control:*

```
17x3 = 51 = 17 RGB leds (multiplexing, pwm sourcing&sinking);
14x6 = 84 leds (multiplexing, pwm on 6 rows/colums );
10x10 = 100 leds (multiplexing, high low);
20x(20-1) = 380 leds (charlieplexing, high low);
// yes it would flicker

```

Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one arduino.

# Answer
> 13 votes
The main issue is with pins 0 and 1.

Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc. But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.

All the other pins, while being multi-function, have their function defined basically by what you attach to them. Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

* As soon as you enable Serial in your sketch (`Serial.begin()`) those two pins can no longer be reliably used for digital IO.

That means that you can *either* use the hardware serial port *or* you can use the pins for digital IO, but not both.

* Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches. You have serial data coming in from the PC while the same pins are being affected by other things connected to them. The most common one is things like GPS modules which connect to those pins and constantly send serial data. That serial data will conflict with the PC's serial data and neither will arrive right.

* How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't. It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering. Just disconnect those two pins from whatever is connected and you will be able to upload sketches again. Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield. You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

* Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc. Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins. That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.

# Answer
> 3 votes
I can't comment due to insufficient reputation but I want to point out that the OP pinout has at least one pin wrong!

**PB6 should be PB5**

I spent quite a lot of time trying to figure out why I couldn't see SCK on scope (SPI bus). I was working low level, not with the IDE.

As this is the first picture that comes up when googling I wanted to avoid the same trouble to others...

# Answer
> 0 votes
> 20x(20-1) = 380 leds (charlieplexing, high low); Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one Arduino.

First, the figure of 380 is correct for 20 pins (202 \- 20) however pins 0 and 1 are connected to pull-up resistors on the Atmega16U2, so they are never really at 0V. If you load a blank sketch, you will measure 5 V on pins 0 and 1.

Second, you can't drive 380 "whatevers" you can drive 380 **LEDs** via Charlieplexing. The property of the LED, that current only flows one way through it, is important to the way it works.

Related question Is there a way to have more than 14 Output pins on arduino?

---
Tags: arduino-uno, serial, pins
---


title: NodeMCU Light Sensor

text:
# Question
Title: 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.

# Answer
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
> 3 votes

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: 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?

# Answer
> 1 votes
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

---
Tags: c++, arduino-ide, esp8266, nodemcu, firmware
---


title: Average response time of Esp8266 module

text:
# Question
Title: Average response time of Esp8266 module
I'm planning a project where I'd like to control an RC car with Arduino and an Esp8266 module.

A software running on a computer would read the input from an USB analog controller and send the data to the Esp8266 module through the wifi network, and the Arduino would read this data and send signal to the ports accordingly.

What I'd like to know is: would ping/delay be an issue? Considering a dedicated wifi network for this, so the only devices connected to it would be the computer and the Esp8266 module.

I need to know what is the average response time of the Esp8266 module before I buy it, because if it is too high I'll think of something else since for this project I'd need a reasonably high response time.

# Answer
I'm pretty sure it can be made to work.
I have a home server with several devices attached to it, including 2 ESP8266 modules - one at home and one in my office. All devices connect using permanent TCP connection and respond to my custom "ping" requests over that connection. Typical round-trip response times are bellow 50ms and often bellow 10ms. There are occasional "hickups" of 100+ms, but they are rare and could be a result many factors. Note that these 2 ESPs are programmed in Lua, which is not optimal efficiency - I was just lazy and the tasks they do are simple enough to not matter.
Most probably if you start an HTTP server on the ESP and bombard it with HTTP requests every time you move the joystick it would be horribly laggy. But with a plain old TCP connection or even a consistent flow of UDP packets I'm pretty sure you will get good results.
Also, I would ditch the Arduino and use only the ESP - you should have no problem controlling two motors (most probably via motor driver board or chip) and perhaps a servo from the ESP directly. This would eliminate the additional lag of serial communication and parsing the serial data. It would also reduce the cost and size of the project.
Having that said, other solutions, like bluetooth or even RF modules should also work, but you asked whether the ESP can do it - and my answer is yes.
> 3 votes

# Answer
I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.

Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.
> 3 votes

# Answer
If you use websocket it will have a really good response time.

It is a test about it: https://www.youtube.com/watch?v=8ISbmQTbjDI

I use it for a quadcopter controller.
> 0 votes

---
Tags: esp8266, wifi, remote-control
---


# Question
Title: autoCalibrateAccelerometerOffset() Why does my Z values swing from 0 to 1g in static condition?
I tried to implement the `autoCalibrateAccelerometerOffset()` function, through the code below on Arduino Genuino 101.

In a static test, without any stress or noise, I read the three axis value.

When I see the data on the serial monitor or on my file created with processing, the Z acceleration values changes from 1~0,99 to 0,00 g.

I think there is an error in my code.

```
#include "SoftwareSerial.h"
#include "CurieIMU.h"

float sensorVals[] = {0,0,0};

void setup() {

    Serial.begin(9600);
    while (!Serial);

    Serial.println("Inizializzazione del device...");
    CurieIMU.begin();

    CurieIMU.setAccelerometerRange(2);
    CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS,1);
}

void loop() {

    sensorVals[0] = CurieIMU.readAccelerometerScaled(0);
    sensorVals[1] = CurieIMU.readAccelerometerScaled(1);
    sensorVals[2] = CurieIMU.readAccelerometerScaled(2);

    Serial.print(sensorVals[0]);
    Serial.print(",");
    Serial.print(sensorVals[1]);
    Serial.print(",");
    Serial.println(sensorVals[2]);
    delay(100);
}

```

# Answer
> 1 votes
Assuming you aren't jumping up and down while this is happening then it could be:

* A loose wire
* A dodgy power supply
* A bad earth connection
* A fault sensor
* A weird magnetic field/flux thing

Check you wiring, make sure all the connections are secure, etc. I bet you have done that already.

I have no idea how to check a power supply, but if you have a different one you could switch that in. Also look into smoothing the power supply with decoupling capacitors (?)

A bad earth, all sorts of weird \[stuff\] happens when you haven't earthed things properly. Different power supplies need to share earths, but I suspect that doesn't apply here.

A faulty sensor - again, unless you have a duplicate you might not know.

Weird flux. I think the sensor is a magnetic sensor and so it could be the natural eddies and flows of magnetic flux have conspired against you. Move the sensor away from power supplies, electrical things and specifically anything you are hacking. Also rotate the sensor through 90 degrees and see if it still happens (With RF it will polarise the fields in a different way, and school was a long time ago and I can't remember if that works with magnetic fields too)

---
Tags: accelerometer, code-review, 101, genuino
---


title: Arduino for push notifications to phone

text:
# Question
Title: 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.

# Answer
> 0 votes
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.

---
Tags: wifi, shields, ethernet
---


title: How to concatenate strings

text:
# Question
Title: 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

```
#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

```
#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

```
#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.

# Answer
> 3 votes
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);

```

# Answer
> 3 votes
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:

```
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.

---
Tags: atmega328, display
---


title: Does Arduino sent output to TX pinout?

text:
# Question
Title: 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.

# Answer
> 1 votes
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
    }
}

```

# Answer
> 1 votes
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.

---
Tags: arduino-uno, serial
---


# Question
Title: 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?

# Answer
> 2 votes
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());

```

---
Tags: arduino-uno, time, rtc
---


title: I2C Arduino ESP8266 Bad Reading

text:
# Question
Title: 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);
}

```

# Answer
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 votes

# Answer
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.
> 0 votes

---
Tags: i2c, esp8266
---


title: Buffering output stream

text:
# Question
Title: 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

# Answer
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 libraries can be of help to you here.
> 1 votes

# Answer
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.

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 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, 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 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.
> 1 votes

---
Tags: timing
---


# Question
Title: Arduino stops loop randomly whenever a button is pressed
I'm having a problem with this Arduino code.

So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.

In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).

Can anyone explain why the arduino will behave in this way?

Thank you so much.

```
int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer

bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;

int setupTime = 5000; // time the user has to close the box after toggling alarm

bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buzzer, OUTPUT);
  pinMode(receiver, INPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  noTone(buzzer);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("7");
  receiverVal = digitalRead(receiver);
  buttonVal = digitalRead(button);
  Serial.print("8");

  if(alarmOn == true){
    Serial.print("6");
    setAlarm();
  }

  Serial.print(buttonVal);
  Serial.print(oldButtonVal);

  if(buttonVal == HIGH && oldButtonVal == LOW){
    buttonModeDecider = 1 - buttonModeDecider;
    Serial.print("Toggled");

    if(buttonModeDecider == 1){
      buttonMode = resetButton;
      Serial.print("1");
    } else {
      buttonMode = stopButton;
      Serial.print("2");
    }

    switch(buttonMode) {
      case resetButton:
      {
        delay(setupTime);
        alarmOn = true;
        break;
        Serial.print("3");
      }
      case stopButton:
      {
        alarmOn = false;
        Serial.print("4");
      }
    }
  }
  Serial.println("5");
  oldButtonVal = buttonVal;
}

void setAlarm() {
  if(receiverVal == LOW || keepAlerting == true) {
    tone(buzzer, frequency);
    keepAlerting = true;
  }
}

```

# Answer
> Arduino stops loop randomly whenever a button is pressed

your button is shorting the supply?
> 0 votes

# Answer
A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.

Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: 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:

# Answer
> 1 votes
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.

---
Tags: arduino-uno
---


title: Using PROGMEM in constructor

text:
# Question
Title: 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() {}

```

# Answer
> 2 votes
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.

---
Tags: c++, progmem, memory
---


# Question
Title: Generating PWM using Arduino Uno and Simulink (interfacing) pins 5 and 6. What's the maximum frequency?
I am building a boost converter using a mosfet. The mosfet is driven by PWM generated by an Arduino Uno through Matlab Simulink. In Simulink I am giving 10 KHz pulse width 50%. Practically 10 KHz available at pins 5 and 6. Up to how much frequency can pins 5 and 6 handle?

# Answer
> 1 votes
See my page about timers. The maximum frequency the hardware can output is 8 MHz if you are running a 16 MHz clock.

10 kHz should be easily achievable if you tweak the hardware registers, as Gerben said.

# Answer
> 0 votes
> Up to how much frequency can pins 5 and 6 handle?

here is a way for you to find out:

1) pin 5/6 are OC0A and OC0B -\> two output compare pins tied to timer0

2) go to the datasheet and timer0 is a 8-bit timer, with a few pwm modes who top out at 0xff or OCR0A -\> useless for your application.

So the theoretical but useless answer is 16Mhz/2, at 1:1 prescaler.

the more practical answer is 16Mhz / 256, at 1:1 prescaler.

with that said, some AVRs (ATtiny25/45/85 for example) can run in asynchronous modes generating incredibly high PWM with very little outside help.

if generating high speed pwm is your thing, check them out instead.

---
Tags: arduino-uno
---


# Question
Title: 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");
 }
 }

```

# Answer
> 1 votes
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;
    }
}

```

---
Tags: motor, timing
---


# Question
Title: Driving two stepper motors using one stepper motor driver
Using an Arduino Mega, I currently control two stepper motors that never operate at the same time and never will. I am using two EasyDriver stepper control boards with two separate power sources. I was wondering if I could go down to just one stepper control board, one power source but somehow switch the 4 input wires from one motor to another when I need to turn a specific motor. Is there a switch I can control with Arduino where I can plug in 8 wires and say "ok, use the 4 left most wires" or "switch to the right most 4 wires". Does that exist or is that more complicated than what I currently have?

# Answer
> 0 votes
If we call the motor leads A1, A2, B1, B2 on each motor and control, you could tie the two motor A1's to A1 on the control, and motor B1's to B1 on control. Then wire a DPDT relay as below. (Coil not shown.) Note, DPDT relays are about $4 on ebay, with labels like “DR21A01 DC 5V DPDT Relay Module Polarity reversal switch Board for Arduino UNO”.

simulate this circuit – Schematic created using CircuitLab

Since you have equipment in place and working, it might not be worthwhile to change your setup. However, even without adding a relay, you probably can power both motor controls and motors with a single power supply, ie could use one instead of two power supplies. The current draw when a stepper motor is idle is a small fraction (eg 10-20%) of the high current drawn when the motor steps. If you don't have power attached to a stepper motor, there is only its cogging resistance to keep it from turning; it does not take a large torque to turn an unpowered stepper motor. If that's a concern, the DPDT relay approach might be unsuitable.

---
Tags: motor, stepper
---


title: Seven segment display multiplexing

text:
# Question
Title: 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?//
    }
  }
}

```

# Answer
> 1 votes
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.

# Answer
> 0 votes
> 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.

---
Tags: arduino-nano, display, multiplexer
---


title: Simple example multiplexer usage

text:
# Question
Title: 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!

# Answer
For connecting 8 analog devices to an Arduino, using only 3 Arduino pins, look at say a 4051 multiplexer IC: 4051 example
> 0 votes

---
Tags: multiplexer
---


# Question
Title: 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?

# Answer
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.
> 2 votes

---
Tags: arduino-uno, esp8266, battery
---