message:
"No more addresses" when using multiple DS18B20 sensors

I want to build a scheme to get data from several DS18B20 sensors and write their temperature to serial. Before I connected them using parasite mode and using 2,7k resistor (because I didn't have 4,7k at home). Back then, it worked for 1 device, if I plug in another, it won't detect any of them (it writes "No more addresses"). Now I replaced 2,7k resistor with 4,7k and it doesn't detect any device connected. But if I do one little thing, which is replacing 4,7k resistor back with 2,7k, it will detect one device.

How to fix it?

Here is exactly how it is all connected now:
[![enter image description here][1]][1]

and here is the default sketch I am using:

<!-- language: c -->

    #include <OneWire.h>

    // OneWire DS18S20, DS18B20, DS1822 Temperature Example
    //
    // http://www.pjrc.com/teensy/td_libs_OneWire.html
    //
    // The DallasTemperature library can do all this work for you!
    // http://milesburton.com/Dallas_Temperature_Control_Library

    OneWire  ds(10);  // on pin 2 (a 4.7K resistor is necessary)

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

    void loop(void) {
      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius, fahrenheit;

      if ( !ds.search(addr)) {
        Serial.println("No more addresses.");
        Serial.println();
        ds.reset_search();
        delay(250);
        return;
      }

      Serial.print("ROM =");
      for ( i = 0; i < 8; i++) {
        Serial.write(' ');
        Serial.print(addr[i], HEX);
      }

      if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
      }
      Serial.println();

      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          Serial.println("  Chip = DS18S20");  // or old DS1820
          type_s = 1;
          break;
        case 0x28:
          Serial.println("  Chip = DS18B20");
          type_s = 0;
          break;
        case 0x22:
          Serial.println("  Chip = DS1822");
          type_s = 0;
          break;
        default:
          Serial.println("Device is not a DS18x20 family device.");
          return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44);        // start conversion, use ds.write(0x44,1) with parasite power on at the end

      delay(1000);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      Serial.print("  Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      fahrenheit = celsius * 1.8 + 32.0;
      Serial.print("  Temperature = ");
      Serial.print(celsius);
      Serial.print(" Celsius, ");
      Serial.print(fahrenheit);
      Serial.println(" Fahrenheit");
    }

Is there anything I am doing wrong? Because I somehow managed to get it working some time ago.

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

body:
A strong-pullup seems to be the key to having multiple sensors in parasitic mode, as described in the datasheet for the DS18b20 devices. Though they suggest using a MOSFET to pull up the 1-wire bus, I've had good results (3 meters of wire, 3 devices more than 2 meters out) by tying an output port directly to the 1-wire bus, bypassing the 4.7K resistor.

    // One wire bus strong-pullup:
    //
    //    +------------+     +5v            +---------+     +---------+
    //    |    MCU     |      |             | DS18b20 |     | DS18b20 |
    //    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
    //    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
    //    | Pullup   > o------o               |  |  |         |  |  |
    //    |            |      |               +--|--+         +--|--+
    //    |            |      |               |  |            |  |
    //    |    Data <> o------o---------------|--o------------|--o------ - - -
    //    |            |                      |               |
    //    +------------+                      V               V

Initialize the strong-pullup port by setting the port as an output and HIGH, the disable and enable it by changing the port mode, not the output value. (Setting the port mode to input floats it, rather than grounding it as setting it LOW would do. This technique was suggested to me by Dave Tweed in Electrical Engineering Stack Exchange.)


sender: user

sender: assistant

body:
A problem with what you are doing on the breadboard is that you show no bypass capacitors.

What makes the pull up "strong" is the ability to provide current to move the data line from zero back to one.  The load on the data line is its capacitance.  To move the data line from 0 to 1, you have to charge that capacitor.  Working on a bread board, you are correct that you have a larger capacitive load.  So you require more current to move the data line from zero to one quickly.

You are correct that the lower 620 ohm resistor will provide more current.  The large current will move the capacitance load of the data line more quickly.  But you are not paying attention to the other side of the resistor, the 5V rail.

The layout you have has inductance in the wires from the Arduino power supply out to the bread board.  An inductor has a voltage drop across it proportional to the rate of change of the current through it:

    V = L  di/dt

The analogy is that inductance is a flywheel: if it is not spinning, it will take force to get is moving.  Similar, once it is spinning, it will take force to stop it.

So when the resistor starts conducting to pull up the data line, the inductance in the wires and breadboard cause a voltage drop.  The +5 side of the resistor voltage drops.  This inductance in the wires leading to the resistor prevents it from rapidly charging the data line back to 1.

That is the role of *bypass* capacitors.  You place 1 or 2 right at the resistor between the +5 and GND strips on the bread board.  Now when the resistor draws current, it initially pulls from the energy stored in the capacitors.  After a short time, the current will start pulling from the +5 wire.  Thereby, you have **bypassed** the inductance of the +5 supply, hence the name.

Add a 0.1 microFarad ceramic capacitor on your breadboard where the wires connect to the contact strips.  You will see this on schematics for anything that has a DC supply off board.  Right next to the power connector will be 2 or 3 capacitors, usually one big 2-10 uF tantalum and one smaller 0.1 uF or so.  Similar across circuit boards you see bypass caps placed at the supply voltage pin of every chip, commonly two: a 0.1 uF and a smaller 10 nF.

It might seem pointless to place a small capacitor in parallel with a larger capacitor.  The values just add, yes?  But again, the time response is different.  Capacitors are not perfect and have internal series resistance.  A big 10 uF electrolytic capacitor may store a lot of energy, but it is not fast in terms of how quickly it can start providing current.  A little 100 nF ceramic monolithic capacitor is very fast, but doesn't have much energy.

So with two bypass caps in parallel, you have the small one for the initial burst of current, the larger cap for the heavy lifting, and last and slowest the 5V wires and traces to supply to steady current.


message:
powering the arduino uno

I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)

Thanks!

body:
The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10*24*7=1680mAh). That is without any application at all on the MCU.

Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.

Here is a great [reference][1] on the subject.

Cheers!

  [1]: http://www.gammon.com.au/forum/?id=11497


body:
You will definitely not get a week out of a 9V cell - they have very small capacities (and are expensive relative to other types of cell).

Your Uno already has a regulator in it and this regulator wastes a certain amount of energy converting between different voltages. I'm certainly no expert, but from what I've gleaned over the last month or so of owning an Uno, powering it from batteries can be tricky if you want to do it for long periods of time.

It's probably worth trying a 12v sealed lead acid battery - these have capacities measured in Amp Hours, rather than milli-amp hours like most other types of cell. The built-in voltage regulator in the Uno is good up to 20V, just be sure to connect to the barrel jack on the board.

Of course, without knowing more about what you're actually trying to power along with the Uno, it's difficult to make proper recommendations.

I would also suggest looking at building your system with a naked MCU and a voltage regulator tailored to your application. That way you can throw away a lot of the stuff that uses power on the board that you don't need. (Start with a Breadboarduino and take stuff out from there!)


body:
Three main things to do to decrease the Uno's power consumption:

1. Remove the power LED (you can Google for instructions if you're not sure how to do it)

2. Bypass the voltage regulator by providing ~5V of power to the 5V pin. You can arrange three sets of AA batteries in series to get about 4.5V which should be fine except that the crystal may run at a different speed (and you may get incorrect results from the millis() function for example). Obviously if that is unacceptable then you will need to provide a constant 5V voltage either by using the Arduino's regulator (which is quite inefficient) or buying a more efficient third-party regulator. The voltage provided by the batteries will vary somewhat, and over time the batteries will start putting out less voltage and eventually your Arduino may start to behave erratically or not at all. If reliability is of high importance then this may not be acceptable to you.

3. Use sleep modes to the greatest extent possible (see http://playground.arduino.cc/Learning/ArduinoSleepCode). If your Arduino only needs to wake up for a few seconds every hour, you can make a few batteries go a very long way. Note that if you're using a regulator, it will still draw significant power even while the Arduino is sleeping.

Bonus tip: buy a micro instead, or build your own board. (Avamander suggests a Pro Mini 3.3V in the comments below, he's probably right, I don't know much about that board)


message:
XBee + Arduino Problem

I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?

body: Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge_Base_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.


message:
None of the programs in Arduino example is compiling

I am new  to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\\ drive

    exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist
        Error compiling.

I don't know what to do. Please help me

body:
A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it [here][1].

What's odd looking too me is:

 1. The double backslashes, they could be causing the file to appear not to exist, and

 1. The `arduino-nightly` component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.

[1]: https://www.arduino.cc/en/Main/Software


message:
Arduino Nano Atmega328P doesn't work on Macbook

I've bought and Arduino Nano compatible on eBay:

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

But by the time I connect it to my Macbook Pro (OS X El Capitan 10.11.2) doesn't appear under "Tools -> Port" in Arduino IDE:

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

I've followed some instructions by other posts here in StackOverflow:

 - https://arduino.stackexchange.com/questions/5119/arduino-nano-no-serial-port-for-macbook-air-2013
 - https://arduino.stackexchange.com/questions/13813/arduino-nano-with-mac-os-yosemite-10-10

But none of them worked :(

If someone could help me out with this issue I'll be grateful.

Thanks.

  [1]: https://i.stack.imgur.com/Qax36.png
  [2]: https://i.stack.imgur.com/IkAtJ.jpg

body:
I was be able to solve the issue.

By looking for the serial chip my board has: CH340G I found this blog post:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

So I downloaded the signed driver for my chip and now it works :D

Driver: http://kiguino.moos.io/downloads/CH34x_Install.zip


message:
Can I increase the 10 event limit in Simon Monk's Timer library?

On Dr. Monk's library page [here][1], he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.

In Timer.h, he defines the maximum number of timed events like this:

    #define MAX_NUMBER_OF_EVENTS (10)

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.

  [1]: http://www.doctormonk.com/2012/01/arduino-timer-library.html

body: I don't see anything that would cause any issue. Just don't exceed 255.


message:
Can I run a Mega 2560 on 14v?

I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.

Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.

body:
You *can*, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).

Unless you have a *switching* regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.


message:
Light only half of the LEDs

How can I only let half of the LEDs light up,
for example, LED 1 on, LED 2 off, LED 3 on...and so on.

I did it this way
(this example fades also all LEDs on and off)

<!-- language: c -->

       int x = 1;
       for (int i = 0; i > -1; i = i + x){
          leds[0] = CRGB(i,0,0);
          leds[1] = CRGB(0,i,0);
          leds[2] = CRGB(i,0,0);
          leds[3] = CRGB(0,i,0);
          Serial.println(i);
          FastLED.show();
          if (i >= 55) x = -1;             // switch direction at peak
          delay(10);
       }

but that is not so nice if you have 100 LEDs or so.

body:
I don't know much about neopixel but as a general coding practice if you want to do something for every other object, you use the modulus operator like so

    if(i % 2 == 0)
    {
      //i is even
      //off
    }
    else
    {
      //i is odd
      //on
    }

So just wrap your current for loop in another one and to the above with the iterating variable.


body:
    int x = 1;
       for (int i = 0; i > -1; i = i + x){
         // using modulo
         if(i % 2 == 0){
         leds[i] = CRGB(i,0,0)}else{
         leds[i] = CRGB(0,i,0);}

          Serial.println(i);
          FastLED.show();
          if (i >= 55) x = -1;             // switch direction at peak
          delay(10);
       }

or

    int x = 2;
       for (int i = 0; i > -1; i = i + x){
         leds[i] = CRGB(i,0,0);

          Serial.println(i);
          FastLED.show();
          if (i >= 55) x = -2;             // switch direction at peak
          delay(10);
       }


body:
This is, for the most part, exactly what others have said. However, nobody has managed to actually use a `for` loop properly; they've carried forward your inefficiencies for some unknown reason.

The whole point of a `for` loop is to execute a block of code a predetermined number of times. In your code, you create a loop that loops for a ridiculous length (65,536 times) but each time checks how many loops there have been.

Once the `for` loop has been constructed properly there are two approaches:

    int NUMBER_LEDS = 100;      // you only ever have to change this
                                // if the number of LEDs change - and it's really
                                // easy to find if you put it at the start of
                                // your code.

    for (int x = 0; x < NUMBER_LEDS; x++)
    {
        if (x % 2 == 0)
            leds[x] = CRGB(x,0,0);
        else
            leds[x] = CRGB(0,x,0);
        Serial.println(x);
        FastLED.show();
        delay(10);
    }

The above code is fine if you just want two LED subsets. If you want more than two, you can use a `switch/case` statement:

    int NUMBER_LEDS = 100;      // you only ever have to change this
                                // if the number of LEDs change - and it's really
                                // easy to find if you put it at the start of
                                // your code.
    int NUMBER_SETS = 4;        // this will give four groups.

    for (int x = 0; x < NUMBER_LEDS; x++)
    {
        switch (x % NUMBER_SETS)
        {
            case (0):
            {
                leds[x] = CRGB(0,0,0);
                break;
            }
            case (1):
            {
                leds[x] = CRGB(x,0,0);
                break;
            }
            case (2):
            {
                leds[x] = CRGB(0,x,0);
                break;
            }
            case (3):
            {
                leds[x] = CRGB(0,0,x);
                break;
            }
        }
        Serial.println(x);
        FastLED.show();
        delay(10);
    }

You don't have to write a `case` block for every outcome of `x%2`; you might want a certain group of LEDs to stay on for two iterations, for example. More information on `switch/case` can be found [here](http://www.cplusplus.com/doc/tutorial/control/), towards the bottom of the page.

I recommend you read this article on [Operators in C++](http://www.cplusplus.com/doc/tutorial/operators/), starting from "Compound Assignement". It helps make code more readable and can considerably decrease the amount of typing you have to do - `i = i + 1` neatly becomes `i++`.


message:
Is there any realy working setup for multicopter with codes

I'm searching pc controlled quadrotor code projects.  I tried to do [strangedev's project][1] but not works for me. Is any one test this project. PID commands works like relays. suddenley speeds up and down. I tried to tune PID constants with Ziegler nichols but no success. Is there any realy working code and setup. Can you share your experiences?

  [1]: https://github.com/strangedev/Arduino-Quadcopter

body:
I've not used the (unmaintained) code you reference, but if a PID is responding much too fast in a new system, cut the parameters down significantly, first focusing on P and later I.  Turn off the D, and the I terms, then slow the P down until it is behaving reasonably.  Once Proportional control is working then try bringing I up in proportion to the change you did with P.

The https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62 code starts with (P,I,D) values of (0.5,0,1), so back off to (0.25,0,0) or (0.05,0,0) or lower to get the speed or response more as you expect, and then experiment.

Higher P will make it faster and saturate to the PID limit values quicker and make it more-relay like.  If your system is in a relay-like bang-bang mode, then Zeigler-Nichols tuning will be hard to do well. Reduce P until you get a non-relay-like response.    Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs.  PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.

The way the unmaintained code looks, value of P=20 will saturate at your output limits of +/-20 with only a pitch measurement of +/-1 degrees.

Show your actual code and values in your question, slow down the PID, and add debugging output.


message:
How to connect HC-05 to an arduino Galileo?

I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using `Serial.` functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo [here](https://www.arduino.cc/en/uploads/ArduinoCertified/IntelGalileoLogicSchematics.jpg).

So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?

body:
[This][1] might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.

Cheers!

  [1]: http://alextgalileo.altervista.org/blog/galileo-uart-and-arduino-serial-objects-mapping/


message:
Multiple Arduino Uno Slaves

I am working on an Arduino project where I need more digital and analofgpins than the Uno offers. I was wondering how to hook up multiple Arduinos (4) together so I can use their digital and analog pins. Thanks in advance.

body:
I suggest using a single [Arduino Mega][1].  It offers 54 digital I/O and 16 analogue inputs.

I suppose you could also use I2C or SPI to communicate between multiple Uno's.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


body:
Ryan Griggs' suggestion of the Mega is likely to be easier and more economical than using multiple Unos. That said can you say more about what you want to do with your proposed design? There are good reasons for distributing the load and the problems are interesting – so it is not obvious that the "right" answer is just to use a bigger central machine.

Besides tightly coupling them with the SPI or I2C you could also consider using Ethernet or Bluetooth. Arduino Ethernet shields tend to be expensive, but there are some wireless devices like the [Adafruit Huzzah][1] that are more economical.

You may find this [post on I2C][2] by Nick Gammon helpful. There is a similar example in [this question][3].

[1]: https://www.adafruit.com/product/2471
[2]: http://www.gammon.com.au/i2c
[3]: https://arduino.stackexchange.com/questions/15872/arduino-mega-with-two-arduino-unos-as-slaves-via-i2c?rq=1


message:
Having issue using Arduino IRQ handler in nRF51822

Could anyone please help me as I currently using [nRF51822-Arduino][1] library with a nRF51822 chip and I couldn't call the interrupt function, `wakeUp()`.

Currently I connect the external interrupt pin to nRF51822 pin: P0_1 or arduino pin: A0 after pin transform in the nRF51822-Arduino library. Maybe I know what value should I put for the variable `pin` for the function below:

    attachInterrupt(pin, wakeUp, CHANGE);

so that when there is an interrupt change, it will call the `wakeUp()` function?

  [1]: https://github.com/RedBearLab/nRF51822-Arduino

body:
Reading the source code for the attachInterrupt() shows that you should use the Arduino Pin number:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/wiring_interrupter.cpp#L70

The Arduino Pin number for A0 is 19 according to the pin transformation:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/pin_transform.cpp#L64

Cheers!


message:
invalid conversion from 'char' to 'const char*'

My intention was to overload a function to handle optional parameters. My code looks like

    void functionA(const char *errorMsg) {
      functionA('0', errorMsg);
    }

    void functionA(char errorCode, const char *errorMsg) {
        ...
    }

The line functionA('0',... generates the error

    invalid conversion from 'char' to 'const char*'

How do I fix that?

body:
What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of `functionA()` and is trying to cast `'0'` to a 'const char *` and that isn't going to work…

If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.


body:
The compiler needs the [prototypes][1] of the functions before the body containing the call to the overloaded function otherwise if starts complaining that the parameters does not match the known function (at this point in the source code).

    // The function prototypes
    void functionA(const char *errorMsg);
    void functionA(char errorCode, const char *errorMsg);
    ...
    void functionA(const char *errorMsg)
    {
      functionA('0', errorMsg);
    }

    void functionA(char errorCode, const char *errorMsg)
    {
      ...
    }

Cheers!

  [1]: http://www.cplusplus.com/doc/tutorial/functions/


message:
How to set address for using more than MPU9250

I am trying to build a project that contains more than one MPU 9250, until now I'm still confused to MPU9250. If I were going to that, does anybody here know how to set addresses to each of the MPU's I am going to use? Thank you for spending time reading my question. I hope someone will help me get through this.

body:
This is the type of information which a Data Sheet is intended to communicate.  In I2C mode the AD0 pin selects between two possible addresses,

1101000 for AD0=0 and
1101001 for AD0=1.

In SPI mode you can presumably have as many as you like by giving each its own chip select.

That said, using multiple sensors may not be very useful unless your apparatus is flexible - only the 3 accelerometer axis would be expect to yield different values based on position relative to the center of rotations.


body:
It is possible to have up to two MPU 9250 devices on an I2C bus without any extra logic. Pin 9 (AD0/SD0) defines the lowest bit in the I2C address of the device. Please see [Chap 7.2 I2C Interface][1]

If you need to connect more than two devices this can be done by connecting the AD0/SD0 pin of each device to a chip select pin on the arduino. This pin is asserted when addressing the device (This solution was provided by @Gerben, see comments below).

An example with three MPU 9250: Arduino D4-D6 are used as chip select pins. MPU1 AD0/SD0 pin connected to D4, MPU2 pin to D5, and MPU3 to D6. D4..D6 are initiate to HIGH. When addressing a MPU the chip select pin is set to LOW and the lower I2C address is used for access. The other MPUs will be listening for the higher I2C address.

Cheers!

  [1]: http://43zrtwysvxb2gf29r5o0athu.wpengine.netdna-cdn.com/wp-content/uploads/2015/02/MPU-9250-Datasheet.pdf
  [2]: http://www.nxp.com/documents/data_sheet/PCA9509.pdf


message:
Can I receive data on the Arduino by sending data to /dev/ttyACM0?

I'm working on a Raspberry Pi connected to an Arduino.
When I execute

    echo 'Hello' > /dev/ttyACM0

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?

body: Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.


message:
Arduino Mega 2560 ADC sampling instant and other timings

Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)

I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command *analogRead*.

I read [ATmega2560 microcontroller Datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf)

Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )

From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.

Let's say that I set the prescaler to 32 with the following commands:

    const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
    const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    ADCSRA &= ~PS_128;  // remove bits set by Arduino library
    ADCSRA |= PS_32;  // set our own prescaler to 32

hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency
( or 2 microseconds ADC clock period )

since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds

If I'm not mistaken, (2 microseconds * 1,5)  = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?

I measured the elapsed time using the micros() function and, like I'd expect,
I found out that there's a little overhead introduced with analogRead function
because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).

analyzing the code in wiring_analog.c
( which is located in the folder [...]/arduino/hardware/arduino/cores/arduino/ )
the actual conversion seems to happen at line 77

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

does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?

how can I know how much time passed before that sbi function call is issued?

I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)

Now, considering the so called "first" conversion, which take 25 ADC clock cycles

does this conversion happen just the first time I call analogRead since I powered on Arduino?
or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)

Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

body:
> does that mean that this is the instant from which the actual ADC
> conversion start, and so 1.5 ADC clock cycles from here, my analog pin
> value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

> how can I know how much time passed before that sbi function call is
> issued?

You could copy the original code and create your own `analogRead2` function that measures the time before setting ADSC.

> I saw that a single instruction on arduino won't take more than 4
> microseconds (but micros() function has that resolution so I don't
> exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

> Now, considering the so called "first" conversion, which take 25 ADC
> clock cycles
>
> does this conversion happen just the first time I call analogRead
> since I powered on Arduino? or does it happen even after some time ,
> because the ADC module gets powered off? (of course, I consider the
> case when Arduino remains powered on all the time)
>
> Judging by the timings I measured it seems like that the former is the
> one really happening, even if I don't use ADC for some time, but can
> anyone confirm?

This first conversion is after the `ADEN` bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.

PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.

PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.


message:
Using a phone battery as a power source possible?

**Use**
I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The **goal** is to have the most compact and long-lasting battery possible for my arduino projects.

**Note**
I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.

**Question**
I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.

*Also:*
Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (http://www.gammon.com.au/power); If utilizing his methods on different batteries are better than using a phone battery please let me know...)

**If Possible...**
Does it make sense for something like a:

 - LED suit (lasting 12 hours)
 - Portable gaming system (lasting 8 hours) - similar to: (https://www.adafruit.com/products/2510)
 *I Know this is for Raspberry Pi*
 - BlueTooth Speaker (lasting 6 hours)

etc...

body:
Sounds like a good solution.

Just note that most cellphones use Lithium batteries. Those are typically around 3.7 volt. They require some special way of charging, or they may **explode** or catch on **fire**. They also get damaged if discharged too much.

These batteries may have some protection circuitry inside them. This would be ideal in your case, as it protects against over-discharge, and accidental shorts.

An alternative would be the cells used in notebooks called [18650](https://en.wikipedia.org/wiki/List_of_battery_sizes#/media/File:Liion-18650-AA-battery.jpg)s. These are available with protection and without. The advantage is that you have a standard size. You can buy battery holders for them. That way you can easily exchange batteries. You can also combine cells to create higher voltages.

As for the runtime; you can make a rough [calculation](http://oregonembedded.com/batterycalc.htm) of it.


body:
I've done this before, but not very practical as a bare "flat-pack" outside its case presents other "issues", the battery "may" catch fire if punctured or shorted too long.  (read fire hazard when punctured) Lithium fires are like thermite, you can't put them out, tossing water on it will only make it worse.

Then there's the voltage mismatch (unless you're using a DUE). A POL  boost converter is needed for best efficiency to get 5-5.2V from a 3.7V cell. And a specialized charging IC is needed so that you don't overcharge/over-rate the current charging the pack. (constant-voltage/constant-current regulator type is needed). I think Adafruit has a lithium breakout board for the 3.7V lithium cell charger, it's for their lilypad stuff i think.


message:
Handling double (8 byte) in Arduino mega 2560?

I am receiving 8 bytes from serial.

I want to convert and save in double variable.

This is how i tried.

    union u_data
        {
            byte b[4];
            double fval;
        } u;

    double BytesToDouble (byte b8,byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1)
    {
        u.b[0] = b1;
        u.b[1] = b2;
        u.b[2] = b3;
        u.b[3] = b4;
        u.b[4] = b5;
        u.b[5] = b6;
        u.b[6] = b7;
        u.b[7] = b8;
     return u.fval;
    }

But i am getting 0.00. Because here double size is 4 bytes.

Is there is any other way to do this?

Thanks

body:
In the Arduino there is no such thing as a double. A double is just another name for a float.

So you will have to either:

1. Manually interpret the double format data and calculate that into a float value, or
2. Send the value as some other format, such as float (32-bit), ASCII text, or (a selection of) integer values.

Since you can't actually use anything more than float, sending data with a higher resolution is pointless, so you are probably best off just sending it as a float.


body: avr-gcc doesn't support binary64. You can use 8 bytes to treat it as an opaque data type, but attempting to manipulate it beyond manually converting to/from binary32 will be naught but pain.


message:
Arduino Power - DC adapter

I have a 12V 2.5 ampere Dc adapter.Can i use it to power arduino uno board?
It says on the arduino website that i can use 9-12V and upto 1 ampere. I am concerned with current limit here..

body:
Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.

As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the [reference design][1]) in the input path and the [MC33269D-5.0 regulator][2] is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).

[1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
[2]: http://www.onsemi.com/pub_link/Collateral/MC33269-D.PDF


body:
Make sure that the adapter you have is the correct polarity for the arduino or it won't work.

The barrel jack is centre positive, so look for this symbol on your adapter:

[![centre positive symbol][1]][1]

The barrel jack should have reverse voltage protection so it won't work if it's the wrong way around. The Vin pin doesn't have this protection, so be extra careful connecting things there.

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


message:
How can I attach sensors without a shield for a wearable project?

I am looking for a solution regarding the gsr, accelerometer, heart rate, skin temperature. From this [other question][1] seems that Grove isn't clear enough with their documentation. So I am looking for other ideas. I already know cooking hacks and I am afraid that with their hardware I can't make my Arduino wearable and comfortable enough, because at the end I'd like to attach a lithium battery with a case (that's why I don't want the extra bulk of a shield).

More details of what I am looking for.

Accelerometer:
Range: +/- 1.0g
Minimum resolution: 0.01g

Galvanic Skin Response
Range: 56k Ohms to 20M Ohms
Two-standard-deviation error of +/- 4.0% otherwise

Skin Temperature
Range: 20.0°C to 40.0°C
Resolution: 0.05°C
Error: +/- 0.8°C

  [1]: https://arduino.stackexchange.com/questions/601/grove-sensors-without-a-grove-shield

body:
The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.

The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.

I'd suggest taking at look at the [Adafruit][1] site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).

[1]: http://adafruit.com


body:
I ran into a similar quandary when making a prototype for a device that needed real test-data from an external, glove-worn accelerometer. I wound up running the data/power/etc pins from my Arduino board to a female RJ-45 jack (I've used a telephone jack on another project where only 4 wires were needed). Then I cut an old cat-5 network cable in half and soldered the wire-ends to data/power/etc pins on my external sensor board. This allowed me to separate one component's wiring scheme from the other's. (FYI: longer lengths of cable between components does increase the risk of noise/interference corrupting digital signals. This can usually be resolved by reducing data rates or by adding a few resistors/capacitors to filter the signal, but I have limited knowledge on this)

Even if you don't have any old RJ45 cables/jacks laying around, it can really help to find some way to "modularize" the various pieces that will be working together when your device is complete. If you're familiar with object oriented programming, think of it as "designing an interface" for each component. Then, even if you completely redesign the wiring for a particular component, you only need to ensure that your "interface" (aka connection) is the same, and you wont need to resolder anything on the other end of the line.


body:
For accelerometer sensing I used LIS3DH from STMicroelectronics, its low power(down to 2uA), small (LGA package 3x3x1 mm) and has cool build-in features (like orientation, tap and doble tap detection among other things). http://www.st.com/web/catalog/sense_power/FM89/SC444/PF250725?icmp=pf250725_pron_pr_feb2014 and there are a lot of libraries like https://github.com/adafruit/Adafruit_LIS3DH

For intro to GSR check this project http://cwwang.com/2008/04/13/gsr-reader/ Pretty easy ;) More advanced design will require a signal generator and an instrumentation amplifier. An example of such design can be found here https://www.maximintegrated.com/en/design/reference-design-center/system-board/6147.html/tb_tab1 Another interesting project is the truth wristband http://produceconsumerobot.com/truth/

The temperature part can be done with a thermistor (IC temperature sensors do not compliant with your resolution spec) and a bridge circuit. For reference check this sensor http://www.digikey.com/product-detail/en/PR103J2/615-1069-ND/2651611 and also some literature about Wheatstone Bridge http://www.ametherm.com/thermistor/ntc-thermistors-temperature-measurement-with-wheatstone-bridge

Hope be helpful.


message:
Const Array still using dynamic RAM during compile, causing failure

Using win7 and arduino 1.6.7 IDE
I have a rather large CONST array of chars and upon compile using atmega2560, it fails and says:

Sketch uses 11,216 bytes (4%) of program storage space. Maximum is 253,952 bytes.
Global variables use 8,414 bytes (102%) of dynamic memory, leaving -222 bytes for local variables. Maximum is 8,192 bytes.
processing.app.debug.RunnerException: Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
 at cc.arduino.Compiler.size(Compiler.java:319)
 at cc.arduino.Compiler.build(Compiler.java:156)
 at processing.app.Sketch.build(Sketch.java:1108)
 at processing.app.Sketch.build(Sketch.java:1083)
 at processing.app.Editor$BuildHandler.run(Editor.java:2011)
 at java.lang.Thread.run(Thread.java:745)
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.

When I delete the CONST array the program compiles successfully, but when I put it back in, the compiler tells me that I'm using too much dynamic RAM.  If I am to understand correctly, consts should store in ROM not RAM.

Here's the even weirder part I put the program in Arduino IDE for Linux and it compiles, but it makes my robot act all crazy.

Any help would be much appreciated.

body:
In a Princeton architecture `const` arrays are stored purely within the `text` (i.e., flash / read only / ROM) area.

In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.

Because of that it has to copy the `const` array from Flash into RAM so it can be accessed as normal variables.

To combat this you can use `PROGMEM` to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.

You can read more here: https://www.arduino.cc/en/Reference/PROGMEM


body:
`Const` data _may_ be stored in ROM but the standards don't require it; you usually have to specify in some (non-standard) way that it be placed there. I.e., `const`-ness is a necessary, but not a sufficient, condition for locating into ROM. [Placing Data into ROM with Standard C][1] by Dan Saks is a short, well-written paper (as is typical of Saks) describing what the standards do and, particularly, do not say about ROMming of constant data. It is well worth a few minutes to read it.

  [1]: http://www.dansaks.com/articles/1998-11 Placing Data into ROM with Standard C.pdf


message:
How to extract the last byte out of an IP adress

Newbie question:

I need to pass the last byte of a local IP as a parameter.
Eg.: when Ethernet.localIP() returns 192.168.0.100,
I need to extract the 100 and put it in a char array or string.

Anyone any ideas? Thx!

body:
`localIP()` returns an `IPAddress` object.  That object has an operator for `[]` allowing you to access the individual parts of it.

    IPAddress ip = Ethernet.localIP();
    Serial.println(ip[3]);


message:
NTP Client Library. Set sync provider pointing to public class function. Possible?

I am trying to develop a NTP client library for ESP8266/Arduino to make adding NTP sync an easier task.

Basically, I've thought about a constructor as **`NTPClient(String host, int interval);`** and a **`NTPClient.begin()`** function to register sync function.

My problem is with that registering.

I have a public function: **`time_t ntpClient::getNtpTime()`** that connects to NTP server, decodes the response and returns a `time_t` variable.

Then, inside **`boolean ntpClient::begin()`** function I try to run **`setSyncProvider(ntpClient::getNtpTime)`**. I've also tried to use **`setSyncProvider(this->getNtpTime)`**.

I get a compile error here:

    ntpClient.cpp:In member function 'boolean ntpClient::begin()
    ntpClient.cpp:79:39: error: cannot convert 'ntpClient::getNtpTime' from type 'time_t (ntpClient::)() {aka long int (ntpClient::)()}' to type 'getExternalTime {aka long int (*)()}
      setSyncProvider(ntpClient*:getNtpTime)
    Error compiling project sources

What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

body:
> What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

The function should be a static member function. A "normal" member function does not have the right prototype as there is a hidden parameter ("this").

    static time_t getNtpTime();

To solve this you need a [single-ton][1] (an instance of the client class) that the static function can use.

    class NTPClient {
    public:
       NTPClient() ...
       {
         ...
         s_client = this;
       }
       time_t getNtpTime();
       ...
       static time_t getNtpTime() ( return (s_client->getNtpTime()); }
       ...
    protected:
       static NTPClient* s_client;
       ...
    };
    ...
    NTPClient::s_client = NULL;
    ...
    NTPClient ntpClient;
    ...
    setSyncProvider(NTPClient::getNtpTime)

Alternatively a global function and a known instance:

    class NTPClient { ... };
    extern NTPClient ntpClient;
    ...
    time_t getNtpTime() { return (ntpClient.getNtpTime()); }
    ...
    setSyncProvider(getNtpTime)

Cheers!

  [1]: https://sourcemaking.com/design_patterns/singleton


message:
SD print in script works in setup but not loop

I am a bit of a novice with the Arduino, and have had to learn a lot for my High Altitude balloon launch. I am getting ready to launch this, but for some reason, my datalogger, printing to an SD card, will work in the setup function but not the loop.

If someone could explain what is wrong with my code, and any improvements that could be made to it, it would be very helpful. I am using SPI, SD, I2C, Wire, Sparkfun BMP, and MPU6050 library.

        #include <SPI.h>
        #include <SD.h>
        #include <math.h>
        #define thermoPin 0

        #include <SFE_BMP180.h>
        SFE_BMP180 pressure;

        #define ALTITUDE 87.8
        #include "I2Cdev.h"

        #include "MPU6050_6Axis_MotionApps20.h"
        #include <Wire.h>

        MPU6050 mpu;
        #define OUTPUT_READABLE_YAWPITCHROLL

        #define OUTPUT_READABLE_REALACCEL

        #define analogInPin 3  // Analog input pin that the potentiometer is attached to

        int sensorValue = 0;        // value read from the sensor

        // MPU control/status vars
        bool dmpReady = false;  // set true if DMP init was successful
        uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
        uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
        uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
        uint16_t fifoCount;     // count of all bytes currently in FIFO
        uint8_t fifoBuffer[64]; // FIFO storage buffer

        // orientation/motion vars
        Quaternion q;           // [w, x, y, z]         quaternion container
        VectorInt16 aa;         // [x, y, z]            accel sensor measurements
        VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
        VectorFloat gravity;    // [x, y, z]            gravity vector
        float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

        volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
        void dmpDataReady() {
            mpuInterrupt = true;
        }

        #define photocellPin 2
        // the cell and 10K pulldown are connected to a9
        int photocellReading;     // the analog reading from the analog resistor divider

        #define chipSelect 4

        void setup() {
          pinMode(A5, OUTPUT);
          pinMode(A4, OUTPUT);
          // Open dataFile communications and wait for port to open:
          if (!SD.begin(chipSelect)) {
            // don't do anything more:
            return;
          }
            File dataFile = SD.open("datalog.txt", FILE_WRITE);
          if(dataFile) {

          // Initialize the sensor (it is important to get calibration values stored on the device).

          if (pressure.begin())
            dataFile.println("BMP180 init success");
          else
          {
            dataFile.println("BMP180 init fail\n\n");
            while(1); // Pause forever.
          }
          // join I2C bus (I2Cdev library doesn't do this automatically)
            #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
                Wire.begin();
                TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
            #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
                Fastwire::setup(400, true);
            #endif
            dataFile.println(F("Initializing I2C devices..."));
            mpu.initialize();

            dataFile.println(F("Testing device connections..."));
            dataFile.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
            // load and configure the DMP
            dataFile.println(F("Initializing DMP..."));
            devStatus = mpu.dmpInitialize();

            mpu.setXGyroOffset(220);
            mpu.setYGyroOffset(76);
            mpu.setZGyroOffset(-85);
            mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
        mpu.setDMPEnabled(true);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
        dataFile.close();
          }

        }

        void loop() {
          // make a string for assembling the data to log:
          int valF, valC;
          valF = analogRead(thermoPin);
          valC = analogRead(thermoPin);
          File dataFile = SD.open("datalog.txt", FILE_WRITE);

          // if the file is available, write to it:
          if (dataFile) {

            dataFile.print(F("Millis since Launch"));
            dataFile.println(millis());
            dataFile.print(F(", Analog Val."));
            dataFile.print(valF);

            photocellReading = analogRead(photocellPin);

            dataFile.print(F("  Analog reading = "));
            dataFile.println(photocellReading);     // the raw analog reading
                                              // We'll have a few threshholds, qualitatively determined
          dataFile.println();
          char status;
          double T,P,p0,a;

            dataFile.print(F("provided altitude: "));
          dataFile.print(ALTITUDE,0);
          dataFile.println(F(" meters, "));

          status = pressure.startTemperature();
          if (status != 0)
          {
            // Wait for the measurement to complete:
            delay(status);

            status = pressure.getTemperature(T);
            if (status != 0)
            {
              // Print out the measurement:
              dataFile.print(F("temperature: "));
              dataFile.print(T,2);
              dataFile.println(" deg F");

              status = pressure.startPressure(3);
              if (status != 0)
              {
                // Wait for the measurement to complete:
                delay(status);

                status = pressure.getPressure(P,T);
                if (status != 0)
                {
                  // Print out the measurement:
                  dataFile.print(F("absolute pressure: "));
                  dataFile.print(P,2);
                  dataFile.print(F(" mb, "));

                  p0 = pressure.sealevel(P,ALTITUDE); // we're at 87.08 meters (Home)
                  dataFile.print(F("relative (sea-level) pressure: "));
                  dataFile.print(p0,2);
                  dataFile.print(F(" mb, "));
                  dataFile.print(p0*0.0295333727,2);
                  dataFile.println(" inHg");

                  a = pressure.altitude(P,p0);
                  dataFile.print(F("computed altitude: "));
                  dataFile.print(a,0);
                  dataFile.print(F(" meters, "));
                }
                else dataFile.println("error retrieving pressure measurement\n");
              }
              else dataFile.println("error starting pressure measurement\n");
            }
            else dataFile.println("error retrieving temperature measurement\n");
          }
          else dataFile.println("error starting temperature measurement\n");
          // if programming failed, don't try to do anything
            if (!dmpReady) return;

            // wait for MPU interrupt or extra packet(s) available
            while (!mpuInterrupt && fifoCount < packetSize) {
            }

            // reset interrupt flag and get INT_STATUS byte
            mpuInterrupt = false;
            mpuIntStatus = mpu.getIntStatus();

            // get current FIFO count
            fifoCount = mpu.getFIFOCount();

            // check for overflow (this should never happen unless our code is too inefficient)
            if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
                // reset so we can continue cleanly
                mpu.resetFIFO();
                dataFile.println(F("FIFO overflow!"));

            // otherwise, check for DMP data ready interrupt (this should happen frequently)
            } else if (mpuIntStatus & 0x02) {
                // wait for correct available data length, should be a VERY short wait
                while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

                // read a packet from FIFO
                mpu.getFIFOBytes(fifoBuffer, packetSize);

                // track FIFO count here in case there is > 1 packet available
                // (this lets us immediately read more without waiting for an interrupt)
                fifoCount -= packetSize;

                #ifdef OUTPUT_READABLE_YAWPITCHROLL
                    // display Euler angles in degrees
                    mpu.dmpGetQuaternion(&q, fifoBuffer);
                    mpu.dmpGetGravity(&gravity, &q);
                    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                    dataFile.print(F("ypr\t"));
                    dataFile.print(ypr[0] * 180/M_PI);
                    dataFile.print(F("\t"));
                    dataFile.print(ypr[1] * 180/M_PI);
                    dataFile.print(F("\t"));
                    dataFile.println(ypr[2] * 180/M_PI);
                #endif

                #ifdef OUTPUT_READABLE_REALACCEL
                    // display real acceleration, adjusted to remove gravity
                    mpu.dmpGetQuaternion(&q, fifoBuffer);
                    mpu.dmpGetAccel(&aa, fifoBuffer);
                    mpu.dmpGetGravity(&gravity, &q);
                    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                    dataFile.print(F("areal\t"));
                    dataFile.print(aaReal.x);
                    dataFile.print(F("\t"));
                    dataFile.print(aaReal.y);
                    dataFile.print(F("\t"));
                    dataFile.println(aaReal.z);
                #endif
            }
            // read the analog in value:
          sensorValue = analogRead(analogInPin);
          // print the results to the dataFile monitor:
          dataFile.print(F("  analog Val of OZONE= " ));
          dataFile.println(sensorValue);
          dataFile.close();
          }
          analogWrite(A4, 168);
          delay(3000);
          analogWrite(A4, 0);
          delay(750);
          analogWrite(A5, 0);
          delay(250);
          analogWrite(A5, 168);
          delay(3000);
            analogWrite(A4, 168);
          delay(2000);
          analogWrite(A4, 0);
          delay(1000);
        }

Possible problems (correct me if I'm wrong):

 - I noticed that the MPU6050 stops transmitting if delays are put into it

EDIT:
I have now tried the script but commented out the accelerometer (MPU6050) portion,  and it successfully writes to the SD card. could someone explain why the accelerometer portion messes up the rest of the code?

body:
I haven't followed all the details of your code, nor looked into all of the libraries being used, so you may need to ignore some of the following comments.

1. You write “my datalogger, printing to an sd card, will work in the setup function but not the loop”.  However, you don't say what you mean by “work”, nor how you tell if it works.

2. It looks like your code in `loop()` uses the same filename as in `setup()`.  If so, there's no reason to write a file in`setup()` because it will just be overwritten later.  (If you have a reason, use a different file name.)

3. Sequences like `status = pressure.startTemperature(); if (status != 0) {... delay(status); ... }` look suspect.  The parameter to [Arduino's `delay()` function](https://www.arduino.cc/en/Reference/Delay) is a number of milliseconds, in an `unsigned long`; is your `startTemperature()` supposed to return a status that's usable as the number of milliseconds to delay?

4.  Your `status` is declared via `char status;` and  `char` is a signed type.  If `status` is negative, the call `delay(status);` will first convert `status` to a signed `long` by sign-extension.  Then it will convert the signed `long` to an `unsigned long` with the same bit pattern.  This will ensure a delay of at least 7 weeks, which presumably is longer than you mean to wait.
[Ref: See the “Conversions from Signed Integral Types” table in microsoft.com/en-us/library's *[Conversions from Signed Integral Types](https://msdn.microsoft.com/en-us/library/xbfs6fd4.aspx)* webpage.]

5. To avoid those long and tedious sequences of `dataFile.print(...);` statements, you can `#include Streaming.h`, which is a [contributed library](https://www.arduino.cc/en/Reference/Libraries) that adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like `<<` stream operators to `.print()` calls, without increasing code size.  If you don't have `Streaming.h` installed, install it via [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).  Then, for example, in place of

      dataFile.print(F("areal\t"));
      dataFile.print(aaReal.x);
      dataFile.print(F("\t"));
      dataFile.print(aaReal.y);
      dataFile.print(F("\t"));
      dataFile.println(aaReal.z);

write

      dataFile << F("areal\t") << aaReal.x << '\t' << aaReal.y << '\t' << aaReal.z << endl;

6. Whether using `Streaming.h` or not, writing `F("\t")` instead of `'\t'` uses half a dozen bytes of program memory where one will do, and uses the same amount or more of RAM.  That is, while F() saves on RAM usage for long strings, it's of negative value for single characters and short strings.


message:
how to use the decoded raw value to send IR signal in arduino

I am IR library from Ken Shirrif at https://github.com/z3t0/Arduino-IRremote/releases/download/MAJOR/IRremote.zip

It is good and I have used the examples to receive and send and to playback IR signals from the library. And they are working good.

To send Unknown signals we should use sendRaw() method with a list of integers got from the receiver.

My question is when I use the receive program, I get the decoded hexadecimal value for even the Unknown signals. And can I use this small decoded signal to send signals apart from the long list of integers.

I am trying to send these codes from android. It would be quite easy to send and store the small hexadecimal decoded value.

Is there a way to use the decoded value to send for raw signals with some encodings at arduino?

body: If the signal is reported as "unknown" the library couldn't identify the protocol (RC5, RC6, NEC, SONY, etc).  If the library doesn't know the protocol,  the decoded number is meaningless. Simply put, an IR remote transmission has a frequency; a header; some data (the actual remote command); and a footer.  Without knowing the protocol the library doesn't know the length and shape of each section, so the purpose of the decoded number is only to show quickly if the decoding is receiving the same code at each keypress. You can verify this yourself.  Every time something makes an already known remote code be reported as "unknown", the code received is different from a real code, so simply guessing (or knowing beforehand) the protocol is not going to help anyway.


message:
problem on implementation of the ultrasonic circuitry

I used an Arduino Uno on my project to produce a frequency greater than 35000Hz and the output of digital pin was connected to the ultrasonic transmitter circuitry:

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

However, it's not working on the transmitting side. Here's the Arduino code:

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

    void loop()
    {
        pinMode(13,OUTPUT);
        pinMode(12,OUTPUT);
        int pirSenses = analogRead(A1);
        int pirOuts=11;
        pinMode(pirOuts,INPUT); /*PIR sensor 1*/
        int pirSense = analogRead(A0);
        int pirOut = 10;
        pinMode(pirOut,INPUT); /*PIR sensor 2*/
        Serial.println(pirSense);Serial.println(pirSenses);

        if (pirOut || pirOuts == HIGH)
        { /*tone produces ultrasonic frequency*/
            delay(8000);
            tone(13, 50132); delay(100); noTone(13); delay(10);
            tone(13,54621);  delay(50);  noTone(13); delay(50);
            tone(13,35689);  delay(60);  noTone(13);
        }
        else if (pirOut||pirOuts==LOW)
        {
            tone(13, 50132); delay(100); noTone(13); delay(10);
            tone(13,54621);  delay(50);  noTone(13); delay(50);
            tone(13,35689);  delay(60);  noTone(13);
        }
        else
        {}
    }

And the transmitter (model "MCPCT-G5100-4139") specification:

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

  [1]: https://i.stack.imgur.com/emtuj.png
  [2]: https://i.stack.imgur.com/SavQ6.png

Please help me with this problem. Thanks!

body:
Your ultrasonic Transducer driver circuit isn't doing a very good job. At most you are getting only a few milliwatts output to the transducer. Your circuit is applying 12 volts through a 2.2K resistor to the transducer, and your Q1 transistor is merely shorting out the Transducer.

From viewing the data sheet on your transducer, it looks like a tiny loud speaker and not a Piezo device. But that is OK.

Try the following push pull driver circuit.  I have tried to keep it simple, but you would need to come up with a PNP transistor (in addition to your existing NPN transistor).

The V2 square wave is your 5 volt output from Arduino.

Also, notice that I have shown the driver circuit using 5 volts, not 12 volts. Using this circuit, if you use 12 volts supply, the output doesn't get any more powerful, and just causes more heating in the transistors.

EDIT 1  :  IMPORTANT :  Don't leave your output pin in the HIGH state.  This turns on transistor Q1 and causes sustained current in the Transducer.  To alleviate this, insert a 47uf capacitor in series with the transducer.

EDIT 2 :  Changed schematic to include output capacitor.

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

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


message:
Arduino Christmas light project with dimmer

I have an existing project using an Arduino Yun that controls Christmas lights with relays to turn them on/off. There are currently 13 separate rows of lights on the (60 foot) tree, each plugged into a wall wart that's controlled by its own relay.

I'm considering adding the ability to dim the lights, so I wanted to figure out the best way to do it. The lights can all be dimmed "in unison" - there's no need for 13 seperately controlled dimmers. But I have to be mindful not to cause any "buzzing" in the audio equipment on stage where the tree is.

I've read about PWN, zero cross, and other terms and saw the zero cross tail from [powerswitchtail.com](http://powerswitchtail.com) that seem useful in the typical project. I'd like to be able to pull this off with no more than 2 "dimmers" for the whole project, if possible.

Where do I start, and how do I do it?

body:
I can think of a couple of ways to approach this:

1. Use a DMX dimmer, something like [this 4-channel dimmer][1], or

1. Use an household [X10 dimmer][2].

DMX is used for stage lighting and there is some information on [controlling DMX devices with an Arduino in the Playground][3] where there is also some [information on the hardware interface and shields][4], it looks pretty simple. DMX is a differential RS485 interface.

X10 is used for home automation, the signaling is done over the AC line. There is some information on [using X10 and an Arduino library][5] in the Tutorials.

Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.

[1]: http://smile.amazon.com/American-Dp-415-Channel-Dimmer-Pack/dp/B000FVZUMM
[2]: http://smile.amazon.com/X10-RWS17-WS12A-Decorator-Dimmer/dp/B00022OCE6
[3]: http://playground.arduino.cc/Learning/DMX
[4]: http://playground.arduino.cc/DMX/DMXShield
[5]: https://www.arduino.cc/en/Tutorial/X10


message:
How to send a group message to multiple receivers using GSM900 and Arduino Mega2560?

I'm working on a project and it can send to one receiver only. What I need is to send a message to multiple receivers. I need a code sample that would satisfy my needs. Please help! I need to finish this ASAP.

body: Simply change the number in the AT command and send the message again.


message:
How to connect an L293D and an MPU6050 to run together?

I'm wondering how to connect the L293D (H-bridge) and an MPU 6050.

I'm using 1 Arduino Uno, 2 DC motors, 1 MPU6050 and an L293D.

When I tried this, I got some sparks/smoke from the breadboard and none of the motors where running. I only used a 9v battery, not 12v.

![mpu 6050 and l293d](https://i.stack.imgur.com/uGD8u.png)

Here's the L293D:

![l293d](https://i.stack.imgur.com/rl1MH.jpg)

MPU 6050 wiring: int-digital 2, SDA-A4, SCL-A5, GND-GND, VDD-Vss

L293D wiring: Vss-VDD, Input4-Digital 5, Output4-Motor, Output3-Motor, Input3-Digital 6, Enable2-5V, Enable1-5V, Input1-Digital 9, Output1-motor, Output2-motor, Input2-Digital 10, Vs-12V battery.

body:
There a some mistakes with the wiring of the supply voltage (Vss) according to the datasheet (http://www.ti.com/lit/ds/symlink/l293.pdf) of the L293D a those on pin 8 (Vss2) and 16 (Vss1). I think those are not connected because each Vss is for one motor of the driver. So you have to connect 9V (or 12V) to both pins.
There is also something wrong with the capacitor (polarity). And your connection of the battery to the breadboard is a bit weird because + of the battery is usally the red not the black wire / marked row on the breadboard.


body:
I don't really se anything wrong with the wiring, atleast your diagram seems to be in order. only thing I would ad is give the pin 8 a ceramic capacitor to ground

but There is a few possible issues you can check.

1 -the sparks make me think that you had a Loose connection at the spark site on the breadboard, maybe the IC was not properly pushed Down in the breadboard, this happens alot, try Again and make sure the IC is complete inserted.

2 - if this does not work You might have destroyed the first L293 or the breadboard tracks but if you have more than one try to see if a replacement or movement of the old ic does the trick

3 -  the motors are to large, and so the current drawn is to high for the L293 to handle and caused thermal shutdown of the L293, a very high current drain will also occur if the motor is stalled. Anyway add some current limiting resistors and see what happends.

4 - if the motor hums without moving then it is because Both the forward and reverse input eg. 1 and 2 is enabled simultaneously.

5 - the code is not appended, so that cannot be verfified, but the MPU 6050 is correctly installed


message:
Reading temp data

I have hacked this kettle so that I can turn it on and off remotely via wifi and that is working perfectly.

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

Added this to get a better signal.

[![enter image description here][3]][6]

This is my micro controlling the 5v buttons on the kettle.

[![enter image description here][4]][7]

I keep running into a wall when it comes to reading the temperature of the water. The kettle does this automatically, but I want to transfer this information to my micro.

If I hook my multimeter to the ground and and yellow wire that connects to the lower voltage board (5v) that had the buttons and display I can use the voltage reading to predict the temp. The reading ranges from 0-5v, but my micro is a 3.3v micro so a direct connection isn't a great idea. I've tried using breakout boards designed to read voltage, but if I connect anything it throws the reading off.

The multi-meter is fine.

How can I get my micro to read the voltage as if it were a multi-meter? I even tried one of those little seven segment voltmeters but that threw off the reading just like the optocoupler and leds and other methods that I tried.

Here is how I have it set up:

  [2]: https://i.stack.imgur.com/F8mzHm.jpg
  [3]: https://i.stack.imgur.com/eS1Dhm.jpg
  [4]: https://i.stack.imgur.com/o56Nwm.jpg
  [5]: https://i.stack.imgur.com/F8mzH.jpg
  [6]: https://i.stack.imgur.com/eS1Dh.jpg
  [7]: https://i.stack.imgur.com/o56Nw.jpg

body:
## Voltage divider

You can possibly use a simple voltage divider. Try connecting two 100K ohm resistors in series between the voltage you want to measure and ground.

Yellow->100K ohm resistor->100K ohm resistor->ground

Now connect your multi-meter to the middle connection between the two resistors.

Depending on the circuit that happens to be driving the yellow wire, you should hopefully see a voltage that varies between ~ 0-2.5 volts. If so, you can connect this voltage to your 3.3v micro analog input.

Note that the value of the resistors is not critical - you just want them to be about the same and pretty large.

## Op Amp
If the yellow wire output is so weak that even a voltage divider with very large resistors is pulling the voltage down significantly, then you can use a high impedance op-amp with 1x gain to buffer the signal.

So, you'd connect the yellow wire to the `+` input of the op amp, and connect ground to the `-` input of the op amp. The output voltage of the op amp would not track the input voltage (the yellow wire) and you can use a voltage divider on the output as above.

## Use digital temp sensor

This option does not directly answer you question, but might be the best solution.

You can get something like a [DS18B20][1] digital temperature sensor for a buck or two and connect it digitally to your MCU and avoid the problem altogether. This chip is happy at 3.3 volts, so you'd just need to put it physically someplace where it is sensing the same temperature as the yellow wire.  This will likely be more accurate too!

  [1]: http://amzn.to/1Jmmwrd


message:
Why is setup() executed twice at runtime?

**Code:**

    void setup() {
      Serial.begin(9600);
      Serial.println("hello");
    }

    void loop() {
    }

**Output:**

    hello
    hello

Why does `hello` print twice?

body:
It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.

If you put a longer message in there you'll probably see the first line get cut off and then the full line.


message:
Using fluctuating voltage as an input

I had an idea to hack a wireless doorbell so it could send notifications to my phone when someone rings the doorbell.

I pulled out the PCB from the doorbell and powered it using the +5v from the Arduino - so far so good

I used the (once was a wire to the speaker) as an analog input

The issue I have is that the voltage for the chime continues for a long time. eg its at 0 before push then it fluctuates for a second, then returns to 519 for a while, before eventually returning to 0.

Is there a smarter way to do this - I have included my code below.

    void loop()
    {
   //detect a changing voltage
   val = analogRead(sensorPin); //pin A0
   delay(500);
   oldVal = analogRead(sensorPin);//pin A0

    //if the voltage changed then +1 to the ring counter
   if (val != oldVal) {
    ringCounter = ringCounter+1;
   }

      if (ringCounter > 3 && pinDevid1State == false) // someone pressed the doorbell
      {
        if(DEBUG){Serial.println("pinDevid1 is HIGH");}
        pinDevid1State = true;
        Serial.println("DingDong");
  digitalWrite(ledPin, HIGH);
  delay(5000);
  Serial.println("Notification Sent.");

  //reset vars
  val = 0;
  oldVal = 0;
  ringCounter =0;
      }

      if (ringCounter < 3 && pinDevid1State == true) // the doorbell stopped ringing
      {
        if(DEBUG){Serial.println("pinDevid1 is LOW");}
        pinDevid1State = false;
  digitalWrite(ledPin, LOW);
  Serial.println("DingDongEnd");
        //Sending request to PushingBox when the pin is LOW
        //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable

  //reset vars
  val = 0;
  oldVal = 0;
  ringCounter =0;

      }

body:
>  I wonder if there is another pin on the board I could read

I guess that would depend on the particular doorbell. The transmitter must send some representation of a button press to the receiver - a pulse train for the duration of the press, or perhaps just CW: carrier on, carrier off - which the receiver somehow passes on to trigger the audio. Look at the receiver's output side to identify that trigger signal and pass it, or a processed version of it, to the Arduino.


body:
>I wonder if there is another pin on the board I could read

You could try to hook up a multimeter to the pins/leads from the doorbell button. Positive to doorbell button pin, negative to power supply ground/doorbell battery.

Once you figure out which pin has voltage when the doorbell button is pressed, you can have that go into a digital or analog input in the Arduino. Make sure that the ground from the doorbell PCB and the Arduino are connected so that they'll have common ground and it should be detectable.


message:
Upload a .hex file, using a standalone ISP, without overwriting bootloader

Is it possible to flash a `.hex` file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?

In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).

For reference, given a compiled `.hex` file, this is what I use to upload it using the built-in programmer:

    avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i

By default, this works as expected. I  can also use `avrdude` to upload it using the AVRISP:

    avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i

This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.

If I try to instruct `avrdude` to upload via the AVRISP without overwriting the bootloader:

    avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i

then it fails in the verification phase:

    avrdude: verification error; content mismatch

Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.

Here is the command I use to compile and link (I am not using the Arduino IDE at all)

    avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m
    avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o
    avr-objdump -S _build/image.elf
    avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

As explained above, I can use the same resulting `.hex` file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).

body:
To preserve the bootloader, you should use the `-D` option in the ISP command line just as it was used in the bootloader upload command line. This will disable usage of full-chip erase.

I expect you would end up with something like

    avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex

However, it is important to add something which I overlooked when first posting this answer, which is that **the ATmega series cannot do a *partial* flash erase via the ISP interface** in the way that it can when the bootloader causes the chip to program itself.  This effectively means that you only get one shot at loading a program to an *already blank* area of the chip this way - after that, to load a different one to the same area you will have to do a mass erase *of the entire chip* and reload *both* the bootloader and the sketch, or else command the bootloader to erase the blocks where the sketch would reside.

Of course you will also need a hex file for your sketch with no contents that conflict with the bootloader, as while the bootloader would refuse to overwrite any of its own blocks when programming a sketch, the ISP is perfectly happy to try to write over the top of the bootloader, which would likely result in a logical AND of the bits of two different pieces of code, and cause the chip to boot to nonsense.  A typical Arduino board configuration reserves space for the expected bootloader, so if the one you are using matches the size reserved in the chosen configuration, you should not have a conflict.

Another option could be to combine the bootloader and sketch hex files, literally concatenating their contents one after the other into the same file.


message:
Can I run a loop in setup()

Are loops not allowed in setup()? The following doesn't print anything inside the `for` loop to the serial terminal

**Code:**

 void setup() {
   Serial.begin(9600);
   Serial.println("Ping");
   for (int i = 0; i >= 10; i++) {
     Serial.println(i);
     Serial.println("Pong");
   }
 }

 void loop() {

 }

**Output:**

    Ping

body:
In principle yes, you can use a loop in setup() however this specific code

    for (int i = 0; i >= 10; i++) {
      Serial.println(i);
      Serial.println("Pong");
    }

will result in the body of the loop *never* executing, as the loop test `i >= 10` is *initially* false.

You probably meant `i <= 10`

Generally speaking, it would be poor program structure to use a loop in setup() in place of one in loop(), however if you need a loop to apply similar operations to a range of things, or to briefly busy wait on a condition as part of setting up operation, that kind of thing could be appropriate.


body:
You could (and I occasionally do) write your entire program in the `setup()` function. `Setup()` and `loop()` are constructs provided for your convenience, but they aren't necessary. In C/C++ compiled programs, it conventional for the C run-time code to call `main()`, and for `main()` to be written by the programmer.

It is conventional within the Arduino IDE world to bury the complicated stuff to let new user get productive quickly with a gentle learning curve.
That includes a pre-written `main()` that provides the calls to `setup()` and `loop()` for you.

The following `main()` function is typical of a number of pre-written Arduino `main()` functions, but you don't have to use the pre-written one; you can supply your own. It will need to call `init()`, and Arduino library function that prepares the hardware and software environment into a known state; after that you're good to go.

    /*
     * main.cpp
     *
     *  Created on: Dec 13, 2011
     *      Author: jrobert
     */

    #include "WProgram.h"

    int main(void){
     init();
     setup();
     for(;;)
      loop();
    }

    extern "C" void __cxa_pure_virtual() {
     while (1)
            ;

    }


message:
Different behavior than in simulator: 5V pin works instead of GND. Why is that?

I use [this simulator][1] to check if what I want to do works. This is how it looks like:

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

I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.

When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.

Why do you think there are some differences? Can I use 5V pin instead of GND if it works?

My Arduino: Arduino Leonardo.

  [1]: http://123d.circuits.io
  [2]: https://i.stack.imgur.com/ZUyqx.png

body:
The RGB LED's are available with common cathode and common anode.  That determines whether you connect the common pin to ground or to +5.

In your schematic you likely mismatched the selected part to what you actually have.  If you have the opposite type of LED as planned, just reverse the connection as you did.  You are not alone in this type of mistake.  [see similar whot? here][1]

A digital multimeter with a diode test mode would be very useful here.  The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground.

But did it really work correctly?  Don't you also see that you have to write LOW to the digital output to make the LED light up?

  [1]: http://forum.arduino.cc/index.php?topic=22413.0


message:
Input clock limit

If you use an external oscillator, and divide-by-8 internally, can you apply up to 160MHz on PB6? For example, can I use my 50MHz oscillator to clock my 328p @ 6250KHz? Note: when I say oscillator I don't mean resonator or crystal

body:
No! 20 MHz max (Please see [8.8 External Clock, pp. 34][1]). The 50MHz clock could be divided by 8 with a [counter][2] or the 150MHz clock by 16 with a [faster counter][3].

Cheers!

  [1]: http://www.atmel.com/images/doc8161.pdf
  [2]: http://www.nxp.com/documents/data_sheet/74HC_HCT393.pdf
  [3]: https://www.fairchildsemi.com/datasheets/74/74VHC393.pdf


message:
#define macro not in scope when i try to use IR library

My code keeps saying that that Button_8 and the rest of the #define macros are out of scope.

    #include <IRLib.h>
    #include <Servo.h>

    #define MY_PROTOCOL SONY
    #define RIGHT_ARROW   0xfd50af //Move several clockwise
    #define LEFT_ARROW    0xfd10ef //Move servo counterclockwise
    #define SELECT_BUTTON 0xfd906f //Center the servo
    #define UP_ARROW      0xfda05f //Increased number of degrees servo
    #define DOWN_ARROW    0xfdb04f //Decrease number of degrees servo moves
    #define BUTTON_0 0xfd30cf  //Pushing buttons 0-9 moves to fixed  positions
    #define BUTTON_1 0xfd08f7  // each 20 degrees greater
    #define BUTTON_2 0xfd8877
    #define BUTTON_3 0xfd48b7
    #define BUTTON_4 0xfd28d7
    #define BUTTON_5 0xfda857
    #define BUTTON_6 0xfd6897
    #define BUTTON_7 0xfd18e7
    #define BUTTON_8 0xfd9867
    #define BUTTON_9 0xfd58a7

    IRrecv My_Receiver(11);//Receive on pin 11
    IRdecode My_Decoder;
    long Previous;
    Servo myservo2;
    Servo myservo;

    void setup()
    {
    myservo.attach(8);
    myservo2.attach(3);
    My_Receiver.enableIRIn();
    }

    void loop()
    {

      if (My_Receiver.GetResults(&My_Decoder))
    {
       My_Decoder.decode();
       if(My_Decoder.decode_type==MY_PROTOCOL)
       {
           if(My_Decoder.value==0xFFFFFFFF)
           My_Decoder.value= Previous;
           if(My_Decoder.value == Button_9)
           {
           myservo.write(0);
           myservo2.write(180);
           }
         else if(My_Decoder.value == Button_8)
          {
             myservo.write(180);
              myservo2.write(180);
           }

        }
    }
    }
when i use a switch statement instead of the 4 and 5 if statement like so:

    switch(My_Decoder.value) {
            case Button_8:   //do something; break;
it works, but i dont know why.

body: C++ is case-sensitive. `Button_8` is different from `BUTTON_8`.


message:
Arduino C, Led > binary alternative all lights

I'm trying to alternatively have a random int generate a binary number with 4 lights.

This is my current code, However, it seems that all the lights(leds) go on, I don't think the minus option works. As in, it won't take a value from the currently randomized digit. (randombinary = randombinary - x)

I also tried just "randombinary - x"

----------

    const int button = 2;
    const int redone = 13;
    const int redtwo = 8;
    const int greenone = 12;
    const int greentwo = 7;
    int randomnumber = 0;
    int randombinary = 0;

    void setup() {

      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(2, INPUT);

    }
      void loop() {

    delay(1000);

      int randomnumber = (1, 15);
      randombinary = randomnumber;

      if (randombinary >=8){
        digitalWrite(redone, HIGH);
       randombinary = randombinary - 8;
      }
     else {
       digitalWrite(redone, LOW);
     }

      if (randombinary >=4){
        digitalWrite(greenone, HIGH);
       randombinary = randombinary - 4;
      }
      else {
        digitalWrite(greenone, LOW);
      }

      if (randombinary >=2){
        digitalWrite(redtwo, HIGH);
      randombinary =  randombinary - 2;
      }
      else  {
        digitalWrite(greentwo, LOW);
      }

      if (randombinary >=1){
        digitalWrite(greentwo, HIGH);
      randombinary =  randombinary - 1;
      }
      else  {
        digitalWrite(greentwo, LOW);
      }

      }

Would appreciate any help!

body:
    int randomnumber = (1, 15);

Guess you have missed to call [random][1]. That statement actually always returns 15. C is a strange language.

    int randomnumber = random(1, 15);

Cheers!

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


body:
So here's the new version, very strange, when I set the number on random, it doesn't work. However, if I enter a number myself, it does.

    const int button = 2;
    const int redone = 13;
    const int redtwo = 8;
    const int greenone = 12;
    const int greentwo = 7;
    int randomnumber = 0;
    int randombinary = 0;

    void setup() {

      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(2, INPUT);

          maarten();

        }
          void loop() {

          }

          void maarten(){

          int randomnumber = random(1, 15);
          randombinary = randomnumber;

        if (randombinary >=8){

          digitalWrite(redone, HIGH);
          randombinary = randombinary - 8;
        }
        else {
          digitalWrite(redone, LOW);
     }

        if (randombinary >=4){

          digitalWrite(greenone, HIGH);
          randombinary = randombinary - 4;
        }
        else {
          digitalWrite(greenone, LOW);
        }

        if (randombinary >=2){

          digitalWrite(redtwo, HIGH);
          randombinary =  randombinary - 2;
        }
        else  {
          digitalWrite(greentwo, LOW);
        }

       if (randombinary >=1){

         digitalWrite(greentwo, HIGH);
         randombinary =  randombinary - 1;
       }
       else  {
         digitalWrite(greentwo, LOW);
      }

      }


body:
Code review (one possible solution can be found below)

 - Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance.
 - Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them.
 - Functions should have expressive names clearly stating what is going on inside.
 - Functions should be short and concise, ideally having only a few lines.

Try something along these lines:

    // setting the number of bits to analyze, corresponding pins and corresponding powers of two.
    // the latter is here for instructional purposes although it is redundant.
    const int numberOfBits = 4;
    const int randLimit = 15;   // 2^(1+numberOfBits)-1 actually;
    int ledPins[numberOfBits] = {13, 8, 12, 7};
    int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two

    void turnOffAllLeds ()
    {
      Serial.println ("turning all off");
      for (int i = 0; i < numberOfBits; i++)
      {
        digitalWrite (ledPins[i], LOW);
      }
    }

    void selectivelyTurnOnLeds(int value)
    {
      turnOffAllLeds ();

      // now for each bit, check if it is set in the value, if yes: turn on corresponding led
      for (int i = 0; i < numberOfBits; i++)
      {
        if ((value & bitValue[i]) > 0)
        {
          digitalWrite (ledPins[i], HIGH);
        }
      }
    }

    void setup()
    {
      for (int i = 0; i < numberOfBits; i++)
      {
        pinMode (ledPins[i], OUTPUT);
      }
    }

    void loop()
    {
      selectivelyTurnOnLeds (random (randLimit));
      delay (1000);
    }

P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code.