message:
How do I correctly use enum within a class?

I am trying to set the status of an object from a private enum and I'm not sure how to get the private member to the public version in the constructor, and I'm pretty sure I should not be using `byte` in the constructor when it's an enum.

Also, I'm not sure if I should even have the values of the enum inside the header at all. Here is my code:

.h

    class CandleRack
    {
      public:

        CandleRack(byte candleRackStatus);
        ~CandleRack();
        void begin();
        void pushButton();
        void selectRandomCandle();
        void turnOnCandle(byte candlePosition);
        void burnCandlesForMs();
        void fadeOutCandle(byte candlePosition);

      private:
        Bounce *_debouncePushButton;
        byte _pushButtonPin;
        enum _candleRackStatus
        {
          inactive = 0,
          candlesOn = 1,
          rewardAnimation = 2,
          tweetArrived = 3,
          partyMode = 4,
        };
        byte _candlePosition;
        byte _candleStatus[NUM_LEDS];
        elapsedMillis _candleTimeElapsed[NUM_LEDS];
        unsigned int _candleOnForMs;
    };

.cpp

    CandleRack::CandleRack(byte candleRackStatus)
    {
      _candleRackStatus = candleRackStatus;
      _debouncePushButton = NULL;
    }

in the sketch

    CandleRack MyCandleRack(0);

error:

    error: expected unqualified-id before '=' token
    _candleRackStatus = candleRackStatus;

Thanks!

body:
I see two separate issues here.

First of all your enum isn't available as a variable.
By declaring it as a private type within your class the enum can't be used outside of that class.

This forces a user of that class to handle unintended calls like (attention, *bug*):

    CandleRack(255);

which can make code harder to read (and debugging more difficult, since it wouldn't be detected by the compiler).

Second of all you try to directly assign a byte *value* to an enum *type*. This will be rejected by the compiler and/or cause runtime errors later (depending on compiler settings).

I recommend that you declare the enum type so that it is accessible directly via the header file:

.h

    enum CandleRackStatus {
        inactive = 0,
        candlesOn = 1,
        rewardAnimation = 2,
        tweetArrived = 3,
        partyMode = 4,
    };

    class CandleRack
    {
      public:

        CandleRack(CandleRackStatus candleRackStatus);
        ~CandleRack();
        void begin();
        void pushButton();
        void selectRandomCandle();
        void turnOnCandle(byte candlePosition);
        void burnCandlesForMs();
        void fadeOutCandle(byte candlePosition);

      private:
        Bounce *_debouncePushButton;
        CandleRackStatus _candleRackStatus;
        byte _pushButtonPin;
        byte _candlePosition;
        byte _candleStatus[NUM_LEDS];
        elapsedMillis _candleTimeElapsed[NUM_LEDS];
        unsigned int _candleOnForMs;
    };

Now you can instantiate your class while using the correct enum type as the parameter.

.ino

    CandleRack MyCandleRack(CandleRackStatus::inactive);

Within your implementation you can now directly store the constructor parameter in the private variable, the compiler will make sure it's always of the correct enum type:

.cpp

    CandleRack::CandleRack(CandleRackStatus candleRackStatus) {
        _candleRackStatus = candleRackStatus;
        // rest of your initialisiation goes here
    }

As an added bonus, there's the possibility to use a couple of C++ language features that will make your implementation easier:

 - [a default parameter value][1]
 - [an initializer (list)][2]

.h

    class
    {
      public:
        CandleRack(CandleRackStatus candleRackStatus = CandleRackStatus::inactive);
        // [...]
    }

.cpp

    CandleRack::CandleRack(CandleRackStatus candleRackStatus) : _candleRackStatus(candleRackStatus) {
        // rest of your initializiation goes here
    }

  [1]: https://en.wikipedia.org/wiki/Default_argument#Default_arguments_in_C.2B.2B
[2]: https://en.wikipedia.org/wiki/Initialization_(programming)#Initializer_list


sender: user

sender: assistant

body:
How about this refactoring?

    class CandleRack
    {
      public:
        enum status_t
        {
          inactive = 0,
          candlesOn = 1,
          rewardAnimation = 2,
          tweetArrived = 3,
          partyMode = 4,
        };
        CandleRack(status_t status = inactive);
        ~CandleRack();
        void begin();
        void pushButton();
        void selectRandomCandle();
        void turnOnCandle(byte candlePosition);
        void burnCandlesForMs();
        void fadeOutCandle(byte candlePosition);

      private:
        Bounce *_debouncePushButton;
        byte _pushButtonPin;
        status_t _candleRackStatus;
        byte _candlePosition;
        byte _candleStatus[NUM_LEDS];
        elapsedMillis _candleTimeElapsed[NUM_LEDS];
        unsigned int _candleOnForMs;
    };

And in a sketch with either the default setting (inactive)

    CandleRack MyCandleRack;

or explicit

    CandleRack MyCandleRack(CandleRack::candlesOn);

Cheers!


message:
The importance of I/O pin DC current

I am thinking about buying Arduino or Raspberry Pi.  I generally know Arduino advantages (fast start-up, low consumption, ADC converters) and disadvantages (low memory, low connectivity, hard programming), but I simply cannot figure out maybe the most important issue: current output for controlling devices.

One of the common cited advantages of Arduino system compared to Raspberry Pi system is that power per I/O pin is much larger.  Arduino Uno allegedly has up to 20 mA @ 5 V per pin and 50 mA @ 3.3 V per pin making quite substantial power of 0.15 W, compared to say typical 10 mA @ 5 V per pin for Raspberry Pi (although there is no official number available).

On the other hand

 - this power is far too low to control any motors and you still have to
   provide shields,
 - new version Arduino 101 reduced that current to 20 mA and even less for some other Arduino models.

So, what is really the importance (if any) of these higher currents for home projects, compared between different Arduinos themselves and compared to Raspberry Pi?

There is also a question of total current for all pins together, which is also limited, but it is soooooo difficult to get official limits (for both Arduino and Raspberry Pi).

Please give me some insight into this issue, so I can decide.

body:
The simple answer is: **It doesn't matter.**

Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.

Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.

Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.

The one thing that you seem to be forgetting (or haven't realised) is that *the microcontroller board does not have to supply **all** the power.*

The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.

It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.

Just one thing you need to remember: **Connect the grounds.**


body:
Bottom line is: the controllers are just not meant for supplying power.

They do have the ability to do so, within limits - fairly stringent limits for a controller chip itself, and *slightly* more generous limits for the on-board power supply. If you really need an all-in-one, you might consider making building your own controller board with a more capable on-board power supply and a number of transistor switches to provide power for the hungrier devices, that can be switched by the MCU chip.

Note that this will not improve the chip's ability to supply power - you can't, by any practical means - but the board can, through the switching transistors.

Figure out your project's power budget, or the budget you'd like to have for your future projects, and design an on-board power supply to exceed that by a healthy margin-of-safety. Likewise, for the individual switched circuits, in order to choose a sufficiently robust switching transistor.

If you prefer an off-the-shelf solution, one of the available motor-driver boards is probably a good choice but it will need to have an independent power supply if there isn't one on the driver board.


body:
I bought a Pi a while back, and found it so tedious to use I put it in my parts drawer and haven't used it since. A Pi is like a small Unix PC - you have to install an operating system, boot it up (which takes time) and then install device drivers etc.

The Arduino (particularly the Uno) boots in under a second, and "just works". It is much easier to use for small to medium projects.

As for the current, as others have replied, you aren't supposed to be powering things, like motors, from the output pins. 20 mA is a nice amount of current to flash an LED, or send data to another device. The output pins are for **data** not for driving things like motors. If you need more than 20 mA you should be looking at driver circuits, like transistors or MOSFETs.

> ... hard programming ...

I wouldn't say that. You program in C++. What are you going to program the Pi in? There are many libraries for the Arduino to simplify programming, but you can get down to the "bare metal" quite simply.


message:
Can I hook up two micros to one GPS module?

I've worked with a few different GPS modules. Most of them seem to just pump out data and not really interact with the micro controller.

I have a quadcopter (Cheerson CX 20 Big Sky) It has a gps break out board that looks similar to the one I've worked with before. Is it likely that I connect another micro controller to this board? I want to add a cellular module to my quad.

I know that the answer may be "it depends" but before I start testing and researching I just want to know if it's even likely to work.

If the gps is just barfing out coordinates and not interacting with the main board I think it could work. I could just tap in and "listen" -- is this even a possibility?

body:
You are quite wrong. The answer is not "it depends", but "yes".

You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener.  Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).

The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the *slew rate* will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.


message:
Code problem w/ Uno+GPS+GPRS?

I've got an Arduino Uno, SIM900 GPRS, and the Adafruit Breakout GPS.

Can this code be optimized?

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    #include <Ubidots_Arduino_GPRS.h>
    //Serial Relay - Arduino will patch a
    //serial link between the computer and the GPRS Shield
    //at 19200 bps 8-N-1
    //Computer is connected to Hardware UART
    //GPRS Shield is connected to the Software UART
    #define APN "myapn"
    #define USER ""  // If your apn doesnt have username just put ""
    #define PASS ""  // If your apn doesnt have password just put ""
    #define TOKEN "ubidotsToken"  // Replace it with your Ubidots token
    #define ID "Your_id_here" // Replace it with your Ubidots' variable ID
    // You can send 1 to 10 variable at the same time
    #define ID1 "idHere" // Replace it with your variable ID
    //#define ID2 "" // Replace it with your variable ID
    //#define ID3 "Your_id_here" // Replace it with your variable ID

    TinyGPSPlus gps; // The TinyGPS++ object for interfacing with the GPS
    //Declare indexes, and strings
    char latitude[12];
    char longitude[12];
    float value_1 = 1;
    char var[18] = "Lat: ";
    char var2[18] = "Long: ";
    Ubidots client(TOKEN);
    SoftwareSerial ss(2,3);
    void setup() {

    // the Serial port of Arduino baud rate.
      Serial.begin(9600);

      client.powerUpOrDown();
      client.setApn(APN,USER,PASS);
    //.endC is for _client.end() in Ubidots_GPRS.cpp
      client.endC();
      ss.begin(9600);
    }

    void loop() {

      //handling GPS data parsing
      while (ss.available() > 0) {
        gps.encode(ss.read());}
      //Once a valid location comes up it updates Lat/Long variables
       if (gps.location.isUpdated())
    {
        strcpy(var, "Lat: ");
        strcpy(var2,"Long: ");

        dtostrf(gps.location.lat(),10,6,latitude);
        strcat(var, latitude);

        dtostrf(gps.location.lng(),10,6,longitude);
        strcat(var2, longitude);
      //Added ss.flush();
        ss.flush();
        ss.end();
        Serial.flush()
      //Added client.beginC() for _client.begin(9600) is Ubidots_GPRS.cpp
        client.beginC();
        client.add(ID1, value_1, var, var2);
        client.sendAll();
        client.endC();
        ss.begin(9600);
      }
     Serial.println(var);
     Serial.println(var2);
    }

From this [link][1], I moved the println from inside .isUpdated() to outside the if statement. I was able to get GPS data sent from the unit to my Ubidots account while driving around town. Afterwards I was able to input the data into Google Maps and the route produced was accurate. Do I need flush()?

  [1]: https://stackoverflow.com/questions/17985830/arduino-using-interrupts-freezes-processing-and-serial-output

body:
It seems you're using the same hardware `Serial` port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with `Serial.print()` and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making `isValid()` to always be false. You should instead create a `SoftwareSerial` instance attached to any 2 digital pins (maybe 2 and 3) like this:

    SoftwareSerial ss(2, 3);

and in `setup()`:

    ss.begin(9600);  // use your module baud rate

Then at the top of `loop()`, use this instead:

    while (ss.available() > 0)
        gps.encode(ss.read());

Get rid of the recursive call of `loop()` within `loop()` since it will cause your stack to rapidly overflow.

If you want data to only be sent when the location values are *updated* based on recent received data (but not necessarily *changed*, since you may still be at the same location), you should use `if (gps.location.isUpdated())` instead.

Your call of `dtostrf()` is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:

    dtostrf(gps.location.lat(), 10, 6, latitude);

You can also put this at the end of `loop()` to check if data is actually being received from the module and processed by the library:

    if (millis() > 5000 && gps.charsProcessed() < 10)
      Serial.println(F("WARNING: No GPS data.  Check wiring."));
      while (1){ // infinite loop
        if (ss.available())
          Serial.print(ss.read());
      }
    }

[This site][1] may provide additional details.

  [1]: http://arduiniana.org/libraries/tinygpsplus/


message:
Turning all LEDs on (FAST.LED)

In Fast.Led lib for arduino there is a code to turn off all leds

    FastLED.clear ();

Is there also a shortcut to turn all LEDs ON, and with a specific color

body:
You can use fill_solid.

For example

    fill_solid( leds, NUM_LEDS, CRGB(50,0,200));

Or

    fill_solid( leds, NUM_LEDS, CRGB::Red);


message:
How to get a button state change within a for loop?

I have a `for` loop inside my `void loop()` that triggers a piezo.

What I want to happen is when I press a button, it breaks the loop of the piezo, but right now, it's as if it isn't detecting the button press inside my `for` loop.

Here's my code:

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>

    #define PIN 6
    #define TONE 8
    const int buttonPin = 2;

    long fadeTime = 5 * 1000L; // X minutes
    int colorStops = 256;
    int delaySpeed = fadeTime / colorStops;
    int notes[] = {262,294,330,349};
    int switchState = 0;         // variable for reading the pushbutton status

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, PIN, NEO_RGB);

    void setup() {
      pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input

      strip.begin();
      strip.show();
    }

    void loop() {
      // read the state of the pushbutton value:
      switchState = digitalRead(buttonPin);

      // Fade in light
      for(int i = 1; i<colorStops; i++){
        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(i,i,0));
        }
        strip.show();
        delay(delaySpeed);
      }

      // Play tone after light fully bright
      for(int i = 1; i<100; i++){
        // Turn off tone on button press
        if (switchState == HIGH) {
          noTone(TONE);
          break;
        }
        tone(TONE, notes[random(0,3)]);
        delay(100);
      }
    }

Does `switchState = digitalRead(buttonPin);` only get called at the start of the `void loop` and so it can't detect the button change until then? Something else?

Also, in case it's useful, here's my hardware set up...

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

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

body:
You aren't reading the state of the button within your loop.

You only read it the once at the top of your `loop()`:

    void loop() {
      // read the state of the pushbutton value:
      switchState = digitalRead(buttonPin);

You need to replicate that every time you want a new reading from the button - so in your loop you need to add that `digitalRead` line:

    // Play tone after light fully bright
    for(int i = 1; i<100; i++){
      // Turn off tone on button press
      switchState = digitalRead(buttonPin);
      if (switchState == HIGH) {
        noTone(TONE);
        break;
      }
      tone(TONE, notes[random(0,3)]);
      delay(100);
    }

Or you can do away with the variable altogether and just test the return value of the `digitalRead`:

    // Play tone after light fully bright
    for(int i = 1; i<100; i++){
      // Turn off tone on button press
      if (digitalRead(buttonPin) == HIGH) {
        noTone(TONE);
        break;
      }
      tone(TONE, notes[random(0,3)]);
      delay(100);
    }


message:
Do I need capacitors for these LEDs?

I have 5 of [these NeoPixel LED's][1].

For these particular LED's, they [recommend][2] "use of a 0.1 μF capacitor between + and ground".

Here's what I've got:

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

The blue's are 100 μF and the little brown ones are...I have no idea. Both were just in this starter kit. Maybe 100 pF?

So, a few questions around this...

1. Are these actually necessary and why?
2. Is there any harm in using much higher capacitors than recommended?

  [1]: https://www.adafruit.com/products/1734
  [2]: https://learn.adafruit.com/adafruit-neopixel-uberguide/individual-neopixels#through-hole-neopixels
  [3]: https://i.stack.imgur.com/FyNpT.jpg

body:
The capacitors are called *decoupling capacitors* and are used to provide current at very short notice.

The LEDs, when not fully on or fully off, switch rapidly on and off.  This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.

The size of the capacitor (capacitance) can have an effect on how effective they are.  Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.

0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations.  The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.

I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.


body:
> Are these actually necessary and why?

The datasheet for the WS2812 says a "typical application circuit" should have them:

[![WS2812 circuit][1]][1]

If the manufacturer recommends it, I would say it is necessary. I'm sure they would be happy to not have to recommend extra parts, but testing would have shown they are necessary. As Majenko replied, putting in 100 µF when you only need 0.1 µF seems way overkill (to say nothing of more expensive).

And don't forget the 150R resistors, eh?

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


message:
Random Blink LEDs

How can I make LEDs blink randomly?

I found a piece of code, but it is not working for me. I probably need something other than `setPixel()`, but I don't know what.

I am using the [Fast.Led library][1] with Arduino Nano and WS2812B LEDs

<!-- language: c -->

    void loop() {
        Twinkle(CRGB::Red, 10, 100, false);
    }

    void Twinkle(uint32_t color, uint16_t Count, uint16_t SpeedDelay, boolean OnlyOne)
    {
        FastLED.setBrightness(MAX_BRIGHTNESS);
        fill_solid(leds, random(NUM_LEDS), CRGB::White);
        FastLED.show();
        for (int i=0; i < Count; i++) {
    //        setPixel(random(NUM_LEDS),red,green,blue);  //!ORIGINAL LINE OF CODE!
            setPixel(random(NUM_LEDS), color);  //!MY LINE!
            FastLED.show();
            delay(SpeedDelay);
            if (OnlyOne) {
                fill_solid(leds, NUM_LEDS, CRGB::Black);
                FastLED.show();
            }
        }

        delay(SpeedDelay);
        return;
    }

  [1]: https://github.com/FastLED/FastLED

body:
I can't tell exactly whats not working with your code,it would be really helpful if you elaborate more.
But here is some code that I wrote and I think it will get the job done:

    //declare our variables:
    int myPins[] = {2, 4, 8, 3, 6}; //Enter the number of the pins being used
    int RNum = 0;

    void loop()
    {
        DigitalWrite(myPins[RNum],LOW);
        RNum = Random(0,MAX) // MAX being the number of LEDs connected minus one
        //the above generates a random number
        DigitalWrite(myPins[RNum],High);
    }

This will turn on one LED at a time.


message:
Does not name a type error when using makeTime

I am getting a "does not name a type" error when trying to use `makeTime()` from the Time.h library, code snippet as follows:

    #include<Time.h>

    tmElements_t tmet;
    tmet.Year = 2013-1970;
    tmet.Month = 8;
    tmet.Day = 28;
    tmet.Hour = 18;
    tmet.Minute = 30;
    tmet.Second = 0;

    time_t dateMet = makeTime(tmet);

Alternatively I've also tried `time_t dateMet = maketime(&tmet);` with the same result. I am no expert so go easy on me but am I missing something small here?

Thanks

body:
You're trying to access the '*properties*' (i.e. the *members*) of the `tmet` variable in a scope where they aren't accessible (outside of a code block). In this global scope of the program the compiler expects a type name on the left side of a statement (i.e. a variable or type declaration), but `tmet`'s members like `tmet.Year` aren't types in and of themselves.

There are two solutions. You can move the access to the members of `tmet` into a code block like the `setup` function:

    #include <Time.h>

    tmElements_t tmet;
    time_t dateMet;

    void setup() {
      // put your setup code here, to run once:
        tmet.Year = 2013-1970;
        tmet.Month = 8;
        tmet.Day = 28;
        tmet.Hour = 18;
        tmet.Minute = 30;
        tmet.Second = 0;

        dateMet = makeTime(tmet);
    }

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

    }

Or you could declare and define `tmet` in one statement, which has a different syntax (since you have to provide the content of a `tmElements_t` in a single line:

    #include <Time.h>

    tmElements_t tmet2 = { 2013-1970, 8, 28, 18, 30, 0 };

    time_t dateMet2 = makeTime(tmet2);

    void setup() {
      // put your setup code here, to run once:
    }

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

    }

Both versions work right away from within the Arduino IDE (i.e. I tested them).


message:
How to control Adruino through Internet

I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?

body: Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.


body:
You need access to the Internet. Since you dont want to use an Ethernet or WiFi shield/module, then, for the most part, you are left with:

 - Using a GSM module with the Arduino to receive data over the Internet
 - Using a PC as a web server to receive data over the internet and forward it to the Arduino over a wired connection (UART) or a wireless connection (e.g. bluetooth)

The most direct would be the second method over UART. So it could be seen like this: `Client/Sending PC -> Over the Internet -> Server/Receiving PC -> Over UART -> Arduino`. So you are now faced with 3 main interfaces: `Internet->PC` for the server and client as well as the `PC->Arduino` interface on the server/receiver side.

To handle the `Internet -> PC` interface for the client, the client PC would need to run a program that will connect to the server PC over the Internet (using the server's public IP) and send the Arduino control data. Similarly, the `Internet-PC` interface for the server PC would require a constantly-running server program that will listen for incoming connections from the client PC and receive the data being sent. Assuming you know Python, with Python you can have both programs up and running within minutes. [This site][1] should help with the programs.

Note that port forwarding will need to be implemented on the router on the server side so that packets from outside its local network can get to it, given that its behind a router. [This software][2] can help with setting port forwarding rules.

The `PC->Arduino` interface will require the `pyserial` package (if you're still using Python). Pyserial can be used to forward the control data received over the internet, to the Arduino over Serial UART. [This site][3] should help with using Pyserial for Python 3. Search for other tutorials.

Finally, the Arduino itself must regularly check the Serial buffer for any received characters from the PC. It must then act on the received data, depending on rules you should have established. A simple example would be: 'a' = Write HIGH to pin 13. This means if ASCII char 'a' were received over Serial, the Arduino would interpret this to mean a command to `digitalWrite(13, HIGH)`. You can make use of the built-in `serialEvent()` to regularly poll the serial buffer. A simple sketch to illustrate this:

    void setup(){
      pinMode(13, OUTPUT);
      Serial.begin(9600);
    }

    void loop(){}

    void serialEvent(){
      if (Serial.read() == 'a')
        digitalwrite(13, HIGH);
      else  //any other character turns off the LED
        digitalWrite(13, LOW);
    }

  [1]: http://www.bogotobogo.com/python/python_network_programming_server_client.php
  [2]: http://upnp-portmapper.sourceforge.net/
  [3]: https://pythonhosted.org/pyserial/

This is, by no means, the only way to do this, only very straightforward IMO. For example, you could also upload your control data to some cheap server and have your PC regularly poll that server for any new commands. Of course, this would be greatly simplified if you decided to use a WiFi module, like the cheap ESP-01, directly with the Arduino.


message:
I2C Master-Slave Arduino system to control array of steppers

trying to make a system where one master Arduino makes moving 9 steppers 28BYJ-48 by 3 stepper on each slave arduino.

While all the parts on their way to me, wonder to check with professionals.

Maybe I've missed something?

Any suggestions and tips are welcome.
Thank you.

[![Sketch][1]][1]
[![Scheme][2]][2]

[1]: https://i.stack.imgur.com/ivEra.png
[2]: https://i.stack.imgur.com/MmlFP.jpg

body:
I don't quite understand the problem. A
 arduino mega would have no problem controlling 9 of these steppers alone. If you are asking about i2c protocol please be more specific about what you need help with.


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

I think your schematic might be wrong there. Only one MEGA is connected to a positive side of a battery.

The MEGA can only run on 7V to 12V. *BUT PLEASE DO NOT apply the voltage to the `3V3` or `5V` pin.*

    Microcontroller ATmega1280
    Operating Voltage 5V
    Input Voltage (recommended) 7-12V
    Input Voltage (limits) 6-20V

And also, I would only put in another MEGA when you don't have enough I/O pins.

    Digital I/O Pins 54 (of which 15 provide PWM output)

In theory you could use 13 steppers on one MEGA. Try slowly scaling up.
You don't need PWM for steppers, maybe you're confused with servo's?

And why not use one of the stepper-driving MEGA's as the master? (In the first picture, slave 1 isn't even connected to the SDA/SCL lines of the I2C bus.

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


message:
Atmel studio 7 - my own libraries

I like to use AS7 to make my programs.
I know c and some c++, but how things work from there I'm green.
I would like to know if there is a folder where I can store my own homemade c and h library files where they get to be available for all my projects.
Now I copy all the files into each of my projects and this works but I find it a bit tedious.

body:
You should create your library as a separate project: File->New->Project and select C or C++ static library:

[![creating c++ static library][1]][1]

Add your library modules in this project. When building, this will create **lib{your_project_name}.a** file (in Debug or Release folder) - your library object file you can use in your other projects.

Usually I include in the same solution both the library project and target project (just library project file, sure the library and it's files resides in single place):

[![project solution][2]][2]

**ORDO** is the library name.

Some check list:

* Include the library file in Libraries folder (shown above)
* Specify the path to the library *.a file for linker (Toolchain->AVR/GNU Linker->Libraries). Note that there should be different paths for Debug and Release configurations.
* Specify the path for library include files (Toolchain->AVR/GNU C or C++ Compiler->Directories)
* In some cases, F_CPU definition might be needed for library project too (same as in your project, under Symbols).
* When changes are made in your library files, use Build solution (F7) when building, if not - you can use Build project (which will be faster).

Setting project dependencies shall also lead to rebuilding the library automatically when needed (not tested, I usually just hit F7 :).

  [1]: https://i.stack.imgur.com/xeDGB.png
  [2]: https://i.stack.imgur.com/GnWfV.png


message:
Rotary Encoder problem with LCD Display

Program reads rotary encoder correctly without bouncing in this code:

    int val = 0;
    byte clkPin = 3;
    byte dtPin = 2;
    bool lastClk;
    bool lastDt;
    void setup() {
      pinMode(clkPin,INPUT);
      pinMode(dtPin,INPUT);
      lastClk = digitalRead(3);
      lastDt = digitalRead(2);
      val = 0;
      attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
      Serial.begin(9600);
    }

    void loop() {
    }

    void clkRise(){
          lastClk = HIGH;
          lastDt = digitalRead(dtPin);
          if(lastDt == LOW){
            val--;
            Serial.println(val);
            }  else{val++; Serial.println(val);}
            }
but when i use lcd to show the result, i get massive bounces (i think) in this code:

    #include <LiquidCrystal_I2C.h>

    #include <Wire.h>

    LiquidCrystal_I2C lcd(0x27,20,4);
    int val = 0;
    byte clkPin = 3;
    byte dtPin = 2;
    bool lastClk;
    bool lastDt;
    void setup() {
      lcd.begin();
      pinMode(clkPin,INPUT);
      pinMode(dtPin,INPUT);
      lastClk = digitalRead(3);
      lastDt = digitalRead(2);
      val = 0;
      attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
      Serial.begin(9600);
      lcd.home();
    }

    void loop() {
      lcd.print(val);
    }

    void clkRise(){
          lastClk = HIGH;
          lastDt = digitalRead(dtPin);
          if(lastDt == LOW){
            val--;
            Serial.println(val);
            }  else{val++;}
            }
it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.

This is what i use to debounce:

    A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                             |
                             |
                             =0.1uF C
                             |
                             ---------------------GND

body:
I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.

Note that use of `Serial.println()` within your `clkRise()` interrupt handler is problematic, because `Serial.println()` uses interrupts itself. As far as I know, `println()` is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous `println()` calls finish their background processing.  The bits of extra delay introduced by LCD code may merely be exposing a problem.

There is no need for either hardware or software debouncing on quadrature inputs.  A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.

For some state machine code, see for example [answer 16420/3917](https://arduino.stackexchange.com/a/16420/3917) and also see [answer 18221/3917](https://arduino.stackexchange.com/a/18221/3917).  Also see [answer 19109/3917](https://arduino.stackexchange.com/a/19109/3917).


message:
How to increase the brightness of a IR transmitter LED?

I have a pair of IR transmitters and receivers, but I have found that the brightness of the transmitter is very low, so that I can't use it to detect an object in front of them.

What should I do?

body:
IR transmitter LEDs are literally just LEDs that emits Infrared Light which is not visible to the human eye.
That being said, IR LEDs behave very similarly to regular LEDs and therefore to increase the brightness you need to increase the Voltage it is receiving, just like you would do with a regular LED.

But the problem with LEDs is that they drain current and that's why we use resistors,to protect our electronics(i.e. Arduino).

So to recieve maximum voltage you can reduce the resistance of the resistor (let's say 220ohm or even 100ohm).

Forgot to mention that the correct wiring of LEDs to an arduino is as follows:

5V pin(or digital pin set to high) -> Anode leg(longer) of LED -> Resistor(connected to shorter leg :3) -> ground pin


body:
If you aren't at the current limit of either the IO pin (40mA) or the LED (usually around 30mA) you can increase the current as far as the lower of those.  That can be done by reducing the value of the resistor you are using with the LED or using a higher current drive circuit.

However, just having an LED turned on all the time is not a good way of using it - you are constantly fighting against the background light.

Instead the LED needs to be pulsed on and off using PWM at a very high frequency (typically 30-50kHz) and you need to detect that pulsed light with the receiver.

This is usually achieved by using a high-pass (or band pass) filter and amplifier on the receiver.


message:
Cannot include .h files back one directory

I am working on a project with multiple arduinos. I want my folder structure to be as follows:

    /
      libs/
        someSharedFile.h
      arduino1/
        arduino1.ino
      arduino2/
        arduino2.ino

When I include `someSharedFile.h` in one of my .ino files like this `#include "../libs/someSharedFile.h"`, I get this error `No such file or directory`.

However, when I move `libs/` to `arduino1` and include the shared file like this `#include "libs/someSharedFile.h"` everything works fine.

I am using IDE 1.6.7 on windows 10.

body:
Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in [your home folder]/arduino/libraries


message:
How do I connect this to my breadboard?

I just purchased [this Grove RTC][1]. It includes a cable presumably to connect it to a breadboard and/or Arduino, but the pin holes on this cable are much smaller than those on a breadboard or Arduino.

How/where would I connect this in the case of using an Arduino Uno?

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

  [1]: http://www.seeedstudio.com/wiki/Grove_-_RTC
  [2]: https://i.stack.imgur.com/SQ2Mb.jpg

body: Either use jumper wire, or pull the connectors from the Housing and connect them with male connectors.


message:
Posting Arduino data via ethernet to PHP server problems

I am currently having difficulties sending data from an Arduino using an ethernet shield to a PHP database in MySQL. My problem is that it appears that the server is receiving the data as there is a time stamp when I send it from the Arduino however, the other values it is receiving are incorrect (see images below). The server says the values of "data", and "serial_number" are 0 but they are supposed to be 10 and 24. Along with that the Arduino is saying that the data has been sent successfully. My code for both the server and the Arduino is listed below. Any ideas on how to fix this or what is going on are much appreciated.

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

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

**Arduino Code:**

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
    EthernetClient client;
    String data;
    int t;
    int h;

    void setup() {
      Serial.begin(9600);
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
      }

      Serial.println("still working here");

    }

    void loop() {
    t = 10;
    h = 24;

    data = "temp1=";

    data.concat(t);

    data.concat("&hum1=");

    data.concat(h);

      if (client.connect("www.smartwater.x10host.com",80)) {
        Serial.println(data);
        client.print("POST /add.php HTTP/1.1\n");
        client.print("Host: www.smartwater.x10host.com\n");
        client.print("Connection: close\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(data.length());
        client.print("\n\n");
        client.print(data);
        Serial.println("Successfull");

      }

      if (client.connected()) {
        client.stop();
      }

      delay(20000);
    }

**add.php (Server Code)**

    <?php
        include("connect.php");

        $link=Connection();

     $temp1=$_POST["data"];
     $hum1=$_POST["serial_number"];

     $query = "INSERT INTO `Main` (`data`, `serial_number`)
      VALUES ('".$temp1."','".$hum1."')";

        mysql_query($query,$link);
     mysql_close($link);

        header("Location: index.php");
    ?>

**connect.php (Server Code)**

    <?php

     function Connection(){
      $server="localhost";
      $user="smartwat_arduino";
      $pass="*****";
      $db="smartwat_Main";

      $connection = mysql_connect($server, $user, $pass);

      if (!$connection) {
          die('MySQL ERROR: ' . mysql_error());
      }

      mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

      return $connection;
     }
    ?>

**index.php (Server Code)**

    <?php

     include("connect.php");

     $link=Connection();

     $result=mysql_query("SELECT * FROM `Main` ORDER BY `timeStamp` DESC",$link);
    ?>

          <title>Data</title>

Stuff

        Timestamp
        Data
        Serial Number

          <?php
        if($result!==FALSE){
           while($row = mysql_fetch_array($result)) {
              printf("
  %s 	  %s  	  %s
",
                 $row["timeStamp"], $row["data"], $row["serial_number"]);
           }
           mysql_free_result($result);
           mysql_close();
        }
          ?>

body:
Data = 10 is not the characters making 1 and 0 but an ascii character with value
10, your php script doesn't understand that.
Try using itoa function to make character array 1 and 0 for your php to understand.


body:
You get a timestamp from running the php file. That doest mean that there is a number in $data or $serialnmber.
What happens if you fill in a value in your php file instead of the variables $data and serialnumber. If the dbase gets filled, you know that than your variables were empty. If they arent filled something is wrong in your php coding


body:
In your Arduino code, the function call that send the real data within the HTTP-POST call, is this:

    [...]
    client.print(data);
    [...]

When executed, the content of the `data` variable is sent to the server.

Supposing `data` is a `String` object then `data.concat()` is [this][1] function, allowing "*... String, string, char, byte, **int**, unsigned int, long, unsigned long, float, double...*" as argument.

So, after the execution, `data` should contain:

`temp1=10&hum1=24`

and such content is exactly what is passed, via `POST` to the `/add.php` script.

Basically, you're passing two variables, called "**temp1**" and "**hum1**". **Please keep note of those variable names**!

Now let's switch the the PHP script, where you have:

    [...]
    $temp1=$_POST["data"];
    $hum1=$_POST["serial_number"];
    [...]

Above two statements, asks PHP to retrieve, via the `$_POST` function, the content of the two variables **data** and **serial_number**.

As such variables are **undefined** (the variables you passed were `temp1` and `hum1`), PHP consider them like `0` and, as such, assign 0 to `$temp1` and `$hum1`.

I bet that to solve your problem you only need to change above PHP with:

    [...]
    $temp1=$_POST["temp1"];
    $hum1=$_POST["hum1"];
    [...]

*BTW: please note that what is inside the $_POST call is totally unrelated with the names of the variables you have on the left of the `=` sign: they are really different things!*

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


message:
Writing and reading multiple values through serial

I am currently busy with a project that requires me to use an Arduino and 3 potentiometers (to change background in RGB format) to write values through the serial port and read and separate them in processing.

What I want to do is to be able to use my Arduino to write multiple values to a processing program. I am quite new to coding and its been a while since I worked with my Arduino. I know how to read and write one value, but not multiple values.

Also is there a way to write 20 values?

Thanks in advance!

body:
The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.

    Serial.print(val1);
    Serial.print(" ");
    Serial.print(val2);
    ...
    Serial.print(" ");
    Serial.println(val20);

    743 234 34 599 2 ... 427 1013 48 2 409

Then in processing you just read the entire line into a String and split it on the spaces into an array.


message:
Arduino Nano ESP8266 software serial problems

I have a problem with my Arduino Nano ATmega328 and my ESP8266 01 module. I have connected the ESP8266 on my Arduino board without FTDI.

I have made the following connection:

I an using a 5V Arduino Nano which of course is 5V. The ESP8266 is a 3.3V device and so I am using a voltage divider to bring the Arduino's 5V down to 3.3V. If you are using a 3.3V Arduino then you do not need the voltage divider.

 - The wiring is very similar to the FTDI.
 - Arduino pin 3 to voltage divider and then to ESP8266 RX
 - Arduino pin 2 to ESP8266 TX
 - Arduino GND to ESP8266 GND
 - Pull CH_PD HIGH with a 10K resistor to +3.3V
 - +3.3V to Vcc

You only need the voltage divider on the Arduino TX pin. The 5V Arduino will read 3.3V as HIGH so you can connect the ESP8266 TX pin directly to the Arduino RX pin.

The problem I had and I can't handle is that when I start up the Arduino Tx and Rx LEDs work continuously so I can't have access to my serial monitor of the Arduino IDE. So with that problem I can't send or receive any command to/from the IDE. Also when I try to upload my program to the Arduino board, I have to disconnect the ESP. If I don't I can't upload it.

Any ideas guys? I would be grateful

[![My circuit schematic][1]][1]

I also try to implement code with `AltSoftSerial` but I have library issues - my laptop does not recognize it (I downloaded it and I put it in the same folder with my code).

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

      #include <SoftwareSerial.h>

        SoftwareSerial ESPserial(2, 3); // RX | TX
        void setup()
        {    Serial.begin(9600);     // communication with the host         computer

         // Start the software serial for communication with the ESP8266
         ESPserial.begin(9600);

         Serial.println("");
         Serial.println("Remember to to set Both NL & CR in the serial monitor.");
         Serial.println("Ready");
         Serial.println("");}

         void loop()
          {
          // listen for communication from the ESP8266 and then write it to the serial monitor
           if ( ESPserial.available() )   {  Serial.write( ESPserial.read();}  / / listen for user input and send it to the ESP8266
          if ( Serial.available() )       {  ESPserial.write( Serial.read()  );  }}

body:
Arduino Nano has its tx-rx serial port shared with the FTDI chip used by downloading and serial console. See https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
This means that if you drive these pins from ESP, it will flash leds, and all communication on these pins will interfere with serial monitor and board programming as well.

You may:

 * disconnect ESP during program downloading
 * pick a different board, which has a separate hardware serial port, such as Arduino Micro, Leonardo, or any Pololu A-star 32u4 boards, this way you have a dedicated serial port to control your ESP
 * wire the tx-rx of ESP to two *other* pins of your Arduino micro, and use a software serial library to bit-bang serial communication. (Note that serial receiving in software mode may require clever programming - since while your code does something _else_ it can not receive _anything_).


message:
Problems with serial communication from Arduino to Bluetooth HC-05

I just purchased some HC-05 Bluetooth devices and I have followed the directions to put the devices in AT command mode by holding EN HIGH when the HC-05 powers up.  When I do this the HC-05 goes into the "slow blink" to indicate it is in command mode.  However, when I send it "AT" I get odd characters in the response.

Note that when I type "AT" I get exactly 4 characters back.  They are just not the "OK" characters I expect.  I also verified that the Arduino IDE serial console is sending both NL and CR characters.

BTW, here is the Mel Patrick HC-05 authored setup program I am running:

https://raw.githubusercontent.com/dmccreary/coderdojo-robots/master/src/bluetooth-remote/hc-05-setup/hc-05-setup.ino

[![HC-05 serial problem][1]][1]

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

It has been suggested that the data from the HC-05 is only going up to 3.3v and that might be the cause of the problem, since the Arduino is looking for a 0-5 volt signal.

I also note that when I remove the TDX line from the HC-05 that no responses come back.  So I suspect that it is getting the "AT" fine through the RTX from the Arduino to the HC-05.  It is just some problem in the return data format.

Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

I am also using an Arduino Nano if that makes any difference.

Thanks - Dan

body: Try setting your baud at 38400. Connect Tx->Tx & Rx->Rx when configuring your module. Tx->Rx & Rx->Tx during execution.


body:
> Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

Yes there are level shifting circuits you can use, resistor dividers and all that stuff, but you will be better off using a proper level shifting circuit, something like this:

[Level Shifter][1]

I believe there is something to do with the speed of switching between high and low and getting crisp rise and falls of the signal.

  [1]: https://www.aliexpress.com/item/10pcs-lot-Logic-Level-Shifter-Bi-Directional-Four-way-two-way-logic-level-transformation-module/32690066582.html?spm=2114.01020208.3.20.Q3BZUJ&ws_ab_test=searchweb0_0,searchweb201602_2_10065_10130_10068_433_434_10136_10137_10138_10060_10062_10141_10056_10140_10055_10054_10059_10099_10103_10102_10096_10052_10053_10050_10107_10142_10051_10106_10526_10529_10084_10083_10080_10082_10081_10110_10111_10112_10113_10114_130_10517_10078_10079_10073_10070_10122_10123_10124,searchweb201603_13,afswitch_1,ppcSwitch_5_ppcChannel,single_sort_0_default&btsid=4d0beadc-7a79-4cd7-b876-a0e413ee9708&algo_expid=224f95e7-1711-466b-a020-f946a3715cd4-0&algo_pvid=224f95e7-1711-466b-a020-f946a3715cd4 "Level Shifter"


body:
If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.

You can change this baud to the desired with AT command.


body:
Set Baud rate to 38400 in serial monitor.

 If you have Arduino UNO with removable Atmega328p - then remove the chip and connect TX of HC05 to TX of Arduino and RX to RX.

Most of the HC05 works perfectly with 5V system (I have one here hooked up to 5V and RX,TX connected directly ( without level shifter) but it's not recommended.


body: If you are indeed receiving something after the AT command, that means you have the baudrate wrong. Change it from the serial monitor to 38400 or something else.


body:
My experience with these units...

1. BAUD rate varies so try them all.
2. Some expect chars in caps and some don't care
3. Some expect a question mark after the command and some don't e.g AT?
4. Some require CR and some don't.
5. Some only stay in AT mode for a second on boot and thus I found I had to set it up in steps, e.g write program to set PIN, then another to set NAME and so on..

Reason for this is that many clones do not have full software and commands installed.


message:
Arduino water pump not working and beeping

I’m new to Arduino and am trying to build a plant watering system without much knowledge on the subject. But my water pump is not working as I expected it to.

I wanted to keep it simple so I bought a Arduino Motor Shield for my Arduino Uno R3. I’m using a motor rated at 3-9V (motor is shown below), I’ve tried two different DC adaptors plugged into the power supply port on the arduino, 12V 1.5A and 12V 2A, even though the motor is rated at 9V, I’ve read that I need a 12V adapter to power the motor shield.
http://www.mabuchi-motor.co.jp/cgi-bin/catalog/e_catalog.cgi?CAT_ID=rs_360sh

The first problem is If I run the motor at full speed, `analogWrite(3, 255)`, it sounds like its going to explode, so I’m trying to run it at a lower speed. But If use values anywhere below 170 the motor will not run and will only make a beeping sound.

Secondly, regardless of the PWM value I run the motor at, the chip gets very hot very quickly.

My question is, why can’t I run the pump at lower PWM values, and why is it getting so hot?
If I bought a 12V water pump and used the same setup, would I not have any of these problems?

EDIT:
an update...
it seems to basically work now. i have a feeling it wasn't working great because I was previously using a powerbar

It will run on max power PWM(255) for about a minute, and then stop working, which is okay. It will stop and then the motor shield lights will start blinking. Does anybody have any guesses what is happening? The motorshield chip is a little hot, so overheating is a possibility. Or is there not enough current ?

video
[https://www.youtube.com/watch?v=xdxf3f_Svqs][1]

    void setup() {

    //  //Setup Channel A
      pinMode(12, OUTPUT); //Initiates Motor Channel A pin
      pinMode(9, OUTPUT); //Initiates Brake Channel A pin
    }

    void loop(){
      //forward @ full speed, A
      digitalWrite(12, HIGH); //Establishes forward direction of Channel A
      digitalWrite(9, LOW);   //Disengage the Brake for Channel A
      analogWrite(3, 170);   //Spins the motor on Channel A at a speed. approx 90 is min

      delay(3000);

      digitalWrite(9, HIGH); //Engage the Brake for Channel A

      delay(1000);

    }

  [1]: https://www.youtube.com/watch?v=xdxf3f_Svqs

body:
Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).

I don't belive a 12V pump would work any different.

As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.

If you were to overheat the L298 it will shut down before being destroyed (it should).


message:
Using Lua in Arduino project

I want to write code for my Arduino in Lua. Where I can find the necessary (pins) I/O lib and examples for Arduino IDE?
UPD: I've got arduino mega with many memory.

body: AFAIK, Arduino IDE supports C++ only. You can use other languages to communicate with Arduino from your PC. Take a look at Firmata.


body:
Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.

In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.


message:
SIM800L project not working

I got a SIM800L, same as the one under this link, [Quickstart SIM800 (SIM800L) With Arduino][1], and played around with an Arduino Nano and Uno. I had a few problems, at the start, not getting it work properly. It turned out that my Nano 5V pin wasn't enough for the SIM unit. It works fine with Uno though.

There is the code I tested the GSM (same link) and got it working somehow, I got simple AT commands and managed to send an SMS. But after I dismantled the connections and the next day I tried again... Nothing. I can see the SIM unit connects to network as the LED blinking slows down to once every 3 seconds but when I type commands in nothing happens in the serial monitor. It doesn't give errors or anything, just nothing happens on the serial monitor.

I did wire it incorrectly, once with the Tx/Rx, but that shouldn't damage the unit, should it?

I tried to upload different programs to my Arduino and they work fine so that shouldn't be the problem. Is there a way to reset the SIM800 unit? Or am I missing something here?

  [1]: http://www.ayomaonline.com/programming/quickstart-sim800-sim800l-with-arduino/

body:
The module needs a good 5v supplier as it might have a peak of 1A or 2A, when it registers to the network or connects to 3G.

You need to make sure that you share the ground between the power supplier and you use some 2 pins on your arduino to connect the GSM module.
Dont try to get a fast baudrate as software serial doesnt work, try with 9600 to start then see if it response to the AT command.

SIM800 is a very simple module, try with an FTDI in case you want to make sure you didnt break your Arduino.

For more help, share your schematic how you have connected the arduino.


body:
I have put in a lot of time with the SIM808, and I always have trouble delivering enough power to it.  Note that the SIM808 will alert you with an "undervoltage warning" sometimes as a response to AT commands.  I bet the SIM800 would do the same.

As Max above is alluding to - try powering the SIM800L via a separate 5V 2A adapter.  When doing this don't forget to still hook up ground between the Uno and your SIM800L board.

If you accidentally hooked 5V to the VDD pin on your module, you may have damaged it.

FTDI is a tool every embedded dev should have.  Get a few!


message:
RS485: is "Y" multidrop allowed?

I imagine that the proper way to implement an RS485 multidrop bus is the following:

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

What happens if, in order to save cables, I connect the same 5 nodes above using this other topology?

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

 - Will it works?
 - If no, why?
 - If "maybe", under which circumstances will it work?

 ----

*P.S.: yes! I know that MEGA has three Serials and, as such, I could implement two different BUSses (1: Mega<->Mega<->Mega; 2: Mega<->Nano<->Nano), but this will increase the complexity of the software I'm running, as it needs some hacking in order to play nicely with two distinct RS-485 busses;*

*P.P.S.: This is the bus discussed in [this other question][3]*

  [1]: https://i.stack.imgur.com/iScLl.png
  [2]: https://i.stack.imgur.com/CmvEl.png
  [3]: https://arduino.stackexchange.com/questions/21932/hardware-network-infrastructure-for-a-fully-arduino-based-home-automation-projec

body:
At low speeds and short distances that won't be a problem.

At high speeds (megabits per second) and long distances (hundreds of meters) you may get reflections unless you get the termination just right.


message:
Multiplexing potentiometers

Is it possible to have two rotary potentiometers read from a single analog input pin?

The analog input is 10 bits (0-1023), so each pot would have 5 bit precision (0-15).

Least significant bits for pot 1 and most significant bits for pot 2.

A SPI/I2C ADC IC (eg. MCP3008) is an option if this is not possible.

**Edit:**

The two pots do not need to be read at the same time.
It seems full 10 bit precision could be achieved if I use a digital pin to enable each pot before it is read.

body:
There are a few ways of doing what you want.  One would be to use an analog multiplexer as in this answer: https://arduino.stackexchange.com/questions/21536/expanding-analog-inputs-to-the-arduino/21538#21538

Another would be to use digital I/O pins to control the power and ground to the potentiometers.  Note that both sides of the pot need to be controlled, not just one, since any connection of one will interfere with the other.

So you will need four IO pins - one for the +5v and one for the GND of each potentiometer.

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

In this example set D3 to OUTPUT and HIGH, D4 to OUTPUT and LOW, and D5 and D6 both to INPUT.  You will now be reading from the top pot.

Then change D3 and D4 to both be INPUT, and D5 to be OUTPUT and HIGH and D6 to be OUTPUT and LOW.  You will then be reading from the bottom pot.

A bit wasteful of IO pins though.

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


body:
Building on @Majenko's answer, I think you could do the same thing, using 1 analog pin (as shown in his answer) and one digital pin.

Rather than using one digital pin for each side of the each pot, you could use one transistor for each side of each pot, and then use one digital pin to switch all 4 transistors on/off at the same time, in the right combination.


message:
How to send data from an Arduino to PC, without using the Serial Monitor?

I have an analog sensor which I want to send data from my Arduino Certified Intel Edison to PC, without using a Serial Monitor and preferably putting the data into a text file.

body:
There are a couple of ways you can communicate between a "Arduino' and a "PC"*.

**1)Serial communication.**

A serial port on your system is created and a program that reads and writes to the serial port is used as communication.
A program that does this is the "serial monitor" which comes in many flavours.
In linux dumping serial monitor incoming data to a file is as easy as:

    cat /dev/ttyS0> myFile

**2)Bluetooth (LE)**
Bluetooth is a low energy consuming protocol that is commonly used for communication between a PC and a "device". The LE uses even less energy.
I'm not aware of any "official Arduino" boards that contain the hardware for Bluetooth on board.

**3) Network**
Today network equals to WIFI of tcpip. These methods allow for huge distances between the pc and the device.

Of these methods the serial communication over USB is the best know because -in Arduino world- this method is most commonly used to upload the "sketch" to the  "Arduino". As such all hardware is commonly available.

*I put quotes around Arduino and PC because in perspective of this answer both arduino and PC are to be interpreted as a device containing a cpu.


body:
I believe you are looking for something like the [Telemetry](https://github.com/Overdrivr/Telemetry) library.

*Full disclaismer : I am the author*

It allows you to send string, numbers, arrays, sparse arrays through the serial port for instance. Each sent data has a label, called topic, that is used to identify it.

The [Pytelemety command line interface](https://github.com/Overdrivr/pytelemetrycli) then allows you to connect to the serial port, plot received data in real time, write parameters to reconfigure the arduino from the computer, etc.

Example of arduino code thats send an incrementing counter

    #include <Telemetry.h>

    Telemetry TM;
    int8_t counter;

    void setup() {
      TM.begin(115200);
      counter = 0;
    }

    void loop() {
      TM.pub_i8("count",counter);
      counter++;
      delay(10);
    }

Overview of the CLI (Command-Line Interface)
[![enter image description here][1]][1]

Overview of a graph (not produced by the arduino program above)
[![enter image description here][2]][2]

Output to file is not implemented yet, although all received data is logged to a file (but this log also contains system information). However, this is an interesting feature, quite straightforward to implement, that I might add in coming days if you are interested.

Central documentation is available [here](https://github.com/Overdrivr/Telemetry/wiki).

  [1]: https://i.stack.imgur.com/mdnAs.png
  [2]: https://i.stack.imgur.com/FifYF.png


body:
I know, I'm late, but I recommend, using python, as I most always do. The `serial` module is part of the basic python installation

<pre>
import serial

S = serial.Serial('/dev/tty/USB0', 115200, timeout=1)

S.write("Hello")
print S.readline()
</pre>

Should echo `Hello`, if the arduino sketch replies all incoming data.

Very handy in combination with `ipython`, where one can interactively poke around with the serial connection object.


message:
Safe to control multiple power sources through a switch through the ground?

I've attached the breadboard layout and schematic of a circuit I'm constructing, which is a simple Arduino radio control car, with a 9V powering the Arduino Uno, and the 6 volt battery pack feeding power to the motors via the L293D. My question is regarding the switch where I've connected the ground from both battery power supplies to one side, and connected the ground of the circuit to the other side. Is this OK and safe to do? Is there anything I should be concerned about with this setup? Is there a safer or better way to do this? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity?

In case you are wondering why I have two switches, the reason is because I wanted to debug the radio receiver using the serial monitor when I wired this to USB, but I also wanted to prevent it from powering up the motors so my project doesn't try and roll away while it's still connected to the USB cable. The switch I'm asking about in my question is sort of a mains power switch, so when it's off USB I can just flip on both switches and set the robot car free...

[![Fritzing wiring diagram of circuit with 9 volt and 6 volt grounds wired to same switch][1]][1]

[![This is the same circuit as the previous picture, but shown in schematic format. Created with Fritzing, this shows an Arduino board wired to an L293D and two battery packs, controlled with a common switch leading to ground.][2]][2]

  [1]: https://i.stack.imgur.com/FEQiD.png
  [2]: https://i.stack.imgur.com/MhmLF.png

body:
You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.

That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.

I *suspect* it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.


message:
How to power an Arduino using automated mains/rechargeable battery switching?

I'd like to power my Arduino circuit like a smartphone. That is:

* When the device is unplugged, power by rechargeable battery
* When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.

Can someone please provide some guidance?

body:
There are many ways you can do this, as you mention there are ready made shields that do this.

You need to take a few thing into consideration:

1. Power - how much power will your cirquit be drawing, as many of these boards will only be able to deliver 3-600mah is this enough, at the same time you will find out how long your cirquit will be able to stay on battery power.

2. Complexity - a ready made controller/charger is already made to work togheter, if you go for a separate charger and booster module you might end up with unwanted power loss, or you need ekstra buttons/sliders to control power.

You could in theory use 1 lipo cell directly to power your MCU, as the voltage spans from 3,6 to 4,7 Volts pr.cell and charge the lipo when NOT in use (you cannot charge a lipo directly while in use, thats why you need a controller). This would be the cheapest way.


body:
Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

----------

This is what I use:
-------------------

 - a 3.3V Arduino (a [Pro Mini][1] in my case),
 - a regular [Li-Ion battery][2],
 - a charging controller that supports [constant voltage][3] (CV) and [constant current][4] (CC) [charging][5],
 - optionally, a 6V solar panel.

----------

This is how it works:
---------------------

 - charger is fed via solar panel and/or USB supply,
 - battery is continuously supervised and charged on demand
 - Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take).
During recharging the charge current will predominantly flow through the battery.
And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

----------

Example setup:
--------------

I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, [battery][6] in a holder to the lower left, solar panel to the upper right.

The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

[![charger turned off][7]][7]

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually *off* and the Arduino is running off the battery.

----------

[![charger in charge mode][8]][8]

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

----------

[![charger in standby mode][9]][9]

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

----------

Background info:
----------------

The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

[![The charger switches between CC and CV mode.][10]][10]

Image source: [Nanjing Top Power][11]

Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only.
I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

----------

Caveats:
-------

There are a couple of cases to consider, though:

### Deep discharge ###

Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.

### High load ###

If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.

### Wrong charger type ###

There are a multitude of ways to charge a battery. Things like [trickle charge][12], [pulse charge][13], [timer based charging][14], and so on.
None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.

Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

----------

Alternatives
------------

The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require [supply filtering][15] for the Arduino.

----------

Shameless plug
--------------

I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called [CoreSensors][16].

----------

Further links:
--------------

 - [New TP4056 Lithium Cell Charger Module with Battery Protection][17]
 - [Solar Pannel and LiOn or Lipo][18]
 - [How to autoregulate a TP4056 for maximum solar power extraction][19]

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardProMini
  [2]: https://en.wikipedia.org/wiki/Lithium-ion_battery
  [3]: https://en.wikipedia.org/wiki/Voltage_source
  [4]: https://en.wikipedia.org/wiki/Constant_current
  [5]: https://en.wikipedia.org/wiki/Lithium-ion_battery#Procedure
  [6]: http://industrial.panasonic.com/cdbs/www-data/pdf2/ACI4000/ACI4000CE17.pdf
  [7]: https://i.stack.imgur.com/D6GoK.jpg
  [8]: https://i.stack.imgur.com/bO1kR.jpg
  [9]: https://i.stack.imgur.com/Rsrqv.jpg
  [10]: https://i.stack.imgur.com/40sok.png
  [11]: https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Prototyping/TP4056.pdf
  [12]: https://en.wikipedia.org/wiki/Trickle_charging
  [13]: https://en.wikipedia.org/wiki/Battery_regenerator
  [14]: https://en.wikipedia.org/wiki/Battery_charger#Timer-based.28HI.29_chargers
  [15]: https://en.wikipedia.org/wiki/Ripple_(electrical)
  [16]: https://github.com/sekdiy/CoreSensors
  [17]: https://www.youtube.com/watch?v=Qw4psECqpwI#t=22.19582
  [18]: http://forum.mysensors.org/topic/1484/solar-pannel-and-lion-or-lipo/8
  [19]: https://electronics.stackexchange.com/questions/152931/how-to-autoregulate-a-tp4056-for-maximum-solar-power-extraction


body:
> Can someone please provide some guidance?

power your arduino from a power bank and then power the power bank via ac adapter.

simplest and likely most inexpensive solution.


message:
ISR executes twice if data coming through SoftwareSerial

I am using Arduino Pro Mini to get GPS info from a u-blox NEO-M8N chip and display it on a Adafruit OLED display. NEO-M8N has a PPS(pulse per second) output which is aligned to GPS's second. Because UART and deserialization is slow, I use PPS signal to make time displays more accurately. The PPS(time pulse) signal and UART message are coming like this:

[![TIMEPULSE and Serial Data][1]][1]

On my Arduino, SoftwareSerial RX/TX is on pin 7/8 (but only use pin 7 because Arduino has no message to send to NEO-M8N), and the interrupt(PPS) is on pin 2. If I just connect pin 7, display update once per second as intended; if I just connect pin 2, time increased by one second per second as intended. BUT if connect them both, `((`time will increased more than one second per second`)` and `(` `processGPS()` will lost sync with upcoming UBX(u-blox message format) message`))` occasionally.

And here is the entire code:

 #include <SoftwareSerial.h>
 #include <Adafruit_SSD1306.h>

 #define OLED_RESET 9
 Adafruit_SSD1306 display(OLED_RESET);

 #if (SSD1306_LCDHEIGHT != 64)
 #error("Height incorrect, please fix Adafruit_SSD1306.h!");
 #endif

 // Connect the GPS RX/TX to arduino pins 7 and 8
 SoftwareSerial S_Serial = SoftwareSerial(7,8);
 int intpin = 2;
 volatile int state = LOW;

 const unsigned char UBX_HEADER[] = { 0xB5, 0x62 };

 struct NAV_PVT {
   unsigned char cls;
   unsigned char id;
   unsigned short len;
   unsigned long iTOW;
   unsigned short year;
   byte month;
   byte day;
   byte hour;
   byte miniute;
   byte sec;
   unsigned char valid;
   unsigned long tAcc;
   long nano;
   byte fixType;
   unsigned char flag;
   unsigned char flag2;
   byte numSV;
   long lon;
   long lat;
   long height;
   long hMSL;
   unsigned long hAcc;
   unsigned long vAcc;
   long velN;
   long velE;
   long velD;
   long gSpeed;
   long headMot;
   unsigned long sAcc;
   unsigned long headAcc;
   unsigned short pDop;
   byte reserved1[6];
   long headVeh;
   byte reserved2[4];
 };

 NAV_PVT pvt;

 void calcChecksum(unsigned char* CK) {
   memset(CK, 0, 2);
   for (int i = 0; i < (int)sizeof(NAV_PVT); i++) {
  CK[0] += ((unsigned char*)(&pvt))[i];
  CK[1] += CK[0];
   }
 }

 bool processGPS() {
   static int fpos = 0;
   static unsigned char checksum[2];
   const int payloadSize = sizeof(NAV_PVT);

   while ( S_Serial.available() ) {
  byte c = S_Serial.read();
  if ( fpos < 2 ) { //SYNC
    if ( c == UBX_HEADER[fpos] )
   fpos++;
    else
   fpos = 0;
  }
  else {
    if ( (fpos-2) < payloadSize )
   ((unsigned char*)(&pvt))[fpos-2] = c;

    fpos++;

    if ( fpos == (payloadSize+2) ) {
   calcChecksum(checksum);
    }
    else if ( fpos == (payloadSize+3) ) {
   if ( c != checksum[0] )
     fpos = 0;
    }
    else if ( fpos == (payloadSize+4) ) {
   fpos = 0;
   if ( c == checksum[1] ) {
     return true;
   }
    }
    else if ( fpos > (payloadSize+4) ) {
   fpos = 0;
    }
  }
   }
   return false;
 }

 void pps()
 {
   state=!state;
 }

 void PrintScreen()
 {
   display.clearDisplay();

   //Size 2
   display.setTextSize(2);
   display.setTextColor(WHITE);
   display.setCursor(0,0);
   float sik = (pvt.gSpeed / 100) / 3.6f;
   if (sik<100)
  display.print(" ");
   if (sik<10)
  display.print(" ");
   display.print(sik,1);//SpeedInKph
   display.setCursor(84,0);
   if (pvt.numSV<10)
  display.print(" ");
   display.print(pvt.numSV);//SV

   //Size 1
   display.setTextSize(1);
   display.setCursor(60,8);
   display.print("km/h");
   display.setCursor(63,0);
   display.print("CHL");
   display.setCursor(108,8);
   display.print("SVs");
   display.setCursor(108,0);
   switch (pvt.fixType){
  case 0:
    display.print("N.F");
    break;
  case 2:
    display.print("2D");
    break;
  case 3:
    display.print("3D");
    if ((byte)pvt.flag & 2)
   display.print("+");
    break;
  default:
    display.print("INV");
    break;
   }

   long  temp;
   //Line 1
   display.setCursor(0,16);
   if (pvt.lat >= 0)
  temp = pvt.lat;
   else
  temp = -pvt.lat;
   if (temp >= 1000000000)
  display.print("lat:");
   else
  if (temp >= 100000000)
    display.print("lat: ");
  else
    display.print("lat:  ");
   display.print(temp / 10000000);display.print(".");
   long temp2 = 1000000;
   temp = temp % 10000000;
   while ((temp / temp2 == 0)&&(temp2>1))
   {
  display.print("0");
  temp2 /= 10;
   }
   display.print(temp);
   if (pvt.lat >= 0)
  display.print("N");
   else
  display.print("S");
   temp = 10000;
   while (((pvt.pDop / temp) == 0)&&(temp>1))
   {
  display.print(" ");
  temp /= 10;
   }
   display.println(pvt.pDop);

   //Line2
   if (pvt.lon >= 0)
  temp = pvt.lon;
   else
  temp = -pvt.lon;
   if (temp >= 1000000000)
  display.print("lon:");
   else
  if (temp >= 100000000)
    display.print("lon: ");
  else
    display.print("lon:  ");
   display.print(temp / 10000000);display.print(".");
   temp2 = 1000000;
   temp = temp % 10000000;
   while ((temp / temp2 == 0)&&(temp2>1))
   {
  display.print("0");
  temp2 /= 10;
   }
   display.print(temp);
   if (pvt.lon >= 0)
  display.print("E");
   else
  display.print("W");
   display.println(" HEAD");

   //Line3
   display.print("hMSL:");
   if (pvt.hMSL < 0)
  pvt.hMSL = -pvt.hMSL;
   temp = 10000000;
   while (((pvt.hMSL / temp) == 0)&&(temp>1000))
   {
  display.print(" ");
  temp /= 10;
   }
   display.print((pvt.hMSL % 100000000) / 1000);display.print(".");
   if ((pvt.hMSL % 1000) < 100)
  display.print("0");
   if ((pvt.hMSL % 1000) < 10)
  display.print("0");
   display.print(pvt.hMSL % 1000);
   display.print("|");
   temp = pvt.headMot / 100000;
   if (temp < 100)
  display.print(" ");
   if (temp < 10)
  display.print(" ");
   display.print(temp);display.print(".");
   temp2 = (pvt.headMot0000)/1000;
   if (temp2<0)
  temp2 = -temp2;
   if (temp2<10)
  display.print("0");
   display.println(temp2);

   //Line4
   display.print("h,vAcc:");
   if (pvt.hAcc >= 100000)
  display.print("  >100");
   else
   {
  display.print(pvt.hAcc / 1000);display.print(".");
  if (pvt.hAcc % 1000 < 100)
    display.print("0");
  if (pvt.hAcc % 1000 < 10)
    display.print("0");
  display.print(pvt.hAcc % 1000);
   }
   display.print(",");
   if (pvt.vAcc >= 100000)
  display.print(" >100");
   else
   {
  display.print(pvt.vAcc / 1000);display.print(".");
  if (pvt.vAcc00 < 100)
    display.print("0");
  if (pvt.vAcc00 < 10)
    display.print("0");
  display.print(pvt.vAcc00);
   }
   display.println("m");

   //Line5
   display.print("V:");
   if (pvt.gSpeed < 1000000)
  display.print(" ");
   if (pvt.gSpeed < 100000)
  display.print(" ");
   if (pvt.gSpeed < 10000)
  display.print(" ");
   display.print((pvt.gSpeed % 10000000)/1000);display.print(".");
   if (pvt.gSpeed % 1000 < 100)
  display.print("0");
   if (pvt.gSpeed % 1000 < 10)
  display.print("0");
   display.print(pvt.gSpeed % 1000);
   display.print("m/s");
   if (pvt.sAcc < 1000000)
   {
  if (pvt.sAcc < 100000)
    display.print(" ");
  if (pvt.sAcc < 10000)
    display.print(" ");
  display.print("~");
  display.print(pvt.sAcc / 1000);display.print(".");
  if (pvt.sAcc % 1000 < 100)
    display.print("0");
  if (pvt.sAcc % 1000 < 10)
    display.print("0");
  display.println(pvt.sAcc % 1000);
   }
   else
   display.println(" ~>100");

   //Line6
   if ((pvt.year<10000)&&(pvt.year>=1000))
  display.print(pvt.year);
   else
  display.print("????");
   display.print("/");
   if ((pvt.month<=12)&&(pvt.month>=1))
   {
  if (pvt.month < 10)
    display.print("0");
  display.print(pvt.month);
   }
   else
  display.print("??");
   display.print("/");
   if ((pvt.day<=31)&&(pvt.day>=1))
   {
  if (pvt.day < 10)
    display.print("0");
  display.print(pvt.day);
   }
   else
  display.print("??");
   if (pvt.valid & 0x04)
  display.print("UTC");
   else
  display.print("INV");
   if ((pvt.hour<=23)&&(pvt.hour>=0))
   {
  if (pvt.hour < 10)
    display.print("0");
  display.print(pvt.hour);
   }
   else
  display.print("??");
   display.print(":");
   if ((pvt.miniute<=59)&&(pvt.miniute>=0))
   {
  if (pvt.miniute < 10)
    display.print("0");
  display.print(pvt.miniute);
   }
   else
  display.print("??");
   display.print(":");
   if ((pvt.sec<=60)&&(pvt.sec>=0))
   {
  if (pvt.sec < 10)
    display.print("0");
  display.print(pvt.sec);
   }
   else
  display.print("??");

   display.display();
 }

 void PrintSec()
 {
   pvt.sec = (pvt.sec + 1)`;
   display.fillRect(114,56,12,8,BLACK);
   display.setCursor(114,56);
   if (pvt.sec<10)
  display.print("0");
   display.println(pvt.sec);
   display.display();
   state = LOW;
 }

 void setup()
 {
   S_Serial.begin(9600);
   pinMode(intpin, INPUT);
   attachInterrupt(digitalPinToInterrupt(intpin), pps, RISING);
   // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
   // init done
 }

 void loop() {
   if (state == HIGH)
  PrintSec();
   if ( processGPS() )
  PrintScreen();
 }

I found a similar issue [here][2] (Interrupt Service Routine Executes Twice ATmega88), but since ISR only executes once if I connect pin 2 alone, I think the cause might be something else.

Is it a software issue or a hardware issue? How to fix it?

  [1]: https://i.stack.imgur.com/PrmLU.png
  [2]: https://stackoverflow.com/questions/18343058/interrupt-service-routine-executes-twice-atmega88

body:
If i understand you correctly you have 2 ways that increase your seconds,

1. when software serial receives data

2. When PPM pin goes high

And when each of theese are run separately things work, but when you use them together seconds increase by 2 each time ?

wouldnt this suggest that your program only should use one of theese to increase your seconds.


body:
**1)** First, deferring `PrintSec` to `loop` through the volatile `state`, which is set by the ISR, actually takes *more* time to update the display.  You might as well just test the pin in `loop`:

    void setup()
    {
      S_Serial.begin(9600);
      pinMode(intpin, INPUT);

      // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    }

    void loop() {

             bool state    = digitalRead(intPin);
      static bool oldState = false;

      // Watch for change
      if (oldState != state) {
        oldState = state;

        // RISING edge?
        if (state)
          PrintSec();
      }

      if ( processGPS() )
        PrintScreen();
    }

**2)** "But I might miss a PPS!" you exclaim.  The bad news is that if you can't finish `PrintScreen` in time to get back to testing the pin, then you're Trying To Do Too Much.

You might want to consider incremental updates of the display.  If you have the previous pieces (i.e., an extra NAV_PVT struct), you could compare each piece to see if it has changed.  If it has, it's ok to spend time writing it.  Just add an extra test to each piece:

    NAV_PVT pvt, prevPVT;
    static bool firstTime = true;
      .
      .
      .
    void PrintScreen()
    {
      if (firstTime)
        display.clearDisplay();

      //Size 2
      display.setTextSize(2);
      display.setTextColor(WHITE);

      //  Update the Speed?
      if (firstTime || (pvt.gSpeed != prevPVT.gSpeed)) {
        display.setCursor(0,0);
        float sik = (pvt.gSpeed / 100) / 3.6f;
        if (sik<100)
          display.print(" ");
        if (sik<10)
          display.print(" ");
        display.print(sik,1);//SpeedInKph
      }

At the end of `PrintScreen`, do this:

      display.display();

      prevPVT   = pvt;
      firstTime = false;
    }

For most updates, only the `seconds` field would get written.

Clearing the screen and drawing the labels could probably happen just once in `setup`.

**3)** I would suggest a more efficient and reliable software serial library.  `SoftwareSerial` disables *all* interrupts for the entire 10-bit character time, once the start bit is received.  This makes it both vulnerable and intrusive to other interrupts, like PinChange and SPI.  Ick.  If you can use pins 8 & 9, AltSoftSerial is the best choice.

If you can't use those pins, and you're not using the USB port to connect to a host, could you use Serial input (pin 0) for the GPS?  The GPS would have to be disconnected to do USB programming, but it could stay connected if you're using an ISP.

**4)** You need a more robust way to restart UBX packet framing, even if chars are lost.  I would suggest something like this:

    void loop() {
      if (state == HIGH) {
        PrintSec();
        fpos = 0; // new packet coming soon, ditch old partial packet
      }
      if ( processGPS() )
        PrintScreen();
    }

At least that will keep you in sync.  Without it, packet completion might not happen until after a 2nd PPS occurs (and 2nd packet begins arriving).  Maybe this explains the symptoms you're seeing?


message:
Interfacing 9-Axes Motion Shield with RPi and WiFi Shield

I recently purchased the [Arduino 9-Axes Motion Shield][1]. I have two questions:

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

Q2. A page [here][2] shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

  [1]: http://www.arduino.org/products/shields/5-arduino-shields/arduino-9-axes-motion-shield
  [2]: http://www.mouser.in/new/arduino/arduino-9-axes/

body:
> Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

> Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the [*Arduino Ethernet*](https://www.arduino.cc/en/Main/ArduinoBoardEthernet) which is not a shield, it is an Arduino.

What other shields you can use it with depends on what pins those other shields use.  Look at the schematics. Read the manuals. Do some leg-work.


message:
Not sure if my Arduino Uno is damaged

When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:

    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?

body:
Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.

Try rebooting your Mac.

If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.