message:
Reversed Input Voltage Arduino Mega timeout communication with programmer error

On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.

Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: https://arduino.stackexchange.com/questions/864/arduino-mega-timeout-communication-with-programmer-error

Is there anything else I should verify? Or is the Arduino always going to be damaged?

Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.

body:
Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.

In short: *"It's dead, Jim!"*


sender: user

sender: assistant

body:
*Don't reprogram the bootloader.*

If you can upload sketches that is unnecessary.

It will probably be fiddly to identify and fix what has failed, but since you can reprogram it via USB it is still 99% working.

I suggest you get one of those USB charging wall-warts that provide 5 V, and just plug that into the USB port if you want to run it away from the PC. You know that the USB power part works.


body:
The Mega has a reverse polarity protection diode ([D1](https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf)) on the board, so you plugging in the wrong polarity barrel didn't damage anything.

So your current problem in unrelated to this.


message:
Removing the barrel jack connector?

My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.

Or could that cause problems?

body: You can remove it safely without any issues, just make sure that there are no short circuits or any other components damaged while doing so


body: You'll likely do less damage de-soldering it than trying to snip it off. Use a de-soldering pump to remove as much molten solder as you can, then heat again with de-soldering braid to wick up the remainder. If the jack's solder terminals were bent over (to stabilize the part before it was soldered) you may need to straighten them with a tweezer-nosed plier. Then you should be able to lift the part off the board. Don't overheat the board or heat any other parts or solder joints than those you intend to remove.


body: De sdering would be safer.  You can then use the Vin pin to supply sour voltage (IIRC you can run as high as 12 volts with the uno)


body:
Unless you have some really specific reason to use a UNO, for example using the 2nd ATMega on the board, you would be much better off with an Micro Pro.

On ebay you can find both 3.3V and 5V versions.
You can even find ones that have redundant pins, to accommodate for a permanent installation of the ISP programmer.

Even if you happen to have a shield that is compatible with the UNO pinout, you could still wire it with a flat cable and save space.

Said this, using mechanical means on a PCB is always putting at risk the tracks, which might come off.

Desoldering is better, since it's reversible.

But you might find that it takes an unusually powerful soldering iron, compared to what is used nowadays for smd components, as you will have to heat up simultaneously several large pads, which have connected large tracks and ground areas that act as heat sink.

In case you do not have desoldering braid and or pump, there's a hackish method to remove large components with multiple pads: flood them in molten solder and literally shake them off the board by hitting the workbench sideways, while the solder is still fluid.

Not nice and at risk of adding splash shorts to the board, not to mention the splash damage to the operator: it can cause burns on unprotected skin or organs.

However, if done correctly, it works without pump or braid.


message:
Bluetooth Trancievers for arduinos

Would it be possible to use to of [these][1] on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.

  [1]: http://www.ebay.com/itm/Bluetooth-Serial-Transceiver-Module-Base-Board-clear-button-For-Arduino-SWTG-/231608470902?hash=item35ecf0cd76

body:
The boards in your link look funny.  Typical boards like this include the "bluetooth circuit" which piggy-backs onto that board, and is soldered at all those little pads.

Have a look at say, the HC-05 board ~  https://www.google.com.au/search?q=hc05+bluetooth+module&tbm=isch

It's easy to see the part that's missing from the one in your link.

For these HC-05 boards, it's possible to pair two together.  They need to be configured as "Master" and "Slave" though.  Some bluetooth boards can do slave-mode only, so be careful before you purchase.


message:
Serial problem after implementing data structures

#Context

I first ran a sketch (**on Arduino Uno**) without any custom data structure and list, so I was using a bunch of arrays, methods and other primitive variables. And it worked perfectly.

*My program acts like a menu which takes serial user input to perform actions. So you could have serial input "man r+(100,0,345)". Or just "man" to set this mode active, and later "r+(100,0,345)" to actualize the data in the "r" field in the "man" instance. I use a custom data structure to manage the input (class called Mode), and a linked list (class called ModeList).*

#Problem

I implemented some data structures (an object and a list) to manage incoming serial data, without modifying the rest of the program. But now, serial communication is not working properly: If I add `Serial.print("Allo")` *anywhere* in the sketch, it will print spaces for a while and stop, before I send any serial data. If it is in the `setup()` function, it prints spaces continuously with some characters from "Allo" from time to time. There's always a different problem along those lines, depending on where I put that simple print statement.

**Here follows the sketch, the header files of the Mode and ModeList classes... By the way, I suspect a memory management problem.**

#The sketch

    #include "Mode.h"
    #include "ModeList.h"

    const int inputSize=12;
    const int nbModes=4;
    int input;
    int toSet[inputSize];
    int i;

    char manName[3]={'m','a','n'};
    char cutName[3]={'c','u','t'};
    char levName[3]={'l','e','v'};
    char autName[3]={'a','u','t'};

    Mode m=Mode(0,manName);
    Mode c=Mode(1,cutName);
    Mode l=Mode(2,levName);
    Mode a=Mode(3,autName);
    Mode* man=&m;
    Mode* cut=&c;
    Mode* lev=&l;
    Mode* aut=&a;
    ModeList modeList=ModeList();

    void setup() {
      Serial.begin(115200);
      Serial.print("Allo");
      modeList.add(man);
      modeList.add(cut);
      modeList.add(lev);
      modeList.add(aut);
      }

    void loop() {
      for(int j=0;j<inputSize;j++)
      {
        toSet[j]=NULL;
      }
      i=0;
      if(Serial.available()>0)
      {
        while(Serial.available())
        {
          if(i<inputSize)
          {
            input=Serial.read();
            if(input!=' ' && input!='(' && input !=')' && input!=',' && input!='\n')
            {
              toSet[i]=input;
              i++;
            }
          }
        }
      }

      if(serialMode(man)||man->getStatus())
      {
        //Set man on
        modeList.setMode(man);

        if(toSet[3]=='r')
        {
          if(toSet[4]=='+')
          {
            //Set ypr rate
            Serial.println("Set ypr rate +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr rate
            Serial.println("Set ypr rate -");
          }
          else
          {
            //Set ypr rate
            Serial.println("Set ypr rate");
          }
        }
        else if(toSet[3]=='a')
        {
          if(toSet[4]=='+')
          {
            //Set ypr angle
            Serial.println("Set ypr angle +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr angle
            Serial.println("Set ypr angle -");
          }
          else
          {
            //Set ypr angle
            Serial.println("Set ypr angle");
          }
        }
        else if(toSet[3]=='t')
        {
          if(toSet[4]=='+')
          {
            //Set thrust
            Serial.println("Set thrust +");
          }
          else if(toSet[4]=='-')
          {
            //Set thrust
            Serial.println("Set thrust -");
          }
          else
          {
            //Set thrust
            Serial.println("Set thrust");
          }
        }
      }
      if(serialMode(cut)||cut->getStatus())
      {
        //Cut engines
        modeList.setMode(cut);
        if(serialMode(cut))
          Serial.println("Cut");
      }
      if(serialMode(lev)||lev->getStatus())
      {
        //Stabilize axes
        modeList.setMode(lev);
        if(serialMode(lev))
          Serial.println("Level");
      }
      if(serialMode(aut)||aut->getStatus())
      {
        //Set aut on
        modeList.setMode(aut);
        if(serialMode(aut))
          Serial.println("Set aut on");
        if(toSet[3]=='s')
        {
          if(toSet[4]=='+')
          {
            //Set ypr angle
            Serial.println("Set ypr angle +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr angle
            Serial.println("Set ypr angle -");
          }
          else
          {
            //Set ypr angle
            Serial.println("Set ypr angle");
          }
        }
        else if(toSet[3]=='A')
        {
          if(toSet[4]=='+')
          {
            //Set altitude
            Serial.println("Set altitude +");
          }
          else if(toSet[4]=='-')
          {
            //Set altitude
            Serial.println("Set altitude -");
          }
          else
          {
            //Set altitude
            Serial.println("Set altitude");
          }
        }
      }
      delay(10);
    }

    bool serialMode(Mode* inputMode)
    {
      char* modeName;
      modeName=inputMode->getName();
      Serial.print("ALLO");
      if(toSet[0]==*modeName&&toSet[1]==*(modeName+1)&&toSet[2]==*(modeName+2))
      {
        Serial.print("Set ");
        for(int i=0;i<3;i++)
        {
          Serial.print(*(modeName+i));
        }
        Serial.println(" on");
        return true;
      }
      else
        return false;
    }

#The Mode class header

    #include "Arduino.h"

    class Mode
    {
        public:
            Mode(int id, char* name);
            int getId();
            Mode* getNext();
            void setNext(Mode m);
            void setStatus(bool status);
            bool getStatus();
            char* getName();
        private:
            char *_name;
            int _id;
            Mode* _next;
            bool _status;
    };

#The ModeList class header

    class ModeList
    {
        public:
            void add(Mode* input);
            int get(int pos);
            ModeList();
            void setMode(Mode* inputMode);
        private:
            Mode* start;
            Mode* end;
    };

body:
>  If I add Serial.print("Allo") anywhere in the sketch, it will print spaces for a while and stop, before I send any serial data.

Classic symptoms of using up all available RAM.

As a workaround I would use the `F()` macro.

eg.

        Serial.println(F("Set ypr rate +"));

Do that in all places where you are printing string literals. That would save you a couple of hundred bytes.


message:
What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?

I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller.

The setup is as follows:

Arduino|---UART--------------------------|MCU2

Arduino|---FLOW_CONTROL_PIN---|MCU2

I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).

At this point I log the amount of bytes sent and compare that to the buffer threshold level.  If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay.  I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).

A problem can arise if the Arduino api is providing more latency than the path under test.  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api.  I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.

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

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.

I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.

I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

> A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.

This is probably what you are experiencing. See HardwareSerial.cpp:

    // Define constants and variables for buffering incoming serial data.  We're
    // using a ring buffer (I think), in which head is the index of the location
    // to which to write the next incoming character and tail is the index of the
    // location from which to read.
    #if (RAMEND < 1000)
      #define SERIAL_BUFFER_SIZE 16
    #else
      #define SERIAL_BUFFER_SIZE 64
    #endif

For this test you might want to edit that file and reduce that number, substantially.

Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

>  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

---

> What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?

However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.

To keep things simple though, what you really need to do here is **not buffer** because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:

    Serial.write ('a');  // or whatever
    Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).


message:
RTC resets when power is off

I have a few RTC modules with a batteries. All of them have this same issue with my project.

They work fine when connected via USB. But if I disconnect the power then reconnect they reset to Jan 1 2000.

I've read several posts about similar problems. But, none seem to apply.

Here is my code:

    #include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
    #include <SPI.h>
    #include <SD.h>
    #include "Wire.h"
    #include <RTClib.h>
    RTC_DS1307 RTC;
    #define BUTTON_PIN       0 // Button
    #define LONGPRESS_LEN    25  // Min nr of loops for a long press
    #define DELAY            20  // Delay per loop in ms

    enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

    boolean button_was_pressed; // previous state
    int button_pressed_counter; // press running duration

    byte zero = 0x00; //workaround for issue #527

    char* modes[]={"Walk", "Bike", "Subway", "Train", "Bus", "X-Bus", "Waiting", "Other"};
    byte mode=0;
    int modeRead;

    // Chip Select for SD
    #define chipSelect 10

    //MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);
    MicroOLED oled(9, 8, 5); // SPI declaration

    void setup()
    {
        pinMode(BUTTON_PIN, INPUT);
        digitalWrite(BUTTON_PIN, HIGH); // pull-up
        Serial.begin(9600);
        button_was_pressed = false;
        button_pressed_counter = 0;

        SD.begin(chipSelect);

        Wire.begin();
        RTC.begin();
        //RTC.adjust(DateTime(__DATE__, __TIME__));

        oled.begin();    // Initialize the OLED
        oled.clear(PAGE);     // Clear the screen
        oled.setFontType(1);  // Set font to type 0
        oled.setCursor(0, 0); // Set cursor to top-left
        oled.println(F("co'mute"));
        oled.display();  // Display what's in the buffer
    }

    int handle_button()
    {
        int event;
        int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

        if (!button_now_pressed && button_was_pressed) {
            if (button_pressed_counter < LONGPRESS_LEN)
                event = EV_SHORTPRESS;
            else
                event = EV_LONGPRESS;
        }
        else
            event = EV_NONE;

        if (button_now_pressed)
            ++button_pressed_counter;
        else
            button_pressed_counter = 0;

        button_was_pressed = button_now_pressed;
        return event;
    }

    void printDate ()
    {
        oled.clear(PAGE);     // Clear the screen
        oled.setFontType(0);  // Set font to type 0
        oled.setCursor(0, 0); // Set cursor to top-left

        DateTime now = RTC.now();

        oled.print(now.year(), DEC);
        oled.print('/');
        oled.print(now.month(), DEC);
        oled.print('/');
        oled.print(now.day(), DEC);
        oled.print(' ');
        oled.print(now.hour(), DEC);
        oled.print(':');
        if (now.minute()<10) {
            oled.print("0");
        }
        oled.print(now.minute(), DEC);
        oled.print(':');
        if (now.second()<10) {
            oled.print("0");
        }
        oled.print(now.second(), DEC);
        oled.println();
        oled.setFontType(1);  // Set font to type 0
        oled.println(modes[mode]);
        oled.display();   // Display what's in the buffer (splashscreen)
    }

    void writeFile()
    {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);
        // If the file is available, write to it:
        if (dataFile) {
            DateTime now = RTC.now();
            //print the date EG   3/1/11 23:59:59
            dataFile.print(now.year(), DEC);
            dataFile.print('/');
            dataFile.print(now.month(), DEC);
            dataFile.print('/');
            dataFile.print(now.day(), DEC);

            printDate ();
            oled.print("*SAVED*");
            oled.display();
            delay(3000);
        }
    }

    void loop()          // run over and over again
    {
        // handle button
        boolean event = handle_button();

        // do other things
        switch (event) {
            case EV_NONE:
            oled.print(".");
            break;

            case EV_SHORTPRESS:
            oled.print("S");
            //modeRead = analogRead(0);    // read the value from the sensor
            writeFile();
            break;

            case EV_LONGPRESS:
            oled.print("L");
            break;
        }

        static int counter = 0;
        if ((++counter & 0X016) == 0) {
            printDate ();
        }
        modeRead = analogRead(A0);    // read the value from the sensor
        delay(DELAY);

        int c=1020/(sizeof(modes)/sizeof(modes[0]));
        for (int i = 0; i < c; i++) {
            if (i*c < modeRead && (i+1)*c < modeRead) {
                mode = i;
            }
        }
    }

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

In this diagram the "pressure sensor" is really a OLED that operates via MOSI and MISO.

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

body:
The RTC board has a battery holder and requires the button battery to be fitted in order to retain the time and date value. As shown in the [Datasheet][1], this battery is for the RTC chip only.

[![DS1307 Circuit][2]][2]

The [Adafruit board][3] requires a CR1220 button battery.

[![Adafruit DS1307 board][4]][4]

The Adafruit webpage mentions the following:

> Note: This product does not come with a CR1220 coin cell battery.

(Providing that it works when the Arduino is powered up) It sounds as if the battery for the RTC is either:

 - not present
 - not connected (not inserted correctly or not making proper connection)
 - inserted upside down
 - a track on the PCB is broken or shorted
 - the battery is flat

The battery should be inserted so that the flat + side is UP. I suggest that you use a DMM to measure the RTC battery voltage at the RTC IC. Place your +ve probe on pin 3 of the IC and the -ve probe on pin 4. It should read slightly above 3.0 Volts.

I also recommend that you disconnect all of the other periferals so that you just have the RCT connected to the Arduino. Then use a known working program such as the one in the [Adafruit tutorial][5] to verify that your RTC is working correctly. You should be able to disconnect the USB and then reconnect it and find that the RTC is still holding the correct time.

[RTC DS1307 Datasheet][1]
[Adafruit RTC Product][3]
[Adafruit RTC Tutorial][5]

  [1]: https://datasheets.maximintegrated.com/en/ds/DS1307.pdf
  [2]: https://i.stack.imgur.com/mx4aF.png
  [3]: https://www.adafruit.com/product/3296
  [4]: https://i.stack.imgur.com/AszFn.png
  [5]: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit?view=all


message:
Which device to use to measure AC current using Arduino?

I'm building a home automation product and want to measure AC current using Arduino (as of now). I've used ACS712 5A Hall Effect Current module but there's a lot of electrical noise and also the accuracy is not good. There's a lot of deflection in value when no current passes through it. I want to pack the whole kit in a box. So how to make sure that there will be no magnetic interference?

Can you suggest some other module to use for the same? Also that can last long enough.

body:
Some sort of Current Transformer usually does the trick.  You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage.  You can find them packaged like [this one][1] with a [web search][2].

  [1]: http://www.dx.com/p/yqj010504-single-phase-ac-current-sensor-module-w-active-output-deep-blue-5a-294209#.Vd20A_lVhBc
  [2]: https://www.google.com/search?q=ac current sensor


message:
expected initializer before void arduino

When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?

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

    float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
    int x = 0,pre_x = 0,t = 0,pre_t = 0;

    long unsigned int t

    void loop()
    {
      x = analogRead(A0);
      t = millis();
      float diff_t = (float)(t - pre_t)/1000.0f;
      area = (0.5 * (pre_x + x) * diff_t) + pre_area;

      Serial.print(area);
      analogWrite(DAC0, area);
      pre_x = x;
      pre_area = area;
      pre_time = t;
    }

body: You add the semicolon that is missing at the end of `long unsigned int t`


body:
**Why have you written t = 0 here and declared it again below??**

    int x = 0,pre_x = 0,t = 0,pre_t = 0;

 **Semi Colon Missing**

    long unsigned int t;

 **Where have you declared pre_time??**

      pre_time = t;


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

    long unsigned int t

No semicolon.

---

Plus, make up your mind what type "t" is:

    int x = 0,pre_x = 0,t = 0,pre_t = 0;
    long unsigned int t;

Is it `int` or `long unsigned int`?

---

> How can I get the code to work?

Avoid C++ syntax errors.


message:
How to use the additional SPIs on Arduino Due

According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

[![Arduino Due Pinout][1]][1]

[source][2]

However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.

Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

  [1]: https://i.stack.imgur.com/VuNPu.png
  [2]: http://forum.arduino.cc/index.php?topic=132130.0

body:
I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI

There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).

The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


message:
Unable to add multiple potentiometer in Midi controller

I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..

        #include <MIDI.h>
    int pot[] = {A0,A1,A2};
    int AnaPinsNum = 3;
    int potIn[] = {0,0,0};
    int analogValue = 0;

    int lastAnalogValue[] = {0,0,0};

     void setup()
     {
      MIDI.begin(4);
      // 115200 hairless MIDI
      Serial.begin(115200);
      int i;
      for (i = 0; i < 3; i++);
     }
     void loop() {

      int i;
      for (i = 0; i < AnaPinsNum; i++)

      potIn[i] = analogRead(pot[i])/8;

      // potentiometer could be too sensitive and
      // give different (+-1) values.
      // send CC only when the difference between last value
      // is more than 1
      if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
        // value changed?
        if (potIn[i] != lastAnalogValue[i]) {
          // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
          // more info: http://arduinomidilib.sourceforge.net/a00001.html
          MIDI.sendControlChange(1, potIn[i], 1);
          lastAnalogValue[i] = potIn[i];
        }
      }

    }

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

Your logic is flawed here:

      int i;
      for (i = 0; i < AnaPinsNum; i++)
        potIn[i] = analogRead(pot[i]) / 8;

      // potentiometer could be too sensitive and
      // give different (+-1) values.
      // send CC only when the difference between last value
      // is more than 1
      if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
        // value changed?
        if (potIn[i] != lastAnalogValue[i]) {
          // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
          // more info: http://arduinomidilib.sourceforge.net/a00001.html
          MIDI.sendControlChange(1, potIn[i], 1);
          lastAnalogValue[i] = potIn[i];
          }
        }

The first three lines read all three analog pins:

      int i;
      for (i = 0; i < AnaPinsNum; i++)

        potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of `i` which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.

      int i;
      for (i = 0; i < AnaPinsNum; i++)
        {   // <------------------------------- add this
        potIn[i] = analogRead(pot[i]) / 8;

        // potentiometer could be too sensitive and
        // give different (+-1) values.
        // send CC only when the difference between last value
        // is more than 1
        if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
          {
          // value changed?
          if (potIn[i] != lastAnalogValue[i])
            {
            // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
            // more info: http://arduinomidilib.sourceforge.net/a00001.html
            MIDI.sendControlChange(1, potIn[i], 1);
            lastAnalogValue[i] = potIn[i];
            }  // end of not same as before
          }   // end of value changed
        }   // <----------------- add this

---

> If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:

Change:

    MIDI.sendControlChange(1, potIn[i], 1);

to:

    MIDI.sendControlChange(i, potIn[i], i);


message:
Arduino Program uses less RAM then expected and doesn't run

I am trying to make a program for my Arduino that will run 4 motors with random actions (forward,backward,left,right) and execution is determined by a random number generator. When I compile there is no errors, and The COM port is connected correctly to my Arduino Mega, but when it uploads the log says this:

    Sketch uses 668 bytes (0%) of program storage space. Maximum is 253,952 bytes.

    Global variables use 9 bytes (0%) of dynamic memory, leaving 8,183 bytes for local variables. Maximum is 8,192 bytes.

That means only 677 B is being used, but the Arduino file is *6 KB*. I know that the program gets somewhat smaller when it is compiled, but not ten times smaller.

What's happening here?

**EDIT**

    // Arduino pins for the shift register
    #define MOTORLATCH 12
    #define MOTORCLK 4
    #define MOTORENABLE 7
    #define MOTORDATA 8

    // 8 bit bus

    #define MOTOR1_A 2
    #define MOTOR1_B 3
    #define MOTOR2_A 1
    #define MOTOR2_B 4
    #define MOTOR3_A 5
    #define MOTOR3_B 7
    #define MOTOR4_A 0
    #define MOTOR4_B 6

    // Motor pins:

    #define MOTOR1_PWM 11
    #define MOTOR2_PWM 3
    #define MOTOR3_PWM 6
    #define MOTOR4_PWM 5

    // LED Pins

    #define led_r 22
    #define led_l 23

    // Actions

    #define RIGHT 0
    #define LEFT 1
    #define FORWARD 2
    #define STOP 3

    // Codes for the motor function.
    #define GO 1
    #define REVERSE 2
    #define BRAKE 3
    #define RELEASE 4

    // Probability

    #define rProb 5
    #define lProb 5
    #define fProb 88
    #define stopProb 2

    // other globals

    #define defSpd 255

    void setup() {}

    void execute(int action) {

     if (action == FORWARD) {

      motor(1,FORWARD,defSpd);
      motor(2,FORWARD,defSpd);
      motor(3,FORWARD,defSpd);
      motor(4,FORWARD,defSpd);

      digitalWrite(led_r, LOW);
      digitalWrite(led_l, LOW);
     } else if (action == RIGHT) {

      motor(1,REVERSE,defSpd);
      motor(2,REVERSE,defSpd);
      motor(3,FORWARD,defSpd);
      motor(4,FORWARD,defSpd);

      digitalWrite(led_l, LOW);
      digitalWrite(led_r, HIGH);
      delay(150);

     } else if (action == LEFT) {

      motor(1,FORWARD,defSpd);
      motor(2,FORWARD,defSpd);
      motor(3,REVERSE,defSpd);
      motor(4,REVERSE,defSpd);

      digitalWrite(led_l, HIGH);
      digitalWrite(led_r, LOW);

      delay(150);

     } else if (action == STOP) {

      motor(1,BRAKE,defSpd);
      motor(2,BRAKE,defSpd);
      motor(3,BRAKE,defSpd);
      motor(4,BRAKE,defSpd);

      digitalWrite(led_r, HIGH);
      digitalWrite(led_l, HIGH);

      delay(1000);

     }

    }

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

      // Random action
      int i = (1, 101);

      if (i > 0 && i <= rProb) {

        execute(RIGHT);

      } else if (i > rProb && i <= rProb + lProb) {

        execute(LEFT);

      } else if (i > rProb + lProb && i <= rProb + lProb + fProb) {

        execute(FORWARD);

      } else if (i > rProb + lProb + fProb && i <= rProb + lProb + fProb + stopProb) {

        execute(STOP);

      }

    }

    void motor(int nMotor, int command, int speed)
    {
      int motorA, motorB;

      if (nMotor >= 1 && nMotor <= 4)
      {
        switch (nMotor)
        {
        case 1:
          motorA   = MOTOR1_A;
          motorB   = MOTOR1_B;
          break;
        case 2:
          motorA   = MOTOR2_A;
          motorB   = MOTOR2_B;
          break;
        case 3:
          motorA   = MOTOR3_A;
          motorB   = MOTOR3_B;
          break;
        case 4:
          motorA   = MOTOR4_A;
          motorB   = MOTOR4_B;
          break;
        default:
          break;
        }

        switch (command)
        {
        case GO:
          motor_output (motorA, HIGH, speed);
          motor_output (motorB, LOW, -1);     // -1: no PWM set
          break;
        case REVERSE:
          motor_output (motorA, LOW, speed);
          motor_output (motorB, HIGH, -1);    // -1: no PWM set
          break;
        case BRAKE:
          // The AdaFruit library didn't implement a brake.
          // The L293D motor driver ic doesn't have a good
          // brake anyway.
          // It uses transistors inside, and not mosfets.
          // Some use a software break, by using a short
          // reverse voltage.
          // This brake will try to brake, by enabling
          // the output and by pulling both outputs to ground.
          // But it isn't a good break.
          motor_output (motorA, LOW, 255); // 255: fully on.
          motor_output (motorB, LOW, -1);  // -1: no PWM set
          break;
        case RELEASE:
          motor_output (motorA, LOW, 0);  // 0: output floating.
          motor_output (motorB, LOW, -1); // -1: no PWM set
          break;
        default:
          break;
        }
      }
    }

    void motor_output (int output, int high_low, int speed)
    {
      int motorPWM;

      switch (output)
      {
      case MOTOR1_A:
      case MOTOR1_B:
        motorPWM = MOTOR1_PWM;
        break;
      case MOTOR2_A:
      case MOTOR2_B:
        motorPWM = MOTOR2_PWM;
        break;
      case MOTOR3_A:
      case MOTOR3_B:
        motorPWM = MOTOR3_PWM;
        break;
      case MOTOR4_A:
      case MOTOR4_B:
        motorPWM = MOTOR4_PWM;
        break;
      default:
        // Use speed as error flag, -3333 = invalid output.
        speed = -3333;
        break;
      }

      if (speed != -3333)
      {
        // Set the direction with the shift register
        // on the MotorShield, even if the speed = -1.
        // In that case the direction will be set, but
        // not the PWM.
        shiftWrite(output, high_low);

        // set PWM only if it is valid
        if (speed >= 0 && speed <= 255)
        {
          analogWrite(motorPWM, speed);
        }
      }
    }

    void shiftWrite(int output, int high_low)
    {
      static int latch_copy;
      static int shift_register_initialized = false;

      // Do the initialization on the fly,
      // at the first time it is used.
      if (!shift_register_initialized)
      {
        // Set pins for shift register to output
        pinMode(MOTORLATCH, OUTPUT);
        pinMode(MOTORENABLE, OUTPUT);
        pinMode(MOTORDATA, OUTPUT);
        pinMode(MOTORCLK, OUTPUT);

        // Set pins for shift register to default value (low);
        digitalWrite(MOTORDATA, LOW);
        digitalWrite(MOTORLATCH, LOW);
        digitalWrite(MOTORCLK, LOW);
        // Enable the shift register, set Enable pin Low.
        digitalWrite(MOTORENABLE, LOW);

        // start with all outputs (of the shift register) low
        latch_copy = 0;

        shift_register_initialized = true;
      }

      // The defines HIGH and LOW are 1 and 0.
      // So this is valid.
      bitWrite(latch_copy, output, high_low);

      // Use the default Arduino 'shiftOut()' function to
      // shift the bits with the MOTORCLK as clock pulse.
      // The 74HC595 shiftregister wants the MSB first.
      // After that, generate a latch pulse with MOTORLATCH.
      shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy);
      delayMicroseconds(5);    // For safety, not really needed.
      digitalWrite(MOTORLATCH, HIGH);
      delayMicroseconds(5);    // For safety, not really needed.
      digitalWrite(MOTORLATCH, LOW);
    }

body:
What is:

    // Random action
    int i = (1, 101);

supposed to achieve?

    /tmp/untitled1/untitled1.ino: In function 'void loop()':
    /tmp/untitled1/untitled1.ino:110:13: warning: left operand of comma operator has no effect [-Wunused-value]

Ergo, `i` is always going to be 101.  So all the `if` constructs will be false, so they get optimized out (they are all constants).  Because of that the other functions are never getting called, so they are optimized out.

So you are left with next to nothing.

I think you may have missed the word `random` out from there...

* Program size: 2798 bytes
* Memory size: 17 bytes
* Compilation took 0.227 seconds


message:
Why should a pin be set as an input if it can read input when set as output?

I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin `HIGH` and reading the input on the other pin and then swapping. With both pins set to `OUTPUT` I can still read in values with `analogRead()` without having to keep switching pin modes.

My question is why is that the case? What is the point of setting a pin to `INPUT` if `OUTPUT` can still read in values? Are there any disadvantages of doing so?

body: The reason for this is because `analogRead()` has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of *digital* operations - i.e., when using `digitalRead()` and `digitalWrite()`.  When using `analogRead()` the Arduino code switches the pin into analog mode first and then reads from it.


body: Because I/O pins can be used for either digital input or digital output and can be switched to perform in a given direction. Some of the pins also have an analog capability, either A-to-D conversion (input) or PWM (kind of a psuedo-analog output) but only in one direction permanently assigned by the hardware and therefore not switchable from one to the other.


body:
> My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

If you do a `digitalRead` you can read the current latched state of an **output** pin (it doesn't change it to input). In other words, you read what was last written to it.

If you do a `digitalWrite` of HIGH to an **input** pin it sets the internal pull-up. If you write LOW it disables the internal pull-up. If it switched it to output for you, you wouldn't be able to enable or disable the pull-up. (Note: this applies to older versions of the IDE, newer ones have a pinMode setting of INPUT_PULLUP).

>  What is the point of setting a pin to INPUT if OUTPUT can still read in values?

That certainly won't work with `digitalRead` because you are writing a value to the pin in OUTPUT mode, so you will merely read back what you are writing. In other words, you have activated the driver transistors, which will override whatever value you are trying to read.


body: It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.


message:
Is it possible to setup a system based on Arduino Due running QNX?

I would like to create some QNX applications and test them in a hardware different than my virtual machine. Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

What would be the challenges to make it work?

body:
Typically the challenge in porting a new OS to a board is to configure stuff like:

- system clock (to drive the scheduler of the OS at the right frequence)
- board specific I/O
- components that are not part of the SoC (but iirc DUE doesn't have any of these)
- individual HW blocks (like on which serial port redirect the character interface, if your application has any)
- wakeup sources, in case you have/want low power modes and you need the board to wake up when something specific happens

None of these are impossible tasks and they are all good to learn more about the system, but otoh it's unlikely you can rush through them.

The good news is that probably you will not need them all and not immediately.

But some you will have to perform and they will require understanding how your OS works and having the technical reference manual of your board and SoC.


body:
> Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

[![QNX Neutrino RTOS Architectuer][1]][1]

Please see the [BSP][2] list.

Cheers!

  [1]: https://i.stack.imgur.com/IkCPG.png
  [2]: http://community.qnx.com/sf/wiki/do/viewPage/projects.bsp/wiki/BSPAndDrivers


message:
Arduino as ISP with serial monitor for ATmega328

I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

1. Is this possible?
2. If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.

body:
Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.

Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.

Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (`UCSRnB &= ~_BV(UCSRnB);`) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).


body: In addition to my previous comment-suggestion that you could implement communication over SPI by adding functionality to both the ISP sketch and the target program, it now occurs to me that another approach would be to implement software serial functionality on both, assigned to some of the pins used for ISP during that process.


body:
as [here][1]? Nick Gammon has a sketch which includes an ISP with serial control. Sketch is available on GitHub [here][2]

  [1]: http://www.gammon.com.au/bootloader
  [2]: https://github.com/nickgammon/arduino_sketches


message:
Arduino loses its program under unusual conditions

I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.

This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.

Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.

Thanks for any help!

body:
I would suggest that you reproduce the issue and then use a device capable of _reading_ the flash, to confirm that it's still identical to the .hex file that was used to program the board.

I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.

But it seems that [you are not alone][1].

Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.

Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.

Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.

  [1]: https://www.physicsforums.com/threads/nor-flash-failures-at-extreme-low-temperatures.207832/


message:
Request for member is Non-class type

Im getting this error:

    iotHook.ino: In function 'void setup()':
    iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'
    request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'

When I try to lunch my begin function of my class:

    class Esp8266 {

      public:
        Esp8266();
        void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
        ...
      private:

        HardwareSerial *wifiCom;
        HardwareSerial *debugCom;
        ...

    }

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
      this->wifiCom = wifiCom;
      this->debugCom = debugCom;

      this->debugCom->begin(115200);
      while (!this->debugCom) {
      ;
      }
    }

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

EDIT 1:
Updated image with new code
[![enter image description here][2]][2]

Why is not picking up the begin function?

  [1]: https://i.stack.imgur.com/LsAdO.png
  [2]: https://i.stack.imgur.com/Io6tr.png

body:
You've confused the compiler by making it think that `esp` is a function that takes no arguments and returns a `Esp8266`. But the no-argument constructor is called by default, so you don't need the parens there regardless.

    Esp8266 esp;


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

The line:

    esp.begin (Serial, Serial1);

Should be:

    esp.begin (&Serial, &Serial1);

It is expecting a **pointer** to a HardwareSerial instance.

---

Also make the instantiation line:

    Esp8266 esp;   // <--------- no brackets!

---

This compiles without errors for me:

    class Esp8266 {

      public:
        Esp8266();
        void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
      private:

        HardwareSerial *wifiCom;
        HardwareSerial *debugCom;

    };

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
      this->wifiCom = wifiCom;
      this->debugCom = debugCom;

      this->debugCom->begin(115200);
      while (!this->debugCom) {
      ;
      }
    }

    Esp8266 esp;

    void setup ()
      {
      esp.begin (&Serial, &Serial1);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

I would rework to use references anyway, saves all that mucking around with pointers:

    class Esp8266 {
      public:
        Esp8266(HardwareSerial & wifiCom, HardwareSerial & debugCom);
        void begin();
      private:
        HardwareSerial & wifiCom;
        HardwareSerial & debugCom;
      };

    // constructor
    Esp8266::Esp8266(HardwareSerial &wifiCom_, HardwareSerial &debugCom_)
      : wifiCom (wifiCom_), debugCom (debugCom_)
      {
      }

    // initialize stuff
    void Esp8266::begin()
    {
      debugCom.begin(115200);
      while (!debugCom)
      {
      }
    }

    Esp8266 esp (Serial, Serial1);

    void setup ()
    {
      esp.begin ();
    }  // end of setup

    void loop ()
    {
    }  // end of loop

---

## Corrected for Leonardo

Sorry, my reply above was compiled for the Mega2560, I didn't notice the Leonardo tag.

Majenko is quite right, you need to rework for the Leonardo. My example using references can reduce down to this now:

    class Esp8266 {
      public:
        Esp8266(Stream & wifiCom, Stream & debugCom)
          : wifiCom_ (wifiCom), debugCom_ (debugCom) { }

      private:
        Stream & wifiCom_;
        Stream & debugCom_;
      };

    Esp8266 esp (Serial, Serial1);

    void setup ()
    {
      Serial.begin (115200);
      while (!Serial) { }
      Serial1.begin (115200);
      while (!Serial1) { }
    }  // end of setup

    void loop ()
    {
    }  // end of loop

By storing a Stream type you can still print to them, however you need to initialize in `setup`, not in the `begin` function, which now becomes redundant.

I agree about not using `this->` although my preference is for trailing underscores as the use of leading underscores is reserved in quite a few cases, depending on the location and capitalization.


body:
Your current problem is that the USB Serial interface of the Leonardo isn't a hardware serial device, it's a CDC/ACM device, and the class for that isn't HardwareSerial, it's Serial_.

So you can't pass it to a function that expects a HardwareSerial.

What you should be using, instead, is the Stream class.  That will allow you to pass any object that is based on the Stream class, such as HardwareSerial, Serial_, Client, etc.  Many different things, including serial and networking protocols, use Stream as their base class.

It does have the down side, though, that you have to initialize the Stream objects in your sketch (that is, do the Serial.begin(...) and Serial1.begin(...) in your sketch not your class) because the Stream class doesn't have the concept of a baud rate, and so no begin(baud) function.

This is what I mean:

    class Esp8266 {

    public:
     Esp8266();
     void begin(Stream &wifiCom, Stream &debugCom);
    private:

     Stream *_wifiCom;
     Stream *_debugCom;

    };

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(Stream &wifiCom, Stream &debugCom) {
     _wifiCom = &wifiCom;
     _debugCom = &debugCom;

     while (!_debugCom) {
      ;
     }
    }

    Esp8266 esp;

    void setup() {
     Serial.begin(115200);
     Serial1.begin(115200);
     esp.begin(Serial, Serial1);
    }  // end of setup

    void loop() {
    }  // end of

Note, as well, my use of pass-by-reference (Stream &whatever) so you don't have to pass a pointer in your begin function.  Also notice the use of unique variable names in the class (I always prefix my member variables with `_`) so you don't have to keep putting `this->` in everywhere.

----

To be able to move the `.begin()` function inside your class you will have to use both `HardwareSerial` and `Serial_` object types within your class.  There's two ways this may be done.

First is [*dynamic casting*](http://en.cppreference.com/w/cpp/language/dynamic_cast):

    void Esp8266::begin(Stream &wifiCom, Stream *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;

        HardwareSerial *hard;
        Serial_ *cdc;

        if (hard = dynamic_cast<HardwareSerial*>(_wifiCom)) {
            hard->begin(115200);
        } else if (cdc = dynamic_cast<Serial_*>(_wifiCom)) {
            cdc->begin(115200);
        }

        if (hard = dynamic_cast<HardwareSerial*>(_debugCom)) {
            hard->begin(115200);
        } else if (cdc = dynamic_cast<Serial_*>(_debugCom)) {
            cdc->begin(115200);
        }

    }

I haven't tested this, and I don't know if the Arduino's cut-down C++ library is even capable of it, but it's worth a try.

The other method is to *overload* the `.begin()` function of your class with multiple versions that take different parameters:

    void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

    void Esp8266::begin(HardwareSerial &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

    void Esp8266::begin(HardwareSerial &wifiCom, Serial_ *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

You're still storing them internally as `Stream` objects in all cases, but within the `begin()` function itself you also have them available as their child classes.  It does mean you have duplicate code copied between the different versions of `begin()`.  You could modularize it a little more though by moving the duplicated code into functions which would only need to be duplicated twice, not three times - one to act on a single `Serial_` object and one to act on a single `HardwareSerial` object:

    void Esp8266::initSerial(Serial_ *ser) {
        ser->begin(115200);
    }

    void Esp8266::initSerial(HardwareSerial *ser) {
        ser->begin(115200);
    }

    void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        initSerial(&wifiCom);
        initSerial(&debugCom);
    }
    ... etc x3 ...


message:
Powering arduino and sensors and motor damaging 16x2 LCD?

I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.

My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.

From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.

The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.

This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.

I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?

Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).

And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

body:
In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.

A few suggestions:

Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.

You should also check the pins for continuity errors, or shorts.

Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.

And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.

I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.

I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.


message:
Knowing the Ohms of a Radio Speaker

I have extracted a speaker frim a cheap radio. And I want to connect it to arduino uno. But, I dont know the rating of the speaker. And I am Afraid that If it is over rated, it can fry my arduino. The diameter of the speaker is 9 cm (approx). Whether this Speaker is more likely to be  of 4 ohms, 8 ohms, or 16 ohms ???
I dont have a multimeter...What cam be the probable value of speaker ?

body:
I googled "measure speaker resistance" and found http://www.wikihow.com/Measure-Speaker-Impedance

Step by step instructions

You will need a multimeter - a great thing to have in any case.


body:
I'm not aware of any simple rule that relates speaker diameter to speaker impedance.  Traditionally, 8 Ω is quite likely for typical cheap speakers, with 4 Ω not far behind in likelihood.

As pointed out in the [Measure Speaker Impedance](http://www.wikihow.com/Measure-Speaker-Impedance) link that AMADANON gave, the DC resistance of the speaker's coil will be somewhat lower than the speaker's AC  impedance.  The link suggests 6 Ω DC resistance for a speaker with 8 Ω impedance.

As far as driving the speaker from an Arduino output pin, all of the likely values of speaker impedance are too low to allow driving it directly.  Dividing the maximum allowed pin current of 40 mA into 5 V gives 125 Ω as the least resistance an Arduino output should ever see.  When I attach a speaker to an Arduino output, I usually put a 200 to 400 Ω resistor in series with it.  For my purposes (eg alert-buzzers) that gives enough volume without overstressing the Arduino.

If you still have the radio, look for a small transformer near the speaker connection.  If the radio has an audio output transformer, it probably will have a few KΩ of resistance in the primary and a low-resistance secondary.  If you attach the primary of that transformer to the Arduino pin you can deliver slightly more power to the speaker, but may need some  [clipping diodes](https://www.google.com/search?q=clipping+diodes&biw=1112&bih=593&tbm=isch&tbo=u&source=univ&sa=X&ved=0CCwQsARqFQoTCNXa8qC6yMcCFckziAodpccJmw) or [flyback diodes](https://www.google.com/search?q=clipping+diodes&biw=1112&bih=593&tbm=isch&tbo=u&source=univ&sa=X&ved=0CCwQsARqFQoTCNXa8qC6yMcCFckziAodpccJmw#tbm=isch&q=flyback+diodes) in the circuit to prevent damage from overvoltages.


message:
Function that returns a Structure

I want to create a structure called CarSpeed it has 4 int FR,FL,BR,BL (FrontRight,..) ; and i would like to create a function that returns this structure :

    ActualSpeed Readspeed(void)
    {
       code to read the speed of the car(already done)
    }

Can someone help me define a function that returns this structure  ? only the way how I should define it, the usual C way doesnt work :

    typedefstruct CarSpeed{...}

and then

    CarSpeed ActualSpeed;
    ActualSpeed Readspeed(void){.. }

body:
I would recommend to use pointers, it's faster and has the same result.

Something like this (disclaimer - I did not compile it):

    typedef struct {
       int a;
       int b;
    } pair;

    int init_pair(pair *ptr) {
       if (!ptr)
          return -1;
       ptr->a = 6;
       ptr->b = 9;
       return 0;
    }

    int do_something() {
       pair mypair;
       return init_pair(&mypair);
    }


body:
Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:

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

    struct CarSpeed
    {
        int fr, fl, br, bl;
    };

(Note that there's no need for `typedef`.)

You can then return an instance of it directly from your function:

    CarSpeed ReadSpeed()
    {
        CarSpeed data;

        data.fr = ...;
        data.fl = ...;
        data.br = ...;
        data.bl = ...;

        return data;
    }

You can call it from another function like this:

    CarSpeed speed = ReadSpeed();

That will copy the contents of the structure into an object called `speed`. In this example, it's an 8 byte structure so it's a non-trivial copy. That shouldn't be a big problem unless you're calling it very frequently though.

As noted in another answer, using a pointer (or a reference) can be more efficient if necessary.


message:
Can a WiFi enabled Arduino make a HTTPS request to my Web Server?

I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?

It only has to act as a client.

body:
It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.

[https://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino][1]

However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet).

[https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/][2]

  [1]: https://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino
  [2]: https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/


message:
How do I set the motor state to "HIGH" at the beginning of this sketch?

My intent with this sketch is to have motors run for one minute, then stand by for 18 minutes. In practice, the sketch starts the motor state at "low" for the OffTime interval, then goes to the OnTime interval and loops. The desired result is exactly the opposite: the "high" interval first, followed by the "low". I have tried setting the motorState to "HIGH" in the constructor and played with the order of the IF statements to no avail.

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis(). I need a solution which doesn't use delay but am having trouble wrapping my head around the logic of millis() as used. (I adapted this code from a tutorial.)

    class LifeTest
    {
      // Class member variables initialized at startup
      int motorPin;
      long OnTime;
      long OffTime;
      // These maintain the current state
      int motorState;                               // Used to set the motor.
      unsigned long previousMillis;                 // Stores last time motor was updated.

      public:
      LifeTest(int pin, long on, long off)
      {
        motorPin = pin;
        pinMode(motorPin, OUTPUT);

        OnTime = on;
        OffTime = off;

        motorState = LOW;
        previousMillis = 0;
      }

      void Update()
      {
        unsigned long currentMillis = millis();     // Check to see if it's time to change the motor state.
        if((motorState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
        motorState = LOW;                         // Turn off motor.
        previousMillis = currentMillis;           // Remember the time.
        digitalWrite(motorPin, motorState);       // Update the motors.
        }
        else if((motorState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
        motorState = HIGH;                        // Turn on motor.
        previousMillis = currentMillis;           // Remember the time.
        digitalWrite(motorPin, motorState);       // Update the motors.
        }
      }
    };

    LifeTest motor1(50, 60000, 1080000);
    LifeTest motor2(51, 60000, 1080000);
    LifeTest motor3(52, 60000, 1080000);
    LifeTest motor4(53, 60000, 1080000);

    void setup()
    {
    }

    void loop()
    {
      motor1.Update();
      motor2.Update();
      motor3.Update();
      motor4.Update();
    }

body:
just change the constructor to

      LifeTest(int pin, long on, long off)
      {
        motorPin = pin;
        OnTime = on;
        OffTime = off;

        previousMillis = 0;

        motorState = HIGH;
        pinMode(motorPin, OUTPUT);
        digitalWrite(motorPin, motorState);
      }


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

> I would appreciate any insight into this problem, as well as an intuition for the practical use of millis().

I have a lengthy tutorial about this at [How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink).

However as this site frowns upon link-only answers (the link might go down) I'll try to explain as well, here.

`millis()` is like having a wristwatch. You glance at it from time to time to see if it is time to do something, like catch a bus to work, put the dinner on, take the cake out of the oven, that sort of thing.

If you `delay()` all the time, you can only do one thing at a time. For example, if your cake takes 30 minutes to cook, and you do this:

    PutCakeInOven ();
    delay (30UL * 60 * 1000);  // delay 30 minutes
    TakeCakeOutOfOven ();

This is fine, but you aren't also cooking some eggs at the same time, or doing the dishes, right?

With `millis()` you can do lots of things! Win-win! The basic technique is to note the time when you started, and then when time is up, you do whatever-it-is you need to do. Like this:

    unsigned long BakeStartTime;
    const unsigned long CookingTime = 30UL * 60 * 1000;  // 30 minutes
    bool CakeInOven = false;

    void setup ()
      {
      PutCakeInOven ();
      BakeStartTime = millis ();  // when the cake went into the oven
      CakeInOven = true;
      }

    void loop ()
      {
      if (CakeInOven && (millis () - BakeStartTime >= CookingTime))
        {
        TakeCakeOutOfOven ();
        CakeInOven = false;
        }

      // do a whole lot of other stuff, like cooking some eggs

      }

You can expand this technique to do dozens of things "at once".


message:
Need help in modifying the design

I am planning to do a project on Sequential tilt motion lock using Arduino uno and accelerometer. I would like to present the accelerometer **within** a rotatable object. So what other components do i have to add to be able to do it i.e.. for wireless transmission of data from the object(that has the acc. meter) to the Uno board. [![Tilt lock circuit ][1]][1]

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

body:
If you do a google search for "arduino wireless serial" you'll get several results. Plugging them into the arduino should be trivial. Most suppliers (other than ebay) will also have examples for you to reference where it comes to coding your project to use the module.

You should also be aware that you will usually need a transceiver, and a receiver.

You might take a look into the XBEE solutions, as they appear to be popular.


message:
What are the basics in writing a program in Arduino?

I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...?

body:
There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects.  The most common method of programming is to use the free [Arduino IDE][1] which will talk to the board from your Mac or PC.  You can run the board straight from the USB port's power, or from an external source if you need it to be portable.

The programming language is very similar to C.  The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.

If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components.  [Fritzing][2] is a great board planner that you can install, or if you would rather, you can use [123D Circuits][3] from your web browser which will let you edit and simulated the circuits.

Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: http://fritzing.org/
  [3]: https://123d.circuits.io/


message:
Underwater positioning system (swimming pool)

I'm making a few experiments with a quite simple rover car I made using Arduino UNO and a few spare parts. Just for the heck of it I made it waterproof and now I want to toss it in my pool to make some underwater exploration. Maybe I'll fit some scrubers under it to make it easer to clean the floor.

My problem is: my rover navigates on its own, avoiding walls and objects using an ultrasonic sensor. But underwater the speed of sound goes up, and different qualities of water make it even harder for this system to work. Sometimes the pool is full of particles, and the scruber will probably worse the water quality around the robot.

My question is: what kind of system is better to navigate underwater, simply avoiding walls? The current behavor (on dry ground) is to turn to the right and go on when it finds a wall, I would like to keep this behavior, but underwater. As it's a simple toy, I'm hardly willing to spend a hundred bucks on a fancy laser proximity sensor, neither I need to map the entire pool with a single pulse, it should be a simple wall avoiding system.

Thank you!

body: How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


message:
How to differentiate between 2 Micros on Linux

I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine.  I need them to have unique serial ports.  Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).

This is the serial number that I get for both:

    $ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
      ATTRS{serial}=="0000:00:14.0"

Is there any way to manually set the serial number on an Arduino Micro?  Or is there any other unique identifying properties I can use for udev rules?

Typically, I do something like this in my ```/etc/udev/rules.d/99-usb-serial.rules``` file:

    SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

body:
The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.

So no matter which board you program it will get the same details as any other board of the same kind.

There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: `USB_VID` and `USB_PID`.

So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.

Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.


body:
That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.

Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: http://forum.arduino.cc/index.php?topic=503703.0

Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a  few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are *supposed* to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.

Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I *think* that's also true for the CP2102, but I'm not certain.

You *may* be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.


message:
String operators

I have a section of code that I am unsure of what it is doing.

    static int bufindw = 0;
    static char buffer[4][96];
    static char *strchr_pointer;
    int result;

    result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The part where I don't understand what is happening is `strchr_pointer - buffer[bufindw] + 1`. `strchr_pointer` and `buffer[bufindw]` will be strings. It gives the result I expect it to give because I know in the end it needs the correct index value in `buffer[][]` and in addition the number 1 is being added to it as well. How can a string minus a string?

body:
Let's break it down logically for you.

You have 4 strings, each capable of containing 96 characters:

    static char buffer[4][96];

That is a block of RAM that covers 4*96=384 bytes.  Let's say that block of ram starts at address 0x100.

    result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The phrase `buffer[x]` returns the address of the string number `x` in your array of strings.  It's the same as `&buffer[x][0]` - the address of the first character in string x.

You also have a pointer `strchr_pointer` which contains something - what that is I don't know because you haven't told us.  Chances are it's the result of a `strchr()` call, which:

> returns a pointer to the first occurrence of the character c in the string s.

So you have looked for a character in a string and found that it's at a specific address.  Let's say that's address 0x111 for the sake of argument.

Ok, so if we take `bufindw` as 0 for the first string in your array, and work from the inside out, we have:

*    buffer[bufindw] = 0x100
*    strchr_pointer = 0x111
  *    strchr_pointer - buffer[bufindw] = 0x111 - 0x100 = **0x11**
  *    strchr_pointer - buffer[bufindw] + 1 = 0x100 - 0x111 + 1 = **0x12**
*    Replace that into the function's parameters:
  *    &buffer[bufindw][strchr_pointer - buffer[bufindw] + 1] = &buffer[bufindw][0x12]

So you have the address of the 0x12'th (18th) character (or character number 16 since they count from 0 not 1), which is address 0x112.

That address is then passed to strtod() to convert it into a double-precision number:
    strtod(0x112, NULL);

That value is then cast to an integer:

    (int)strtod(0x112, NULL);

So the decimal portion is discarded (not rounded, chopped off).

Say your string contains: "`This is the value:23.83589743`" and is located at 0x100.

You use strchr() to find the first occurrence of ':', and it finds it at address 0x111, which is the 18th character of the string, so 0x100 + 17 = 256 + 17 = 273 = 0x111.  You subtract the start of the string and add one to it, so you end up with 18, which is the start of the numeric value (the 18th character).  The string from that point on contains "`23.83589743`".  That is then passed to `strtod()` and cast to an integer, and so is truncated to `23`.

It's not surprising you're confused, the whole thing can be re-written much simpler:

    strchr_pointer = strchr(buffer[bufdindw], ':');
    result = (int)strtod(strchr_pointer, NULL);

All that manipulating of the buffer address is like doing "x = 6 + y - 3 + 4 - 7" - completely pointless, since you might just as well write "x = y".


message:
Connecting a switch and a MOSFET to an Arduino?

I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.

I am using:

- Arduino Uno R3
- Magnetic Switch
- N-Channel MOSFET IRLB3034
- 5 Meter White LED Strip
- 12VDC 30W Power Supply
- 10k Ohm Resistors

My setup looks like this:
![breadboard diagram](https://i.stack.imgur.com/lDJYg.png)

Schematic:
![schematic](https://i.stack.imgur.com/y3mX4.png)

Code (if it helps):

    const int buttonPin = 2;     // the number of the switch pin
    const int ledPin =  9;      // the number of the LED pin

    // variables will change:
    int buttonState = 0;         // variable for reading the switch status
    int brightness = 0;
    int fadeAmount = 5;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

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

      // check if the switch is ON.
      // if it is, the buttonState is LOW:
      if (buttonState == LOW) {
        // fade LED on:
        analogWrite(ledPin, brightness);
        if (brightness < 255) {
          brightness = brightness + fadeAmount;
        }
      }
      else {
        // fade LED off:
        analogWrite(ledPin, brightness);
        if (brightness > 0) {
          brightness = brightness - fadeAmount;
        }
      }
      delay(30);
    }

I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.

body:
There is no need for the 10KOhm. MOSFETs are voltage controlled devices unlike transistors which need controlled current. I think your problem might be in debouncing of switch. You are probably getting some false positives which might be making your software go awry.
I recommend having a small debouncing routine. For eg - only if you find 3 successive positives will the switch press be termed a true positive or so.


body:
I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/FbvYW.png)

<!-- End schematic -->

How to make the diagram a bit smaller?


message:
What changed in the new Due?

I recently purchased a batch of Due boards and find that they are cosmetically different. After attaching the Atmel-ICE and reading the firmware from both processors, I find that the firmware is different. The green masked one had a sticker indicating a new IDE should be downloaded from arduino.

The back of the board shows silkscreen changes to the logo (DUE in an oval rather than rectangle) but both boards say BOARD MODEL DUE R3-E. The traces appear the same, the placement of parts appears the same, and other than different colored headers the parts are similar. The main processor has the same part number, but distinctly different markings. Internally the processors report the same device signature and revision.

What has changed in the firmware? Are there other changes I've missed? Other than needing an even newer IDE are there changes that will affect my sketches?

If I load the older firmware onto the newer Due processors, should it operate the same, allowing use of the old IDE, and in case my sketches do face a problem with the new version?

![enter image description here][1]

![enter image description here][2]

  [1]: https://i.stack.imgur.com/0RZid.jpg
  [2]: https://i.stack.imgur.com/Tla7u.jpg

body:
The 'new' board with green soldermask and the lighter headers is made by arduino.org.  The old one was probably made by the same company, but prior to the split in the founders.

Right now there is arduino.cc (the original website) and arduino.org (the website set up by the company that split from Arduino).  There is a lot of different perspectives about who really owns `Arduino` and I won't attempt to weigh in here.

The changes in firmware are still unknown.  It's likely that they are simple strings or response changes so the boards can be differentiated in software.  The `new` IDE is in alpha, and is yet another attempt to differentiate between the two Arduino groups.  I haven't attempted to program either with either group's IDE, but if I do I'll update this answer with the results.

At least there's a way to visually identify the difference once received - wish they had given them different part numbers so Digikey wouldn't have sent me a mixture...


message:
PPM from remote control is very noisy

I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this?
Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.)

My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.

My values are between 50 and 200

Where 140 is the preferred midpoint i'd like to work with.

This is my somewhat cryptic number line.

140 is in the middle. Where my window of stability is between 130 and 150

and values below 100 and above 180 are where the robot does some work.

50 ---x---<100-----130--<140>--150----180>---x---200

      /*

        Smoothing

        Reads repeatedly from an analog input, calculating a running average
        and printing it to the computer.  Keeps ten readings in an array and
        continually averages them.

        The circuit:
          * Analog sensor (potentiometer will do) attached to analog input 0

        Created 22 April 2007
        By David A. Mellis  <dam@mellis.org>
        modified 9 Apr 2012
        by Tom Igoe
        http://www.arduino.cc/en/Tutorial/Smoothing

        This example code is in the public domain.

      */

      // Define the number of samples to keep track of.  The higher the number,
      // the more the readings will be smoothed, but the slower the output will
      // respond to the input.  Using a constant rather than a normal variable lets
      // use this value to determine the size of the readings array.
      const int numReadings = 10;

      int readings[numReadings];      // the readings from the analog input
      int index = 0;                  // the index of the current reading
      int total = 0;                  // the running total
      int average = 0;                // the average

      int inputPin = A0;

      void setup()
      {
        // initialize serial communication with computer:
        Serial.begin(9600);
        // initialize all the readings to 0:
        for (int thisReading = 0; thisReading < numReadings; thisReading++)
          readings[thisReading] = 0;
      }

      void loop() {
        // subtract the last reading:
        total= total - readings[index];
        // read from the sensor:
        readings[index] = analogRead(inputPin);
        // add the reading to the total:
        total= total + readings[index];
        // advance to the next position in the array:
        index = index + 1;

        // if we're at the end of the array...
        if (index >= numReadings)
          // ...wrap around to the beginning:
          index = 0;

        // calculate the average:
        average = total / numReadings;
        // send it to the computer as ASCII digits
        Serial.println(average);
        delay(1);        // delay in between reads for stability
      }

also link to my code in github
https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino

Since this is being asked. Let me clarify on this black voodoo thing called a PPM.

Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.
The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels.
Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short.
-http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html

As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.

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

First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)

---

To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:

    // PPM generator

    const byte SIGNAL_PIN = 3;
    const int SIGNAL_COUNT = 6;
    const unsigned long PULSE_WIDTH = 300;  // µs
    const unsigned long BLANK_TIME = 25;    // ms
    const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 };

    void setup ()
      {
      pinMode (SIGNAL_PIN, OUTPUT);
      }  // end of setup

    void loop ()
      {
      delay (BLANK_TIME);
      digitalWrite (SIGNAL_PIN, HIGH);  // start
      delayMicroseconds (PULSE_WIDTH);
      digitalWrite (SIGNAL_PIN, LOW);   // end of start pulse

      for (byte i = 0; i < SIGNAL_COUNT; i++)
        {
        delayMicroseconds (widths [i] - PULSE_WIDTH);
        digitalWrite (SIGNAL_PIN, HIGH);  // start of pulse
        delayMicroseconds (PULSE_WIDTH);
        digitalWrite (SIGNAL_PIN, LOW);   // end of pulse
        }  // end of for loop

      delay (1000);
      }  // end of loop

This is intended to generate a series of pulses (six in this case) which might be generated by some fancy <s>toy</s> fun device.

---

Output from it:

[![PPM generator][1]][1]

As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.

*Note*: Output on pin 3 on the Uno.

---

Now we need a decoder. So let's use interrupts:

    const byte SIGNAL_PIN = 2;
    const int SIGNAL_COUNT = 6;

    volatile unsigned long widths [SIGNAL_COUNT + 1];
    volatile byte count;

    unsigned long lastPulse;

    // ISR
    void gotPulse ()
      {
      unsigned long now = micros ();

      // a long gap means we start again
      if ((now - lastPulse) >= 25000)
        count = 0;

      lastPulse = now;
      if (count >= (SIGNAL_COUNT + 1))
        return;

      widths [count++] = now;
      }

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      attachInterrupt (0, gotPulse, RISING);
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      }  // end of setup

    void loop ()
      {
      if (count >= SIGNAL_COUNT)
        {
        Serial.println (F("Got sequence."));
        for (int i = 1; i < SIGNAL_COUNT + 1; i++)
          {
          Serial.print ("Channel ");
          Serial.print (i);
          Serial.print (" = ");
          Serial.println (widths [i] - widths [i - 1]);
          }
        count = 0;
        }

      }  // end of loop

This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.

---

Results?

    Got sequence.
    Channel 1 = 612
    Channel 2 = 2020
    Channel 3 = 1016
    Channel 4 = 1512
    Channel 5 = 2220
    Channel 6 = 2428
    Got sequence.
    Channel 1 = 612
    Channel 2 = 2020
    Channel 3 = 1016
    Channel 4 = 1512
    Channel 5 = 2220
    Channel 6 = 2424
    Got sequence.
    Channel 1 = 616
    Channel 2 = 2020
    Channel 3 = 1012
    Channel 4 = 1516
    Channel 5 = 2220
    Channel 6 = 2424
    Got sequence.
    Channel 1 = 616
    Channel 2 = 2020
    Channel 3 = 1012
    Channel 4 = 1516
    Channel 5 = 2216
    Channel 6 = 2432

Highly consistent results, with a small error factor of around 16 µs compared to `600, 2000, 1000, 1500, 2200, 2400`

---

In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:

[![PPM Test setup][2]][2]

The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.

  [1]: https://i.stack.imgur.com/XBAjj.png
  [2]: https://i.stack.imgur.com/DxH0K.jpg


message:
Split a string as 2x16 for LCD

How do I split a string into two based on it's length to display on a 2x16 LCD?

I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?

Thanks

body: That's what <a href="https://www.arduino.cc/en/Reference/StringSubstring">`String::substring()`</a> is for. Simply take the first 16 characters and the characters from 16 to 32, and output them.


body:
String::Substring does take a start and an end value. So you can do something like this:

    String s1 = longtext.substring(0,15);
    String s2 = longtext.substring(16,31);


message:
How to sense mobile signal coming to a room using arduino uno

How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

body:
You can't.

Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".

And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".

What you *could* do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.


message:
Arduino, lcd 16x2 and UTP cable shows gibberish text?

I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.

I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.

Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?

Thanks!

body:
Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?

What is the impedance of your total length of cable?

These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


message:
Does the arduino board have to be always physically connected to the electronic device you are running?

If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

body:
If the "basic electronic board" is programmable, then yes, you can upload a program to it.

In general, though, "some LEDs" and similar devices are not programmable, and without something to *drive* them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the *brain* of the operation.  Remove the brain from someone and you'll find their body no longer functions.


body: And Arduino UNO is basically a ATMega328 chip (with some extras) on a circuit board. So if you add an ATMega328 to your own circuitboard, you don't need an Arduino Uno.


body:
If the question is "Can I program the Arduino without anything else connected to it?", then yes, you can program it with out the sound and light board connected. But the program will start running shortly after the upload finishes.

If some devices were connected to it and some were not, it's possible the program won't function properly at that point (and obviously the not-connected devices won't function at all!), so you should make sure the Arduino can't or won't try to do anything to the few connected ones that might be harmful when some others are not connected, in case that is possible (this would be an unusual, but plausible, situation).