message:
Arduino sketch won't run until I open up GUI in processing

I am trying to make a human detection robot using D6T omron thermal sensor. However, I am facing some problem here. My Arduino Uno didn't run the sketches until I open up my GUI in processing. The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board. The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

I am trying to move my robot away from my PC. Therefore, it is a must for me to provide my board an external power supply but it just does not work. I am confused here. Fyi, it will be interfacing with my PC thru Xbee in the near future.

Ps: this is my final year project. Your effort will be much appreciated and credits will goes to you. Thanks guys!

Attached below is my code (Arduino sketch):

    #define E_right 10
    #define E_left 11

    int RightMotorForward = 9; // Pin 10 has Left Motor connected on Arduino boards.
    int RightMotorReverse = 8; // Pin 9 has Left Motor connected on Arduino boards.

    int LeftMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
    int LeftMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards.

    float top_sum, bottom_sum, left_sum, right_sum, center_row_sum;

    #include <Wire.h>
    #include <WireExt.h>

    #define D6T_addr 0x0A
    #define D6T_cmd 0x4C

    int rbuf[35];
    float tdata[16];
    float t_PTAT;

    void setup()
    {
      Wire.begin();
      Serial.begin(9600);
      Serial.flush();
      pinMode(E_right, OUTPUT);
      pinMode(E_left, OUTPUT);
      pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
      pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
      pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
      pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
    }
    //-----------------------------------------------------------------------------

    // The following Loop is to make the Robot move towards heat source.
    void loop()
    {
    int i;

      if (Serial.available() > 0) {
        int inByte = Serial.read();
        if (inByte == 0x0001) {

          Wire.beginTransmission(D6T_addr);
          Wire.write(D6T_cmd);
          Wire.endTransmission();

          if (WireExt.beginReception(D6T_addr) >= 0) {
            i = 0;
            for (i = 0; i < 35; i++) {
              rbuf[i] = WireExt.get_byte();
            }
            WireExt.endReception();

            t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
            for (i = 0; i < 16; i++) {
              tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
            }

          }
        }
      }

    top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
    bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
    right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
    left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
    center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

    if ((left_sum>center_sum)&& (center_sum>right_sum))
    {
       analogWrite(E_right, 230);
       analogWrite(E_left, 205);

       digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
       digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor OFF
                      // wait for  0.5 seconds
       delay(500);
       //turn left
    }

    else if ((right_sum>center_sum)&&(center_sum>left_sum))
    {
       analogWrite(E_right, 230);
       analogWrite(E_left, 205);

       digitalWrite(RightMotorForward, LOW);   // turn the Right Motor OFF
       digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
       // wait for  0.5 seconds
       delay(500);
       //turn right
    }
    else if ((center_row_sum>right_sum)&&(center_row_sum>left_sum))
    {

       analogWrite(E_right, 230);
       analogWrite(E_left, 205);

       digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
       digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
       delay(500); //forward

    }

    }

Attached below is my code in processing:

    import processing.serial.*;

    float[] tdata = new float[17];
    float tptat; // PTAT
    String portName;
    //int serialport = 0;

    String buf;
    float colourGreen; //change green in relation to temperature

    int lbTemp = 25; //lowest relative temperature
    int hbTemp = 35; //highest relative temperature
    Serial myPort;  // Create object from Serial class

    void setup() {
      size(640,640);
      //println(Serial.list());
      //portName = Serial.list()[serialport];
      myPort = new Serial(this, "COM7", 9600);
      myPort.clear();

    }
    void draw() {
      myPort.write(0x01);
      delay(100);
      while (myPort.available() > 0) {
        delay(300);
        buf = myPort.readString();
        myPort.clear();
        tdata = float(split(buf, ','));
        for (int i = 0; i <16; i++) {
          colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
    fill (255,colourGreen,0);

          if (i == 0)
        { rect(480,0,160,160);}
          else if (i == 1)
        { rect(320,0,160,160);}
          else if (i == 2)
        { rect(160,0,160,160);}
          else if (i == 3)
        { rect(0,0,160,160);}
          else if (i == 4)
        { rect(480,160,160,160);}
          else if (i == 5)
        { rect(320,160,160,160);}
          else if (i == 6)
        { rect(160,160,160,160);}
          else if (i == 7)
        { rect(0,160,160,160);}
          else if (i == 8)
        { rect(480,320,160,160);}
          else if (i == 9)
        { rect(320,320,160,160);}
          else if (i == 10)
        { rect(160,320,160,160);}
          else if (i == 11)
        { rect(0,320,160,160);}
          else if (i == 12)
        { rect(480,480,160,160);}
          else if (i == 13)
        { rect(320,480,160,160);}
          else if (i == 14)
        { rect(160,480,160,160);}
          else
        { rect(0,480,160,160); }

        if (tdata[i]<5) {fill(255);} else {fill(0);}
          if (i ==0)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),560, 80);}
          else if (i == 1)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),400, 80);
          }
          else if (i == 2)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 240, 80);
          }
          else if (i == 3)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),80, 80);
          }
          else if (i == 4)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 560, 240);
          }
          else if (i == 5)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 400, 240);
          }
          else if (i == 6)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 240, 240);
          }
          else if (i == 7)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 80, 240);
          }
          else if (i == 8)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 560, 400);
          }
          else if (i == 9)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 400, 400);
          }
          else if (i == 10)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 240, 400);
          }
          else if (i == 11)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 80, 400);
          }
          else if (i == 12)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 560, 560);
          }
          else if (i == 13)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 400, 560);
          }
          else if (i == 14)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 240, 560);
          }
          else
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 80, 560);
          }
        }
        delay(800);
      }
    }

body:
> My Arduino Uno didn't run the sketches until I open up my GUI in processing.

How do you know?

> The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board.

That is because the TX/RX LEDs are linked to the USB interface chip. With no USB connection there can be no lights.

> The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

That is because there is USB communication.

Your sketch is running fine. However your sketch looks to be wrong.  Major portions of it (i.e., the portion that does any detection at all) relies on serial data coming in.  How can you have it working, in that case, if you disconnect the serial interface so that no data ever comes in?


sender: user

message:
Two voltage sources on the same circuit

I am looking to power a Trinket Pro 5V microcontroller using a 9V voltage source. I have logic running on this controller to gather the data from an accelerometer (powered off of the 5V pin on the controller) and output it to three strands of 21 RGB LEDs (https://www.adafruit.com/products/1655).

RGB LEDs cannot exceed a power source of 5V and after passing through the Trinket voltage regulator the 5V pin on the Trinket just does not have enough power for all three strands.

Please, advise on the appropriate hardware for this case. What is the maximum voltage that RGB LEDs can handle and how does the schematic look on the protoboard.

Thank you for your expertise.

sender: assistant

body:
First of all: 9V means that you are using a 9V "transistor" battery (like [this][1]), right?

If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).

As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).

This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A > 3A).

The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).

Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).

One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)

  [1]: https://upload.wikimedia.org/wikipedia/commons/8/8d/Duracell_9_Volt_0849.jpg


body:
According to the link you supply you might either receive the WS2812 or the SK6812, datasheet on Ws2812 claims you can supply up to 7V , but this is still less than 9V , the SK6812 is lacking in max voltage but says 5v typical.

If you still want to use the 9V supply you will need a extra voltage regulator.

A little math: each pixel can max draw 60mA, if you have 21 of them we multiply and get 1260mA, thats 1.26 Amps but thats max values we might divide by two and still be relative safe. Let's not.  So we need a 1.26A source from 9V to 5V then we can calculate the power we need to dissipate. (9-5) x 1.26 = 5.04W of heat. Ok you need a regulator that can dissipate that kind of heat.

A 7805 regulator will not do,  you need a switching buck converter.

As to driving this on battery power I don't think alkaline will be able to deliver 1.3A (adding for the MCU) without loosing voltage to inner resistance, some rechargeable might. Lipo can deliver but at a different voltage that will need a new calculation of potential waste using linear regulation, or a buck regulator.  In my opinion the charging of lipos require special attention and are not my preference, but might be option here.


message:
Powering from 3V coin cell to VCC, using I/O pin as supply GND

I'm thinking of creating a "small" electronic dice.
(I will solder the button a little different though xD)

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

But there are some concerns on my design:

**Powering from a coin-cell**

It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

**Can I use a I/O as (input/supply) GND?**

You can actually use outputs as positive voltage, and you can sink currents.
But does that mean I can connect the negative side of the coin-cell to an output, and sink it?
This way it should power my arduino's VCC pin through the "digital GND"

**Using the reset button**

I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

(I probably won't use it though, it's placed inconveniently for this project, but I am wondering.)

**A crude drawing below:**

The fun thing is, polarity of the LED's/segments doesn't matter, since I can change which side is high or low? :)
Also, I've only drawn half the LED's/segments. And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

(btw, battery GND pin should be pin 4, not pin 2)

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

  [1]: https://i.stack.imgur.com/ffpEC.jpg
  [2]: https://i.stack.imgur.com/3fqtU.jpg

body:
Yes you should be fine with the voltage from a coin cell - though don't expect it to last long!

No you can't use an I/O as ground - they are set to input by default, and even if they weren't, if wouldn't be guaranteed to work, and even if it did happen to work*, it would be horrible.  I don't quite understand why you want to do it this way - why not just connect the cell's -ve to the GND pin, right next to the VCC?

If you seed your random number generator suitably (e.g. from an unconnected analogue input) you ought to be OK since that will suitably random - you'll be reseeding it each time with a different seed.

*Stranger things have happend! The very fist ARM chip worked without power, running from parasitic currents from the inputs, as they discovered by mistake when they tested it with the power supply disconnected.


body:
> It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

That is correct.

> You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

Definitely not. That is a sure-fire way to kill the Arduino.

Also you have a Catch-22 situation. To make the pin conduct to ground you have to set it to output and switch it LOW. How can you do that if the chip is powered off? You need to power the chip on in order to power the chip on. It just can't work.

> I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

You will only get random numbers if you seed the PRNG with a random number. If you can get a source of entropy (noise on an analog pin for instance) then yes, that could work.

> And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

It's not "better" - it's **REQUIRED**.  With just one resistor and one segment on that segment will get 8x the current compared to having all 8 segments on. You then either get very dim segments with lots on, or smoke from segments when not many are on.


body:
> Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for _another (low power) device_, but
you should power the Arduino itself from its Vcc and GND pins.

> I could use the reset button, but would it still give me "random
> enough" numbers?

You will likely see the very same sequence every time you reset it.
There are ways around this:

* You can seed the random number generator (RNG) at startup with an
  `analogRead()` from an unconnected pin, but it's not clear how much
  entropy you can expect from this.
* You can save the RNG's entropy into the .noinit memory section, this
  way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the
dice, if only for one reason: the time when the user presses the button
(that you read with `micros()`) is a very good entropy source for
seeding the RNG.

For example, whenever the user presses the button you could:

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

    srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

This way you combine the entropy from the button press with the entropy
from the analog pin (if any), with whatever entropy may already by in
the RNG.

**Edit**: More on entropy gathering.

As you seemingly already know, `random()` is a pseudo-random number
generator intended to produce a sequence of numbers that _look_ random.
Unless you have some other source of randomness in your program, every
time you restart the Arduino you will get the _very same_ sequence of
numbers. Getting true randomness (also called “entropy”) on an Arduino
is not so easy. Here are some ideas you may want to explore.

## Read from an unconnected analog input

This trick seems to be pretty popular. It can even be found in the
[Arduino documentation on
randomSeed()](https://www.arduino.cc/en/Reference/RandomSeed):

> use randomSeed() to initialize the random number generator with a
> fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a
test program that prints out the output of `analogRead(0)` and it seems
to cycle through the same few values in an almost predictable way.
I estimate this gives around one or two bits of entropy per call. On the
plus side, each call takes just over 100 µs.

## Read from an analog noise source

There is a lot of literature on building analog noise sources. Such
sources are used inside crypto-grade random number generators, but the
circuits are likely to be more complex than you would like. There seems,
however, to be a very simple alternative. In [a comment to this
post](https://arduino.stackexchange.com/a/12410), CharlieHanson wrote:

> Connecting the analogue input to the collector of a run-of-the-mill
> transistor, with the emitter grounded and base open helps to make a
> noisy input.

I have not tested this idea, but it is certainly worth exploring.

## Time user input

If the user is required to press a button to throw the dice, the timing
of the button press is probably the best entropy source you can have.
With a 8 MHz clock, the `micros()` function has a resolution of
8 µs (64 clock cycles). Assuming the user is unable to control his
timing better than 0.1 seconds, then you have more than
13 bits of entropy per button press.

If, instead of `micros()`, you use timer 1 running at the full CPU
speed, then you would have 16 bits of entropy per button press. And
you would not need `random()` at all, as you could just output
`1+TCNT1%6`. That would be like throwing a dart at a carnival wheel
spinning at 80 _million_ RPM (8 MHz / 6)!

## Measure clock drift

The drift of a clock relative to another clock [can be used as an
entropy
source](https://en.wikipedia.org/wiki/Clock_drift#Random_number_generators).
The ATmega chip in your Arduino has two independent clocks: the internal
“calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator
used by the watchdog timer. Both are low-accuracy clocks subject to
somewhat unpredictable drift, which is a good thing for this
application. You can gather entropy from this by configuring the
watchdog timer as a periodic interrupt source, and using timer 1 at full
speed to time the interrupt arrival times:

    #include <avr/wdt.h>
    #include <util/atomic.h>

    // Configure Timer 1 for counting CPU cycles and the watchdog as an
    // interrupt source firing (roughly) once a second. Call once in
    // setup().
    void configure_timers()
    {
        // Timer 1.
        TCCR1A = 0;          // normal counting mode
        TCCR1B = _BV(CS10);  // prescaler = 1

        // Watchdog. This is a timed sequence.
        ATOMIC_BLOCK(ATOMIC_FORCEON) {
            WDTCSR = _BV(WDCE)  // enable changing the prescaler
                   | _BV(WDE);  // ditto
            WDTCSR = _BV(WDIF)  // clear interrupt flag
                   | _BV(WDIE)  // enable interrupts
                   | WDTO_1S;   // timeout ~ 1 second
        }
    }

    volatile uint16_t wdt_time;
    volatile bool wdt_fired;

    // Watchdog interrupt service routine.
    ISR(WDT_vect)
    {
        wdt_time = TCNT1;
        wdt_fired = true;
    }

    // Add entropy to the RNG from the timing of the last WDT interrupt.
    // Call periodically in loop().
    void get_wdt_entropy()
    {
        if (!wdt_fired) return;  // No WDT event since last time.
        uint16_t wdt_time_copy;
        ATOMIC_BLOCK(ATOMIC_FORCEON) {
            wdt_time_copy = wdt_time;
            wdt_fired = false;
        }
        srandom(random() ^ wdt_time_copy);
    }

I have tested this idea by plotting the time _differences_ between
successive interrupts. On an Arduino Uno clocked at 16 MHz, I see
short-time fluctuations with an amplitude of about 300. That should
provide around 8 bits of entropy per second.

## Save the entropy pool across reboots

Once you have spent some effort to gather entropy from the environment,
it would be a pity to lose it all at power down. It is common practice
to save the entropy pool to disk when a computer shuts down, and restore
it at boot time. This avoids the problem of the RNG always starting in
the same predictable state. On the Arduino, you have no disk, but you
can use the EEPROM instead. The problem is you cannot know in advance
when the user is going to switch the device off. Then, ideally, you
would save the entropy every time the user requests a new dice value.
The new problem is that the EEPROM is only guaranteed to work reliably
for 100,000 write/erase cycles. This may not be a serious problem
(100,000 is plenty of throws), but it can nonetheless be mitigated by
using a wear-leveling scheme, where you distribute the writes across the
whole EEPROM instead of always overwriting the same bytes.

Wear-leveling can add significant complexity to your program, but it
turns out there is, in this particular case, a wear-leveling scheme that
is trivial to implement: just write at a random location! At startup,
you do not know what was the last location written to, but you do not
need to: you read and mix the whole contents of the EEPROM:

    #include <avr/eeprom.h>

    // Save the entropy to EEPROM. Call this every time the user requests a
    // new value.
    void save_entropy()
    {
        uint32_t *address = (uint32_t *)(random() & E2END & ~3);
        eeprom_write_dword(address, random());
    }

    // Restore the entropy from the EEPROM. Call once in setup().
    void restore_entropy()
    {
        uint32_t seed = 0;
        for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
            seed ^= eeprom_read_dword(address);
        srandom(seed);
    }

## Combine the entropy sources with the XOR operator

As you probably already noticed, the bitwise xor operator (^) is used
every time one wants to combine entropy sources. The main reason is
that, if `a` and `b` are independent random variables, then `a^b` is at
least as random as the most random of `a` and `b`. Which means that
XORing a “good” random variable with a “bad” one is harmless. This is
somewhat formalized as the [piling-up
lemma](https://en.wikipedia.org/wiki/Piling-up_lemma).

As an example, doing `randomSeed(analogRead(0))` at program startup is
fine, but doing it repeatedly during program execution is a terrible
idea: most of the time this will put the RNG in one of a very few
states. If instead you

    srandom(random() ^ analogRead(0));

then you are combining the current randomness of the RNG with the output
of `analogRead()`, and putting this back into the RNG. And this is
harmless even if `analogRead()` is quite predictable.

**A side note on randomSeed()**: Arduino releases prior to 1.6.5 had a
bug that would truncate to 16 bits the entropy provided with
`randomSeed()`. On those releases it is better to use the [avr-libc
srandom()
function](http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga4fca27496ca29c0a723d197696641eff).
The bug has since [been
fixed](https://github.com/arduino/Arduino/commit/0051eadd2a5c7c81c24363b9dfa966c098c6a046).


body:
>You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

It would not be a good idea to use a input pin as they can only sink a maximum of 40mA per pin.

Also, incase any power surges are experienced and it is connected to Vcc if that 5v is exceeded then it could damage your board. It might be a better solution to use the RAW pin even if it does ultimately use more power.


message:
How to use unregulated VIN voltage?

I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin. <br>
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?

body:
The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.

To access the USB power just use the 5V pin - it is directly connected to the USB.

However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting *polyfuse* on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).


message:
Max current through an Arduino Mega?

How much current can I put through the pins of an Arduino Mega at the same time?

The situation: I am building a 7x7x7 LED cube, and my plan was to multiplex in 7 layers of 49 pins, lighting each layer, one at a time. This would mean each pin on the Arduino Mega would only have to supply max. 1 LED at a time.

However, if all 49 LEDs in one layer were on, it would presumably draw 49*20mA (from the LED specs sheet), which is 980mA. This seems like quite a lot of current to put through an ATMega chip, so I was wondering if I could do it, either continuing like this, or using transistors to control the lighting of each layer, or what?

Any help or advice is appreciated!

EDIT: Using ATMega2560, not ATMega328 or alternate.

body:
You're on the right track here. In the datasheet for the ATmega1280 I find this box:

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

What you want to look at is `DC Current Vcc and GND Pins  ....  200.0 mA`

This is the total limit of *all the current* going through the chip (because everything must come through Vcc), and it is the *absolute maximum*. Don't go near it. You need to boost this with some transistors.

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


body:
It's listed in the Electrical Characteristics of the specific MCU used in the Arduino you have.

For the Mega2560, its remarkably similar to the 328 in the Uno.

Absolute Max, 40mA per pin, 200mA VCC or GND current. 20mA per pin recommended max. A huge note, various ports have individual limits:

>**3: Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:**
ATmega1281/2561:
1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
4.)The sum of all IOL, for ports F0-F7 should not exceed 100mA.
ATmega640/1280/2560:
1.)The sum of all IOL, for ports J0-J7, A0-A7, G2 should not exceed 200mA.
2.)The sum of all IOL, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
3.)The sum of all IOL, for ports G3-G4, B0-B7, H0-B7 should not exceed 200mA.
4.)The sum of all IOL, for ports E0-E7, G5 should not exceed 100mA.
5.)The sum of all IOL, for ports F0-F7, K0-K7 should not exceed 100mA.
**If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.**

>**4: Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:**
ATmega1281/2561:
1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
4)The sum of all IOH, for ports F0-F7 should not exceed 100mA.   ATmega640/1280/2560:
1)The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed 200mA.
2)The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
3)The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
4)The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
5)The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.


body:
The ATmega 2560 (assuming that's the chip on your Arduino Mega) has an absolute limit of 40mA on each pin, and 200mA in total for all pins. So yes, you will not be able to drive that load directly from the Arduino.

[![Absolute Maximum Ratings][1]][1]

With external circuitry however, anything is possible. If it were me, I'd use some TPIC6B595 IC's to drain current and BC635 NPN's to source it.

The 595's can sink up to 150mA each (so up to 8 LEDs at 18.75mA each, use a 270Ω resistor in series with each LED if you're running everything from 5V.) You would need 7 595's for 49 LEDs (49 / 8 rounded up.)

You can daisy chain the serial in/outs on them so you just need to shift out 8 bytes from the Arduino (either using SPI or the software equivalent, shiftOut or whatever it's called, on any digital pin.)

[TPIC6B595N Datasheet][2]

To source current, BC635's are rated up to 1A with a typical current gain (hFE) of 100. Collector pin goes to 5V, Emitter pin goes to all the LED anodes on a layer, Base pin connects in series to a 510Ω or 470Ω resistor and an Arduino digital pin. You would need 7 635's, one for each layer. They turn 10mA from a digital pin into 1A from the power supply.

[BC635 Datasheet][3]

Speaking of power supplies, you will not be able to power the whole thing from the Arduino 5V pin (especially if powered from USB.) You will need an additional 5V power supply. If you want simplicity you could use a L7805 voltage regulator and stick a heatsink on it.

[L7805 Datasheet][4]

All of these are popular components which can be obtained from eBay for next to nothing.

If you have more questions specific to Arduino, they might be better suited to the Arduino Stack Exchange.

[Arduino Stack Exchange Link][5]

  [1]: https://i.stack.imgur.com/NobBL.png
  [2]: http://www.farnell.com/datasheets/2008101.pdf
  [3]: http://www.farnell.com/datasheets/1693081.pdf
  [4]: http://www.farnell.com/datasheets/1805459.pdf
  [5]: http://arduino.stackexchange.com


message:
Reading 2 numbers from serial

I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using `Serial.read()`. Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).

As turned out, my problem was in another portion of the code and all below code works perfectly as is!

How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.

If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of `[0;7]` and `[1000;2000]`. Thanks for any advice. Disclaimer, I read a lot, including [this][1], but most questions go into detail about the packaging format, whereas I am concerned about the reading method.

Code I use at the moment:

    // read numbers from the char representation!
    // on the serial connection
    // each DIGIT is sent separately

    String inputString = "";         // a string to hold incoming data
    boolean stringComplete = false;  // whether the string is complete
    uint8_t channel; // holding the number of the channel to modify
    uint16_t signal; // ppm signal length in us (1000-2000)

    void setup() {
      Serial.begin(115200);
      inputString.reserve(200);

      pinMode(9,OUTPUT); // fixed pin 9 for PPM output
    }

    void loop() {
      if (stringComplete) {
        channel = uint8_t(inputString[0])-48;
        signal = 0;
        for (uint8_t n=1; n<5; n++) {
          signal = (signal*10) + uint8_t(inputString[n])-48;
        }
        Serial.print(F("ch: ")); Serial.print(channel);
        Serial.print(F(" signal: ")); Serial.print(signal);
        Serial.print(F("\n"));
        //PROCESS Data
        inputString = "";
        stringComplete = false;
      }
    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        // if the incoming character is a
        // newline (10) or carriage return (13)
        // set a flag for a complete transmission
        if (inChar == 10 | inChar == 13) {
          stringComplete = true;
        }
      }
    }

  [1]: https://arduino.stackexchange.com/questions/4875/how-to-send-two-different-sets-of-int-numbers-over-serial

Another version I tried, without strings is:

    // channel and pulse-length
    uint16_t numbers[2] = {0, 0}; // channel,value
    uint8_t buf[5];

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

    void loop() {
      if (serial_input(numbers,buf)) {
        numbers[0] = buf[0]-48;
        numbers[1] = (buf[1]-48)*10+(buf[2]-48);
        Serial.print(F("channel: ")); Serial.println(numbers[0]);
        Serial.print(F(" signal: ")); Serial.println(numbers[1]);
        // Do Stuff
      }
    }

    uint8_t serial_input(uint16_t* num, uint8_t* buf) {
      uint8_t newData = 0;
      uint8_t k = 0;
      num[0] = 0; num[1] = 0;
      while(Serial.available()) {
        delayMicroseconds(2100);
        char ser = Serial.read();
        if (isDigit(ser)) {
          buf[k] = uint8_t(ser);
          k++;
          newData = 1;
        } else {break;}
      }
      return newData;
    }

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:

    void serialEvent() {
      if (!newdata) {
        channel = Serial.parseInt();
        signal = Serial.parseInt();
        newdata = true;
      }
    }

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...

body:
there is a great function:
https://www.arduino.cc/en/Serial/ParseInt

I have tested the following script up 2kHz incoming, but it should go even faster.
Do something like this

    int number = 0;
    int number2 = 0;
    bool get_data = false;
    void setup() {
      Serial.begin(115200);
      inputString.reserve(200);

      pinMode(9,OUTPUT); // fixed pin 9 for PPM output
    }

    void loop() {
        if(get_data == true){
          Serial.print(number);
          Serial.print(number2);
          get_data = false;
        }
    }
     void SerialEvent()
       if(!get_data){
         number = Serial.parseInt();
         number2 = Serial.parseInt();
         get_data = true;
       }
    }


body:
115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.

`serialEvent()` is no better than manually looking at things like `serialAvailable()` in your loop since that is all it does anyway. It just runs after each iteration of your loop.

One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:

    // Input text in the form "123 456\n"
    char instring[20]; // Room for 19 characters plus terminating null
    int spos = 0; // Location in the array
    int val1 = 0;
    int val2 = 0;

    void loop() {
        if (Serial.available()) {
            char *bita, *bitb;
            int c = Serial.read();
            switch (c) {
                case '\r': break; // ignore
                case '\n':
                     spos = 0;
                     bita = strtok(instring, " ");
                     bitb = strtok(NULL, " ");
                     if (bita && bitb) {
                         val1 = atoi(bita);
                         val2 = atoi(bitb);
                     }
                     // You now have two new values in val1 and val2
                     break;
                default:
                    if (spos < 18) {
                        instring[spos++] = c;
                        instring[spos] = 0;
                    }
            }
        }
    }


message:
ATtiny85 and INPUT_PULLUP

I have read some conflicting sources about what pins have internal pullup resistors available for the Attiny85 microcontroller. Can all I/O pins work with INPUT_PULLUP, or just some of them? And if so, which ones?

Thanks!

body:
Check the datasheet, probably just search for "internal" or "pullup" ![enter image description here][1] I believe there are little more pins/ports as portB, so they should all have internal pull ups.

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


message:
Has anybody seen/created a gps guided vehicle with arduino?

I thought the idea of Amazon Prime air drone delivery was a pretty cool one when it first came out and I started to question whether something like that (an autonomous gps guided vehicle) could possibly be created with the Arduino microcontroller(s). Any thoughts?

body:
Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U

I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.


body:
GPS is not, by itself, enough to make an Amazon Prime-like delivery drone.  GPS only provides a very rough position (thanks to the US Military imposing a large margin of error on non-military users, or so the urban legend goes (it's actually a difference in transmission systems that makes the difference)). It's good enough for getting you to your destination and working out roughly where you are, but getting to a specific pinpoint location just can't be done.

So you need other sensors as well. Things that can examine the environment and work out where you are in relation to other things. Especially people. Object avoidance is the critical component of any autonomous drone, and unless you can come up with a completely safe and foolproof system the FAA will be down on you like a ton of rectangular building blocks.


message:
Arduino sensors with various periods

Right now I have DHT11, PIR sensor, relay, and a photocell on the same board. I am planning to upload the data to a web server. But I want both DHT11 and photocell to be uploaded hourly; PIR and relay by every 3s. Is it possible for a single Arduino to perform such thing?

body:
Yes. Perfectly possible.

How accurate do you need the "hourly"? If you want any form of accuracy at all you will really want to use an RTC module to provide the real time.

Otherwise that, and the higher speed 3s updates, can be timed using the `millis()` function.  The BlinkWithoutDelay example in the IDE shows you the basic idea of working with timestamps to examine elapsed time.

Also there are simple libraries that could help you, such as [SimpleTimer](http://playground.arduino.cc/Code/SimpleTimer).


message:
How do I reduce this down to a smaller, more permanent prototype?

I've prototyped a little light/sunrise alarm clock w/ an Arduino Uno and a breadboard. How do I go about figuring out what components I'd need to reduce this down in to a more semi-permanent prototype?

Obviously I don't need everything the Uno has to offer and I'd like to slim this down into a custom box I build.

But what sort of microcontroller(s) would I need to size this down? How else can I simplify it?

To be clear, I'm not trying to turn this in to any sort of finished/super-polished product. Just wanting to get out of the breadboard and in to some soldering of something a bit more set in stone.

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

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

  [1]: https://i.stack.imgur.com/AUmuv.jpg
  [2]: https://i.stack.imgur.com/EuMmv.png

body:
At a bare minimum, you need a power supply, and an AtMega or AtTiny chip.

The AtMega and AtTiny's have an internal clock, 1mhz. It's not terribly accurate for timekeeping purposes (1% error, I think, as opposed to 20ppm = 0.02% for the external clock), but I see you have an RTC, so a 1% drift is probably fine (I can't see your code, so I don't know if the internal time is used for anything). Remember that you will need to adjust your code for the different clock rate, anything that uses anything time-related will run at 1/16th speed (delay, serial comms, etc). You will need to set the fuses to use the internal clock.

If your power source isn't 5v, then you need a transformer.

What type of AtTiny or AtMega you use depends on your code, and how many pins you use. I see 5 pins, they are all used as digital I think? You might get away with one of the 14-pin AtTinys. I suspect your code is probably pretty small. You can probably get away with nearly any AtTiny. To select an AtTiny, go to http://www.atmel.com/products/microcontrollers/avr/tinyavr.aspx

Nick Gammon (who will probably be providing his own answer as I type) has an excellent site on how to put the parts together, at http://www.gammon.com.au/breadboard

This site mentions programming the bootloader. On a low-memory chip, you do not need a bootloader, you can upload your program using SPI (same way as you upload the bootloader in Nick's example). Alternatively, you can use a programmer like the USBASP, which makes the whole process a lot easier. When you build your final board, I strongly suggest putting a 6-pin ICSP header (same as the 2x3 pins on the end of your Arduino board) on, to make reprogramming easier. You plug the USBASP into the 6-pin header, and click File->Upload using programmer.

ADDITIONAL:

If you want your project "really nice", you can design and etch your own PCB. If "good enough is good enough" (which for me it always is), I suggest you use stripboard (also known by it's brandname, veroboard).

In either case, spend some time thinking about your exact layout. Use a computer layout tool, and spend some time working out the best layout. I generally spend at least 5 times as much time on the layout, as I do on building the board - if a project is twice as big, I will spend twice as much time soldering, but at least 4 times as long laying it out.


body:
I did an awful try at making a nice breadboard for it.

BUT.

I think you're better off using some perfboard, small solderable wires and an Arduino Nano.

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

This because the Arduino Nano has an FTDI chip, crystal and power regulator and is barely bigger than an 328 DIP package.

You could easily mount the pieces of perfboard inside/on your enclosure.

Aim to add the snooze button on top with the settings buttons on the sides.
The buzzer could be in the back or other side. The display (if any) should be in the front. Your "Neopixels" are no different than WS2812B "led's".

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


body:
Several steps are required:

 1. **Define what you want** to achieve in a clear and explicit manner, eg start documenting your project by writing down your decisions and design goals, for example on a project wiki somewhere. This could be the time where you explore the internet to gather several inspirational sources & modules you want to reuse.

 2. **Check that your schematic is correct**, eg that first prototype works reliably. Obviously, going from prototype to a "more permanent prototype" should include checking everything works as expected (getting validation from here would be an option).

 3. **Prepare a hardware design**, eg routing on your prefered CAD software. Many options exist: Fritzing, Eagle, Kicad, ... You may need help/tutorials to do this properly

 4. **Manufacture the pcb**, or get your board manufactured. Several options are available (see below)

 5. **Assemble & test**; depending on results, go back to step 1, 2, 3 ;)

To **check that your schematic** is correct, well, you can post it somewhere. As a starter: your initial post has some errors.

 - resistors required for LED
 - red (+) seems to be on GND, not +5v (!!)
 - using a pulldown for the button where an internal pullup is sufficient is a waste of ressource

Answer above has errors, too (as stated). So make sure your schematic & prototype work before trying to get it more permanent.

To **manufacture the PCB**, several options:

 - Veroboard & through hole components. Not small, but cheap, easy & reliable.
 - DIY: toner transfer method (numerous examples & howto online) :
   requires a bit more time/skills, but if you plan to do several
   boards/experiments, can be worth it. Can be rather cheap. Cannot
   yield high precision pcb.
Note: other DIY PCB manufacturing techniques exist.
 - boardhouse contract manufacturing: yields perfect results (if your
   design files are OK...), can't be quick & cheap (but can be either,
   relatively)


message:
Sparkfun Si4703 FM not getting to loop

I recently purcahsed an si4703, from sparkfun

https://www.sparkfun.com/products/11083

I got it soldered to some headers and now I am not getting anything to work on it, my wire diagram is as follows

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

( I know the FM module pictured is different but its ultimately wired up the same I think)

And I am just trying to run the out of box example code modified to my Arduino Mega board

    #include <SparkFunSi4703.h>
    #include <Wire.h>

    int resetPin = 35;
    int SDIO = A15;
    int SCLK = A14;

    Si4703_Breakout radio(resetPin, SDIO, SCLK);
    int channel;
    int volume;
    char rdsBuffer[10];

    void setup()
    {
      Serial.begin(9600);
      Serial.println("\n\nSi4703_Breakout Test Sketch");
      Serial.println("===========================");
      Serial.println("a b     Favourite stations");
      Serial.println("+ -     Volume (max 15)");
      Serial.println("u d     Seek up / down");
      Serial.println("r       Listen for RDS Data (15 sec timeout)");
      Serial.println("Send me a command letter.");

      radio.powerOn();
      radio.setVolume(0);
    }

    void loop()
    {
      Serial.println("looping");
      if (Serial.available())
      {
        char ch = Serial.read();
        if (ch == 'u')
        {
          channel = radio.seekUp();
          displayInfo();
        }
        else if (ch == 'd')
        {
          channel = radio.seekDown();
          displayInfo();
        }
        else if (ch == '+')
        {
          volume ++;
          if (volume == 16) volume = 15;
          radio.setVolume(volume);
          displayInfo();
        }
        else if (ch == '-')
        {
          volume --;
          if (volume < 0) volume = 0;
          radio.setVolume(volume);
          displayInfo();
        }
        else if (ch == 'a')
        {
          channel = 930; // Rock FM
          radio.setChannel(channel);
          displayInfo();
        }
        else if (ch == 'b')
        {
          channel = 1067; // BBC R4
          radio.setChannel(channel);
          displayInfo();
        }
        else if (ch == 'r')
        {
          Serial.println("RDS listening");
          radio.readRDS(rdsBuffer, 15000);
          Serial.print("RDS heard:");
          Serial.println(rdsBuffer);
        }
      }
    }

    void displayInfo()
    {
       Serial.print("Channel:"); Serial.print(channel);
       Serial.print(" Volume:"); Serial.println(volume);
    }

However I do not think it is ever getting to the actual loop, it seems to get stuck on the code `radio.powerOn()` and then does nothing after that, what can I do to make this work?

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

body:
According to your hookup image, you have connected I2c pins to A14 and A15, I2c on Mega is on pins 20 and 21 , clearly marked SDA and SCL.

Also note that this module can ba powered by 5V but is only 3.3V tolerant on the input pins, you should use a level converter.


message:
Controlling Arduino through Internet and Bluetooth

I have an Arduino sketch that controls an LED through the Internet, and another through Bluetooth. The thing is I want to combine both sketches so that I can control my Arduino LED by Bluetooth as well as through the Internet. Is it possible to do that?

body:
If I were you, I would separate the "hardware" from the "software". This is quite an interesting "pattern". It's used by almost every Operating System, to assure compatibility with devices all around the world.

But how?

**Layers**

The "OSI-model" typically describes a few layers. But to me, the most interesting part is the difference between "Host layer" and "Media layer".

**Media Layer**

The media layer(s) typically handle the transportation of your bits, addressing and data collision. In "the internet" you can 'simply' change from copper to glasfiber without it being noticeable in your end application (apart from being faster).

**Host layer**

The same for the host layers, whatever PC or network adapter you have, your program will run fine (if this abstraction/integration is done well).

**Applying this**

So how do we apply this? In a basic, small application.

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

We want our Host to not care too much about which Media(layer) it is using.
The Arduino has to be able to be configured or detect which media layer it is using.

Something like this is neccesary (this is not actual code, more pseudo code):

    String messageBuffer = "";

    void Setup(){
       setupWifi(pin1,pin2);
       setupBluetooth(pin3,pin4);
    }

    void Loop(){
       messageBuffer = getWifiMessage();
       handleMessage(messageBuffer);
       messageBuffer = getBluetoothMessage();
       handleMessage(messageBuffer);
    }

If you set up this correctly, you'll only have to write the buffer handling code once. Which is very useful!
Handling buffers along with all the logic/effects it will cause, should be solid. You (probably) don't want different behaviour when you use bluetooth as when you use WiFi. Imagine your web-browser only working when you use copper, but not when you use glasfiber :)

***Protocol***

Your message should be exactly the same for WiFi and bluetooth. This way you won't have to deal with two different protocols and it will be easier to implement this at the other (control) side.

A good protocol/message can be this:

"@12#13,255,255,0;"

 - I use the @ as an start indication. This is very usefull for receiving, since you know where to start (obviously?).
 - You'll have to make rules for what will follow (maybe a set amount of characters, in my example, between @ and # it will indicate an "address". When you send it to multiple devices, you only want (in my example) device 12 to react. This often is handled by the bluetooth or wifi already, but it can be good to have some sort of unique header. So that random messages (which might look alike) won't be seen as one of your messages.
 - An message ID is useful, you kinda want to have different types of messages, for either "LED brightness" or "debug request" or "set output".
 - Each message could have an x amount of parameters, it's often better to separate these. It's important that you specify the maximal amount of parameters and what behavior they will cause.
 - Some protocols use a set length, but an end delimiter ";" is often the best way to let the other device know your message is completely received.

*Some notes*

 - Try to aim for existing protocols, it will be cool if your device is compatible and creating yet another protocol isn't particularly useful.
 - Mind that possible transmitted text does not include your start/end delimiters. You could use the message length or exclusions/inclusions in this case.
 - Be wary that the protocol adds overhead. But usually being able to "read" a message will make it much more easier to program a handler or generally work with it.
 - Check if the message is fully received and does not have errors. If you have an error, be sure your system can handle it and will respond with a message telling so. In no way your system should lock down on error or not provide a reaction (which makes debugging a pain).

**The server**

From whatever device you're sending your stuff, it should have bluetooth and/or WiFi. Bluetooth is fairly easy and should get you started quite fast.

If you're using WiFi, you should check if your device can make a TCP/IP connection. TCP/IP is basically a "shell" around your message, to shoot it over the internet ;D it comes with some neat addressing and error checking built in (but you can't be 100% sure there will be no error between your receiver and arduino).

**But why?**

Not only is it useful to learn how to do this, having to write the handler and protocol specification for both the Wifi and bluetooth (and possible usb, rf, ethernet etc).
Apart from that, in embedded systems, you want to be sure that something works, using different handlers for different physical layers will create vague specific errors and might rip up your program logic. Also, if your protocol/application is used/reviewed by more people, you'll be more certain that it works well.

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


body:
*Judging from your reaction, you don't want to use a WiFi/Bluetooth/Ethernet shield*

Arduino has no built-in Bluetooth or Ethernet.
The question is shifting a little towards software, but okay.

**1. Using your PC as Ethernet/Bluetooth receiver**

You can (and I believe you want to) use your PC as the receiver.

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

Talking in network terms, your phone has to become a "client" and your PC will become a "server".

I would advise using [Processing][2] on your PC as a "Server".
Within processing you can [easily set up a connection to your Arduino][3].

And even use your [PC's bluetooth][4] or you might just set up a ["bluetooth COM port"][5] which makes your Bluetooth device look like a serial device like the Arduino.

There is a little catch though. Processing can easily set up a TCP/IP connection. On your phone this might be a little less trivial. Your browser generally uses HTTP(s) to connect.

So you should either [implement HTTP in Processing][6] or [make/use an app that supports TCP/IP message sending][7].

  [1]: https://i.stack.imgur.com/Bma5F.png
  [2]: https://processing.org/
  [3]: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing
  [4]: http://www.extrapixel.ch/processing/bluetoothDesktop/
  [5]: http://windows.microsoft.com/nl-nl/windows/choose-com-port-bluetooth#1TC=windows-7
  [6]: https://processing.org/discourse/beta/num_1231628867.html
  [7]: https://play.google.com/store/apps/details?id=com.sollae.eztcpclient


body:
You use MIT App Inventor ([http://appinventor.mit.edu/explore/][1] or alternatively [http://www.appinventor.org/][2]), create your own app and after that you can access all the results of Arduino on your smartphone.

  [1]: http://appinventor.mit.edu/explore/
  [2]: http://www.appinventor.org/


message:
Open WiFi Configuration Automatically

Is it possible to have an Arduino Uno + WiFi 101 recognize when the USB cable has been connected and prompt a user to enter a network name and password?

Can this be stored on the Arduino itself or does it need to be something run locally on the user's PC?

body:
To render a UI, you need a PC program. It would handle presenting an interface as well as communicating the user's input to the Arduino over UART. I would recommend writing your own program as it would give you a lot of freedom in the UI design. Processing and Python are good options. To avoid using the IDE, you'll need a USB-TTL adapter cable. If you use the default USB connection, you need the drivers which only ship with the installer AFAIK. To detect the COM port, you can either have the user check the Device Manager or make your program auto-detect it, though this isnt very reliable. [This link][1] shows some Python code on detecting the Arduino's port or at least, displaying a list of open ports and allowing the user to choose. You can set the baud rate and other stuff permanently in your code; the COM port is the only variable. Also all handshaking b/w the Arduino and PC can be done without the knowledge of the user.

That said, there are already existing programs (for most common OSes) that can provide minimal functionality. If you dont need a fancy GUI, then **putty** (on Windows) can serve to read input from a user and pass it on to the listening Arduino. You can use putty's default baud rate (9600) in your Arduino sketch so that the user doesnt have to set this. Again, the COM port must be known. Device Manager is the only real option.

With this second approach, you could make a user enter some string (or even a char) in putty to prompt the Arduino to ask for the SSID and password. Once the Arduino is powered, it does nothing but wait for that input string and once it receives it, it sends something like: `Enter SSID: ` , the user complies (and presses the Return key to terminate) and this is repeated for the password. The Arduino sketch would look like this:

    #define MAX_LEN 20  //max length of name or password

    char PROMPT[] = "ready\r"  //the initial string input from a user
    char SSID[MAX_LEN];  // buffers for the ssid and pwd
    char PWD[MAX_LEN];

    init_done = 0;  // this var is set when an ssid and pwd have been received

    void setup(){
      Serial.begin(9600);
      //anything else
    }

    void loop(){
      if (!init_done)
        continue;
      //  your other code
    }

    void get_data(){
      Serial.print("Enter Network SSID: \r\n");
      while (Serial.available() == 0);  // wait for input

      // no timeouts used here; wait till user presses return key
      int i = 0;
      char c;
      while (i < MAX_LEN - 1){  // read chars till the buffer is almost full
        c = Serial.read();
        if (c == '\r') // means end of input
          break;
        SSID[i++] = c;
        while (Serial.available() == 0);  // wait for next char
      }
      SSID[i] = 0;  // null terminate
      while (Serial.read() != -1);  // flush serial buffer

      Serial.print("Enter password: \r\n");  //same as before
      while (Serial.available() == 0);

      i = 0;
      while (i < MAX_LEN - 1){
        c = Serial.read();
        if (c == '\r') // end of input
          break;
        PWD[i++] = c;
        while (Serial.available());
      }
      PWD[i] = 0;
      while (Serial.read() != -1);

      //Serial.print("Done.");
      init_done = 1;
    }

    void serialEvent(){
      if (!init_done){
        while (Serial.peek() != PROMPT[0]) // read off any garbage
          Serial.read();
        int i = 0;
        while (1){
          if (Serial.peek() == PROMPT[i++]) // compare received chars to PROMPT
            Serial.read();
          else
            return

          if (i == sizeof(PROMPT)){ // read enough chars
            while (Serial.read() != -1);  // flush the buffer
            get_data();  // get ssid and so on
          }
        }
      }

  [1]: https://stackoverflow.com/questions/24214643/python-to-automatically-select-serial-ports-for-arduino


message:
Take the program from the arduino board

How to remove the program from arduino board which is already there in it.?And I need that program in my arduino IDE how to take it please help me?

body: You can't. The program in the Arduino IDE is compiled to machine code (bits and bytes basically) and that's what is uploaded to the Arduino.


body: It's a bit like baking a cake. Or brewing cider. Once you have baked your cake can you get the eggs, flour and sugar back again? Can you make apples from cider? No. And it's the same with compiling. Once you have compiled your source code you can't turn it back into source code again.


body:
You can retrieve the program currently in your Arduino with the
`avrdude` tool. This tool comes with the Arduino installation. The way
to call it is somewhat OS-dependent. On Ubuntu, for an Arduino Uno, I
type:

    avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:r:prog.hex:i

This creates the file `prog.hex` with your program in [Intel
HEX](https://en.wikipedia.org/wiki/Intel_HEX) format. You can save this
file if you want to re-install it on the Arduino later. You can also
turn this file into an assembly listing with `avr-objdump`:

    avr-objdump -m avr -Dz prog.hex > prog.lst

You may be able to make some sense of this listing if

1. you are well versed in AVR assembly language
2. you have lots of spare time

As others have said, you cannot expect to get the original C++ source
back.


message:
How to convert array of chars to array of ints?

I have a rather newbie question but I can't figure it out.

Lets say I have this char array:

    char array[] = "10,11,12,1,0,1,0";

How can I convert it to an array of int like this?

    int arrayINT[] = {10,11,12,1,0,1,0};

body:
If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the `strtok()` function to split it into individual strings.  Then you can use `atoi()` to convert those individual strings into integers:

    char array[] = "10,11,12,1,0,1,0";
    int intArray[7]; // or more if you want some extra room?

    int ipos = 0;
    // Get the first token from the string
    char *tok = strtok(array, ",");
    // Keep going until we run out of tokens
    while (tok) {
        // Don't overflow your target array
        if (ipos < 7) {
            // Convert to integer and store it
            intArray[ipos++] = atoi(tok);
        }
        // Get the next token from the string - note the use of NULL
        // instead of the string in this case - that tells it to carry
        // on from where it left off.
        tok = strtok(NULL, ",");
    }

Note that `strtok()` is a *destructive* function. It will decimate your existing string with NULL characters as it slices it up.


message:
Measuring LPO (Low-Pulse Occupancy)

I'm using an Arduino clone ([Seeeduino Lotus](http://www.seeedstudio.com/wiki/Seeeduino_Lotus_v1.0)) together with a Shinyei PPD42NS sensor to measure air quality. The sensor reports its measurement as Low-Pulse occupancy. What would be the best way how to collect the value with Arduino? Currently I'm simply looping for some predefined duration using [`pulseIn`](https://www.arduino.cc/en/Reference/PulseIn):

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

    unsigned long starttime;
    register unsigned long sample_time; // ms
    register unsigned long lowpulseoccupancy = 0; // us

    // Wait for the signal to return to HIGH
    pulseIn(DUSTPIN, LOW);
    // Now start measuring
    starttime = millis();
    while ((sample_time = (millis() - starttime)) < DUST_SAMPLE_TIME_MS) {
        lowpulseoccupancy += pulseIn(DUSTPIN, LOW);
    }

    ratio_pct = lowpulseoccupancy / (sample_time * 10.0);

Is there a better way? In particular, this tight loop prevents Arduino from doing anything else for 30s (or a similar period).

I was thinking about using [interrupts](https://www.arduino.cc/en/Reference/AttachInterrupt), either triggering on `CHANGE`, or (if that's possible) having two functions, one triggering on `RISING` and another on `FALLING`. Are there any caveats when doing so?

body:
You can trigger on `CHANGE`, and check in your handler which case it is:

       attachInterrupt(digitalPinToInterrupt(my_pin), my_handler, CHANGE);
        (...)
        void my_handler(void) {
          if(LOW==digitalRead(my_pin)) {
            //do_falling();
          }
          else {
            //do_rising();
          }
        }

Another option would be to use a timer to poll your input, and implement a logic on top of this.


message:
How to combine Leonardo with Ultrasonic sensor?

I am working on an Arduino project that replaces the computer mouse. I want to do this in combination with an ultrasonic sensor. I found some nice examples on youtube, but they didn't post the code. And an example on this website. But I don't get it completely. I don't have much Arduino skills, but do have some. How can you attach for example `echoPinScroll` to a board?

I hope someone can give me advice on how to use this ultrasonic to control my mouse!

    #include <Mouse.h>

    int echoPinCursor=2;
    int trigPinCursor=3;

    int echoPinBtn=4;
    int trigPinBtn=5;
    int echoPinScroll=6;
    int trigPinScroll=7;
    int x;
    int y;
    long duracionCursor, distanciaCursor;
    void setup() {
     Serial.begin(9600);
     pinMode(trigPinCursor, OUTPUT);
     pinMode(echoPinCursor, INPUT);
     pinMode(trigPinBtn, OUTPUT);
     pinMode(echoPinBtn, INPUT);
     pinMode(trigPinScroll, OUTPUT);
     pinMode(echoPinScroll, INPUT);

    }

    void loop() {

    //mover el cursor
    int direccionx=moverx();
    int direcciony=movery();

    Mouse.move(direccionx, direcciony,0);
    delay(2);

    }

    int moverx(){
    distanciaCursor=obtener_distanciaCursor();
    if (distanciaCursor >= 1  || distanciaCursor <= 11){
       x--;
     }
    if (distanciaCursor >= 12 || distanciaCursor <= 24){
       x++;
      }
     return x;
    }

    int movery(){
    distanciaCursor=obtener_distanciaCursor();
    if (distanciaCursor >= 25 || distanciaCursor <= 37){
       y--;
       }
    if (distanciaCursor >= 38 || distanciaCursor <= 50){
       y++;
      }
    return y;
    }

    long obtener_distanciaCursor(void)
    {
    digitalWrite(trigPinCursor, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPinCursor, HIGH);
    delayMicroseconds(10);

    digitalWrite(trigPinCursor, LOW);
    duracionCursor = pulseIn(echoPinCursor, HIGH);

    distanciaCursor = duracionCursor/58.2;
    return(distanciaCursor);

    }

body:
What is your hardware setup?

From your code, it looks like you're not using the pins `trigPinBtn, echoPinBtn, trigPinScroll, echoPinScroll`. Weird. I can't figure out:

 1. which ultrasound module you're using
 2. what do you expect, eg which movement(s) in front of which ultrasound sensor shall generate which mouse action(s)

I would recommand having an iterative approach:

 1. Play with your ultrasound sensor(s), eg understand properly how to wire them to the arduino, how to interface them (software/lib), what kind of values you can get from them, etc... This will depend on the HW module you have chosen (if any yet).
 2. Read the documentation that comes with the mouse lib of the Leonardo and play with it independently/with existing, working examples.

That is divide and conquer: understand each bit before trying to assemble them.

THEN, and only then, you will have a better understanding of the different part of your project. You will then be able to formulate an overview of your project goals, and how you can do it. That is, start documenting your project **before** it is done: doing so will <s>force</s> help you to have a clear idea of **what** it is that you're trying to achieve... and thus how to achieve it.

But yeah, the overall project might look something like this:

    // Ultrasound distance sensor #1, hooked to the arduino with xxx and yyy; generates movement along the x axis
    // Ultrasound distance sensor #2, hooked to the arduino with zzz and ttt ; generates movement along the y axis
    // Something for the wheel? The buttons?

    //global values & objects
    setup()
    //initialize hardware& libs

    loop()
    //get raw ultrasound distances
    //translate these into x and y movements
    //do something about buttons & wheel?
    //update mouse values


message:
LED fading effect using a push button

Guys please help me out in verifying my program for my project -- led fading effect using a push button.

My project is simple, I want to start the LED fading effect (i.e., glowing and dimming one after another) at one click on the push button that is pushing and then leaving the push button and on my another click I want the effect to get off.

The main problem is coming in the programming part and rest all the circuit and components are fine.

THIS IS MY SKETCH :-

    int ledpin = 9;
    int buttonpin = 8;
    boolean buttonpressed = false;   // to check whether the button was pressed //
    int brightness = 0;
    int fadeamount = 5;

    void setup ()
    {
    pinMode (ledpin, OUTPUT);
    pinMode (buttonpin,INPUT);
    digitalWrite (ledpin,LOW);
    }

    void loop ()
    {
    if ( digitalRead (buttonpin) == HIGH)
     {
      buttonpressed = true;
     }

     else {
         if ( buttonpressed = true && digitalRead(ledpin) == LOW)
           {
               brightness = brightness + fadeamount;
               if ( brightness == 0 || brightness == 255)
                {
                 fadeamount = -fadeamount;}
                 analogWrite(ledpin, brightness);
                 delay (30);
                 buttonpressed = false;
            }
          if (buttonpressed == true && analogRead(ledpin) == brightness)
            {
              digitalWrite(ledpin,LOW);
              buttonpressed = false;
            }
       }
     }

**THIS IS THE CIRCUIT DIAGRAM**
[![][1]][1]

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

body:
There are basically two parts to your program and it's best if you deal with them completely separately:

1. Reading a push button to turn fading on or off
2. Fading if fading is turned on

Start by making an LED fade all the time. The Fade example can help you with that.

Then as a separate sketch program the button to turn an LED on or off each time you press it.

Once you have those working change the LED in the second sketch to setting a flag, and make the code from the first sketch look at that flag.


body:
The 1k (pulldown-)resistor must be placed at the other side of the button (the pin8 side, not the 5v side).

The led needs a resistor, to limit the current.

There is no need for the `buttonstate` variable, as you can just check the brightness to see if the PWM value must be changed.

    int ledpin = 9;
    int pushbutton = 8;

    int brightness = 0;
    int fadeamount = 1;

    void setup ()
    {
      pinMode (ledpin,OUTPUT);
      pinMode (pushbutton,INPUT);
    }

    void loop ()
    {
      if( digitalRead(pushbutton)==HIGH && brightness<255 )
      {
        // fade in led
        brightness = brightness + fadeamount;// increase brightness
        if( brightness>255 ) // check that brightness doesn't exceed 255
          brightness = 255;
        analogWrite(ledpin,brightness);
        delay (1);
      }
      else if( digitalRead(pushbutton)==LOW && brightness>0 )
      {
        // fade out led
        brightness = brightness - fadeamount;// decrease brightness
        if( brightness<0 ) // check that brightness doesn't go below 0
          brightness = 0;
        analogWrite(ledpin,brightness);
        delay (1);
      }

    }


body:
try this, its simple and easy to understand,

    int ledPin = 9;
    int btnPin = 8;
    int brightness = 0;
    int btnState = LOW;
    bool trigger = LOW;
    void setup ()
    {
      pinMode (ledPin, OUTPUT);
      pinMode (btnPin, INPUT);
    }

    void loop ()
    {
      if ( digitalRead(btnState) && !btnState)
      {
        if (trigger)
        {
          for (int i = 0; i < 256; i++)
          {
            analogWrite(ledPin, i);
            // wait for 30 milliseconds to see the dimming effect
            delay(30);
          }
        }
        else
        {
          for (int i = 255; i >= 0; i--)
          {
            analogWrite(ledPin, i);
            // wait for 30 milliseconds to see the dimming effect
            delay(30);
          }
        }
        trigger = !trigger;
      }
      btnState = digitalRead(btnState);
    }


body:
I changed things a bit and got a solution

    int led = 3;
    int buttonpin = 8;
    boolean waspressed = false;

    int inertia = 10;

    void setup (){
      pinMode(buttonpin,INPUT);
      pinMode(led,OUTPUT);
      analogWrite(led,0);
    }

    void loop(){
      if(digitalRead(buttonpin) == HIGH){
        waspressed = true;
      }else{
         if (waspressed == true){
           fadeLed(digitalRead(led), inertia);
           waspressed = false;
         }
      }
    }

    void fadeLed(boolean input, int inertia){
      for(int state=0;state<256;state++){
        if (input==LOW){
          analogWrite(led, state);
        }else{
          analogWrite(led, 255-state);
        }
        delay(inertia);
      }
    }

I created a function called `fadeLed` that receives two arguments: The actual state of the led and the delay - in miliseconds - that is going to determine how long the fading is going to last.

You can see that the rest of the code is pretty much the one you got in the other question you asked. This is because we already got a good code to control the behavior of the button, so its a good practice to keep it and just change what you want to be changed: to fade instead of blink. So we just change a single line and create a function to be called by that line. Functions are a good way to keep a clean code and are a good programming practice. They make the code easy to read and maintain.

The function `fadeLed()` uses [PWM][1] to fade the led. In Arduino Uno, PWM is available in digital pins 3, 5, 6, 9, 10, and 11. This may change according to the model you are using. It's very important to understand PWM so you can know why `analogWrite()` is used in a digital pin.

If you check the documentation of [analogWrite()][2], you are going to see that for most of the Arduino boards the default resolution is 8 bits, i.e, 0 to 255. To use all this 256 values to fade the led, a `for` loop is used. If you are not used to for loops, I strongly recommend you to read the [documentation][3].

The for loop is programed to go through 256 iterations - the variable `state` going from 0 to 255. At each iteration, the value of `state` is incremented by 1. When `state` gets to be equal to 256, the loop ends itself. Every iteration verifies the value of `input`, which is just the state of the led when the button was released. **This value is passed to the function only when the button is released, but the function uses it internally at every iteration**. If `input` is `LOW`, it means that the led was off, so `analogWrite(led, state);` uses the value of `state` - increasing at every iteration - to fade the led, turning it on. If `input` is  `HIGH`, it means that the led was on, so `analogWrite(led, 255-state);` will fade the led turning it off. In this case, **`255-state` is just a way to set a range starting at 255 and ending at 0 while using a range that we already have - `state` - that starts at 0 and ends at 255.**

The last line is just to set how long the fade action is going to last. To be more specific, `delay(inertia)` determine how long **each iteration** is going to last. So, when you set inertia to 10, will you see that fading will take 10(miliseconds)*255(iterations) + execution times =~ 2,6 seconds. I chose this name when I was coding and I'm not sure now if it was the better one. Maybe something like duration will have a more clear meaning. If you want to set the duration of the fade on your code - instead of the duration of each iteration - you can to something like

    int fadeDuration = 3000; //duration of fade in ms

    ...

    void fadeLed(boolean input, int inertia){
      for(int state=0;state<256;state++){
        if (input==LOW){
          analogWrite(led, state);
        }else{
          analogWrite(led, 255-state);
        }
        // delay in every iteration to achieve 3 seconds in total.
        delay(fadeDuration/256); //=(total fading duration)/(number of iterations)
      }
    }

Hope this is clear. Don't forget to check the links I placed, they are *all* VERY important.

  [1]: https://www.arduino.cc/en/Tutorial/PWM
  [2]: https://www.arduino.cc/en/Reference/analogWrite
  [3]: https://www.arduino.cc/en/reference/for


body:
you should break down the code into two pieces, one to read the button and another to fade the led.

to fade an led, you just need to change its brightness and hold at that brightness for a short period of time. to drive the led at its brightness, use pwm.

that's all there is.

fancier ones will try to do a gamma correction but to just get started, the above is sufficient enough.


message:
Protecting your computer from stupid (arduino) mistakes

I recently ran way to much voltage through my Arduino and back into my computer via the USB connection. I'm looking for a USB hub with a fuse or some sort of protection to protect my laptop from these types of mistakes.  Any suggestions as to products that would serve this function or other precautions I might take?

body:
You get used to what not to do fairly quickly :)

Perhaps what you're after is a ruggeduino - http://www.rugged-circuits.com/ruggeduino/

I get the feeling that this sort of thing encourages bad habits, but then it also encourages more exploration.

You need to think carefully about what you're doing, if you put in any second source of power (e.g. USB + power plug, or USB + a signal from another device).


body:
Both the arduino and a USB port do have some protection against wrong connections and such. The arduino has a diode to prevent wrong polarity to reach your power supply, it also have a resetable fuse (the kinda big, often green SMD part close by your USB connection on your Arduino) that should protect your USB port pretty good from its side of the cable. Your USB port also have some good protections going on as far as i know, so basically it should be hard to break a USB port by accident.

That was the theoretical part, In real life things aren't always what they claim to be, so I use a cheap powered USB hub, that i always use as a first line of defense.


body:
There are a number of USB Isolator products available all around the world.

Here is a list of just a few:

- [Adafruit - USB Isolator][1]
- [OLIMEX - USB Isolator][2]
- [Avantech - USB Isolators][3]
- [CESYS - USB Isolator][4]
- [Hjelmslund Electronics - USBISO-AA][5]

  [1]: https://www.adafruit.com/products/2107
  [2]: https://www.olimex.com/Products/USB-Modules/USB-ISO/
  [3]: http://www.bb-elec.com/Products/USB-Connectivity/USB-Isolators/USB-Isolators.aspx
  [4]: http://www.cesys.com/products/usb-isolator/
  [5]: http://usb-rs485.eu/default.asp


body:
*Please note, that I have no experience in this field, this is simply what I found after some digging.*

I was concerned about connecting a Raspbery Pi Pico device to my brand new computer and did some digging in the ["USB Power Delivery" specification][1]:

  > #### 7.1.7.1 Output Over Current Protection
  > Sources operating in SPR mode ***Shall*** implement over current
  > protection to prevent damage from output current that
  > exceeds the current handling capability of the Source. [...]

"Shall" means, that this is a mandatory requirement:

  > #### 1.4.2.11 Shall/Normative
  > ***Shall*** and ***Normative*** are equivalent keywords indicating a mandatory
  > requirement.  Designers are mandated to implement all such requirements
  > to ensure interoperability with other compliant Devices.

At this point I am already confident enough to plug the device into my computer, so I'll stop digging into the details here.

My understanding is, that the USB controller will detect the fault, disconnect the device and then upon reset and/or reboot it would start working again.

External protection circuits should not be required, at least that is my takeaway.  Maybe for really old computers?

**Edit:**

It doesn't seem quite that simple after all, over-voltage protection may not be covered:

  > ##### 6.4.6.1.6 Over-Voltage Protection Event
  > The Over-Voltage Protection Event bit **May** be set when the
  > Source detects its output Voltage exceeds its limits triggering
  > its protection circuitry.

It seems advisable to use some sort of external device after all.  Not sure how realistic this failure case is for devices which are powered from the host, but for devices with external power this seems smart.

[1]: https://www.usb.org/document-library/usb-power-delivery


message:
GPRS SIM900 and GPS NEO-6M don't work together

I'm trying to get GPS coordinates and send them to my API through the GPRS SIM900 and GPS NEO-6M shields.

In `setup()`, I first start the GPRS shield and call the function that connects to the internet. Then in `loop()`, I start to capture GPS coordinates and finally I send to my API, but my code doesn't work with this logic. I'd like to connect once and get GPS coordinates and send them to the API many times making a tracking.

The app stops if I run the code. `connectToInternet()` in `setup()` and `getGpsPosition()` in `loop()`. The SIM900 shield connects but the NEO6-M shield does not display the coordinates. The GPS only captures the coordinates if I do not connect to the internet.

Could someone help me? Following is my code and printout of the response to AT commands.

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    #include <inetGSM.h>

    static const int RXPin = 4, TXPin = 3;
    InetGSM inet;
    TinyGPSPlus gps;
    SoftwareSerial serialGps(RXPin, TXPin);
    char msg[50];
    boolean started = false;
    const char* dataCoord = "";

    void setup() {
      // Serial connection.
      Serial.begin(19200);
      Serial.print(F("------------------------------------------------- \r\n"));
      Serial.println(F("Starting App Tracking Arduino"));
      Serial.print(F("------------------------------------------------- \r\n"));
      // Turn on GPRS
      powerUpGprs();
      // Start configuration of shield SIM900 with baudrate.
      if (gsm.begin(2400)) {
        Serial.println(F("\nstatus=READY"));
        started = true;
      } else Serial.println(F("\nstatus=IDLE"));
      if (started)
        connectToInternet();
      // Start configuration of shield GPS NEO-6M with baudrate.
      serialGps.begin(9600);
    }

    void loop() {
      // This sketch displays information every time a new sentence is correctly encoded.
      while (serialGps.available() > 0)
        if (gps.encode(serialGps.read())) getGpsPosition();
    }

    /**
      Power up
    */
    void powerUpGprs() {
      pinMode(9, OUTPUT);
      delay(100);
      digitalWrite(9, HIGH);
      Serial.println(F("\nPower Up SIM900!"));
    }

    /**
      Connect to Internet via GSM
    */
    void connectToInternet() {
      Serial.print(F("\r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      //GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.vivo.com.br", "vivo", "vivo"))
        Serial.println(F("status=ATTACHED"));
      else
        Serial.println(F("status=ERROR"));
      delay(1000);
      //Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");
    }

    /**
      Get GPS position
    */
    void getGpsPosition() {
      Serial.print(F("\r\n\r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      Serial.print(F(" GET POSITON \r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      // geolocation
      TinyGPSDate &d = gps.date;
      TinyGPSTime &t = gps.time;
      char* timestamp;
      if (!d.isValid()) {
        timestamp = "00/00/0000 00:00:00";
      } else {
        char sz[32];
        sprintf(sz, "d/d/d d:d:d",
          d.day(), d.month(), d.year(),
          t.hour(), t.minute(), t.second());
        timestamp = sz;
      }
      String position = String("");
      position.concat(String("timestamp=") + String(timestamp));
      position.concat(String("&latitude=") + String(gps.location.lat(), 6));
      position.concat(String("&longitude=") + String(gps.location.lng(), 6));
      position.concat(String("&altitude=") + String(gps.altitude.meters()));
      position.concat(String("&speed=") + String(gps.speed.kmph()));
      Serial.println(dataCoord);
      send2Api();
    }

    /**
      Send To API, The function inet.httpPOST(),
      this is submit method POST via http request
    */
    void send2Api() {
      Serial.print(F("\r\n\r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      Serial.print(F(" SEND TO API\r\n"));
      Serial.print(F("------------------------------------------------- \r\n"));
      // Read until serial buffer is emapty.
      gsm.WhileSimpleRead();
      // TCP Client HTTP, send a POST request to the server and save the reply.
      int numdata = inet.httpPOST("api.myapp.com.br", 80, "/geolocations ", dataCoord, msg, 100);
      // Print the results.
      Serial.print(F("\nNumber of data received: "));
      Serial.println(numdata);
      Serial.print(F("\nData received: "));
      Serial.println(msg);
    };

If I connect to internet the GPS does not display the coordinates.

[![Run app with  connectToInternet() and getGpsPosition][1]][1]

But if I don't connect to internet the GPS displays the coordinates.

[![connectToInternet() function omitted][2]][2]

  [1]: https://i.stack.imgur.com/f6hZq.png
  [2]: https://i.stack.imgur.com/oboag.png

body:
You are using 2 SoftwareSerial instances and you're losing bytes when you aren't listening to the other port. Also your `inetGSM` library uses pins 3 for RX with the SIM900 and in your Arduino sketch, pin 3 is also the Arduino TX pin to the GPS module. Therefore, anything sent by the Arduino over pin 3 is received by both modules. Confusion.

 - Use the GPS module with another pair of pins, maybe, 7 for RX and 8 for TX. Connect the GPS TX to 7 and its RX to 8.
 - Try adding: `gsm._cell.listen();` right before this line:

    `// Read until serial buffer is empty.
    gsm.WhileSimpleRead();`

 - Also add `serialGps.listen();` right before this line:

    `// Print the results.
    Serial.print(F("\nNumber of data received: "));`

Refer to this [answer][1] for more details.

  [1]: https://arduino.stackexchange.com/questions/22633/solved-dbno-resp-using-inet-httppost-on-loop/22637#22637


message:
Shared Memory using SHM Library

I am trying to read sensor data from a FIFO buffer embedded in the sensor (LSM9DS1), and store that data on a Teensy 3.2 board to later be put in a file. I can only read 6 bytes at a time from the FIFO.

The sensor's FIFO is read by the Teensy when an interrupt triggers an isr function. I want to store the data on the Teensy memory. Then, after the ISR store the memory, I plan to parse the data and do a few simple calculations in the loop() function before writing it to file.

What is the best way to accomplish this? I tried using a FIFO library for Arduino [here][1], but it doesn't work with interrupts. I encountered errors with declaring it as a volatile memory type.

Could I used shared memory using the sys/shm.h library from C++? If so, how can I import this to my arduino code?

  [1]: https://github.com/rambo/SimpleFIFO

body:
*Shared memory* only makes any sense in two combined situations:

1. You have a kernel arbitrating processes, threads and memory allocation, with process isolation
2. You have multiple threads or processes in your application

You certainly don't have number 1 unless you can install an operating system on the Teensy 3.1 (some RTOS may provide a SHM analogue).

As for 2 yes, it could be said you have two threads. But you don't have any form of process isolation, so what one "thread" can access the other "thread" can access.

Both the ISR and the `loop()` function have access to the exact same memory. Any global variables are accessible to both. You may need to inform the compiler that a variable is modified in one thread and read in another though. The simplest way of doing that is to make the variable *volatile* by prepending the `volatile` keyword to the definition.


message:
Pin 13 fires relay when powering on... How to disable?

I'm using [pro mini 5v 16MHz][1] and a [DC 12V 2 Channel Relay Module Optocoupler][2]. The relay Jd-VCC is powered by a 12V and it's VCC is 5V (the same as Arduino VCC). The relay is active low and I soldered pins 12 and 13 of the pro mini to IN1 and IN2 of the relay.

When I power the board up it cycles Pin 13(and the on-board LED) ON and then OFF before resuming to the code I uploaded. I believe that this can be fixed by disabling this blinking function in the startup process.

I understand that I can use other pins. Why not learn how to remove this from startup, if I prefer to use this pin for circuit layout purposes?

Any help would be much appreciated. Most of my searches ended up with people using the pin as an input... My issue is when using D13 as an active low pin it has some funky behavior at startup but then works as programmed.

Thanks!!!

  [1]: http://www.miniinthebox.com/atmega328p-pro-mini-328-mini-atmega328-5v-16mhz-for-arduino_p4309665.html?currency=USD&litb_from=paid_adwords_shopping&utm_source=google_shopping&utm_medium=cpc&adword_mt=&adword_ct=94710053401&adword_kw=&adword_pos=1o5&adword_pl=&adword_net=g&adword_tar=&adw_src_id=1364803665_328601281_21739983481_pla-146299556698&gclid=CjwKEAjw_ci3BRDSvfjortr--DQSJADU8f2jz14aOXr1fw3OR7rMu4B3kx12ipYcuGdeNrVdQo7bzBoCU37w_wcB
  [2]: http://www.ebay.com/itm/like/391359931507?lpid=82&chn=ps&ul_noapp=true

body:
There are three things you can do:

1. Remove the bootloader entirely and program the board with a hardware programmer (USB-ASP, Another Arduino, etc).
2. Edit the bootloader source, recompile, and reinstall it to the board using a hardware programmer (as in option 1).
3. Just don't use pin 13 for the relay.

Of the three options the third one is by far the simplest.


message:
My RTC is returning a sporadic date/time

RTC seems to be sporadically returning bogus date/times. Here are the logs from my serial monitor:

    2016/3/23 8:19:46
    2017/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2165/165/165 15:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46
    2016/3/23 8:19:46

That `2165/165/165 15:19:46` appears throughout the logs.

Here's the relevant code:

<!-- language: c -->

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

    RTC_DS1307 rtc;

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

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }
      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }
    }

    void loop() {
      DateTime now = rtc.now();

      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(" ");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
    }

I have a [Grove RTC module][1].

  [1]: http://www.seeedstudio.com/wiki/Grove_-_RTC

body:
Previous reports of this RTC problem ([1](https://forums.adafruit.com/viewtopic.php?f=22&p=194535),[2](https://forums.adafruit.com/viewtopic.php?f=25&t=66041),[3](https://forum.arduino.cc/index.php?topic=189283.0)) attribute it to hardware issues, such as broken wires (to SCL or to battery) and overvoltage (`>`3.6 V supply vs 3 to 3.3 V).

If your setup uses breadboards or other temporary connections, you might try adding some redundant wires.  If your setup uses soldered connections, go over them carefully, looking for shorts and opens; or use a solder sucker / solder wick to remove old solder; then solder anew to make fresh, bright connections.

If you don't locate a hardware problem (and perhaps even if you do) you could add error-testing to your sketch.  That code would see if all relevant fields have valid, in-range values.  If any fields are invalid, it would delay a few milliseconds and then reread the RTC.


body:
The RTC library does not check for communications success. In particular, here:

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

    DateTime RTC_DS1307::now() {
      Wire.beginTransmission(DS1307_ADDRESS);
      Wire.send((byte) 0);
      Wire.endTransmission();

      Wire.requestFrom(DS1307_ADDRESS, 7);
      uint8_t ss = bcd2bin(Wire.read() & 0x7F);
      uint8_t mm = bcd2bin(Wire.read());
      uint8_t hh = bcd2bin(Wire.read());
      Wire.read();
      uint8_t d = bcd2bin(Wire.read());
      uint8_t m = bcd2bin(Wire.read());
      uint16_t y = bcd2bin(Wire.read()) + 2000;

      return DateTime (y, m, d, hh, mm, ss);
    }

There should be a check for a zero returned from `Wire.endTransmission()`. It isn't otherwise possible to detect if the data is invalid (if we got the endTransmission OK) however generally speaking I2C will return 0xFF if the transmission has ceased.

The code in the library for `bcd2bin` is this:

    static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); }

You can see that if passed 0xFF (255) it will return:

<!-- language-all: lang-none -->

       255 - (6 * 15) = 165

Thus if any of the minutes, hours, day or month (which are not further affected in the code above) are 165 (or if the year is 2165) you can assume the whole date/time is bad.