message:
Relay switching problem with ATmega328P + 10 relays

I am trying to switch ON/OFF 10 relays connected to ATmega328P via Bluetooth HC-06 module. The problem I am facing is that when I try to Switch ON more than 3-4 relays, some of the previously ON relays switch OFF and the ATmega328 restarts.

I am using a 12V 2A power supply.

I have set up my circuit as shown below

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

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

My code

    int r1 = 4, r2 = 5, r3 = 6, r4 = 7, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 12, r10 = 13;
    char state;
    String msg;
    int r = 0;

    void setup()
    {

        pinMode(r1, OUTPUT);
        pinMode(r2, OUTPUT);
        pinMode(r3, OUTPUT);
        pinMode(r4, OUTPUT);
        pinMode(r5, OUTPUT);

        pinMode(r6, OUTPUT);
        pinMode(r7, OUTPUT);
        pinMode(r8, OUTPUT);
        pinMode(r9, OUTPUT);
        pinMode(r10, OUTPUT);

        Serial.begin(9600);
    }

    void loop()
    {

        while (Serial.available())
        {
          state = Serial.read();

          if (state == '\n')
            break;

          msg += state;

        }

        if (msg.length() > 0)
        {
          /*Serial.print("Data: ");
          Serial.println(msg);*/

          if (msg == "on1")
          {
              digitalWrite(r1, HIGH);
              Serial.print("O1");
          }
          else if (msg == "on2")
          {
              digitalWrite(r2, HIGH);
              Serial.print("O2");
          }
          else if (msg == "on3")
          {
              digitalWrite(r3, HIGH);
              Serial.print("O3");
          }
          else if (msg == "on4")
          {
              digitalWrite(r4, HIGH);
              Serial.print("O4");
          }
          else if (msg == "on5")
          {
              digitalWrite(r5, HIGH);
              Serial.print("O5");
          }
          else if (msg == "on6")
          {
              digitalWrite(r6, HIGH);
              Serial.print("O6");
          }
          else if (msg == "on7")
          {
              digitalWrite(r7, HIGH);
              Serial.print("O7");
          }
          else if (msg == "on8")
          {
              digitalWrite(r8, HIGH);
              Serial.print("O8");
          }
          else if (msg == "on9")
          {
              digitalWrite(r9, HIGH);
              Serial.print("O9");
          }
          else if (msg == "on10")
          {
              digitalWrite(r10, HIGH);
              Serial.print("O10");
          }

          //off---------------------------------------------------------

          else if (msg == "off1")
          {
              digitalWrite(r1, LOW);
              Serial.print("F1");
          }
          else if (msg == "off2")
          {
              digitalWrite(r2, LOW);
              Serial.print("F2");
          }
          else if (msg == "off3")
          {
              digitalWrite(r3, LOW);
              Serial.print("F3");
          }
          else if (msg == "off4")
          {
              digitalWrite(r4, LOW);
              Serial.print("F4");
          }
          else if (msg == "off")
          {
              digitalWrite(r5, LOW);
              Serial.print("F5");
          }
          else if (msg == "off6")
          {
              digitalWrite(r6, LOW);
              Serial.print("F6");
          }
          else if (msg == "off7")
          {
              digitalWrite(r7, LOW);
              Serial.print("F7");
          }
          else if (msg == "off8")
          {
              digitalWrite(r8, LOW);
              Serial.print("F8");
          }
          else if (msg == "off9")
          {
              digitalWrite(r9, LOW);
              Serial.print("F9");
          }
          else if (msg == "off10")
          {
              digitalWrite(r10, LOW);
              Serial.print("F10");
          }
          else if (msg == "offall")
          {
              digitalWrite(r1, LOW);
              digitalWrite(r2, LOW);
              digitalWrite(r3, LOW);
              digitalWrite(r4, LOW);
              digitalWrite(r5, LOW);
              digitalWrite(r6, LOW);
              digitalWrite(r7, LOW);
              digitalWrite(r8, LOW);
              digitalWrite(r9, LOW);
              digitalWrite(r10, LOW);
          }

        }

        msg = "";

        delay(1000);
    }

body:
I can see lot of problems.

- No decoupling capacitors on ATMega.

- Capacitors on both sides voltage regulators are usualy essential for regulator stability.

- Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.

- Bare HC06 doesn't like 5 Volts on its 3.3V logic level input

- Xtal oscilator usualy requies two capacitors (22pF) for better stability.


sender: user

sender: assistant

body: Where do the switching transistors get their +5v? The dropouts and shutdown suggest that the "+5v" is sagging as more relays try to draw off of it. Try supplying the relay current from a more capable supply, possibly a voltage regulator off the +12v supply - it will be wasteful but if it works, you'll know that was the problem.


message:
Switch statements with Bluetooth serial input not working

I am trying to control the brightness of an LED using PWM. I am also trying to make it so that when I click a button on my bluetooth app, I can get it to change the frequency of the PWM pin.

For changing the frequency, I am changing the value of the timers. When I click "30 HZ" on my bluetooth app, I am sending a value of "A", 122 HZ = "B" etc..

I hooked up a oscilloscope and changing the frequency does work.

The problem is that when I click a button, it receives A or B etc.. but it doesn't enter the switch statement every time. It is very laggy. It will also receive inaccurate numbers at times.

I think I need something in differentiating between various serial inputs? (one for choosing frequency and one for the duty cycle of the LEDs)? and also being able to enter the switch statements and then staying in there until another char is received.

Below is my code and I would appreciate any help!

    const int pwmPin = 11;
    const int TurnLightPin = 13;

    int ledState = LOW; // ledState used to set the LED
    unsigned long previousMillis = 0;  // will store last time LED was updated
    const long interval = 500;  // interval at which to blink (milliseconds)
    int dutyCycle = 0;

    char state =' ';

    void setup() {
      // put your setup code here, to run once:
      //Change register values to adjust PWM frequency for PWM Pins 3 and 11:

      //TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to           64 for PWM frequency of   490.20 Hz (The DEFAULT)
      //TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to      128 for PWM frequency of   245.10 Hz
      //TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz
      //TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz  pinMode(TurnLightPin, OUTPUT);

      pinMode(TurnLightPin, OUTPUT);
      pinMode(pwmPin, OUTPUT);

      Serial.begin(9600); // Default baudrate of bluetooth -- 9600 bits/second
      Serial.println("HC-06 Bluetooth connected!!!");
      Serial.flush();

    }

    void loop() {

      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= interval) {
         // save the last time you blinked the LED
         previousMillis = currentMillis;

         // if the LED is off turn it on and vice-versa:
         if (ledState == LOW) {
           ledState = HIGH;
         } else {
           ledState = LOW;
       }

       // set the LED with the ledState of the variable:
      digitalWrite(TurnLightPin, ledState);
    }

     //PWM Stuff:

    while(Serial.available()){

       // if (Serial.available() > 0){
      state = Serial.read();
      Serial.print("State received - Before Switch Statement: ");
      Serial.println(state);
      //}

    switch (state) {

    case 'A':

      TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz

      while(Serial.available() && (Serial.read() != 'B' || Serial.read() != 'C' || Serial.read() != 'D')){

        dutyCycle = Serial.parseInt();
        int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
      //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
        analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
        Serial.print("A-30 HZ - PWMValue:");
        Serial.println(pwmValue);
        Serial.print("A-30 HZ - State:");
        Serial.println(state);
        }

        state = ' ';
        break;

    case 'B':
        TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

        while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'C' || Serial.read() != 'D')){

        dutyCycle = Serial.parseInt();
        int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
      //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
        analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
        Serial.print("B-122 HZ - PWMValue:");
        Serial.println(pwmValue);
        Serial.print("B-122 HZ - State:");
        Serial.println(state);
      }

      state = ' ';

      break;

    case 'C':

       TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to   128 for PWM frequency of   245.10 Hz

        while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'D')){

        dutyCycle = Serial.parseInt();
        int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
       //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
        analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
        Serial.print("C-245 HZ - PWMValue:");
        Serial.println(pwmValue);
        Serial.print("C-245 HZ - State:");
        Serial.println(state);
      }

      state = ' ';

      break;

    case 'D':

        TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to    64 for PWM frequency of   490.20 Hz (The DEFAULT)

        while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'C')){

          dutyCycle = Serial.parseInt();
          int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
        //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
          analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
          Serial.print("D-490 HZ - PWMValue:");
          Serial.println(pwmValue);
          Serial.print("D-490 HZ - State:");
          Serial.println(state);
        }

        state = ' ';

        break;
    default:

      TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

      while(Serial.available()){

        dutyCycle = Serial.parseInt();
        int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
        //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
        analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
        Serial.print("default - PWMValue:");
        Serial.println(pwmValue);
        Serial.print("Default - State:");
        Serial.println(state);
      }

      state = ' ';

      break;
        }//End of Switch Statement
      } // End of While loop for PWM
    } // End of void Loop

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

body:
I don't like your serial parser at all. Lots of whiles, reads, places to get stuck in...

For example mine looks like:

    void loop() {

      if (Serial.available()) {
        int ch = Serial.peek(); // check first character in buffer

        switch (ch) {
          case 'a' ... 'd':
            TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
            TCCR2B |= 0b111 - (ch - 'a'); // a => 7, b => 6, c => 5, d => 4
            Serial.read(); // remove character from buffer
            Serial.println(TCCR2B, HEX);
            break;

          case 'A' ... 'D':
            TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
            TCCR2B |= 0b111 - (ch - 'A'); // A => 7, B => 6, C => 5, D => 4
            Serial.read(); // remove character from buffer
            Serial.println(TCCR2B, HEX);
            break;

          case '0' ... '9':
            dutyCycle = Serial.parseInt();
            analogWrite(pwmPin, (int)(dutyCycle*2.55));
            Serial.println(dutyCycle);
            break;

          default:
            Serial.read(); // some invalid character? Drop it
            break;
        }
      }
    }
However it needs some extra character after number (needed by parseInt)


body:
i had major issues with ws2812 and the hm-10, and i couldn't get a great solution for it, and although your setup is different, it may help…

my solution was to stop things that were interrupting the interrupt, in this case, the leds, so to create;

    void dataLow () {
      // drop the power on the data pins for the leds
      digitalWrite(DATA_PINA, LOW);
      digitalWrite(DATA_PINB, LOW);
      Serial.println("DATA_PINS - LOW");
    }

    void dataHigh () {
      // turn the power back on for the leds
      digitalWrite(DATA_PINA, HIGH);
      digitalWrite(DATA_PINB, HIGH);
      Serial.println("DATA_PINS - HIGH");
    }

and then to clean the data. i was looking for 2 numerical characters, and if i got anything else, then dump the data.

    bluetooth.listen();
    while (bluetooth.available() > 0) {
        dataLow();
        char inChar = bluetooth.read();
          // if its a character, add it to the string
          if (isDigit(inChar)) {
            inString += (char)inChar;
          }
          // if the string is longer than 2, truncate and return nothing
          if(inString.length() > 2) {
            inString[2] = '\0';
          }
          // if the serial recieves bluetooth end of line /n print string data out
          if (inChar == '\n') {
            Serial.print("String: "); Serial.println(inString.toInt());
            program=inString.toInt();
            inString = "";
            dataHigh();
          }
          // read user input from serial monitor
          if (Serial.available()){
            delay(10); // The DELAY!
            bluetooth.write(Serial.read());
          }
      }

it was still twitchy, but it mostly works.


message:
Bluetooth module is neither sending nor receiving data at baudrate(115200)

Im sending data between my arduino and android via bluetooth, using a simple chat app called "Bluetooth Terminal" . the code work perfectly at baudrate(9600) but I need to increase the speed to that of (115200) but nothing gets transmitted, or at least visible, anymore.

here's my code

    #include <SoftwareSerial.h>

    const int TXD = 3;
    const int RXD = 4;
    SoftwareSerial mrBlue(TXD, RXD);
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      mrBlue.begin(9600);

    }

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

      if (mrBlue.available() > 0) {

        String data = mrBlue.readString();
        Serial.println(data);

      }

      if (Serial.available() > 0) {

        String data = Serial.readString();
        mrBlue.println(data);
      }

      delay(20);
    }

body:
Software serial is really limited because it needs relatively precise timing, full attention of CPU and there can't be any interruptions from other sources.

You can see source code for better understanding how it works.

And if you need faster communication, you should get board with more hardware serials.


body:
Software serial is not working good with 115200 speed because of too much CPU usage. When I'm using only the bluetooth communication in Arduino, I'm connecting HC-05 (for example) to hardware serial pins and everything works fine.

If you want to increase the speed you must also change it in AT mode.


message:
How to check 8266 module

I am using an Arduino board with an ESP8266 module to connect to a WiFi device.
How do I check if the device is connected?

body:
You can use:

    AT+ CWJAP?
or

    AT+ CIPSTATUS
to see if you're connected to wifi. (The first will tell you access point status, the second will tell you IP address.)


body:
Firstly,If your ESP8266 module is coded then AT commands won't be responding directly, In that case You can check in Serial monitor(if u already wrote print in the existing code on module) else u have to flash a new code.

If didn't flash any code then use AT commands(AT+CWJAP?) for checking SSID.
(AT+ CIPSTATUS) for IP adress.


message:
How to delay outside loop

I am using a function outside `loop()`, which is called after an interrupt. Inside this function, I am setting several relays that need to change after a second or two, depending on my setting. I tried the delay, it doesn't work. `millis()` isn't working as well; I found out it stops counting when I exit the loop function.

My code looks something like this:

    const long on_interval = 2000;
    unsigned long currentMillis = millis();
    bool hv_bool = false;

    void hv_switch() {
        if (digitalRead(hv_pin)==HIGH){
            hv_startup();
        }
    }

    void hv_startup() {
        unsigned long previousMillis = 0;
        digitalWrite(pre_charge, HIGH);
        digitalWrite(main_charge, LOW);
        //Wait interval
        previousMillis = currentMillis;
        while (currentMillis - previousMillis < on_interval) {
            Serial.println(millis());
            //Wait
        }
        digitalWrite(pre_charge, LOW);
        digitalWrite(main_charge, HIGH);
        hv_bool = true;
        loop();
    }

    void setup(){
        //Set some ports

        //Initiate interrupt
        attachInterrupt(digitalPinToInterrupt(hv_pin), hv_switch, RISING);
    }

    void loop() {
        //Low voltage loop after startup, high voltage off
        while (hv_bool == false) {
            Serial.println("Waiting on high voltage");
            digitalWrite(hv_led, LOW);
            digitalWrite(pre_charge, LOW);
            digitalWrite(main_charge, LOW);
        }
    }

body:
@EdgarBonet has it - hv_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.

But a bigger problem is that loop() is called from hv_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.

So I'd suggest several fixes:

 - Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.

 - Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

- In loop(), test the flag. If it is set, *clear it* and call another function to handle the less urgent processing required by the interrupt.


message:
The Right Com Port (COM 7) is NOT Showing

I just finished a camp for the arduino and the arduino uno that they gave us is not working with my computer even though everything was working on their computers. I am trying to upload with the same schematic, same Arduino, and the same code. It is not wanting to upload even after changing in the preferences to the same com Port. I have tried updating the drivers, but Windows 7 64 bit s saying this error message : This device cannot start. (Code 10) .  Also, there is an exclamation mark in the device manager but how hard I try, it doesn't go away.

body:
> The Right Com Port (COM 7) is NOT Showing

It would appear that Microsoft Windows does not necessarily assign the same COM port for a given device from machine to machine.  It is usually up to the user to map which COM port is being used for which device.  Some applications which work with specific devices have been known to "search" for that specific device and automatically connect to the correct COM port.

> ...saying this error message : This device cannot start...

There is this Microsoft Web Page [here][1] about this error.

More specific help may be found [here][2].  In particular, this passage looks promising:

> On Windows 7 (particularly the 64-bit version), you might need to go
> into the Device Manager and update the drivers for the Uno or Mega
> 2560. Just right click on the device (the board should be connected to your computer), and point Windows at the appropriate .inf file again.
> The .inf is in the drivers/ directory of the Arduino software (not in
> the FTDI USB Drivers sub-directory of it).

  [1]: https://support.microsoft.com/en-us/kb/943104
  [2]: https://www.arduino.cc/en/Guide/Troubleshooting


body: I found out that I could not use the arduino drivers because I am using a DCcduino uno that has a separate driver.


message:
how does serialEvent work?

I have come across several examples about serialEvent() function, which look like this:

    void serialEvent(){
      if(Serial.available()){
        \\do something
      }
    }

The serialEvent() function is called when data is available, so which is the necessity of the `if` (or `while`) structure since that would be always `true`?

*(In several cases I have excluded the `if` structure, and the code works fine)*

body:
As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.

The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:

    while (true)
    {
        loop();
        if(data_available)
            serialEvent();
    }

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.

But if you want to read multiple bytes at the same time, you would have to wait until the loop() is executed again to read the next byte.

You will solve that problem if you write your  serialEvent()  like this:

    void serialEvent()
    {
        while (Serial.available())
        {
            // do something
        }
    }

That way, you will read all the information available at once and then return to the loop.


body:
It's a burdon how incomplete and hidden a lot of things are in the IDE of Arduino.

It took me five hours to discover how the `serialEvent()` function works for other ports (as `serialEvent2()` for the serial-port #2.

It's the same with how the function itself works. I still don't know...
As an example just insert a delay in the above answer and it proves that: "That way, you will read all the information available at once and then return to the loop." is NOT true.

    void serialEvent()
      {
        while (Serial.available())
          {
            // do something
          }
        delay(1000);
      }


message:
Convert a Double to an UnSigned Char

So, I'm working on **RedBear Blend Micro V 1.0**, and I must use the function:

    ble_write(Serial.read());
To read some input from the serial monitor(*Input being stuff I type in the Serial Monitor*) and send it via bluetooth.
It works perfectly this way!

Now what I need to do is create a random **double** data type number, and insert it in the place of **Serial.read()**

Read This:

**ble_write**
-------------
*Syntax:
    void ble_write(unsigned char data);
  ble_write sends a single byte data to the BLE Central.*

So, can you please help me, to:

1)Generate a random **double**

2)Send it using the ble_write() function?

For a full list of function sin the ReadBear Library click on the link:
https://github.com/RedBearLab/nRF8001

body:
**Edit**: Chris Stratton rightfully points out that the question is
about a `double`, not a `float`:

* a `float` is four bytes in every platform I know about, as per the
  IEEE-754 standard
* a `double` is eight bytes in almost all platforms, with the notable
  exception of AVR: [the AVR double is highly non-standard, four bytes
  long, and essentially equivalent to `float`][AVR double]

Most, but not all Arduinos, are AVR-based.
In the following I assume you are talking about AVR doubles, i.e.
floats. If this is not the case, then just replace the array of 4 bytes
by an array of 8 bytes.

[AVR double]: https://gcc.gnu.org/wiki/avr-gcc#Deviations_from_the_Standard

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

**Original answer**:
A `float` is four bytes, so it is somewhat equivalent to an array of
four unsigned chars, i.e. to `unsigned char[4]`. You can use this
equivalence with an `union`. For example, the following function will
send a float byte by byte:

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

    void ble_write_float(float x)
    {
        union {
            float f;
            unsigned char c[4];
        } data;

        data.f = x;
        ble_write(data.c[0]);
        ble_write(data.c[1]);
        ble_write(data.c[2]);
        ble_write(data.c[3]);
    }

Notice that this will send the bytes in whatever is the natural order of
the sending processor. If it's an AVR (like most Arduinos), this will be
LSB (least significant byte) first. You have to make sure that this is
what the receiver expects.

Following Ignacio Vazquez-Abrams' suggestion, for sending a random float
you could just send four random bytes. However, it may be wiser to have
an idea of the random distribution you want for your float, and use
things like `random()` and `map()` to achieve that distribution. Using
four random bytes, you get a very wide distribution (all the possible
floats are equally likely) which includes weird things like denormals,
infinities and NaN (literally meaning “not a number”).


message:
analogRead() takes >400 us on Arduino Zero but ~100 us on Uno, why?

I've been trying to figure out why the analogRead() function takes about four times as long on an Arduino Zero than on an Uno, when the Zero has a faster clock than the Uno.  Arduinos website says that it should take around 100 microseconds, and it does on the Uno, but it takes a little over 400 microseconds on the Zero. To time it, I've been setting a digital pin high immediately before the function call and low immediately after and measuring the period on a digital osscilloscope.  I'm just trying to test analogRead, so I'm not doing anything else in this code.  I've tried putting the ADC in freerun mode, and it trims ~15 us off of the ~415 us it currently takes.  I've also used the on-chip debugger to look at the disassembly, and the line that takes too long is always the line waiting for the conversion to complete.  I was also wondering if other ARM-based Arduinos (like the Zero) take over 100 us.  Thanks!

    int   sensorPin = A1;
    int      ledPin = 11;
    int sensorValue = 0;

    void setup() {
      analogReadResolution(12);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      digitalWrite(ledPin,HIGH);
      sensorValue = analogRead(sensorPin);
      digitalWrite(ledPin,LOW);
    }

body:
Arduino is universal platform, lot of wrappers to hide real hardware and it is slow. For example digital write is about 100times slower than direct access to hardware.

For example for AVR Mega328p based Arduino analogRead looks like (without macros):

    int analogRead(uint8_t pin)
    {
     uint8_t low, high;

     if (pin >= 14) pin -= 14; // allow for channel or pin numbers

     // set the analog reference (high two bits of ADMUX) and select the
     // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
     // to 0 (the default).
     ADMUX = (analog_reference << 6) | (pin & 0x07);

     // start the conversion
     sbi(ADCSRA, ADSC);

     // ADSC is cleared when the conversion finishes
     while (bit_is_set(ADCSRA, ADSC));

     // we have to read ADCL first; doing so locks both ADCL
     // and ADCH until ADCH is read.  reading ADCL second would
     // cause the results of each conversion to be discarded,
     // as ADCL and ADCH would be locked when it completed.
     low  = ADCL;
     high = ADCH;

     // combine the two bytes
     return (high << 8) | low;
    }

There are no extra function calls, no much extra actions and ADC is enabled in the startup code (as most of hw).

On the other side there is ARM based arduino with SAM3X8E:

    uint32_t analogRead(uint32_t ulPin)
    {
        uint32_t ulValue = 0;
        uint32_t ulChannel;

        if (ulPin < A0)
          ulPin += A0;

        ulChannel = g_APinDescription[ulPin].ulADCChannelNumber ;

     static uint32_t latestSelectedChannel = -1;
     switch ( g_APinDescription[ulPin].ulAnalogChannel )
     {
      // Handling ADC 12 bits channels
      case ADC0 :
      case ADC1 :
      case ADC2 :
      case ADC3 :
      case ADC4 :
      case ADC5 :
      case ADC6 :
      case ADC7 :
      case ADC8 :
      case ADC9 :
      case ADC10 :
      case ADC11 :

       // Enable the corresponding channel
       if (adc_get_channel_status(ADC, ulChannel) != 1) {
        adc_enable_channel( ADC, ulChannel );
        if ( latestSelectedChannel != (uint32_t)-1 && ulChannel != latestSelectedChannel)
         adc_disable_channel( ADC, latestSelectedChannel );
        latestSelectedChannel = ulChannel;
        g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_ANALOG;
       }

       // Start the ADC
       adc_start( ADC );

       // Wait for end of conversion
       while ((adc_get_status(ADC) & ADC_ISR_DRDY) != ADC_ISR_DRDY)
        ;

       // Read the value
       ulValue = adc_get_latest_value(ADC);
       ulValue = mapResolution(ulValue, ADC_RESOLUTION, _readResolution);

       break;

      // Compiler could yell because we don't handle DAC pins
      default :
       ulValue=0;
       break;
     }

      return ulValue;
    }

As you can see there is little bit more actions to do single measure using HAL (Hardware Abstraction Level) so you have another level of abstraction here.

If you want faster actions, you can access hw directly, or use HAL and skip unnecessary steps. It would be much faster then.


message:
Atmega328p clock and safe operation zone

im not used to write in english but i hope you guys can understand. I have some doubts about using the arduino pro mini 3v3@8Mhz

- I know its possible to change the clock to 1 MHz with the fuses easily by setting CKDIV8 to '0'. But i dont understand if its possible to divide the internal 8 MHz clock to intermediate values like 4 MHz and 2 MHz.

- I know i can divide the clock with program running. The problem is i would like to run the arduino with a voltage less than 2,4V and arduino will start at 8MHz(out of safe operation area) for later change the clock to 4MHz(inside of safe operation area). Is there another way by software to always be in the safe zone ?

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

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

body:
Just let CKDIV8 set (it just sets system clock prescaler to /8). And you can set different system clock prescaler later.

For changing system clock prescaler you need:

    #include <avr/power.h>

And:

    clock_prescale_set(clock_div_2); // possible values are clock_div_1 ... clock_div_256

Just don't forget that millis, delays and basically everything based on F_CPU might be slower/faster when prescaler gets changed.


message:
creating object of another class when initializing an object of a class

Here's what I want to achieve:
I'm building a class for controlling step motors. In that class I want to have a method called "init". In that method I'd like to create an object of class Tone, which I'll need to control a motor.
BUT I want to have seperate Tone class object for every object of my class that I create. How can I do it?

So, for exmaple, if I have:

    myClass newmotor1;
    memotor1.init();

After executing these two lines, I'd like to have my object newmotor1 (which I have, because I just created it) AND an object of class Tone, which I'll use.

body:
You don't need to "create" anything. Just have an object in your class:

    class Tone {
        public:
            void dosomething() {
                // Whatever is in here
            }
    };

    class MyMotor {
        public:
            Tone tone;
            void init() {
                // Nothing much else to do in here now.
            }
    };

You then:

    MyMotor newmotor1;

And you can access:

    newmotor1.tone.dosomething();


message:
can i configure 2 (XBee series 2) modules using one explorer

Can I configure 2 XBEE modules one then another using 1 XBEE Explorer, or I MUST do this configuration operation for them at the same time and I need 2 Explorer modules?

body:
You only need one.
In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other ([see here](https://learn.adafruit.com/xbee-radios/point2point))

There are more advanced configurations that you can use ([check this tutorial for extended information](https://learn.sparkfun.com/tutorials/exploring-xbees-and-xctu)).


message:
Doorbell for someone with hearing issues

I have an Arduino Uno with the basic kit, not very good at coding it however.

How could I make a doorbell that lights up an LED instead of making a noise?

I'm trying to make a doorbell for someone with hearing issues.

A simple LED lighting up would be more than enough. Would I need a wifi shield if it's not close enough to be hard wired?

Thanks

body:
I know you are keen on using your Arduino.  But simpler solutions abound.  For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.

However, I can see a situation that an Arduino can fit very nicely into:

Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino.  4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).

There are 2 tricky bits that may need explaining.  The first is how to sense the door bell.  If mechanical you could use a micro switch:

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

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid.  The other tricky bit is controlling a room light.  I would suggest using a [COTS][2] remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.

  [1]: https://i.stack.imgur.com/bSooh.jpg
  [2]: https://en.wikipedia.org/wiki/Commercial_off-the-shelf
  [3]: http://www.lutron.com/en-US/Products/Pages/StandAloneControls/Dimmers-Switches/MaestroIRDimmer/ModelNumbers.aspx


body: If you must do wireless, you can get by with a 433MHz rx+tx module. Be sure to align both antennas either vertically or horizontally. These modules kind of need two MCUs though, but clones are cheap. Personally I would add a small switch underneath the doorbell button, but separate from its circuitry. Debounce it. On the receiving end you need a good set of LEDs - iphone has a very annoying but attention-grabbing light pulse for people hard of hearing. You can see it on youtube. I would copy that pulse timing and intensity as closely as possible, thus infringing on Apple's no doubt copyrighted+patented 'technology'. Be a pirate, arrr!


message:
Arduino: Reading PPM values from MQ-131 Ozone sensor

I have this sensor MQ131 by sainsmart: https://www.amazon.co.uk/gp/product/B00NL8XIQG/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=A3DRI1TTHCTDIG

All I can read is the analog value which does not reflect the gas concentration. Any Arduino code for that to read the ppm concentration?
How long does the sensor needs to be preheated?

body:
First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.

I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.


body:
According to the picture, the sensor is a Winsen MQ131 low concentration (black bakelite version). You can have additional information on the sensor in [the datasheet][1].

Your sensor is mounted on a PCB with some features like converting values (analog to digital), controlling the heater, maybe providing I2C bus... Without any additional information, it's difficult to give guidance on your module (the Amazon link doesn't mention any datasheet for the module).

In order to use your sensor, you can connect it directly on the sensor and pilot it by yourself. [You can find some code on GitHub (for inspiration or fork)][2].

  [1]: https://github.com/ostaquet/Arduino-MQ131-driver/blob/master/datasheet/MQ131-low-concentration.pdf
  [2]: https://github.com/ostaquet/Arduino-MQ131-driver


message:
Problems with Powering Led Project Through Vin Pin

I am working on lighting some WS2812 Leds with a nodemcu form hiLetgo. The project works when it is powered from the usb that is on the board, but as soon as it is powered from the barrel jack, the leds will only light up to the last color that they were set, ignoring code. A schematic and code are included for reference.[![The schematic][1]][1]

<!-- language: c -->

    #include <ESP8266WiFi.h>
    #include <Adafruit_NeoPixel.h>

    // Which pin on the ESP8266 is connected to the NeoPixels?
    #define PIN            D8

    // How many NeoPixels are attached to the ESP8266?
    #define NUMPIXELS      30

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int delayval = 10; // delay for half a second
    int x, y, z;

    void setup() {
      // put your setup code here, to run once:
      pixels.begin(); // This initializes the NeoPixel library.
      x = 0;
      y = 0;
      z = 0;
    }

    void loop() {
      // put your main code here, to run repeatedly:
       for(int i=0;i<NUMPIXELS;i++){
        x = (x+1)%6;
        // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255

        pixels.setPixelColor(i, pixels.Color(x,y,z)); // Moderately bright green color.

        pixels.show(); // This sends the updated pixel color to the hardware.

        delay(delayval); // Delay for a period of time (in milliseconds).

      }
      y= (y+1)%6;

    }

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

body:
First: What is the purpose of that resistor you have in there? It serves no purpose as far as I can see, and would only cause problems anyway. Lose it.

Second: You have logic voltage level problems:

* You are supplying 5.2V to the LEDs.
* The ESP8266 is a 3.3V device.
* The ESP8266 outputs 3.3V as a logic HIGH.
* The WS2812 accepts 0.7Vdd as logic HIGH (as stated in [the datasheet](https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf)).
* **0.7 × 5.2 = 3.64v**

Ergo, the LEDs aren't seeing the logic HIGH signal as logic HIGH because it is too low a voltage.

Add to that the voltage drop across the resistor and your logic HIGH voltage will be even less.

So:

1. Lose the pointless resistor
2. Either reduce the supply voltage to the LEDs or increase the output HIGH voltage level with a logic level shifter circuit (3.3v -> 5v).


message:
Changing Uid Using MFRC522 Via Arduino Error

Well, I' ve just bought and recieved a MFRC522 rfıd module and done to much research on it. After watching several videos, I sorted out a library for using this module via arduino.
You can click the first link below to be navigated to Miguel Balboa' s github page including the library that I mentioned and example codes written by him using that library. Though I' ve downloaded the zip file, ran such codes as dumpInfo, read and write, unfortunetely I couldn' t made "changeUid" example work. U can reach this example code via the link below as well. My connection is true, I' m sure bout' that[![Connection is same an shown in code][1]][1]  If anybody had faced this kind of problem or knows the solution, their answers will be enough satisfying for me I guess... (By the way, error was this sentance: Are you sure this is a uid changeable card -I was sure, my card was a Mifare 1K card- failure, the card responded as NAK)

**link: https://github.com/miguelbalboa/rfid**

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

body: Search for UID changeable card. The kit included this RFID reader just had a normal RFID card and keychain. You will probably have to buy it yourself. I bought it from aliexpress but I don' t remember which seller. Good Luck! (I mean who read this...)


message:
How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial?

void Multi_print (String str)
    {
      Serial.print(str);
      mySerial.print(str);
     }

    void Multi_println (String str)
    {
     Serial.println(str);
     mySerial.println(str);
    }

    void Multi_parse_int (int value)
     {
        Serial.print(value);
        mySerial.print(value);
     }

body:
Just send your data to a tee: this is a type of pipe fitting where you
push the data through one end and it goes out through the other two
ends. As it happens, both Serial and Softserial (and almost anything
that can `print()`) inherit from the virtual `Print` class. You can
implement a tee as a `Print` that outputs to two `Print`s:

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

    class Tee : public Print
    {
    public:
        Tee(Print &_p1, Print &_p2)
        : p1(_p1), p2(_p2)
        {}

        size_t write(uint8_t c)
        {
            size_t count1 = p1.write(c);
            size_t count2 = p2.write(c);
            return min(count1, count2);
        }
    private:
        Print &p1, &p2;
    };

The `write(uint8_t)` is the only method you really need to implement to
have a working `Print`. Then, all the `print()` and `println()` methods
will work.

Example usage:

    Tee dualSerial(Serial, mySerial);
    dualSerial.print("The answer is ");
    dualSerial.println(42);

Note that `parseInt()` will not work, as it is not a method from
`Print`. But if you think twice, you will realize that `parseInt()` on a
pair of channels just does not make sense.


body:
LOL, while Edgar was busy answering your question, I posted a github implementation called [NeoTee](https://github.com/SlashDevin/NeoTee) which will tee any number of streams.  I have occasionally wanted such a class (attached at the end).  He has explained the approach nicely.

One quirk of the Arduino `Print` and `Stream` classes is that the `flush` method is in `Stream`, not `Print`.  So to provide that method in the `NeoTee` class requires deriving from `Stream`.  But `Stream` requires that you implement `read`, `available` and `peek`.  Although `available` can return the sum of the characters available on all `Streams`, the usefulness of `read` and `peek` is functional, but dubious.  ;-)

One example sketch is available in the library.  For your sketch, you would declare something like this:

    Stream *streams[2] = { &Serial, &mySerial };
    NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );

And used thusly:

    tee.print( '!' ); // prints one character to both
    tee.print( 123.45 ); // prints a floating-point number on both

<hr>
NeoTee implementation:

    #ifndef _NEOTEE_H_
    #define _NEOTEE_H_

    //------------------------------------------------------
    // NeoTee
    // Copyright (C) 2016, SlashDevin
    //
    // This library is free software; you can redistribute it and/or
    // modify it under the terms of the GNU Lesser General Public
    // License as published by the Free Software Foundation; either
    // version 2.1 of the License, or (at your option) any later version.
    //
    // This library is distributed in the hope that it will be useful,
    // but WITHOUT ANY WARRANTY; without even the implied warranty of
    // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    // Lesser General Public License for more details.
    //

    #include <Stream.h>

    // This library is like the UNIX "tee" command, which splits an output stream
    // into two streams, but with N branches.  On the Arduino, an output stream is
    // instance of the Arduino Print class, and the flush method is in Stream.
    //
    // Simply declare your own array of streams:
    //
    //     Stream *streams[2];
    //
    // Pass the array and its size in to the NeoTee constructor:
    //
    //     NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );
    //
    // Any Stream operation on "tee" will be duplicated on all Streams in the array.
    //
    //     tee.println( F("This is sent to all Stream instances in the array.") );
    //
    // Because there is no base class with "begin" and "end" methods, you
    //   must call those explicitly on the individual Streams (e.g., Serial.begin)

    class NeoTee : public Stream
    {
      Stream **Streams;
      uint8_t  NumStreams;

    public:

      NeoTee( Stream **streams, uint8_t numStreams )
        {
          Streams    = streams;
          NumStreams = numStreams;
        }

      virtual void flush()
        {
          for (uint8_t i=0; i<NumStreams; i++)
            Streams[i]->flush();
        }

      virtual size_t write(uint8_t c)
        {
          size_t minWritten = 0;
          for (uint8_t i=0; i<NumStreams; i++) {
            size_t written = Streams[i]->write( c );
            if ((i == 0) || (minWritten > written))
              minWritten = written;
          }
          return minWritten;
        }

      using Stream::write; // make the other overloads visible

      virtual int available()
        {
          int total = 0;
          for (uint8_t i=0; i<NumStreams; i++)
            total += Streams[i]->available();
          return total;
        }

      virtual int read()
        {
          for (uint8_t i=0; i<NumStreams; i++)
            if (Streams[i]->available())
              return Streams[i]->read();
          return -1;
        }

      virtual int peek()
        {
          for (uint8_t i=0; i<NumStreams; i++)
            if (Streams[i]->available())
              return Streams[i]->peek();
          return -1;
        }

    };

    #endif


message:
How do I Read and Write data from a USB stick?

Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?

body: The Uno does not have any USB ***host*** or OTG capabilities on its own, and bit banging it is not easy. A USB Host shield, or a better microcontroller is needed.


message:
Why does servo library conflict with irremote?

I am building an Arduino Mega robot. I am planning to use IRremote.h library for it. I am using multiple libraries in my code and I do not know which timers are taken. I always get errors when compiling because I am using the wrong timer. Here are the libraries I am using:

    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include <RTClib.h>
    #include <Servo.h>
    #include <IRremote.h>

I get this error message when compiling:

    libraries\IRremote\IRremote.cpp.o: In function `__vector_42':

    C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\IRremote/IRremote.cpp:339: multiple definition of `__vector_42'

    libraries\Servo\avr\Servo.cpp.o:C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\Servo\src\avr/Servo.cpp:95: first defined here

    c:/users/lyuba/desktop/nick/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Mega or Mega 2560.

Here is the code in the library where I can change the timers:

    // Arduino Mega
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      //#define IR_USE_TIMER1   // tx = pin 11
      //#define IR_USE_TIMER2     // tx = pin 9
     // #define IR_USE_TIMER3   // tx = pin 5
      #define IR_USE_TIMER4   // tx = pin 6
      //#define IR_USE_TIMER5   // tx = pin 46

What can I do to use irremote library? Looking at the error message, the servo library conflicts with irremote. How can I fix this?

body: Usual problem is trying to use the same counter for both. For example arduino pins 6,7,8 are on TC4 and if you try to use IR on pin 6 and servo on 7 or 8, it won't work. You can't use pwms on these pins with servo either (it is possible to do it directly in registers, but in arduino framework it might get bad behavior)


message:
Receive sms on android phone without GSM module

I have done a simple project which measures CO gas in air.Now I want that sensor will measure the level of CO gas and sms will be received on android phone when the area is under danger zone.How to receive sms on android phone without GSM module?

body:
There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

1. Directly using GSM - for which you NEED a GSM shield
2. Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.

Also you need an internet connection available wherever the Arduino happens to be.

All in all a lot of work and you're really no better off than using a GSM shield.


body:
**Alternative from price perspective:**

Assuming that you have internet at the location of sensor (WiFi or cable) you can buy a RaspberryPi (revision 3 has already integrated WiFi and bluetooth). Using python code you can than send SMS message using some free SMS service provider if there are any in your country using their API.

If SMS notificaion is not critical, you can use RaspberryPi to send an email or some other sort of notification. Heck you can even create a Twitter profile for your sensor and call it Mr.Sensor and then post tweets with sensor values. Possibilities are endless, it all depends on your use case and available infrastructure.

I hope you will find something that will satisfy your needs :)


message:
How to volunteer for arduino projects?

I have master in electronics and IT. I know various microcontrollers programming in `c`. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?

body:
Most of the libraries to read sensors like as Dallas/Maxim 1Wire products, or to interface to RF-, WiFi-, and other radios are user-contributed and maintained, and most, if not all, of them are community maintained and on github.

Update:

> Is there any official repository for arduino libraries where someone
> can contribute and submit patches?

"Official": I don't think so, at least I don't know of one if there is, but I am also just learning my way around the open sources.

But you'll probably find most of the libraries in github, and they are usually there to share development. They aren't generally grouped as "Arduino", but by each author's github username.

So the best approach is probably to identify the library in your "libraries" folder that you want to update, and its author's name which is usually in the source-code header comments. And, if you get lucky, a URL to the github project. Otherwise go to github and search for the library, using the author's name or a quick comparison of some the source code to be sure you've really found the same library.

(As I am a user & beneficiary of open source code, you have my sincere thanks for choosing to do this! I haven't gotten that far yet; I hope to, soon.)


body:
The Arduino paradigm is based on abstracting the hardware to a few simple function calls.  So many drivers appear simple to the end user (end programmer).

Most go [here][1] for a list of libraries (which have already been written) and how to use them.  I believe these libraries are distributed with the Arduino SDK.  To learn more about writing libraries go [here][2]. I am not aware of any formal method of submitting Arduino libraries.  If I wanted to find out more I would go [here][3] and participate in the forum.  However, using the forums search, I found [this][4] specific (several years old) post where it says:

> You can add a page to the Playground section:
> http://playground.arduino.cc/ You might start by adding your website
> with Arduino code to the index of the playground, perhaps a page in
> the Playground section is not needed. The index can contain links to
> websites, to the Arduino forum or to a page in the Playground section.
>
> You can not change or add to the reference or official libraries.

  [1]: https://www.arduino.cc/en/Reference/Libraries
  [2]: https://www.arduino.cc/en/Hacking/LibraryTutorial
  [3]: http://forum.arduino.cc/index.php/board,53.0.html
  [4]: http://forum.arduino.cc/index.php?topic=262051.0


message:
Real Time Clock Module Reset

I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!

body: It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.


message:
Can anyone recommend a breadboard for the new Arduino 101?

I just got an Arduino 101 board. I was told that it's practically the same as the UNO. But have no experience using the UNO and I've only done super simple things on the 101 board without using a bread board.

What I want to do is have 2 servos connect to the board. I've only connected one servo without using a breadboard. I've looked on Instructables.com and other places that connect at least 2 to up most 12 servos. They all use different breadboards without specify if the brand, model, or if size even matters. I don't know how breadboards work and which holes I plug the wires into. Furthermore, I haven't found any videos on people working on the 101 board.

Next, I'm not sure if the servos will share the same volt port. There's only 3V and 5V on my Arduino 101 board. If they all need 5V, I'm not sure how to make both servos share. I don't know how they will share the same ground port as well. I know for sure, they will have their own analog port.

A list of recommendations would be nice. Thanks.

body: A breadboard is nothing but a way to attach multiple wires to the same pins. There are many different kinds as can be seen [in these images](https://www.google.nl/search?q=breadboard&espv=2&biw=1777&bih=861&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUte3Jjf_NAhXG7hoKHVZwAjQQ_AUIBigB&dpr=0.9). There's no right or wrong when it comes to breadboards, as long as you have enough pins to prototype you should be good to go.


body: I agree to "A breadboard is nothing but a way to attach multiple wires to the same pins.", but just one recommendation for the breadboard. Don't buy the ones without the rails for voltage and ground, they are useful.


message:
Arduino SPI - MOSI not writing any data but clock works

I am trying to iterate over an int array and writing those values to a chip. Here is my code.

    #include <SPI.h>

    int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
    ,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
    ,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
    ,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
    ,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
    ,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
    ,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
    ,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
    ,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
    ,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
    ,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

    #define samples 120

    const int cs = 9;

    int counter = 0;

    const int chipSelectPin = 10;

    void setup()
    {
      pinMode(cs,OUTPUT);
      pinMode(chipSelectPin, OUTPUT);

     SPI.beginTransaction(SPISettings(20000,LSBFIRST,SPI_MODE3));
    }

    void loop()
    {

      digitalWrite(cs,LOW);

      SPI.transfer(sine[counter]);

      digitalWrite(cs,HIGH);

      counter += 1;

      if(counter >= samples)
      {
        counter = 0;
      }

    }

Very simple, I am using an Arduino nano and according to [this reference][1] the clock pin is 13 and MOSI is 11. I am seeing the clock signal for pin 13 but pin 11 is inactive.

  [1]: https://www.google.com/search?q=arduino nano pinout&espv=2&biw=1366&bih=643&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiS3uOm0P3NAhXCyyYKHQLmB5MQ_AUIBigB#imgrc=i5z_gVO0W559NM:

body:
You need to use SPI.begin() before the beginTransaction().

The documentation is not 100% clear but beginTransaction does not replace SPI.Begin to setup the SPI hardware.

Documentation not very clear: https://www.arduino.cc/en/Reference/SPIbeginTransaction


body:
In addition to @Talk2's answer `SPI.transfer(...)` transfers one byte of data. Your array is made of `int` which means each entry is 2 bytes long.

Instead you should use `SPI.transfer16(...)` to transfer 16-bit values.


message:
Using multiple RTC libraries in one program

There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one?  Will there be some conflict if for example I include DS1307.h   and RTCLib.h and other RTCXXXX.h libraries as well?

body:
If you want to load multiple RTC libraries I guess you are connecting to multiple RTCs.

If they use the same interface to communicate, i.e. I2C there is a possibility you will initialise the bus multiple times.

You should be OK with the functions not clashing, because they are within classes, but its possible some of the referenced structures/ classes my clash.  You _might_ be able to resolve this by namespacing the libraries.

An alternative might be to write your own library that handles all of the RTCs that you are interested in.  This will force you to consider what each RTC requires and identify problems.

At the end of the day I agree with what Gerben is saying.  Don't do it unless you really have to.


body:
> can I load several RTC libraries into my code and then use the functions I like from each one?

It will depend on the libraries. Most likely they had some persistent variables, global to the routines, that help information exchange. If only some of the routines are used and others not, values in those variables may not be consistent.

> Will there be some conflict

That will depend on the way those libraries are implemented. No way of telling without seeing the code.

The point of doing this is a little bit suspect. It is not clear to me why you would want to have more than 1 RTC in an environment. If you are thinking about giving your program the option to function with multiple RTCs (but using one RTC at any given time), you can use either macro (at compile time) or wrap the RTCs in a logic layer (at run time).

For example, you can have a `rtc_init()` to reset different RTCs; and `rtc_read()` to return the time from the rtc. `rtc_read()` can be implemented based on which RTC is detected during initialization...


message:
how to make led fade on and blink while wav file plays

To clarify I'm extremely new to this and I'm using an Arduino Uno with a wave shield. My circuit works as intended but I haven't learned enough of the code to know what to do to make it do exactly what I want.

Right now the following code makes the sound play on button press but the led sequence doesn't at all. If I move `root.rewind(); play(root);` to after the last `digitalWrite` then the led sequence runs but the audio doesn't play until the led sequence ends. I'm out to make the audio play while the led sequence runs. Any suggestions?

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

    if (state == 1) {
        root.rewind();
        play(root);
        for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
            analogWrite(LED,i);     // set the LED brightness
            delay(15);              // wait 15ms because analogWrite
                                    // is instantaneous and we would
                                    // not see any change
        }
        analogWrite(LED, HIGH);     // turns the LED on
        delay(300);                 // waits for a second
        analogWrite(LED, LOW);      // turns the LED off
        delay(100);                 // waits for a second
        analogWrite(LED, HIGH);     // turns the LED on
        delay(300);                 // waits for a second
        analogWrite(LED, LOW);      // turns the LED off
        delay(100);                 // waits for a second

        digitalWrite(RESET, LOW);
    }

body:
As this can not be your entire sketch we can only guess that you are using some sort of SDCard music playing Arduino shield and library.

An application can not call the delay() function if the application is trying to accomplish more than one task.  Calls to delay() block the processor from doing anything other than waiting for the delay to time out.

In order to (appear to) do multiple tasks, run a loop with no calls to the delay() function.  Instead call the millis() function checking if enough time has elapsed to call the LED function or the sound function.  In neither function should you call the delay() function!  If you did not write the function (for example you are using a library) you may need to edit the code in the library to ensure it is following the no-calls-to-delay()-function rule!

In general terms, this is referred to as a state machine.  In this case, the state machine is driven by the amount of elapsed time as reported by the call to the millis() function.


message:
USB connector between Arduino and a lever (switch)

I am not sure an Arduino forum is the right place to ask this question, but since I'm using Arduino here I thought it would be a good starting point. I am trying to connect a lever (you can think of it as a switch, when it's pressed it's ON, and otherwise it's OFF) to an Arduino via a USB connector. My setup worked perfectly fine when I connected the lever directly to the Arduino, but via the USB it doesn't work. Since I already built and invested in USB connectors I would like to solve this issue, or at least understand what I am doing wrong in here.

I've attached a photo to demonstrate the wiring. Note that it works if I bypass this USB connection. I'm trying to understand why this doesn't work via a USB. [![enter image description here][1]][1]

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

body: I'd suggest using a multimeter to figure out what's connected to what after hooking up the complete wiring scheme; there aren't that many options and you should be able to figure out what's connected to what soon enough. On a more philosophical note, it's only a bad idea if the alternatives weren't worse.


message:
SD Card Info Unexpected

So I have just begun testing my Wireless SD Shield from Arduino with my Arduino UNO. Upon running my the basic CardInfo sketch, it uploads and displays data, but far more than expected. The SD Card is entirely empty, as in, if I plug it into my computer, there are no files on it. However, this is the Serial Monitor Output I receive:

[![Part 1][1]][1]

[![Part 2][2]][2]

  [1]: https://i.stack.imgur.com/2is3r.png
  [2]: https://i.stack.imgur.com/edenQ.png

The reason I have included screenshots rather than copy and pasting the output, is that if I try and copy and paste, it does not copy all of the Files Found on the card, it only copies the first 8 lines.

Any help would be greatly, appreciated!

This code does not compile for me and gives me an avrdude error which I believe is due in some part to the above pictures:

    //Program by Jeremy Blum
    //www.jeremyblum.com
    //SD Card Demonstration
    //Based on Example by Tom Igoe

    #include <SD.h>

    //Set by default for the SD Card Library
    //MOSI = Pin 11
    //MISO = Pin 12
    //SCLK = PIN 13
    //We always need to set the CS Pin
    int CS_pin = 4;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Initializing Card");
      //CS Pin is an output
      pinMode(CS_pin, OUTPUT);

      if (!SD.begin(CS_pin))
      {
          Serial.println("Card Failure");
          return;
      }
      Serial.println("Card Ready");

    }

    void loop()
    {
      String dataString = "Hello";

      //Open a file to write to
      //Only one file can be open at a time

      File dataFile = SD.open("log.txt", FILE_WRITE);
      if (dataFile)
      {
        dataFile.println(dataString);
        dataFile.close();
        Serial.println(dataString);
      }
      else
      {
        Serial.println("Couldn't open log file");
      }
      delay(5000);
    }

Whereas, this code does:

    #include <SD.h>         //SD Card Library
    #include <Wire.h>       //I2C Library
    #include <DallasTemperature.h>
    #include <OneWire.h>

    OneWire oneWire(2); // initiate pin connected to DS18B20
    DallasTemperature sensors(&oneWire); // pass oneWire as parameter to Dallas Temp. library

    //SPI SD Card Pins
      //MOSI = Pin 11
      //MISO = Pin 12
      //SCLK = PIN 13
      int CS_pin = 4;
    //  int pow_pin = 8;

    //Light Sensor Pins
      int light_pin = 0;

    float refresh_rate = 500;  //Dataloger Refresh Rate
    float id = 0;

    void setup()
    {
      Wire.begin();
      Serial.begin(9600);
      sensors.begin(); // initiate the sensors on the DS18B20
      Serial.println("Initializing Card");
      //CS Pin is an output
      pinMode(CS_pin, OUTPUT);

    //  //SD Card will Draw Power from Pin 8, so set it high
    //  pinMode(pow_pin, OUTPUT);
    //  digitalWrite(pow_pin, HIGH);

      //Initialize Card
      if (!SD.begin(CS_pin))
      {
          Serial.println("Card Failure");
          return;
      }
      Serial.println("Card Ready");

      //Write Log File Header
      File logFile = SD.open("LOG.csv", FILE_WRITE);
      if (logFile)
      {
        logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data
        String header = "ID, Light, Temp";
        logFile.println(header);
        logFile.close();
        Serial.println(header);
      }
      else
      {
        Serial.println("Couldn't open log file");
      }

    }

    void loop()
    {
      //Check Light Level
      int light_level = analogRead(light_pin); //Write the value of the photoresistor to the serial monitor.

      //Read Temperature
      sensors.requestTemperatures(); // request the temperatures from the DS18B20, does not actually do anything simple sets it up
      float currentTemp; // initialize variable to store and hold current temperature readings
      currentTemp = sensors.getTempCByIndex(0); // go and get temperature in Celcius for the first temp probe, temperature probe 0 (could have more than one sensor here if wanted)

      Serial.print("Temperature = ");
      Serial.print(currentTemp); // prints actual temperature and starts new line
      Serial.print(" Celcius ");
      /* Serial.print((char)223); print degree symbol in LCD format */
    //  Serial.println("C");

      //Create Data string for storing to SD card
      //We will use CSV Format
      String dataString = String(id) + ", " + String(light_level) + ", " + String(currentTemp);

      //Open a file to write to
      //Only one file can be open at a time
      File logFile = SD.open("LOG.csv", FILE_WRITE);
      if (logFile)
      {
        logFile.println(dataString);
        logFile.close();
        Serial.println(dataString);
      }
      else
      {
        Serial.println("Couldn't open log file");
      }

      //Increment ID number
      id++;

      delay(refresh_rate);
    }

Both sketches are quite different, so I reccomend just looking at the intial void setup() part of each if you want to read through them.

body: Joy of tech... It's full file table, with old, deleted entries appearing as current files. You can nuke it with a quick or slow format, but the problem will return later. I don't know this shield, but there must be some problem with the code - it really shouldn't show deleted entries. Try another library, or google for problems with your current lib.


body: They are Mac's OS X "Spotlight" hidden indexing files.  [This answer](https://apple.stackexchange.com/questions/6707) shows how to turn it off.


message:
Arduino Micro Cannot get Interrupt 6 work on PIN 7

After finding out about the situation with pin7 from this tutorial:

https://forum.sparkfun.com/viewtopic.php?f=32&t=35847

        void setup(){

        EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                      // EICRA sets interrupt type for INT0...3

        /*
        ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
          0      0   Triggers on low level
          1      0   Triggers on edge
          0      1   Triggers on falling edge
          1      1   Triggers on rising edge
        */
    EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

    void loop(){
    //do other things here
    }

    ISR(INT6_vect) {
      // interrupt code goes here
      }

I have set:

    EICRB |= (0<<ISC60)|(0<<ISC61);

Because I need it to be triggered on LOW.

I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.

I have a sensor attached there which goes LOW in case it is triggered.

I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.

body:
I've used following code and loopback from pin 8 to pin 7:

    // loopback:  pin 8 -> pin 7

    void setup() {
      pinMode(7, INPUT_PULLUP);
      pinMode(8, OUTPUT);
      pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
      pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

      EICRB |= _BV(ISC60);  // Triggers on edge
      EIMSK |= _BV(INT6);   // activates the interrupt
    }

    ISR(INT6_vect) {
      PINC = _BV(PC7);  // toggle led 13 (@ PC7)
    }

    void loop() {
      digitalWrite(8, HIGH);
      digitalWrite(LED_BUILTIN_TX, HIGH);

      delay(500);
      digitalWrite(8, LOW);
      digitalWrite(LED_BUILTIN_TX, LOW);
      delay(500);

    }

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).


message:
Cheapest way to change digital output source

Powering at 5 volts, atmega328 output ~4.7 volts. I need to output between 12 and 24 volts @ 2 amp. I'm currently using relay but they are costly. Is there a way to do it with transistors or any thing cheaper?

Thanks

body:
As @Gerben said in the comments, I would also recommend an N-channel MOSFET.  OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch.  You can find that app note [here](http://www.onsemi.com/pub_link/Collateral/AND9093-D.PDF).

The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off.  You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET.  The basic circuit can be seen in the application note.

Hope that helps!


message:
Is it possible to connect a camera to an arduino?

I working on a project that requires a small camera to be covering a (insect) nest entrance. The video needs to be transmitted to a computer to be processed. I am interfacing with Java using the RXTX library and will then be tracking objects using OpenCV.

[This is the camera](http://www.ebay.co.uk/itm/321943226649)

My question is, it it possible to connect this camera to an Arduino (Uno or Yun) and transmit the data back to a computer?

body: Yes. Check out ArduCam. Do a google search. http://www.arducam.com


message:
Yikes! Invalid device signature. Fail to burn bootloader and read fuses

I know this problem is kinda common but I had to post it anyway.

Before anything, I would like to inform you guys that I changed the fuse of my Arduino Pro 3v3 @ 8MHz to allow 1.8 V brownout and also programmed CKDIV8 AND CLKOUT. In other words, the fuse configuration is this: E:FE, H:DA, L:3F.

The programmer is the Arduino 2009 running as ISP programmer. The target is Arduino Pro Mini 3V3 @ 8Mhz.

I also used a 0.1uF cap between reset and ground in the Arduino programmer.

After a good time using the Arduino Pro without problems, some random problems began to appear when I tried to upload a program with the programmer (Arduino as ISP). So I tried to burn the bootloader again and the following message appeared ""avrdude: Yikes! Invalid device signature."

The same occurs when I try to communicate with avrdude using this command "avrdude -c arduino -p m328p -P COM3 -b 19200 -v".

Some tests I did:

 - Continuity test directly at uC pins between those signals: SCK, MISO, MOSI, (/SS - /RESET). No problem good connection.

 - Verified the clock in XTAL1 and XTAL2. No problem 8MHz.

 - Verified the clock in CKOUT (Arduino Pro pin 2) and measured 1MHz.

 - I also tried to delay the avrdude using -B5, B10 and another values. With a quick search on Google some people are saying that those delays don't work with the Arduino as ISP.

 - I used some sketches for slow clocks, which I don't remember, and no luck.

 - External power and no luck again.

What am I missing? Do I need to change something to communicate with Arduino Pro running at 1MHz?

body:
If you are burning the bootloader through the IDE it won't expect the CKDIV8 fuse to be set.

I have a [bootloader programmer](http://www.gammon.com.au/forum/?id=11635) which you could use to reprogram the bootloader. You just need another Arduino (eg. Uno, Mega) and connect 6 wires between each of them like this:

[![Program bootloader][1]][1]

The sketch for programming the bootloader is available on Github:

<https://github.com/nickgammon/arduino_sketches>

You want the one in the "Atmega_Board_Programmer" subdirectory.

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


message:
Why does Serial.print print out the wrong thing?

I am using a flame sensor. I am reading the state and then printing it. Here is my code:

    void loop(){
     flameState = digitalRead(flamePin);//variables already defined and are global
    existsFire();//calls the void
    delay(1000);
    }

    void existsFire(){

    Serial.println("Flame: " + flameState);

    }

Before, this printed out the right thing. Today, it was printing out "lame:". The "F" and the flameState were missing. I changed it to:

    void existsFire(){

    Serial.print("Flame: ");
    Serial.println(flameState);

    }
Everything worked fine. Is there a problem with my Arduino Mega. What do I need to do to fix this?

body:
You've stumbled across the difference in the C++ language between a `String` and an "array of characters". What you gave `Serial.println()` was an array of characters:

    Serial.println("Flame: "...);

and then tried to add a number to it.

    Serial.println("Flame: " + flameState);

If it had have been a `String`, then what you typed would have been fine:

    String flame = "Flame: ";
    Serial.println(flame + flameState);

Adding (literally `+`) a number to a `String` adds characters to the `String` to represent the number. Unfortunately you didn't start with a `String`, you started with an array of characters:

    "Flame: "

Adding a number to THAT changes where the array starts. `flameState` must have been `1`, and `"Flame: " + 1` would have been `"lame :"` - as you found out!

The version that worked did so through a little bit of magic:

    Serial.print("Flame: ");
    Serial.println(flameState);

The first line called a version of `print()` that accepted an array of characters and printed each of them out. The second line called a _different_ version of `println()` that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the `ln` part of the name).


message:
Shift Register w/ Internal Pullups?

Is there a chip that is just a parallel in / serial out shift register but with integrated internal pullups?

I could use a full-blown I/O expander but I really just need more momentary button inputs. I don't need outputs and I would rather not bother adding resistors or with writing commands to initialize the chip.

body:
Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s).  This is because they are normally connected to a [totem pole][2] driver.  Such a driver eliminates the need to avoid floating inputs.

Also, pull up resistors require current when the input is driven toward the opposite power rail.  Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.

Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.

Added later...

[Here][1] is a description about connecting a ps/2 keyboard to an Arduino.  Included are schematics, code examples and supporting library.

(USB keyboards are not well suited for this purpose as they require a USB Host.  As most Arduinos do not have this, a USB Host shield is required.)

  [1]: http://playground.arduino.cc/Main/PS2Keyboard
  [2]: https://en.wikipedia.org/wiki/Transistor–transistor_logic#TTL_with_a_.22totem-pole.22_output_stage


message:
SD test is taking long answer when it fails

I am working on an Arduino application that logs sensors values into SD files. It is essential that the SD is inserted and working when a test is started, thus I need to check the presence of the SD regularly (every 2 seconds or so) to prevent launching a test without SD inserted by the user.

When I run the following code, it runs very fast when the SD test succeeds (<10ms), but it takes more than 2000ms when the test fails. Is there another test I could run that does not takes 2 seconds to indicate that the SD is not inserted (or not working)? All my buttons are frozen and they do not trigger any action while checking if no SD is inserted.

Here is my code (both loops have the same issue):

    #define csSD   53
    #include <SD.h>

    Sd2Card card;

    void setup() {
      Serial.begin(57600);
      bool SDOK = SD.begin(csSD);
      if(SDOK) {
        Serial.println("SD.Begin Setup OK");
      } else {
        Serial.println("SD.Begin Setup Fail");
      }
    }

    unsigned long t;
    //void loop() {
    //  t=millis();
    //  if(SD.begin(csSD)){ // SD.Begin test runs fast when there is a SD, even though it return true when you try to begin SD a second time
    //    Serial.print("SD.Begin loop OK : ");
    //  }else {
    //    Serial.print("SD.Begin loop Fail : ");
    //  }
    //  Serial.println(String(millis()-t)+"ms");
    //  delay(500);
    //}

    void loop() {
      t=millis();
      if(card.init(SPI_HALF_SPEED, csSD)) {
        // card.init test returns true as it should (when SD is present and working), but runs fast only when SD is working
        Serial.print("card.init loop OK : ");
      } else {
        Serial.print("SD.Begin loop Fail : ");
      }
      Serial.println(String(millis()-t)+"ms");
      delay(500);
    }

body:
You could always try this very simple sketch. I have never measured how quick it runs, but it is pretty quick.

    Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

Just make sure to change 4 in `!SD.begin(4)` to whatever your ChipSelect pin happens to be for your component.

Furthermore, you could add a `return` statement after your "initilization fails" loop because that will immediately stop the program, after all you do not want to run it if the SD card is not reading data! And last thing, it may be a little overkill to check the SD card after initial initilization, after all, it will be highly unlikely for an error to occur once everything is working fine unless you mess with the SD card alot while it is running, which I am sure you won't.


body:
The [SD](https://www.arduino.cc/en/reference/SD) library builds on the sdfatlib library, in which SD_INIT_TIMEOUT is defined as 2000 ms, which gives your 2 second timeout. You could try lowering that number to get a faster response, although that may run the risk of timing out even when a card is present.

Four different timeout periods are defined in the sdfatlib source:

    /** init timeout ms */
    uint16_t const SD_INIT_TIMEOUT = 2000;
    /** erase timeout ms */
    uint16_t const SD_ERASE_TIMEOUT = 10000;
    /** read timeout ms */
    uint16_t const SD_READ_TIMEOUT = 300;
    /** write time out ms */
    uint16_t const SD_WRITE_TIMEOUT = 600;

The 300 ms read timeout is faster, as @Paul suggests in his comment, so you could just use a card read as the test rather than an initialisation, or try setting the init timeout to 300 instead. A read test would be simpler, as it doesn't involve modifying library files. It might not cope with a re-inserted card, though - I suspect that requires reinitialisation each time.

Note: the version of sdfatlib included with the SDlib in my Arduino install appears rather older than the [current version](https://github.com/greiman/SdFat). The included version defines the timeouts in Sd2Card.h, while the latest has is in SdInfo.h. The snippet above is from the older, included code.


message:
Is it possible to use a USB camera with Arduino?

It is necessary to recognize the motion and record video live.

**Update**
Save enough on your memory card.

***PS**
Maybe I'll repeat the question, but I am not guided in English.
Sorry for my English*.

body:
An Arduino is not a powerful processor and can not do much image processing.  I doubt that there is a USB camera that could be connected to the Arduino.

There are a range of OVO cameras that can connect to the Arduino, but I don't think you will be able to record live video on an Arduino with these, where would you store the file for starters?

There is a PIXY camera system, this has its own microprocessor and interfaces with an Arduino.  It can record video and do object recognition.
http://charmedlabs.com/default/pixy-cmucam5/

Hope that helps.


message:
How to get readings on serial monitor in every 10s?

I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.

The code is as follows:

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

    /*
       The circuit:
      * VCC connection of the sensor attached to +5V
      * GND connection of the sensor attached to ground
      * TRIG connection of the sensor attached to digital pin 2
      * ECHO connection of the sensor attached to digital pin 4
     */

    const int trigPin = 2;
    const int echoPin = 4;

    void setup() {
      Serial.begin(9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
    }

    void loop()
    {
      long duration, cm;

      pinMode(trigPin, OUTPUT);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);

      cm = microsecondsToCentimeters(duration);

      Serial.print(cm);
      Serial.print("cm");
      Serial.println();

      delay(100);
    }

    long microsecondsToCentimeters(long microseconds)
    {
      return microseconds / 29 / 2;
    }

body:
Yeah it shouldn't be an issue, remember `delay(time`) is a millisecond command, so if you want to get a reading every 10ms, simply put `delay(10)`, and **not** `delay(100)`. Like the comment above mentions, you should have no problem with a 9600 baud rate serial monitor link showing data every 10ms.

Also, I would highly reccomend checking out the NewPing library (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home)
which is an update library for the ultrasonic distance sensor which I assume you are using based off your code. With that, you can send up to 30 "pings" per second, so if the above solution doesn't fix it for you, this definitely should.


body:
There is one fundamental error with your code that I feel I should point out - one that I see time and time again.

The basic structure of your code is:

* Forever:
    * Send a ping
    * Wait for the pong
    * Print the result
    * Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.

However, you won't.  What you will actually get is a result *every so often*, where that time is defined as 100ms + the time to send and receive a ping.

So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then `pulseIn()` will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per [the manual](https://www.arduino.cc/en/Reference/PulseIn)

When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).

Instead you need to use `millis()` to check to see *if it is time to print something* so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.


message:
Engine Speed Control Observation

I am using an Arduino Mega to control the speed of an internal combustion engine.

The speed is sensed via a Variable Reluctance Sensor (VRS) on the crankshaft. This signal is then converted into a 5V square wave which is feed into Interupt 2 (Pin 21) on the Arduino.

The flywheel of the engine, onto which the VRS is sensing has one tooth. Therefore one square wave blip (from 5v to 0V) as it is passing it and then back up to 5v. The interupt that this is attached to increases a counter by 1. The time taken for the counter to reach 20 is recorded. I want to use this speed reading value in a PID algorithm which then in turn actuates a servo.

This methodology was sucessfully used in a very similar engine with a 22 toothed flywheel but is not working on this engine with 1 tooth.

The problem is the speed reading - the values that I am recording for the time taken for 20 revs ( in micro seconds), and displayed on the serial terminal is wrong and I do not know why. The numbers printed are all mulitples of one another e.g. 440960,551200,661440,771680 which all divide into one another with an even fraction. The correct reading here is 661440, this has been verified with observation of the square wave input through and oscilloscope.

I cannot find why!

I have attached the code [here][1]

  [1]: https://gist.github.com/gawnieg/c4d290e8b0b4f5f2bbfc39ae6087e768

body:
Your methodology there is somewhat flawed. Not only will you never see that Counter1 >= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.

A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.

Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using `millis()`) and when a certain (to be decided by you) time has elapsed (the *sample time*) you record the pulse count and reset it to 0. You then have a number of rotations per time period.

If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.

    void loop() {
        static uint32_t ts = millis();
        uint32_t pulses;

        if (millis() - ts >= 1000) {
            ts += 1000;
            uint8_t sr = SREG;
            noInterrupts();
            pulses = Counter1;
            Counter1 = 0;
            SREG = sr;
            Serial.print(pulses);
            Serial.println(" revolutions per second");
        }
    }

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.


message:
Xbee not activate on arduino micro

I have 2 nodes: one is a PC+arduino mega+xbee the other one is arduino micro+xbee.
The 2 xbees are communicating fine, I have tested this with 2 separate arduinos.
My problem is that when the second xbee hooked up to the micro it seems it does not try to send or receive data from the serial lines.
It is connected to the first RX/TX pins in proper order (RX->Tx, Tx->Rx) on the micro.

This is obvious for me because if I start my program's setup section on the ardu with:

    void setup()

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

The whole main program won't be running because the serial just never gets ready only if I plug my PC in.

When I try to send data from the PC->micro through xbee I see the Xbee receives it (led goes on the board) but nothing happens on the micro.

The micro right now is set to periodically send some debug data through the serial, I don't get that back either otherwise I would see the serial TX led on the micro blinking that it is sending the data. It only works when the PC is connected through USB.

Do I need some additional code for the xbee or is it require a hardware modification? I use a 5V-3V ttl converter as an extra hardware.

body:
From your description, it kind of hard to figure out which arduino doesn't react. Maybe a picture would help.

If it is the arduino that is connected to the PC then the problem is that the serial connection is already used to talk to te PC and therefore can't be used to talk to the XBee. you'll need to use one of the other serial connections on the atmega (serial1, 2 or 3)

Mind you that you don't need a microcontroller to connect an XBee to the PC. A simple UART to USB converter is enough.


body:
It is probably because you are using the only Serial to communicate to both the devices - your PC and XBee. At any instant, you can communicate to only one device. So you might need an extra serial to get you go.

And, may be due to this conflict you can see TX led blinking. May be it's communicating with anyone of them, and the other one is receiving garbage.


message:
Using Arduino libraries with ARM based microcontroller

A week ago I started messing with LoRa. I got my [STM32L151 IM880A kit](http://www.wireless-solutions.de/products/starterkits/sk-im880a.html).

Company that provided SX1272 LoRa modem chip (used in kit), provided some libraries, but lots of functionalities are still not implemented and is still not suitable for use in multi P2P aplications.

After googling I came across Libelium company which used SX1272 chip in their products design and they provided useful set of [libraries](https://github.com/Libelium/waspmoteapi/tree/master/libraries/SX1272) that provides lots of functionalities and also implements some sort of LoRa frame protocol stack ideal for use in P2P applications.

The problem is that I'm using STM32 in my project and Libelium libraries are written for Arduino. So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Tips, hints, links would be appreciated (I don't have experience in using Arduino and I'm not familiar with Arduino library structure).

body:
Every time I work on a project I use arduino libraries and port them to my micro controller.
I used [sublime][1] text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.

You would do that till you have finished and it would take some time.

  [1]: https://www.sublimetext.com/ "sublime"


body:
> So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Yes. the STM32 port of arduino uses GCC, which isn't that different MDK or ADS - I have ported quite a few from back and forth from GCC <-> MDK, and one from GCC to ADS. If the code is well written, in many times all you need to do is to change the isr-related code pieces (a few names) and hit the recompile.


message:
Array deletion problem

I am a bit confused about how memory works in Arduino.  I have created an integer array like so:

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

    int* arr = new int[3] {1, 2, 3};

When I go to delete it:

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

    delete[] arr;

The first element is deleted, and all the remaining ones are still  present and accessible.

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

    Serial.println(arr[0]); // prints 0
    Serial.println(arr[1]); // prints 2
    Serial.println(arr[2]); // prints 3

body:
It is not a good idea to use dynamic memory in such a small devices in general.

And delete doesn't mean setting values to something at all. It's just returning allocated memory back ("to system" is not correct term here as there is no system).

You should try to use objects with some action in constructor and destructor (like printing values).

For example:

    class test {
    public:
      test(int _i):i{_i} { Serial.print("test:"); Serial.println(i); }
      ~test() { Serial.print("~test:"); Serial.println(i); }
      int i;
    };

    void setup() {
      Serial.begin(57600);
      test * arr = new test[3] {4,6,9};
      delete[] arr;

    }

    void loop() {
    }

prints:

    test:4
    test:6
    test:9
    ~test:9
    ~test:6
    ~test:4


body:
First of all: it is not a good idea to do dynamic memory maagement in embedded systems (in casu arduino)
Secondly freeing memory means: marking the memory as available. It does not mean "setting the memory to 0"
because `ar` still points to the same locaton in memory it is "normal" that it also still reads the old values. Only -according to the C CP0P0 pàrogramming rules- you should not do so. Reading will not cause problems but writing will very likely.


body:
Deleting `new`ed memory only informs the system that you are no longer using it and releasing it for re-assignment. The pointer still points to memory containing your array but that memory is no longer reserved for you. You could, in theory, go on using it, but another `new` might well reassign it for another use and the data that was in it would likely get over-written.

It would be good form to zero your pointer (`arr = (int *)0;`). It accomplishes several things:

 - Your code clearly reminds you that the pointer is no longer usable;
 - Your code clearly informs the next reader that the pointer is no longer usable;
 - An attempt to use the pointer is quite likely to fail immediately (depends on the envrionment's ability to trap attempted accesses to location 0). The alternative is your code may work anyway - until someday that memory actually *does* get re-assigned and suddenly, code that has worked "forever", breaks, and in a non-obvious way. Save yourself or the guy or gal who follows you some grief, and make it a habit to zero your pointers once they are no longer valid.