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

Please create a minimal, complete, verifiable example and edit it into your question in place of the pages of code.

No need to apologise - I'm just trying to help you get help. It's not about the formatting (although it's good that it's properly formatted now) but about allowing people to focus on the problem. If you read the MCVE article I linked, you'll get a better understanding.

Even more reason to break it down to a minimal example ☺ The exercise will help you understand it☺

The diagram looks wrong. Why are there two 10Mohm resistors?

@gerben It was an error with my fritzing app. All the resistors have a value of 10Mohm not just two

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.

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.


text:
Arduino DigitalWrite() Super Basic Circuit measure voltage with multimeter
I am having a problem measuring the voltage with a multimeter. I am not sure if arduino is even sending out a voltage from the Pin.
I will try to create a really basic circuit drawing for reference. (Drawing attached).

What I am trying to do is to measure with a Multimeter the Voltage (or current) across the alligator clips.
I will attach the code below:
//Code Section Start//

int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(10000);                  // waits for a second
}

//Code Section End//

Typically the digital write I believe will out put 5 volts and with a 1k Ohm resistor that is only 5mA current. I have heard Arduino can take up to 40mA currents so I don't think I am frying something.
There are two weird things I have noticed. When I try other Pins like "int ledPin = 10;" The green light on the Arduino does not light up. It only lights up when I use pin 13. However, even using Pin 13 or any other pin, I cannot find a voltage or current with the Multimeter. I am using an Arduino Micro.
Can someone please help me identify what I am doing wrong or some method of how to check what is wrong? So that I can have a complete circuit with a voltage I can measure.

If you see the LED being toggled, you are probably tapping into the wrong pin/pad. With the power off, try to retrace (by observation) the electrical path between LED and your tapping point (where you attach the resister). Do you have a schematic of the specific board you are using?

I can't quite understand your diagram. Are the alligator clips supposed to be touching each other, or separated?

... or are they both clipped side by side to the same 'groundy' bit of wire? If so, move the positive one to the other side of the 1k resistor

Thank you guys for answerng so quickly. duskwuff the Alligator clips are clamped together.  @Neil_UK the Alligator clips do not relate to the positive and negative lines, sorry I should have been more specific. The positive and negative lines are the wires that connect to the multimeter (Since the alligator clips are metal I believe if i just put the wires from the multimeter on them, that should read the current/Voltage)

@Yuriy The LED is on the board. (https://www.arduino.cc/en/Main/arduinoBoardMicro) the left board in the pic, right next to the word micro is a LED. How do i trace that? Also How would I be tapping the wrong pin/pad? I am int pin 13 I thought that was all I had to do? Can I track the electrical current through this diagram? (http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) I believe that is the schematic for the arduino micro.

OK, well move the positive meter connection to the other side of the 1k reistor

@Neil_UK Ahh right thank you! The V=IR if R=0; V/R=inf so the Multimeter wouldn't work! Thank you very much!I really appreciate all you guys helping!

On the Arduino micro board (https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf), the green LED is connected to IO13 (pin 13). So it makes sense that it lit up only when you are using pin 13, but not with pin 10...

As you have drawn it, the alligator clips are clamped together (shorted togther).  You reading the voltage "across" a shorted element in the circuit should yield ~0V (shorts by definition have no to very little resistance, meaning there should be no voltage across them).  In order to get your proper voltage reading, you should place the multimeter positive clip above the resistor (where the voltage drop is occuring).
Remember.
Measure current THROUGH.
Measure voltage ACROSS.
p.s. if you're trying to alternate the pin, you should do something like DigitalWrite(pin10, digitalRead(pin10)!=HIGH); (if it's low, then the statement evaluates to true, setting the pin high, if it's high, then the statement evaluates to false, setting the pin low)

As you connected the alligator clips (from the image it seems that they are touching each other) you won't be able to measure anything.
This is how to connect a multimeter to read the current (A) and the voltage (V). You can consider the + of E as the pin 13 and the - as the ground

Remember that your code will not change the state of pin 13, it will be always high.
If you want to make the signal change try this on your void loop :
  digitalWrite(ledPin, HIGH);
  delay(10000);
  digitalWrite(ledPin, LOW);
  delay(10000);

you are telling that you are not getting any current or voltage on your multimeter
right......
i suggest you to use the following code:-
int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
}

this will stay your arduino pin 13 always high then you can measure the voltage on that pin........

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Change conditioning in real time
I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:
int solenoidPin = 4; //connected to Digital 4
int moisturePin = A0; //connected to Analog A0

void setup() {
  Serial.begin(9600);
  pinMode(solenoidPin, OUTPUT);
}
void loop() {
  int val;
  moisture = analogRead(moisturePin); //connect sensor to Analog A0
  Serial.println(val); //print the value to serial port
  delay(1000); //wait 1 second for next reading

  if (moisture <= 350) //if moisture is less than reading 350 {
  digitalWrite(solenoidPin, HIGH); //switch solenoid ON
  delay(600000) //water for ten minutes
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
}

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the if (moisture <= 350) while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

  if (moisture <= 350) //if moisture is less than reading 350 {

That is wrong, because you have the brace { after the comment. You need it before the comment, eg.
 if (moisture <= 350) { //if moisture is less than reading 350

Or preferably in my opinion:
if (moisture <= 350) //if moisture is less than reading 350
  {

I'm just asking if it's possible to change the if (moisture <= 350)

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace 350 in the code. You could use a simple LCD or LED display to show what the current reading is.

delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read How to do multiple things at once which shows how you can keep doing other things, while waiting for time to elapse.

Thanks for catching that small { fluke. Now, back to the the change in the condition. You mentioned a potentiometer. Where exactly in the circuit would that go?

Actually, come to think of it, the potentiometer would probably be series with the moisture sensor. Please correct me if I'm wrong.

That could be fiddly to get right. Normally you have a potentiometer with the 2 end pins connected to Gnd and +5V and the middle (wiper) to an analog input. It acts as a voltage divider and then you can read a number in the range 0 to 1023 which indicates how far you have turned the knob.

There's another "fluke" here: delay(600000) //water for ten minutes - there should be a semicolon after the right parenthesis.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is it possible to digitally stop a moving motorbike using an Arduino module?
I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.
Is it possible to do it using an Arduino and some other modules maybe?

Put a (NC-)relay in series with the ignition cable. That way you can "remove the key" using the Arduino.

with autos in general, it might be illegal to stop it if its moving, as that could cause a wreck and expose you to injury liability. its best to keep it from being started, or kill it when idle.

Legality might not be an issue here as this is just a throwaway project I have to do for internals.I am not really aiming to make this a commercial product.

Make an actuator poke a stick through the wheel, this often is very (or too) effective. (:

Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.
Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.
Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.

starting an engine can draw 50 amps, make sure the relay can handle that much current (most cannot)

If the motorbike has a starter motor, I hope it's on a relay of its own.

If you try to use the brakes with the Arduino, make sure you do it gently; an abrupt break (especially on the front wheel) might cause lethal injuries.


text:
Serial read in ESP8266-01 not working
I am new to programming. kindly bear with me. I am trying to use ESP8266-01 device for serial read and write application. Before writing the full program for my application, i wanted to test how it functions. I programmed the ESP8266-01 device to read the data from its Rx pin and write it to Tx pin. I used a standard USB-TTL cable to send and receive data from PC using Hterm. The ESP device does not read the data available at the Rx pin. what am i missing ?. Also kindly help me in understanding the difference between serial.println and serial.write with respect to ESP8266-01 device. As per the program if i check the data from the Tx pin of the ESP8266 device, i get only "No data received". I am using arduino IDE 1.6.11. Kindly provide some guidance
regards
Sriniketh
#include <ESP8266WiFi.h>

void setup() {

Serial.begin(9600);
}

void loop()
{
  byte serin=0;
  if (Serial.available()>0)
  {
    serin=Serial.read();
    delay(100);
    Serial.println(serin);
    delay(100);
    Serial.write(serin);
  }
  else
  {
    Serial.println("No data received");
    delay(5000);
  }

}

You might mean bear rather than bare in “kindly bare with me” (which means,  “kindly take off clothes together”)

can you successfully flash the arduino sketch over that serial connection?

A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx.  That's the wrong thing to do.  Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter.  This will let a 3.3v device talk to a 5V device.  Some ESP boards are 5V tolerant, but I don't know what you have so ...
Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other
 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)


text:
How many pins are needed for a sensor?
I'm currently looking to buy an Arduino, but never touched robotics before. Would anyone be able to give me an idea how many pins a sensor such a magnetometer would use? This is for Arduino Uno.
Sorry if this is stupid, just really have no idea how to approach Arduino design without having one here and can't get one for a few weeks at the least.
Thanks!

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.
GND of magnetometer ----> Arduino GND
Vcc of magnetometer ----> Arduino 3.3 Volt
SDA of magnetometer ----> Arduino Analog Pin 4
SCL of magnetometer ----> Arduino Analog Pin 5
I hope it will help you.

Would anyone be able to give me an idea how many pins a sensor such a
  magnetometer would use?

Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be any two Analog pins of Arduino.
And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.

Probably wrong about  “any two Analog pins” bit.  A4, A5 on Uno are SDA, SCL, two of the lines required for hardware-based I2C.  See eg 3-axis magnetometer breakout wiring and test at adafruit

How many pins are needed for a sensor?

As many pins as are needed for that sensor.
Every sensor is different. The datasheet or manual for the sensor or the chip or other device that the sensor is based around will tell you how the interface to it works - what each pin does, how you use it, etc.
It is up to you to read that documentation and learn how the sensor works to then be able to plan how best to connect it to your Arduino.
Some sensors require specific connections, such as the two I2C pins in your example sensor. Others may need the SPI pins. Then there are sensors that use analog inputs. That may be one pin for, say, an LDR, or three pins in the case of a 3-axis accelerometer.
In short: RTFM.

One, maybe two. It's impossible to say for sure without a concrete example.
I would recommend looking up the type of sensor(s) you want to use, and read the data sheet(s). Things you'll want to consider are things like operating voltage (3.3v or 5v), current draw (>40mA?), are any additional passive components required (capacitors, resistors, ...), etc.
Data sheets will describe in great detail, how to use a specific device.

If you are satisfied with this answer, it's good form to select it and indicate your question as answered :)

Broadly speaking, look for sensors/outputs that use I2C or SPI interfaces. If you use I2c, you can wire all your sensors with two digital pins. This is especially important with multi-axis sensors that would otherwise chew up 3-6 pins each.
I2C is probably easier because SPI need one extra pin per device, in addition to the 2 base pins. Still, that's about 10 devices on one UNO, IF you spend the extra $1 or $2 on the SPI/I2C sensors/LCDs/etc instead of going for what at first seems like a cheaper part.


text:
How many pins does this circuit (HMC5883L) use?
I've been told 2 by a friend but this looks to only use one?
https://www.adafruit.com/product/1746

Two (SDA and SCL) and no additional pins when connecting other I2C (TWI) devices.

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.
GND of magnetometer ----> Arduino GND
Vcc of magnetometer ----> Arduino 3.3 Volt
SDA of magnetometer ----> Arduino Analog Pin 4
SCL of magnetometer ----> Arduino Analog Pin 5
A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.
I hope it will help you.

It is I2C so 2 pins.
Optionally it can use a third pin to indicate data ready.

It depends what you think of as a pin.
You have VIn and Gnd, SCL and SDA are the 4 main pins you will need to connect.  The 3.3V and RDY pin don't seem to be connected in any of the pics I can see.
So the answer is 2 pins plus 2 power.
Oh from the page on how to use it, https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/wiring-and-test:
"This 3-axis magnetometer breakout is thankfully very easy to use. It only requires 2 power pins and 2 data pins."
Interestingly it doesn't appear to use pull up resistors, which most I2C device require, so the might be built into the board.

Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be A4 & A5 pins of Arduino.
And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.


text:
Can Digital/Analogue pins double as power supplies?
I'm doing research into if the Arduino Uno has enough power pin slots to power multiple components, and I'm unsure if it's possible to convert some of the pins from the Digital and Analogue sections to be power/ground. Anyone know>

Only for very light loads (a few mA).
But why would you want to? The number of power pins doesn't dictate the number of devices you can power. Power pins can have as many things connected to one pin as you like. As long as you stay within the board's total power budget you are fine.

@user32033 This may help you understand more: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

Yes, for most modules that use modest power, it can be handy to treat modules as shields, in cases where pins can align. You just set each pin on the common 4-pin module connector as needed and plug them in.  I've done this several times with DHT22 modules, and it's fun "plug and play"ing on such a low-level.
With an UNO, you get a generous 40ma per output, though I would use a real power rail for anything over 100mw or so.
To make a pin act as VCC:
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

To make a pin act as ground:
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);

the other advantage to this is being able to switch the module on/off with digitalWrite() (from HIGH to LOW) to save power or reset flaky sensors.

But note that the output pins have a not-insignificant impedance of 25ohm, which means that the more you draw from them the lower the voltage will be.

the dht22 uses less than a ma. All but a couple of the "37 sensor" kit's modules would work with pin power; the relay+buzzers mainly. 25r limits 5v to 200ma, far more than the rated current...

"25r limits 5v to 200ma" No, it means that if you try to draw 200mA you will get 0V. Even just 40mA means a drop of 1V, which will put it out of spec for most 5V or 3.3V devices.

@IgnacioVazquez-Abrams: sure, but 40ma is far more than most sensors use, a 4v triggers UNO's inputs...

Right, but is far less than, say, a ESP8266 module needs.

again, I would use a real power rail for anything over 100mw or so... i'm not syaing power everything though it. i'm saying it can be fun to throw together an led and a temp sensor in 5 mins no solder ;)


text:
Two solenoid valves, both independent
I am currently working an automatic home gardening system. There are two moisture sensors and two solenoid valves to allow water to plant two different zones. Preferably, I want to water the plants for x amount of time. I started programming this and I noticed that with my code below, if one solenoid valve goes off, the entire program will delay until one of the solenoid valves closes and thus the other solenoid valve will not open until the other one is closed.
However, I want to prevent this from happening and I want the program to continue reading the moisture readings while one of the solenoid valves is open so that the other solenoid valve can open whenever the zone needs water as well.
int solenoidPin1 = 1; //connected to Digital 1
int solenoidPin2 = 2; //connected to Digital 2
void setup(){
  pinMode(solenoidPin1, OUTPUT);
  pinMode(solenoidPin2, OUTPUT);
}
void loop(){
  int moisture1 = analogRead(moisturePin1);
  int moisture2 = analogRead(moisturePin2);
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
}

I was thinking that I should do the following for the conditioning part. Will this work instead for what I'm trying to do?
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  }
  else if (moisture1 >= 550){
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  }
  else if (moisture2 >= 550){
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }

Note: I'm using a capacitive moisture sensor, so the output voltage/reading is higher the drier the dirt is.

The essence of your problem is that the delay() function blocks
your program until the delay is over. This is only acceptable if the
program is doing one single things at a time. If you need to do multiple
things in parallel, like monitoring two moisture sensors, this approach
does not work.
Then, the first thing is to get read of delay() and instead use
millis() for managing time in a non blocking fashion. The essence of
this approach is to never wait. Instead, if it is time to do something
right now, you do it. If not, you just don't do it this time, but you
don't wait. This is nicely covered in the Blink without delay
Arduino tutorial. You should get familiar with this technique, as it is
essential for many Arduino projects.
Your problem is slightly more complex than blinking an LED though, as
the valve can be in two different states, and the action to perform
depends on that state. This is managed by a software construct called a
finite state machine. Essentially you have to remember the current
state and, depending on it, you decide what to do and what the next
state should be. Here is how you could do the timed watering with this
approach:
static enum { OFF, ON } stateValve1, stateValve2;
static uint32_t startedValve1, startedValve2;  // time when started

if (stateValve1 == OFF && analogRead(moisturePin1) <= 250) {
    digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
    startedValve1 = millis();
    stateValve1 = ON;
} else if (stateValve1 == ON
        && millis() - startedValve1 >= WATERING_TIME) {
    digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
    stateValve1 = OFF;
}

// and the same for valve 2.

For more in-depth coverage of the subject, I recommend you read the
Majenko's tutorial on finite state machines
At this point, the next step would be to throw in some modularization in
order to make the code less repetitive. I suggest making a class for
representing a “timed valve”. The valve has a turnOn() method that
turns it on, but does nothing if the valve is actually already on. The
class takes care of turning the valve off when the time has elapsed. But
since it cannot do that all by itself, you have to call an update()
method periodically to give it a chance to check whether it's time to go
off. Here is my implementation of that class:
const uint32_t WATERING_TIME = 100000;  // for example

class TimedValve
{
public:
    TimedValve(uint8_t pin) : valvePin(pin), state(OFF) {}
    void turnOn() {
        if (state == ON) return;  // do nothing if already ON
        digitalWrite(valvePin, HIGH);
        state = ON;
        timeStarted = millis();
    }
    void update() {
        if (state == ON && millis() - timeStarted >= WATERING_TIME) {
            digitalWrite(valvePin, LOW);
            state = OFF;
        }
    }
private:
    uint8_t valvePin;
    enum { OFF, ON } state;
    uint32_t timeStarted;
};

And you would use it like this:
const int solenoidPin1 = 1;
const int solenoidPin2 = 2;
const int moisturePin1 = A1;
const int moisturePin2 = A2;

void setup(){
    pinMode(solenoidPin1, OUTPUT);
    pinMode(solenoidPin2, OUTPUT);
}

void loop()
{
    static TimedValve valve1(solenoidPin1), valve2(solenoidPin2);

    // Turn the valves ON if needed.
    if (analogRead(moisturePin1) <= 250)
        valve1.turnOn();
    if (analogRead(moisturePin2) <= 250)
        valve2.turnOn();

    // Let them turn OFF if it's time.
    valve1.update();
    valve2.update();
}

Excellent. Thank you so much for you help. I had no idea about the Arduino being finite state machine. I also didn't know you could create an "object" with the Arduino IDE. Interesting...

@KingDuken: Any computer is, in a sense, a finite state machine (an “FSM” for short). But here, I am not using the term to describe what the Arduino actually is, but rather as a name for a software construct, i.e. a way to write a program. This construct could be implemented on any computer, big or small. The Wikipedia article I linked to describes the FSM as an abstract model of computation, whereas Majenko's tutorial is a good introduction to the FSM as a software construct, with a bias towards Arduino programming.

I finally managed to get around and test this out. AND IT WORKS! However, I wasn't able to use D1 because using the TX pin isn't exactly ideal. I don't know why but it worked when I used a different digital pin. Thank you again for your help!

There is one slight problem. I need it delay before the water cycle because the moisture sensor is really sensitive and if it detects water before the water settles in the soil, it will turn off the water valve.

@KingDuken: I can't understand your last comment. With this program, the moisture sensor controls the opening of the valve, but not the closing: the valve closes only after a fixed watering time. The sensor cannot “turn off the water valve”.


text:
Button press with Arduino repeated many times
I have 5V -> button -> 10K resistor -> PIN2 setup with Arduino UNO.
My code is very simple:
int count = 0;

void setup() {
  pinMode(2, INPUT);
  Serial.begin(9600);
}

void loop() {
  int state = digitalRead(2);
  Serial.println(state);
  if (state == HIGH) {
    count++;
    Serial.print("Hi");
    Serial.println(count);
  }
  delay(1000);
}

If the button is pressed print "HiX", but what I get is very strange. When I press the button only once I get this:
0
0
0
0
0
1
Hi1
1
Hi2
1
Hi3
1
Hi4
1
Hi5
1
Hi6
1
Hi7
1
Hi8
1
Hi9
1
Hi10
0

The button press is registered 10 times.
What am I doing wrong ?

Nothing, button contacts "BOUNCE" on off for a while when activated. YOU need to either add a de-bounce circuit, or configure your code to ignore then signal for 50mS or whatever. Though I am assuming that code is even right...

You pressed it once, but you must have held it for 10 seconds. You got a "Hi" for every iteration through the loop. If you only want one message per press, then you need to remember the previous state of the switch in a variable, and then compare that to the current state.

Use one of the "bounce" libraries for Arduino or write something similar, see: https://github.com/thomasfredericks/Bounce2/wiki

it is is really "bouncing" issue, why does it last 10 seconds ?
edit: To be clear, I press the button for less than a second.

As Yasu said in his answer, your input is floating when the button is not pressed

I can't comment that's why I'm writing this as an answer but,
Are you doing exactly this this to wire the button?

I'd like to see your schematic but from what you describe there's a pull-down connection missing

seems like you are right, my schematic was not correct, but I still needed some debouncing code to make it work smoother. thanks

there could be some stray capacitance that's holding the charge.
generally for cases like that, put the buttons active low + pull-up to avoid cases like yours.

I think it's not a problem of debouncing...
There is a delay(1000) in the loop so after 1 second, the switch is not bouncing anymore.
But switching to VCC is the problem. Connect the switch to GND and use the internal pullup resistors (pinMode(2, PULLUP).
The switch then pulls it down to ground. Now it is floating and probably still HIGH after opening the switch....

Try out this code and schematic. It may solve your problem of debouncing.

const int buttonPin = 2; // Push Button at Pin 2

int buttonState = 0;
int lastButtonState = 0;

int counter = 0;

void setup()
{
  pinMode(buttonPin, INPUT_PULLUP); // Push Button with pull-up
  Serial.begin(9600);
}

void loop()
{
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState)
  {
    if (buttonState == HIGH)
    {
      counter++;
      Serial.println("Hi !");
      Serial.print("Number of button pushes:  ");
      Serial.println(counter);
    }
    else
    {
      Serial.println("Button off");
    }
    delay(50); // Delay a little bit to avoid bouncing
  }
  lastButtonState = buttonState;
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Do software SPI read from a register using shiftin()
How to read from a register using software SPI, presumably shiftin()?
It works using the builtin SPI library + hardware SPI.
I seem to be able to write but not read using manual shiftin()/shiftout(). I need to do this because I need a version of this to work on a device that doesn't have hardware SPI. I always read out 0x00000000 using shiftin() as below, but the SPI hardware/library works as expected.
(yes, I've double checked the pin numbers). LIS_MISO_PIN = 12.
  // this works (write):
  SPI.transfer(WriteAddr);
  SPI.transfer(Data);

  // this works (write):
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, WriteAddr);
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Data);

  // this works (read):
  SPI.transfer(Reg | 0x80);
  *input = SPI.transfer(0x00);

  // does NOT work, as well as various permutations:
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Reg | 0x80);
  *input = shiftIn(LIS_MISO_PIN, LIS_SCK_PIN, MSBFIRST);

SPI reading is done one byte at a time, how would shiftIn handle that?

Is your LIS_MISO_PIN set as INPUT? Does your device use SPI mode 0?

How about using SoftSPI? ShiftIn/Out does not work. https://github.com/MajenkoLibraries/SoftSPI

How do you declare and initialize "input" ? This smells of uninitialized pointer...

Could you please add a link to the software SPI that you have used.


text:
Why does my Arduino Nano send the wrong voltage on a digital output PIN?
Adruino nano powered by 12v through VIN pin.
Normally I expect ~12v on digital output pin, when i write HIGH to this pin, and ~0v when i write LOW. But what I have instead
digitalWrite(pin, HIGH); // I have 1.5v on pin
digitalWrite(pin, LOW);  // I have 0.5v

Algorithm is quite simple - On push button toggle output pin state.
Connections:

VIN - +12v
GND - ground
d2 - input pin (0 0, 12 - 1, button);
d3 - output pin (we change state of this pin)

Input works as expected.

simulate this circuit – Schematic created using CircuitLab

Code: http://pastebin.com/77hqTuWA

You put 12V on an input pin? You likely fried something. ATMega are 5V max devices.

USB powered with LED instead of Voltmeter is working fine. R1 is 47k BTW

With 47k as the pullup to 12 V you probably have not fried your AVR. It's only 100 uA into the protection diodes in the processor. But you do need to change that ....it's definitely not a good thing to do. You can either turn on the internal pullup or add one to the 5 V rail (say 1K or higher).  For the output pin I'd posit you have some load you are driving and it's too heavy for the port. Restrict your output current to 20 mA or less (either source or sink). The processor stands up well to too a high a sink current, but you can blow the internal rails in the chip if you source too much.

why not just use INPUT_PULLUP on D2 and remove the 12v pullup parts completely?

@Neka "R1 is 47k BTW" - If it's 47kΩ, then put it in your diagram as 47kΩ, not 100Ω! How do you expect people to give useful answers with such misinformation?

The microcontoller in an Arduino operates on 5 Volts (or perhaps 3.3 Volts).  An on-board voltage regulator reduces the 12 Volt input to 5 volts for the ICs on the board.
Connecting the pull-up resistor (R1 in your drawing) to 12 Volts may damage the microcontroller (especially if it is really 100 Ohms as your drawing shows).  The pullup resistor must be connected to the 5 Volt pin on the Arduino board.
The output voltage of an Arduino pin should be near 5 Volts, but may be less if you place a heavy (high-current) load on it.

The arduino is powered by 12v but regulates down to 5v or 3v for the microcontroller. Then your output pin current is important. Anything over 20mA will result in a large voltage droop due to the ESR of the pin. Highly depends on your circuit and your full code.

As others have said, you should not pull d2 to 12 V. You are
sending about (12 V − 5 V) ÷ 100 Ω
= 70 mA into the high-side diode that protects that input pin.
This diode is only rated for 1 mA, thus you will likely fry it in a
short time.
To avoid the damage, you could increase the value of R1 in order to
lower that current to a safe value, but it would be simpler and safer to
completely remove the resistor and use the internal pullup instead, as
in
pinMode(2, INPUT_PULLUP);

As for the measured output on d3, you expect 5 V when the pin is
written HIGH. Your 1.5 V reading is suspicious. My guess is that
you forgot to
pinMode(3, OUTPUT);

In this case, writing the pin to HIGH does not have the expected
effect. Instead, it activates the internal pullup, which should make the
pin read 5 V, but then even a very small load (about 0.1 mA)
can make the voltage drop to 1.5 V.
If you are really getting 1.5 V while the pin mode is set to
OUTPUT, then you are really pulling far too much current from the pin.
My guess would be around 130 mA (a 26 Ω output resistance is
typical). The absolute maximum rating for the pin is 40 mA, so
again, you are going to fry something.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to drive a strip of 12 V no-addressable LEDs?
I recently bought this LED Strip. I got the 5M 3528 300LEDs SMD RGB Non-waterproof ones. However, I am not sure how to use them. On the strip there is four wires. I have tried supplying power to the wire that says it needs power and then I put ground to each of the other wires, but that only turns on a colour. How do I make it so I can choose what colour to use (Wiring, Code, etc.)?

The page you link to sells different models of LED strips. Some of them, which are based on the WS2812B chip, allow the LEDs to be individually addressed. However, the strip you got has no WS2812B and is not addressable. The original title of your question, “WS2812B LED Strip”, was then extremely misleading. That's why @Orotavia posted a first answer that is not applicable to your strip. I edited the title to better reflect the reality.

EDIT: I'm sorry, I misunderstood! I assumed your LEDs were the 4pin serial version, whereas it makes more sense to me that they are the 6pin analog version. I must've brushed over the part where you said you grounded the colored wires and got that corresponding color.
You will provide 12V to the Power wire. To light the strip Red, you'd ground the Red wire, ground Blue for Blue, etc. Ground Red and Blue to light Purple, mixing colors etc etc.
So what if you wanted teal? or maybe a different shade of green? You'll need a way to generate PWM on the R, G, and B pins. Basically if you have an 80% duty cycle on Blue, that means it's only grounded 80% of the time. This corresponds to 80% brightness of the blue LEDs, then you could mix that with say 60% red and 10% green, or whatever you wanted to get a full 16 million colors. This is most easily accomplished with a microcontroller, and so I'll provide schematic and code tips for the simplest solution: an Arduino.
Schematic

simulate this circuit – Schematic created using CircuitLab
I chose Pins 9, 10, and 11 of the Arduino because they are all PWM; you can choose any PWM pins you want (denoted by ~ or # usually). Just reflect those changes in the sketch.
Arduino pins are also only capable of sinking about 40mA if I remember correctly, so you'll need to control some MOSFETs with the PWM. I find you can't go wrong with the IRFZ44N, but that's just what I've had available to me.
Arduino Sketch
How you control it is up to you; sensors, potentiometers, networked, bluetooth, constant fade pattern, there's a slew of options. So this code will tell you the necessary functions, but from there it's a matter of programming and integration of whatever else you want.
void setup(){
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop(){
  //255 -> 100%   ;   0 -> 0%
  analogWrite(9, 255); // turn red to 100%
  analogWrite(10, 0); // turn green to 0%
  analogWrite(11, 128); // turn blue to 50%
}

If this doesn't work, please let me know and I'll fix it. I forget if analogWrite is okay with being called in a simple, unrestrained loop over and over, and I also forget if Arduino pins have internal pull-downs

The line's on the strip are Power, Red, Green, Blue

Sorry, I've misunderstood! I've edited my post to hopefully better answer your question.

Note that the specs of the strip mention “Working Input Voltage: 12VDC”.

Note also that 1) The MOSFETs will invert your signal: Arduino pin HIGH → MOSFET conducting → strip line grounded → LED shines. 2) You may want to add pulldowns to the MOSFET gates, as the Arduino Uno has no internal ones: at power-up the output pins will float for about one second while the bootloader runs.

Oops, yeah I didn't even select the correct LED strip for 12V. I've also fixed the inversion issue and added pull-downs. Sorry for so many errors, Amorris, I think Edgar Bonet has caught them all now though, should be good to go.

This code only displays a bright red and a dim blue, not a teal colour or whatever colour you said it would make. If you could, please link to a page for some addressable WS2812B strips? Luckily, I only bought those for $4 :P

The PWM explanation section was just to describe PWM, sorry if that wasn't clear but it doesn't match up to the code. Modify the numbers as you see fit to get the color you want, be it teal or any other. As for an LED strip, just google 'WS2812B LED Strip', you'll find tons. WS2812B are the addressable ones, WS2812 (no B) are NOT addressable. Be careful with eBay sellers claiming they have addressable LEDs when they really don't. An alternative is SK6812 too, those are addressable.


text:
LED fade with LDR sensor depending on the light
I need help on a project. I just started to experiment with arduino 2 weeks ago and I am building a lamp that react to movement and interactions.
So the idea is; when there is nobody in the room, the light stay white.
And when there is someone, it turns orange and I want it to « breathe » (fade function).
I am using a LDR sensor to make it happen and so far my code looks like:
int LDRvalue = 1;
int RedLED = 9;
int GreenLED=10;
int BlueLED=11;
int pinLDR = A0;

void setup()
{
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
Serial.begin(9600);

}
void loop()
{
LDRvalue = analogRead(pinLDR);
Serial.print("valeur ldr: ");
Serial.println(LDRvalue);

int colour = map(LDRvalue, 0, 1023, 0, 255);
Serial.print("valeur mappe: ");
Serial.println(colour);

if(LDRvalue >= 1023)
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);
}

else if((LDRvalue >= 800) & (LDRvalue < 1023))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);

}

else if((LDRvalue >= 600) & (LDRvalue < 800))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 105);
analogWrite(BlueLED, 0);
delay(1000);

}
else if((LDRvalue >= 300) & (LDRvalue < 600))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 35);
analogWrite(BlueLED, 0);
delay(1000);
}

else if((LDRvalue >= 150) & (LDRvalue < 300))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 15);
analogWrite(BlueLED, 0);
delay(1000);

}

else if((LDRvalue >= 0) & (LDRvalue < 150))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 0);
analogWrite(BlueLED, 0);
delay(1000);
}

delay(1);

}
void color(int red, int green, int blue)

{
analogWrite(RedLED, red);
analogWrite(GreenLED, green);
analogWrite(BlueLED, blue);
}

The code is working for the light changes depending on the human presence.
But I don’t know how to make it fade and breathe when it turns orange.
Could you help me to make it happen ?

For one, you need to change the & in your if statements with &&. & is a bitwise AND, && is a logical AND. Which one of the if statements is orange? It seems like you have 3 different kinds of orange.

Thanks for the answer, I have 3 orange because the more there is a light change the more it turns orange to red. I forgot to talk about it. But for each of these orange, I need it to breathe, maybe more each time.

While some parts of your code don't make much sense to me, the breathing led code is easily searchable on the internet, with one of the first results being:
#include <math.h>
#define ledPin 11
int i=0;
int breathe_delay = 15;   // delay between loops
unsigned long breathe_time = millis();
void setup() { }
void loop() {
  nonBlockingBreath();  // call the nonblocking function
  // yourOtherCodeHere();
}

void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    // this is the math function recreating the effect
    analogWrite(ledPin, val);  // PWM
    i=i+1;
  }
}

As you can see the code above works for monochromatic LEDs only, so my advise is to combine the code above with a conversion from HSL to RGB, like RGBConverter library, specifically the hsvToRgb function.
This way your version of the nonBlockingBreath function will become:
byte[3] rgb;
void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float value= (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    hsvToRgb(hue, saturation, value, rgb);
    analogWrite(RedLED, rgb[0]);  // PWM
    analogWrite(GreenLED, rgb[1]);  // PWM
    analogWrite(BlueLED, rgb[2]);  // PWM
    i=i+1;
  }
}

Obviously you will have to set the hue and saturation variables accordingly to the tonality of orange you wish to breath.


text:
Arduino Audio Recorder - Speed Correct but Wrong Pitch
I'm working on an audio recorder project on an Adafruit Adalogger with SAMD21 ARM-based processor using the Arduino IDE. The desired sampling frequency is 10 kHz, 12-bit resolution with an analog (MEMS) microphone. I'm saving data to an SD card in binary format.
The code I've provided below is working almost nearly exactly as desired. My only issue comes about when playing back the recorded data on my PC. The recording speed is correct if I playback at 10 kHz sampling frequency, but the pitch of the sound recorded is much too low (exactly 0.5 times what it should be). On my PC, if I playback at 20 kHz, the speed is of course 2x, but the pitch is now correct. FYI pitch and speed are related quantities, when increasing one, the other should also increase linearly (i.e. increase speed 2x, pitch should be increased 2x as well).
If I record in 8-bit resolution, I have no issues; both the playback speed and pitch are as desired. The speed/pitch issue only comes about when saving in 16-bit mode. I should note as well the Adafruit only has a 12-bit ADC, however by selecting 16-bit analog read resolution, it pads the initial four spots with zeros. My issue keeps coming back to the way in which I'm saving the data, I think it's a simple solution, but just can't seem to figure out where the mismatch is coming from.

#include <SPI.h>
#include <SdFat.h>
#include <stdint.h>

SdFat SD;
File myFile;
#define SD_CS_PIN 4

int mic = A0;
const int btnStart = 5;
const int btnStop = 6;
const int ledStart = 12;
const int ledStop = 13;
int recPressed = 0;
int stopPressed = 0;
int flag = 0;
uint16_t buf00[512]; // buffer array 1
uint16_t buf01[512]; // buffer array 2
unsigned int bufByteCount;
unsigned long recByteCount = 0L;
unsigned long recByteSaved = 0L;
byte bufWrite;

static void   ADCsync() {
  while (ADC->STATUS.bit.SYNCBUSY == 1); //Just wait till the ADC is free
}

void setup() {

  // ADC Setup
  // ---------------------------------------------------------------------------------------------------------

  // Set gain and voltage reference
  ADCsync();
  ADC->INPUTCTRL.bit.GAIN = ADC_INPUTCTRL_GAIN_1X_Val;      // Gain factor select as x1
  ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_INTVCC0_Val; // Internal voltage reference used

  // Set sample length and averaging
  ADCsync();
  ADC->AVGCTRL.reg = 0x00; //Single conversion no averaging
  ADCsync();
  ADC->SAMPCTRL.reg = 0x0A; //sample length in 1/2 CLK_ADC cycles Default is 3F

  // Set prescaler, resolution, and mode
  int16_t ctrlb = 0x0400; // Control register B hibyte = prescale, lobyte is resolution and mode
  ADCsync();
  ADC->CTRLB.reg =  ctrlb;

  analogReadResolution(16); //Set bit-resoltion of ADC (12-bit max)
  // ---------------------------------------------------------------------------------------------------------

  // Clock timer setup used for interrupts
  // ---------------------------------------------------------------------------------------------------------

  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  //REG_TC4_COUNT16_CC0 = 0x0087;                 // Set the TC4 CC0 register for standard audio range (22.05kHz sampling rate)
  REG_TC4_COUNT16_CC0 = 0x0095;                   // Set the TC4 CC0 register for standard audio range (20 kHz sampling rate)
  //REG_TC4_COUNT16_CC0 = 0x012B;                 // Set the TC4 CC0 register for sleep apnea range (10 kHz sampling rate)
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  // REG_TC4_INTENSET = TC_INTENSET_OVF;          // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV16 |     // Set prescaler to 16, 48MHz/16 = 3MHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ---------------------------------------------------------------------------------------------------------

  pinMode(10, OUTPUT); // DON'T change this - Hardware CS pin must be left as output for SD library functions to work correctly
  pinMode(ledStart, OUTPUT);
  pinMode(ledStop, OUTPUT);
  pinMode(btnStop, INPUT_PULLUP);
  pinMode(btnStart, INPUT_PULLUP);

  if (SD.begin(SD_CS_PIN, SPI_FULL_SPEED)) { // initialise card on SPI to 8MHz SPI bus speed
    for (int dloop = 0; dloop < 4; dloop++) {
      digitalWrite(ledStart,!digitalRead(ledStart));
      delay(100);
    }
  } else { // if error, flash LED twice per second, until reset
    while(1) {
      digitalWrite(ledStart,!digitalRead(ledStart));
      delay(500);
    }
  }
}

void loop() {

  if (digitalRead(btnStart) == LOW && recPressed == 0) {
    StartRec(); // launch StartRec method
  }
  if (digitalRead(btnStop) == LOW) {
    StopRec(); // launch StopRec method
  }

  if (flag == 1) {
    recByteCount++; // increment sample counter
    bufByteCount++;
    if (bufByteCount == 512 && bufWrite == 0) {
      bufByteCount = 0;
      bufWrite = 1;
    } else if (bufByteCount == 512 & bufWrite == 1) {
      bufByteCount = 0;
      bufWrite = 0;
    }

    if (bufWrite == 0) {
      buf00[bufByteCount] = analogRead(mic);
    }
    if (bufWrite == 1) {
      buf01[bufByteCount] = analogRead(mic);
    }
    flag = 0; // clear interrupt triggered flag
  }

  if (recByteCount % 1024 == 512 && recPressed == 1) { myFile.write(buf00,512); recByteSaved+= 512; } // save buf01 to SD card
  if (recByteCount % 1024 == 0 && recPressed == 1) { myFile.write(buf01,512); recByteSaved+= 512; } // save buf02 to SD card
}

void StartRec() { // Start recording method

  digitalWrite(ledStart,HIGH);
  digitalWrite(ledStop,LOW);
  recByteCount = 0;
  recByteSaved = 0;
  recPressed = 1;
  stopPressed = 0;
  myFile = SD.open("recordingvoice.bin", FILE_WRITE);
  REG_TC4_INTENSET = TC_INTENSET_OVF;
}

void StopRec() { // Stop recording method

  REG_TC4_INTENCLR = TC_INTENCLR_OVF;
  myFile.close();
  digitalWrite(ledStart,LOW);
  digitalWrite(ledStop,HIGH);
  recPressed = 0;
}

void TC4_Handler() { // Interrupt method
  if (TC4->COUNT16.INTFLAG.bit.OVF && TC4->COUNT16.INTENSET.bit.OVF) {

    flag = 1; // set interrupt triggered flag

    REG_TC4_INTFLAG = TC_INTFLAG_OVF;         // Clear the OVF interrupt flag
  }
}

I'm using a MATLAB script I've written to playback the data, notably v.2012 since it provides the "specgramdemo" function which I'm utilizing to visualize the spectrogram and also, but less importantly, provides playback functionality of the recording.
close all
clear all
clc

[inStr, pathStr] = uigetfile('*.bin','input files','D:');
A2 = inStr;
fid = fopen([pathStr, inStr], 'r');
% [filename, permission, machineformat] = fopen(fid)
sixteen_bit_pad = fread(fid, inf, 'uint16', 'ieee-le');
fclose(fid);
sixteen_bit_pad = sixteen_bit_pad';

% prompt = {'Enter sampling frequency for recording in Hz:'};
% dlg_title = 'Sampling Frequency';
% num_lines = 1;
% defaultans = {'10000'};

% Fs = str2double(inputdlg(prompt,dlg_title,num_lines,defaultans));
Fs = 20000;

twelve_bit = zeros(size(sixteen_bit_pad));
twelve_bit(1:1:end) = bitshift(sixteen_bit_pad(1:1:end),-4);

time = linspace(0, length(twelve_bit)/Fs, length(twelve_bit));

figure, plot(time, twelve_bit)
xlabel('Time (seconds)'); ylabel('Amplitude (12-bit Value)');
specgramdemo(twelve_bit, Fs)

If you happen to have these tools at your disposal and want to hear first-hand the mismatch, I've included a .bin file that has some voice/breathing sounds recorded. File here: Binary File

How many bytes/second are in the recorded file? eg. if you record for 10 seconds what is the file size / 10? flag should be declared volatile.

What are you using to play back the audio on the PC? Are you remembering to tell it about the difference between files containing 8-bit samples and files containing 16-bit samples? It sounds like you're trying to play back the 16-bit files with software that is expecting 8-bit samples. Are you also getting a lot of distortion on loud sounds?

@BruceAbbott Thanks Bruce, noted and will update my code to reflect such! By no means am I a programmer, still learning as I go and appreciate the quick tip. For a duration of 10.2016 seconds, I've recorded 204,032 samples. With each sample being 2 bytes length, total of 408,064 bytes. 408,064/10.2016 gives 40,000 bytes/second.

@DaveTweed, I'm using a MATLAB script I've written to playback the data, notably v.2012 since it provides the "specgramdemo" function which I'm utilizing to visualize the spectrogram and also, but less importantly, provides playback functionality of the recording. I've updated my original post to include the script. I do get some distortion yes, some "clicking" sounds in the recording and saturation of the signal with high amplitude sounds.

"For a duration of 10.2016 seconds, I've recorded 204,032 samples" - you have twice as many samples as you should have, which suggests that you are recording 2 samples per interrupt - which would mean the flag is not working as expected.


text:
Arduino Mega 2560 SoftwareSerial Not Working
We have an xBee Pro S2C that is using this library (https://github.com/andrewrapp/xbee-arduino) very well on a Software Serial connection to ports 2 and 3 on an Arduino Uno. However, when we take the same setup and try it on a Arduino Mega 2560 using any of the ports specified here:
*
https://www.arduino.cc/en/Reference/SoftwareSerial

Not all pins on the Mega and Mega 2560 support change interrupts, so
  only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51,
  52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14
  (68), A15 (69).

*
We cannot get this setup to work on the Arduino Mega 2560. We did not try every combination of these ports but tried most of them and it continues to fail. We can get successful packets on an Uno on pins 2 and 3.
Code is as follows:

#include "Arduino.h"
#include "laser_essentials.h"
#include "XBee.h"
#include <SoftwareSerial.h>
#define IS_STAR 1
#if IS_STAR

#define rxPin 10 //input
#define txPin 11 //output
#else
#define rxPin 2 //input
#define txPin 3 //output
#endif
#include "SoftReset.h"

///setup xbee object

XBee xbee = XBee();
SoftwareSerial xBeeSerial = SoftwareSerial(rxPin, txPin);

//Setting up class & contructors

Laser::Laser () {

        pinMode(rxPin, INPUT);
        pinMode(txPin, OUTPUT);
        xBeeSerial.begin(9600);
        xbee.setSerial(xBeeSerial);
        Serial.begin(9600);

Any thoughts as to why this might not work on a Arduino Mega?

Does the Mega work at all? Can you flash an LED with it?

Yes, we have tried some basic sketches and all seem to perform fine on it.  In addition, we have the same issue on a completely different Mega, so we must be doing something wrong.

Why use software serial in the first place? A Mega has multiple hardware serials.


text:
How can I learn to use Generic ESP8266 boards Libraries in Arduino?
I am new to ESP8266. I am using the Arduino IDE to program the ESP8266-01 module. How can learn to make my own codes for ESP using Arduino?
I am going through the example programs and learning which part of the code does what. But, is there a better way to understand the syntax of those libraries.
Thanks!!

there's not much to learn; it's like an UNO with some extra libs built-in...

They publish a reference page for the included libraries at each release of the ESP8266 core for Arduino. The latest at this time is here:
http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html
You can adjust that URL for the release version you're using.
The libraries try to follow the API of the standard Arduino libraries and that documentation mostly focuses on the differences. So you will also find some documentation for these libraries in Arduino's library reference pages:
https://www.arduino.cc/en/Reference/Libraries
and the reference pages for the Arduino core API:
https://www.arduino.cc/en/Reference/HomePage
Of course the definitive (albeit less beginner friendly) reference will always be the source code. There are two ways to quickly determine the location of the source code for a library:
Option 1:

Select the appropriate board from the Tools > Board menu. The Arduino IDE may select the library to be used based on which board is selected.
File > Examples > {library name} > pick any example
Sketch > Show Sketch Folder. This will open the {library name}/examples/{example name} folder. The source files for the library will be found in the library root folder, src folder, or utilities folder.

Option 2:

File > Preferences > Show verbose output during: > compilation (check) > OK
Write or open a sketch that includes the library.
Sketch > Compile/Verify
Wait for the compilation to finish.
Examine the contents of the black console window at the bottom of the Arduino IDE window. The path to any library used by the sketch will be found in that output.


text:
High power consumption of ATmega32u4 when connected to iOS device
Just wondering if I can get some help here.
I have a simple scheme of MIDI controller based on ATmega32u4:
ATmega32U4 with TXLED and RXLED as output pins and USB functionality
And my team wants me to make this device Android/iOS compatible (because our Arduino prototypes worked fine with iPads and even iPhones).
I am experiencing a high power consumption of ATmega32u4 when connected to iOS devices. When we connect our device to iOS we get the following message:

Meanwhile, when I make almost the same scheme and run the identical sketch on ATmega328 chip it works just fine!
I tried running all the stuff on Arduino boards, and the result is stable:

works on Arduino Uno and Arduino Mega (based on ATmega328 chip);
doesn't work on Arduino Micro and some of its Chinese clones like Arduino Micro Pro (based on ATmega32u4).

We've found a small trick/workaround: connect even two our ATmega32u4 devices through an active USB hub with additional power supply to one iPad, and they both work perfectly, then we switch off the additional power on the hub, and devices continue to work fine using the power from this single iPad without any messages about high power consumption.
This case leads me to the thought that high consumption of ATmega32u4 chip appears only on the device initialisation stage.
Is there a way to solve this?
Thanks in advance.

It would help if you provide a schematic or summary of the power supply/distribution on your device.  What is connected and how much current does it use? How much capacitance is connected? Also, you could get a lot of useful information about power-on transients with an oscilloscope and a current probe.

The schematic is available through the first link provided. Basically, I have no any power-eager devices, it is just digital inputs, even with no analog inputs available. When I leave only diode matrix, the problem stays the same. That is why I consider that the problem in ATmega32u4 chip rather than schematic (the same schematic with ATmega328 chip works fine).

Moreover. If I disconnect all of the input switches and potentiometers leaving just plain Arduino Micro clone with basic MIDI device sketch, connected iOS device complains about high power consumption. Arduino Uno (ATmega328 based) device is working fine here.

If it's too much trouble for you to add a schematic to your question, I'd guess it'll probably be too much trouble for some to bother trying to answer it.

do you have big caps on there that cause a high inrush current that a powered hub doesn't mind supplying?

The idea of questions on SE is that they are self-contained and meaningful without having to look at external links that may vanish later

The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.
You can connect your controller to a computer and check USB properties to confirm this.


text:
Where is Arduino on Fedora?
I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

It depends how you installed it.
If you downloaded the tarball and extracted it then it's wherever you extracted it.
If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.
If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in ~/.arduino15

Assuming you have installed the tool from the Fedora repositories (that is, using yum/dnf or from the Software tool), the command to run the IDE will be installed at /usr/bin/arduino and you can run it from the command line just by typing arduino — or do the same in the search box in GNOME Shell.
Most of the package itself, including examples and libraries, will be installed under /usr/share/arduino.
And, once you run that program, it will create a new "sketchbook location" at ~/Arduino — that is, a folder named "Arduino" in your home directory. If you've run the IDE already, that folder will already exist.


text:
Easy bipolar motor control?
Is here some easy way to control bipolar motor
 without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise  and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

It depends on the motor but is quite unlikely for most motors due to the limited current (and voltage) the Arduino's GPIO pins can provide.

I have 4 wire motor

Please give us more details.  It will attract better answers.

Welcome to Arduino SE.  Be sure to take the tour to see how things work here:  https://arduino.stackexchange.com/Tour

Please edit your question (click the edit button, etc) and tell what you mean by control – ie, turning the motor on/off, or changing direction or speed, etc.  Also list motor model number or specs  – a low-voltage micromotor might not need external parts, but most motors will.  If you improve the question people may vote it up.

No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.
You need a motor driver (or at least some transistors and diodes etc) to control the motor.

Taking a guess here, the current this motor requires will be exceeding the safe operation limits of the Arduino's GPIO pins. Furthermore without a flyback diode the voltage spike across the motor (an inductive load) when the current is reduced/switched off might kill the GPIO pin.
You will need a motor driver or transistor with flyback diodes to operate it.
This is a nice tutorial that has it sorted out for a CD ROM brushless motor.

It's not just about the current - back EMF from the motor's coils will do nasty things to the Arduino.


text:
How to Read Voltage Level?
I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.
volts = analogRead(A3);    // read the input pin
Serial.println(volts)

Show where and how in your code you declare volts, and how are you wiring the voltage you want to read to the analog input.

Also, in what way is this not working?

Other than missing the semicolon on the end of the second line, this chunk of code will work. Can you please show your whole program?

Note that instead of printing out the number of volts on the input, it will output an ADC count that stands for some number of volts; by default, 1024/5 counts per volt.

//use this syntax and add ; sign at end of each line and try to read voltage level via voltage divider circuit.
volts = analogRead(A3);    // read the input pin
Serial.println(volts);             // debug value

First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.
float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!

Your first solution will always be 0. 5 / 1024 does integer division which always results in 0. Any number multiplied with 0 is then 0.

@gre_gor I stand corrected! Good catch. I completely forgot about that. :)


text:
What's wrong with my code?
I was trying to do a LED display that turns on a LED at pin 13 that goes on then turns off after a delay then the next pin (which is pin 12 counting down) will turn on and then turn off.
I also put in a potentiometer that can change the delay to make it faster or slower.
Here's the code:
float pinOn = 13;
int outMin = 0;
int outMax = 13;
float delayNum = 1000;

void setup () {
  for (int i=outMin; i<=outMax; i++) {
  pinMode(i, OUTPUT); }
  Serial.begin(9600);
}

void loop () {
  // Reads Potentiometer -- sets delay relative to the Potentiometer input
  int sensorValue = analogRead(A0);
  delayNum = sensorValue;
  // Turns on the Pin designated by 'pinOn'
  digitalWrite(pinOn, HIGH);
  delay(delayNum);
  digitalWrite(pinOn, LOW);
  // Checks if 'pinOn' is 0 which then resets it back to 13 if not 0 then counts down
  if (pinOn = 0) {
    pinOn + 13;
  } else {
    pinOn - 1;
  }
}

All it does is turn on pin 13 for a moment then permanently turns on pin 1 and 0 and it gets stuck like that.

Bugs like this are why everyone should learn to use a debugger, and enable all warnings on your compiler -- every modern compiler will catch if (a = b) and warn you about it if you enable all warnings and, ideally, make it treat warnings as errors. I also think this counts as a "general coding" problem; if you replaced the contents of the blocks with puts("foo") or other non-Arduino C statements, the answer would be exactly the same.

if (pinOn = 0) is doing an assignment (single =) not a comparison (double ==), so pinOn is begin set to 0 each time through the loop. The result of an assignment is the value being assigned. So it's the same as if ( 0 ), which is false.
Now, on to the two branches. pinOn + 13 is a statement and the result is not being assigned to anything. You need an equals sign somewhere:
if (pinOn == 0) { // == means "is equal to"
  pinOn += 13; // same as pinOn = pinOn + 13
}
else {
  pinOn -= 1;
}

Thanks so much! I forgot that the comparator equals is supposed to be '==' not '=' :P it works now thank you!


text:
Arduino Mega Shield Library for Eagle CAD
I'm a noob to PCB designing and electronic stuff. I want to design a pcb shield which is compatible with an Arduino mega 2560. I'm using Eagle CAD. I checked the sparkfun library but I couldn't find a way to design Mega Shield. Can anybody give me a library or any alternative way to do this?

You should try Circuit Maker instead.

Alright Thanks @Jeroen3 I'll give a try. Is it comes with inbuilt libraries for Mega shields?

Try KiCAD, there are plenty of templates for Arduino, Raspberry, BeagleBone etc.

Since you're new user, perhaps it's easier to take an existing project and modify it for your need.
For Eagle, examples can be found on Github.

https://github.com/zortness/rocket-mega-shield
https://github.com/practicalarduino/ProtoShieldMega

However, due to recent developments in the PCB EDA world I would suggest you take a look at Circuit Maker. It's more fit for sharing an collaborating designs and libraries. You can easily fork an existing board and use their community parts repository.


text:
How can I get my Attiny85 interupt to trigger
I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.
I decided to do the code using the arduino IDE and the code is as follows:
const int hallPin = 2;     // the number of the hall effect pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);

  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

void loop()
{
  if(hallState>1)
  {
      digitalWrite(ledPin,HIGH);
      delay(2000);
      digitalWrite(ledPin,LOW);
      delay(2000);
      hallState=0;
  }
}

void pin_ISR()
{
    hallState++;
}

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.
Here is the circuit:

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.
So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85
Edit: Adding Schematic

I would do some testing on different pieces of the project.

I would do some testing on different pieces of the project. It looks like your LED might be connected backward. I don't use that part so I wonder is "loop()" really the normal "main()" entry point? I would try the code in loop() by replacing "if(hallState>1)" with "if(1)" just to make sure the LED will actually blink. Do you need to enable interrupts or is that implied somehow?

Hi, thanks for the comment. I actually already tested the LED works by commenting out the IF statement and replacing the loops contents to turn the LED on for 2 seconds then off for 2 seconds. this worked fine and the LED did exactly that. This leads me to believe its the interrupt code thats a bit flaky

Have you tried writing it as a normal ISR and enabling the interrupt yourself instead of using attachInterrupt()?

@IgnacioVazquez-Abrams Not yet, I shall read up on how to do that and see if I can get that to work. Thanks for the suggestion.

Please add a schematic.

@uint128_t I have added the schematic as an edit at the bottom.

Your LED is backwards, for a start. Have you verified with a DMM/scope that the output of the hall-effect sensor is changing state? You will also want to make sure (by reading the source code) that pins are being mapped the way you think they are.

The LED is fine in the circuit its just backwards in the diagram. (short pin connected to ground) I've used a multi meter to verify the hall effect sensor voltage drops low when a magnet is brought in the vicinity.
As I said above i've tested using a 2 second timer in the loop turning the LED on and off, so there problem is not there. Its within the interrupt but im not sure where exactly. The problem with the ATTINY85 is theres no serial debug :(

"its just backwards in the diagram" - then draw a proper diagram. Draw a schematic of what you have actually connected up, otherwise it just wastes our time.

Pull-up resistor on reset is where? Decoupling capacitors on the supply rails?

Are you sure attachInterrupt(0, ... is correct? i.e., that 0 is the right interrupt? Maybe try with digitalPinToInterrupt(pin), as the documentation suggests.

@marcelm interesting thought. Though the Atmel documentation states that the interrupt can only be on pin 0

@Festivejelly the Atmel documentation will state nothing about "pin 0". That is an Arduino-esc abstraction of which there are many different version depending on what core library you use. The Atmel documentation will talk about "INT0" which is the alternative function of one of the pins (for the ATTiny85, this is on PB2).

@TomCarpenter I see that makes sense now. I made the erroneous assumption that meant pin0. With this in mind I should be able to fix this...

Okay so I think my code was okay. Its just for the attiny85 attachinterupt you still feed in 0 as the pin value but the actual pin is pb2 or physical pin 7... phew confusing. It still wasnt working so I added a pullup resistor between the positive hall pin and the digital out of the hall and voila! It now works. Thanks to all you guys pointing out my shoddy understanding of how the pins work.

You main problem is that you have wired up your MCU wrong.
Pin 5 (PB0) is not the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.
As a result your code will not do anything when the hall sensor changes because it is not looking at it.

I would suggest not trying to use the attachInterrupt() abstraction. Instead I would simply enable the external interrupt directly:
GIMSK |= _BV(INT0);

And use a proper ISR handler:
ISR(INT0_vect) {
    //Your ISR code here.
}

Thats interesting, I think i've been getting confused between the pin numbers and the physical pin locations.

You were of course correct. Thanks for clearing that up. It makes a lot more sense now. I've plugged it into pin 5 because I read somewhere attachInterrupt had to be set to 0 so I figured the wire had to go to physical pin 5 (pb0). This is apparently not the case. I guess that function simply enabled the interrupt with the default value.


text:
Connecting an Arduino Nano, Mega and LCD via I2C works but fails when shutting down Mega
I have connected an Arduino Nano, Mega and a LCD via I2C/TWI (SDA/SCL).
The Nano is playing the master while Arduino Mega and LCD are slaves. This works well till I power off the Arduino Mega. Of cause I don't expect the Mega to answer.
In particular the SCL line seems to pull-down the connection. Disconnecting SCL from the Mega will reestablish the connection to the LCD. I added two pull-up resistors 4.7k to both SDA SCL but no improvement from that.
Is there no way than physically disconnecting the lines?

See
How to setup an I2C bus which stays valid if a slave is powered down or fails?
Basically I2C uses pull-ups to have all lines HIGH until any device bring it LOW. Arduino uses INPUT_PULLUP / OUTPUT+LOW states for this. But if you switch Arduino off (turn off Vcc), internal diodes cut the power on pins to Vcc (which is zero) +diode voltage (which is small), effectively to logical LOW. And I2C see that as the device is activelly sending LOW all the time - so communication is blocked.
If you just add pullup resistors, you either have them high enought so it not prevent this state or you have them low enought to draw the lines HIGH even when there is LOW on device, which prevents other devices to draw them LOW for communication. You need "cut off" such incactive lines - either physically disconnect (pull wires from connector - such as if you just get the Mega out of socket, or use some relays powered from Mega Vcc, which disconnet them when the power goes out) or electrically disconnect - using some circuits designed for it. There are some already sold or you can create your own to the same efect (if you are skilled in this area - otherwise it is much easier and faster to pay for some already made solution)

Or... don't power off the Arduino Mega. Use the same power supply for everything that is connected to the same I2C bus.

Well it would work too :) But I think, there is a reason, why the user wants to power off one of its arduinos, otherwise he would not get in the problem at all.

BTW: I use setup, where I2C network uses 4 wires -SDA,SCK, GND and PWR - so I just power up the I2C bus with pullups and anything connected via I2C is powered from the same source (the I2C bus serves also as Power grid - and can be powered from real power source, not just Arduino). So either it is connected to I2C and powered, or it is not powerd, but also not connected to I2C at all.

that is what we are here for: recognizing what could be a xy-problem: http://xyproblem.info/  My main Arduino Mega project has two of 5 wires. A 5V I2C bus with 5V power plus a interrupt signal and a 3.3V I2C bus with 3.3V power and interrupt signal. The interrupt signal is to detect when a Slave needs attention, for example alarm signals from motion sensors.

There are I2C Multiplexers/Switches that you can use to disconnect automatically such as the PCA9540. I do not know if they are available on breakout boards.


text:
How to write a digitalWrite array for MCP23017 expander chip?
I'm using multiple expander chips for my project and I was wondering if there is a way to shorten the loop code by using array? So that I don't have a super long code.
void setup() {
  mcp.begin(0);
  mcp1.begin(1);
  mcp.pinMode(0, OUTPUT);
  mcp.pinMode(1, OUTPUT);
  mcp.pinMode(2, OUTPUT);
  mcp.pinMode(3, OUTPUT);
  mcp.pinMode(4, OUTPUT);
  mcp.pinMode(5, OUTPUT);
  mcp.pinMode(6, OUTPUT)
  mcp.pinMode(7, OUTPUT);
  mcp1.pinMode(0, OUTPUT);
  mcp1.pinMode(1, OUTPUT);
  mcp1.pinMode(2, OUTPUT);
  mcp1.pinMode(3, OUTPUT);
  mcp1.pinMode(4, OUTPUT);
  mcp1.pinMode(5, OUTPUT);
  mcp1.pinMode(6, OUTPUT);
  mcp1.pinMode(7, OUTPUT);
}

void loop() {
  mcp.digitalWrite(0, LOW);
  mcp.digitalWrite(1, LOW);
  mcp.digitalWrite(2, LOW);
  mcp.digitalWrite(3, LOW);
  mcp.digitalWrite(4, LOW);
  mcp.digitalWrite(5, LOW);
  mcp.digitalWrite(6, LOW);
  mcp.digitalWrite(7, LOW);
  mcp1.digitalWrite(0, LOW);
  mcp1.digitalWrite(1, LOW);
  mcp1.digitalWrite(2, LOW);
  mcp1.digitalWrite(3, LOW);
  mcp1.digitalWrite(4, LOW);
  mcp1.digitalWrite(5, LOW);
  mcp1.digitalWrite(6, LOW);
  mcp1.digitalWrite(7, LOW);
}

Which library are you using?

Use a variable ( iterator) and count from 0 to 8 (excluding):
void setup()
{
    mcp.begin(0);
    mcp1.begin(1);

    for (uint8 pin = 0; pin  < 8; pin ++)
    {
        mcp .pinMode(pin, OUTPUT);
        mcp1.pinMode(pin, OUTPUT);
    }
}

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
        mcp1.digitalWrite(pin, LOW);
    }
}

If the order in which the digital pins are written to LOW matters than split them like in your example, (however, I do not think that is the case).
void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
    }

    for (pin = 0; pin < 8; pin++)
    {
        mcp1.digitalWrite(pin, LOW);
    }
}

Note : for clarity I would call the mcp variables mcp1 and mcp2 instead of mcp resp mcp2, or an even more intuitive name if there is a clear function for both mcp's.
Using uint8 creates an unsigned byte instead of an int which saves also one byte of stack memory.

apt. I would also throw the routine in a function so I don't even have to repeat the looping code to apply it...

@dandavis ... it can be done, personally, I wouldn't do it because it barely reduces the number of lines and makes it less clear, but it's true it reduces copied code. Normally I start refactoring when it is 3 times used OR (2 times and on different locations).

If you are using the Adafruit MCP23017 library there is a shortcut you can use for setting all the GPIO pins in one go:
mcp.writeGPIOAB(val);

val is a 16-bit value which defines the IO level of all 16 pins at once.
There is a similar function for reading:
val = mcp.readGPIOAB();

You can also read just one bank of GPIO pins (why they didn't have a similar write function I have no idea):
valA = mcp.readGPIO(0);
valB = mcp.readGPIO(1);

Unfortunately there aren't any shortcut functions for setting the pin modes.