# Question
Title: Problem with codebender project not compiling
I have written a codebender project which returns this error:

```
Oops! Looks like there was a serious issue with your project.

If you are not sure what could be wrong please contact us

/mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()':
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster'
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster'

```

What does it mean by `vtable`?

The code uses basic classes and inheritance.

The program is designed to select and play the game of your choice. I have only programmed the basic structure.

Class `games` contains a ref to the class `gamesMaster`.

Class `gamesMaster` contains a ref to `simpleTimer`.

Classes `playHiLow` and `playSimon` are children of `gamesMaster`.

Class `games` handles and input and outputs, `win` and `lose` control and keeps track of lives.

Class `gamesMaster` handles the `simpleTimer`, displays a new round, checks for the correct answer, and checks if game has finished successfully.

The `main()` function runs a routine in the `games` class.

The code is listed here: https://codebender.cc/sketch:144869

```
class simpleTimer
{
private:
    unsigned long _previousMillis;
    unsigned long _interval;

public:
    simpleTimer()
    {

    }
    void start(float mins)
    {
        _interval = (unsigned long) (mins * 60 * 1000);
        _previousMillis = millis();
    }
    bool stillRunning()
    {
        return (millis() - _previousMillis < _interval);
    }
};

class gamesMaster
{
public:
    unsigned short lives;
    gamesMaster()
    {
        timeOutTimer = new simpleTimer();
        gameTimer = new simpleTimer();
        gameTimer->start(1.5);
        lives = 5;
    }
    void right()
    {
        Serial.println("Correct");
    }
    void wrong()
    {
        Serial.println("Wrong");
    }
    void winGame()
    {
        Serial.println("**********");
        Serial.println("* WINNER *");
        Serial.println("**********");
    }
    void loseGame()
    {
        Serial.println("\\ /          \\ /");
        Serial.println(" X    LOST    X");
        Serial.println("/ \\          / \\");
    }
    void startTimeOut(float mins)
    {
        timeOutTimer->start(mins);
    }
    bool notTimedOut()
    {
        return timeOutTimer->stillRunning();
    }
    bool gameTimerOver()
    {
        return !gameTimer->stillRunning();
    }
    simpleTimer *timeOutTimer;
    simpleTimer *gameTimer;

    virtual void setupForNewRound(void);
    virtual bool checkAnswer(unsigned short);
    virtual bool reachedEnd(void);
};

class gameHiLow: public gamesMaster
{
public:
    gameHiLow() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(HiLow) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(HiLow) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(HiLow) End of game");
        return HIGH;
    }
};

class gameSimon: public gamesMaster
{
public:
    gameSimon() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(Simon) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(Simon) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(Simon) End of game");
        return HIGH;
    }
};

class games
{
private:
    unsigned short _gameToPlay;
    unsigned short _levelToPlay;
    gamesMaster *myGame;
    unsigned short _getAnswer()
    {
        if (Serial.available() > 0)
        {
            int inByte = Serial.read();
            Serial.println("  ->(games) Decode Answer");

            switch (inByte)
            {
                case '<':
                    return 1;
                    break;
                case '>':
                    return 2;
                    break;
            }

        }
        return 0;

    }
    bool _respond()
    {
        unsigned short answer;
        while(myGame->notTimedOut())
        {
            if((answer = _getAnswer()) != 0)
            {
                if(myGame->checkAnswer(answer) == HIGH) return HIGH;
            }
        }
        return LOW;
    }
public:
    games(unsigned short gameToPlay, unsigned short levelToPlay)
    {
        _gameToPlay = gameToPlay;
        _levelToPlay = levelToPlay;
        switch(_gameToPlay)
        {
            case 1:
                myGame = new gameHiLow();
                Serial.println(" ->(game) play Higher or Lower Game");
                break;
            case 2:
                myGame = new gameSimon();
                Serial.println(" ->(game) play Simon Game");
                break;
        }
    }
    void play()
    {
        unsigned short answer;
        while(!myGame->gameTimerOver())
        {
            myGame->setupForNewRound();
            myGame->startTimeOut(.5);
            if(_respond() == HIGH)
            {
                myGame->right();
                if(myGame->reachedEnd())
                {
                    myGame->winGame();
                    return;
                }
            }
            else
            {
                myGame->wrong();
                if(--myGame->lives <= 0)
                {
                    myGame->loseGame();
                    return;
                }
            }
        }
        myGame->loseGame();
    }
};

//////////////////////////////////////////////////////////////////////////////////
games *game;

void setup()
{
    Serial.begin(9600);
    unsigned short gameToPlay = 1;
    unsigned short levelToPlay = 1;
    game = new games(gameToPlay, levelToPlay);
}

void loop()
{
    Serial.println("Let the games begin");
    game->play();
    Serial.println("Program Complete");
    delay(5000);
    exit(0);
}

```

# Answer
> 1 votes
I agree with @GeryOshlike. But that's not the only option.

Yes, you can make them *pure virtual*:

```
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;

```

Or you can make them virtual with a default function:

```
virtual void setupForNewRound(void) { }
virtual bool checkAnswer(unsigned short) { return false; }
virtual bool reachedEnd(void) { return false; }

```

Pure virtual will complain when you compile if you haven't implemented those functions in your child class. By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.

If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route. If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.

# Answer
> 0 votes
As discussed here

https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable

declare these functions pure virtual:

```
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;

```

---
Tags: programming, c++
---


# Question
Title: Buzzer - Does the voltage change with the frequency?
So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?

Note that the project just says "buzzer" - not any more details.

Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

# Answer
No, the frequency of the "buzzer" has no relationship to the voltage.

The *duty cycle* of the generated tone is proportional to the *average voltage* though. Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave. This means that the *average* voltage is 50% of the supply voltage.

If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.

Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.

The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to *droop*. That has nothing to do with the frequency though and it would droop just the same at all frequencies. Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage. Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.
> 1 votes

---
Tags: frequency
---


title: Atmega328 board output voltage

text:
# Question
Title: Atmega328 board output voltage
I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?

Thanks in advance.

# Answer
> 2 votes
It depends on the input voltage you give it. If you run the ATMega328p at 3.3V then you get 3.3V out. If you run it at 5V you get 5V out.

A word of caution about running at lower voltages: The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).

---
Tags: atmega328
---


# Question
Title: adding a dead band to my motor and gearbox
I have a motor and gearbox that has limits and a pot built in.

I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.

I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.

I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.

I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.

How can I do that?

```
sensor       = pot on motor,
where        = 0 to 5 input,
vent1UPlim   = limits,
vent1DOWNlim = limits

```

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.

```
        //            pot           0-10v     ONE WAY
          if (sensorValue > (where + 0.5)) {
          if (digitalRead(vent1UPlim)==    HIGH) {
            DoneInitializationA=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMA ,       HIGH);
            mydisp.drawStr(0, 2, "-close-|");
          }
          else {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationA)
          {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationA=true;
          }
        }

           //                                   OTHER WAY
          if (sensorValue < (where - 0.5)) {
          if (digitalRead(vent1DOWNlim)==  HIGH) {
            DoneInitializationB=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMB ,       HIGH);
            mydisp.drawStr(0, 2, "-open -|");
          }
          else {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationB)
          {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationB=true;
          }
        }

```

# Answer
> 1 votes
The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.

eg.

```
if (abs (sensorValue - where) >= 0.5) {
  {
  // do something

  if (sensorValue > where)
    {
    // one way
    }
  else
    {
    // other way
    }
  } // end of large enough to worry about

```

---

In response to this (since deleted):

> would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up **and** down).

---
Tags: programming, arduino-mega, motor, arduino-motor-shield
---


title: Connecting to Arduino Ethernet Shield

text:
# Question
Title: Connecting to Arduino Ethernet Shield
How do I figure out how to connect to my arduino using ethernet shield?

It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.

The client example works, so it's not broken or anything.

I'm using `Arduino 1.6.5` IDE on a `Mega 2560`. I'm trying to run the `Examples/Ethernet/WebServer` example.

# Answer
Your question is kind of trivial, but from what I understood you're typing the IP address (that the Arduino displays on the serial monitor) into your browser.

First, make sure you connect your Ethernet shield to your router using an ethernet cable. (Now it's connected locally...)

Second, even if you type in your Arduino's IP address into the browser, the browser will return nothing because the Arduino simply has nothing to display, and hasn't been programmed to accept requests.

To actually have the Arduino display something you can try the Webserver example sketch or you can follow this great Tutorial that I found very useful for beginners.

BTW ports are only used to expose your Arduino to the Internet, in other words if you don't portforward to your Arduino, your Arduino won't be able to get requests from outside your local network (Wi-Fi,Ethernet).
> 1 votes

---
Tags: shields, ethernet
---


title: Is my Arduino Ethernet Shield broken?

text:
# Question
Title: Is my Arduino Ethernet Shield broken?
I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.

It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.

When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.

**The setup:**

I have followed an Adafruit guide, connecting the Arduino as such:

On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.

As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.

The LED strip is not too long - about 2 meters with about 150 LEDs.

**What I have tried:**

* When I detach the Arduino from my breadboard, the Ethernet Shield will still not connect
* I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
* I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
* I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?

# Answer
> 0 votes
I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.

150 LEDs takes way too much power for the arduino to handle as you can see here.

So you likely burnt something on your board and might have to replace it :/ make sure which board is damaged(the arduino itself or the shield) before replacing it.

If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.

Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).

---
Tags: power, ethernet
---


# Question
Title: How does RXD/TXD request signal look betwen 16u2 and 328p on oscilloscope?
I have a broken Arduino Uno. The man tells that he connected power supply and USB at the same time.

I got the new 16u2 (empty) chip. then asked my friend to re-solder it. He was using an air soldering station, but that did not work out. Then I try do that by myself. After 6 or 8 time I was successful. I think.

With stk500v2 programmer thru ICSP I burned in the hardware called:

```
Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

```

which I found in Arduino "hardware" folder.

I then burned bootloader to 328p controller:

```
optiboot_atmega328.hex

```

That hardware also from Arduino folder.

The problem is that I can upload sketch

```
error: avrdude: stk500_getsync(): not in sync: resp=0x00

```

meaning that device not recognizing.

My PC founds Arduino in device manager. 328p with ICSP programmable and working. (checked with blinking.hex 13 pin)

When pressing reset button the 13 led turns of then blinks fast several times that means the boot loader installed property.

Right after pressing upload the Rx blinks 3 times after that I am getting error.

Strange isn't it?

So what I what to know:

* I suppose the first must start blinking Tx led?
* Can anyone show me how must look like rxd txd interrupts?
* So about my assumption that I overheated 16u2 and it does strange things. What are you thinking about that?

# Answer
See screenshot below. The Rx on the Uno (incoming data) should flash first.

The programmer sends `STK_GET_SYNC` and the board replies `STK_INSYNC`:

```
Sent: STK_GET_SYNC / CRC_EOP  (30/20)
Got: STK_INSYNC / STK_OK (14/10)

```

Afterwards you see the bigger blocks on the lower line as the programmer sends the hex code to the board. Then about half-way through the bigger blocks are on the top as the board sends back the verification data (by reading the flash back).

The little blips would be the other side acknowledging a packet of data.

---

For more details see What happens when code is uploaded using the bootloader?
> 0 votes

---
Tags: arduino-uno, atmega328, bootloader
---


# Question
Title: 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.

# Answer
> 1 votes
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).

---
Tags: arduino-uno
---


# Question
Title: 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;
};

```

# Answer
> 1 votes
> 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.

---
Tags: arduino-uno, serial, c++, communication, memory-usage
---


# Question
Title: Arduino nano getting powered through analog input?
I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected. How can I fix this?

# Answer
Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.

Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.
> 2 votes

# Answer
This addresses a subset of your question which was covered in your added comment-question. I've addressed use of a 20V full scale input range to make the answer more general. The results would be "even better" for your 5V input case. Note that is Vin ~= 5V you would want a measurenet range somewhat above 5V max so that you can handle typical voltage variations.

> Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?

If you used a say 10k resistor in the upper leg of a voltage divider and added a MOSFET switch with an on resistance (Rdson) of 2 Ohms (a terrible spec) between Vin and the divider then the error introduced would be about 2/10k = 1:5000. If measuring a say 12V battery and using a Vinmax voltage of 20V the error in voltage measurement would be in the order of 20V/5000 = 4 mV. If using an Arduino Nano with a 10 but ADC the resolution (not accuracy) is 1 in 2^10 = 1:1024 or 20V/1024 = about 19 mV for a 20V input range. ie the resistor introduces an error of about 1/5th of a bit of available measuring accuracy. Worse (or better) - if you use 1% resistors they will swamp errors caused by ADC resolution. Even use of say 0.1% resistors or calibration is liable to produce a result where ADC resolution is not the main limiting factor.

Even with no resistive divider, getting accuracies that are doinated by the 1:1024 ADC resolution and not other factors takes care and effort. At 5V in ax ADC resolution of 1:1024 means that a variation of 1 part in 2048 could cause an erroneous reading. Input offset voltages, thermal effects, board and connector resistances and ground voltage dropsm and offsets can easily provide greater error magnitufes.

Test: Take a working design. Set meter to lowest voltage range such that 1 mV can easily be seen. (Ideally 200 mV range. 2V range marginally OK). Measure ground voltages between various "ground" points at various locations in the system. Differences ofm mV to 10's of mV can often be found. Differences are poptentially higher if power current are present - say 10's of mA or more.
> 0 votes

---
Tags: power, analogread, input
---


# Question
Title: 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: 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.

# Answer
> 0 votes
*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.

# Answer
> 0 votes
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!"*

# Answer
> 0 votes
The Mega has a reverse polarity protection diode (D1) on the board, so you plugging in the wrong polarity barrel didn't damage anything.

So your current problem in unrelated to this.

---
Tags: arduino-mega, power, bootloader, avrdude
---


# Question
Title: 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;
}

```

# Answer
You add the semicolon that is missing at the end of `long unsigned int t`
> 1 votes

# Answer
**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;

```
> 1 votes

# Answer
```
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.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: 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.

# Answer
> 2 votes
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 with a web search.

---
Tags: arduino-uno, sensors, current
---


# Question
Title: Compatibility between Particle Photon and Arduino
Is it possible to run Arduino on a Particle Photon?

I want complete software control over the device so I can connect it to the internet and do stuff without going through Particle's cloud, logins, etc.

# Answer
> 0 votes
You can use the new particle dev platform to do this https://www.particle.io/dev

---
Tags: wifi
---


# Question
Title: How useful could the Arduino Yun be in computer vision in a robotics project?
I've recently ordered an Arduino Yun and several other components to begin on a small robotics project (based on an old 4x4 RC Truck). Although not mandatory for what I'd like to do, I was wondering how feasible it would be to mount a small camera or two and write some software for the Linux portion of the Yun to do basic image/video analysis such as face detection and computer vision based path finding?

Mostly this is a question about the processing power capabilities of the Yun. Has anyone had any luck doing simple image analysis/recognition on this processor?

(Also, if anyone with 150+ rep could edit this to create and add the "computer-vision" tag that would be great)

# Answer
It probably has enough memory and speed to run basic object recognition software, but I there's a better solution, and that's to do your image capture and your object recognition with another device, and use the Arduino to act on the incoming data in some way. That would give you enough juice to do object tracking or searching. I plan to do this for my copter gimbal hopefully to be able to track objects on the ground, like criminals running from the cops for example.

This product will work great for that. Since you need a camera anyway, I think this is a pretty good deal... http://petapixel.com/2013/09/01/pixy-low-cost-camera-recognizes-follows-objects-color/

Can be purchased here: http://www.adafruit.com/products/1906

AdaFruit has tutorials to help you get started. (Computer-vision doesn't exist as a tag right now and I can't create it, but I tried, sorry)
> 3 votes

# Answer
For this application the Arduino YUN is the worst possible solution because

* **Low** RAM
* **Terrible** Processor
* No storage (you can add a microSD card though)
* **High** Cost

The raspberry Pi 2, UDOO, RADXA, Ordio, pretty much anything with a **quad core processor** and **1GB of RAM** will do a **decent job**.

Face detection is RAM intensive, so you will need to worry about it lagging.

Alternatively you could also have the image processing part be done elsewhere like on a server (on a local network this could be your laptop) or something.

**Personally**,I would never recommend the Arduino YUN because it just simply isnt worth paying the 75$ for when for about the same price you could have a arduino pro micro and a raspberry pi (with a WiFi adapter, mircoSD card etc.) which is capable of doing probably way more than you actually need to.
> 2 votes

# Answer
Maybe you can consider adding Raspberry Pi board to run OpenCV which is well supported by hundreds of books and tutorials. See 20 tutorial from initial setting up to running typical functions in http://www.stemapks.com/opencv.html

Also, http://opencv-srf.blogspot.hk/

Then, there are many examples / tutorial / book on linking Arduino to RPi.

On the other hand, from web demo, Pixy CMUcam5 seems very good as a semi-ready-made solution. Watch the demo and see if it does what you want. If yes, then, it is easy solution. OpenCV is a library, it can do many tricks but need learning.

Hope this helps
> 1 votes

# Answer
I am guessing not very useful. Image recognition is quite CPU-intensive, and Arduinos are slow, memory-starved, 8-bit processors.

The Unix side of the Yun runs at 400 MHz, which is quite a bit faster than the Arduino part, but still quite slow compared to a mobile phone or desktop computer. And 64MB of RAM isn't enough to hold even a single HD image, never mind the data you would need to have in RAM to do image analysis. You'd probably have to limit yourself to 640x480, and the slow processor and lack of enough flash for large code libraries would be a problem. (You've only got 16 MB of flash memory on the LINUX processor.) I don't know if you can run programs from an SD card or not. That might solve your code storage problems, but you're still going to struggle with 64 MB of RAM.
> 0 votes

---
Tags: arduino-yun, robotics, signal-processing
---


# Question
Title: Arduino Hardware timer and interrupts issue
I recently started programming with Arduino and and currently I'm making a project to read RPM and Speed of my car using Arduino Uno. So far I got everything working but the speed value does not show properly. I have used one hardware counter and two interrupts in this project.

1. Timer 1 on pin 5 - Count pulses from car's ECU to calculate speed.
2. Int0 on pin 2 - Read ignition pulse to calculate RPM.
3. int1 on pin 3 - 5v in from headlight switch to control the brightness of the display (MAX729 7 seg 8 digit).

I can get the proper reading from RPM and also the brightness control is working properly. Here is my codes below.

```
    #include <LedControl.h>

// inputs: DIN pin, CLK pin, LOAD pin. number of chips
LedControl display = LedControl(12, 10, 11, 1);

//SPEEDO-----------------------------------------------------------
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
int kph;
int roundedKph;
int previousKph;
int prevCount;
//----------------------------------------------------------------

//RPM-------------------------------------------------------------
//Configuration for the Tachometer variables
const int sensorPin = 2;
const int sensorInterrupt = 0;
const int timeoutValue = 5;
volatile unsigned long lastPulseTime;
volatile unsigned long interval = 0;
volatile int timeoutCounter;
int rpm;
int rpmlast = 3000;
int rpm_interval = 3000;
//---------------------------------------------------------------

//Brightness control---------------------------------------------
int brightnessIndicator = 13;  //Light pin 13 led to show that brightness control is in action.
int brightnessIn = 3;  //Sensor in from headlight positive wire to control the brightness.
//---------------------------------------------------------------

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

  display.shutdown(0, false);  // turns on display
  display.setIntensity(0, 10); // 15 = brightest
  printTrueno(); //Print my car's name
  delay(3000);
  initToZero(); //Print all zeros before going to the loop

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero

  //Config for the Tach
  pinMode(sensorPin, INPUT);
  attachInterrupt(sensorInterrupt, &sensorIsr, RISING);
  lastPulseTime = 0;
  timeoutCounter = 0;

  //Config for brightness control
  pinMode(brightnessIndicator, OUTPUT);  //LED output
  pinMode(brightnessIn,INPUT);  //Sensor in
  attachInterrupt(1, changeBrightness, CHANGE);  //Attach the 2nd interrupt
  changeBrightness();  //Check for head lights on or not.
}

void loop() {
  //SPEEDO-----------------------------------------------------------
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph. 10x allows retaining 10th of mph resolution.
  kph = ((unsigned int) mph)*1.6; // Convert to kph and cast to integer.

  int x = kph / 10;
  int y = kph % 10;

  // Round to whole mile per hour
  if(y >= 5){
    roundedKph = x + 1;
  }
  else {
    roundedKph = x;
  }

  //If kph is less than 1 kph just show 0kph.
  //Readings of 0.9kph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  if(x < 2){  // 1 was triggered by some noise signal.
    roundedKph = 0;
  }

  // Don't display kph readings that are more than 50 kph higher than the previous reading because it is probably a spurious reading.
  if(roundedKph < 181){
    if((roundedKph - previousKph) > 50) {
      Serial.println(previousKph);
      printNumber(previousKph, 0);
    }
    else {
      Serial.println(roundedKph);
      printNumber(roundedKph, 0);
    }
  }

  previousKph = roundedKph; // Set previousMph for use in next loop.
  //-----------------------------------------------------------------

  //RPM--------------------------------------------------------------
  if(rpm >= 0) {  //Remove the minus values

    //Let's keep this RPMr value under control, between 0 and 9999
    rpm = constrain (rpm, 0, 9999);

    //If the engine is not running, print 0
    if ((micros() - lastPulseTime) < 5e6 ) {
      rpm = rpm;
    }
    else {
      rpm = 0;
    }

    if (rpm < 250)
      rpm = 0;
    //Serial.println(rpm);
    printNumber(rpm, 1);
  }
  //-----------------------------------------------------------------
}

//Each time the interrupt receives a rising tach signal, it'll run this subroutine
void sensorIsr() {
  unsigned long now = micros();
  interval = now - lastPulseTime;
  if (interval > 5000){
     rpm = 61000000UL/(interval * 2);
     lastPulseTime = now;
  }
}

void changeBrightness() {
  int val = digitalRead(brightnessIn);  //Read the sensor value

  if(val == 1){  //If the headlights are on, pin goes HIGH.
    digitalWrite(brightnessIndicator, HIGH);   //turn the LED on
    display.setIntensity(0, 6); //Reduce the brightness.
  }
  else {
    digitalWrite(brightnessIndicator, LOW);    //turn the LED off
    display.setIntensity(0, 14);  //increase the brightness.
  }
}

void printNumber(int v, int flag) {
    int ones;
    int tens;
    int hundreds;
    int thousands;

    if (flag==0){
      ones = v%10;
      v = v/10;
      tens = v%10;
      v= v/10;
      hundreds = v;

      //Now print the number digit by digit
      if (hundreds>0)
        display.setDigit(0,0,(byte)hundreds,false);
      else
        display.setChar(0,0,' ',false);

      display.setDigit(0,1,(byte)tens,false);
      display.setDigit(0,2,(byte)ones,false);
    }
    else if (flag=1) {
      ones = v%10;
      v = v/10;
      tens = v%10;
      v = v/10;
      hundreds = v%10;
      v = v/10;
      thousands = v%10;

      //Now print the number digit by digit
      display.setDigit(0,4,(byte)thousands,false);
      display.setDigit(0,5,(byte)hundreds,false);
      display.setDigit(0,6,(byte)tens,false);
      display.setDigit(0,7,(byte)ones,false);
    }
}

```

I think the problem is between Timer1 and first interrupt. Can someone please help me to solve this?

Thank you very much.

# Answer
> 2 votes
I think you made a mistake in the program design. You have things backwards, and your tach interrupts are messing with program flow because they are happening too fast.

The tachometer runs 0~100 rev/sec. Send the pulses to the counter and, twice a second, multiply the count by 120 and display the RPM. You only care what the RPM is to the nearest hundred, anyway, right?

You get an ECU pulse every ~0.4m traveled. Record the interval (x ms) between pulses in your interrupt routine. 0.4m/x ms * 1 km/1000 m * 3,600,000 ms/hr = ~1448/x km/hr. Do the (expensive) division, using the last interval recorded, twice a second when you update the RPM.

Now your interrupt routine is getting called every 12ms, tops, instead of 8ms typical. And, your main loop is running at a steady 500 ms.

# Answer
> 1 votes
```
else if (flag=1) {

```

should be

```
else if (flag==1) {

```

What else would flag be anyway? Why not just use "else"?

---

```
 // Don't display kph readings that are more than 50 kph higher than the previous reading because it is probably a spurious reading.
  if(roundedKph < 181){
    if((roundedKph - previousKph) > 50) {
      Serial.println(previousKph);
      printNumber(previousKph, 0);
    }
    else {
      Serial.println(roundedKph);
      printNumber(roundedKph, 0);
    }
  }

  previousKph = roundedKph; // Set previousMph for use in next loop.

```

In the code above you admit roundedKph might be wrong, but use it anyway for next time around the loop. That means next time around you will discard a correct reading.

---

```
   //If the engine is not running, print 0
    if ((micros() - lastPulseTime) < 5e6 ) {
      rpm = rpm;
    }

```

What does that achieve?

---

```
int rpm;

```

That should be **volatile**.

---
Tags: arduino-uno, interrupt, timers
---


title: Removing the barrel jack connector?

text:
# Question
Title: 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?

# Answer
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.
> 5 votes

# Answer
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
> 2 votes

# Answer
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)
> 1 votes

# Answer
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.
> 0 votes

---
Tags: power
---


# Question
Title: 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);
}

```

# Answer
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
> 3 votes

---
Tags: programming, arduino-mega, sketch, arduino-motor-shield
---


# Question
Title: 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];
    }
  }

}

```

# Answer
> 0 votes
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);

```

---
Tags: arduino-uno, midi
---


title: Request for member is Non-class type

text:
# Question
Title: 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) {
  ;
  }
}

```

EDIT 1: Updated image with new code

Why is not picking up the begin function?

# Answer
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*:

```
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 ...

```
> 2 votes

# Answer
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;

```
> 1 votes

# Answer
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.
> 0 votes

---
Tags: c++, arduino-leonardo
---


# Question
Title: 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!

# Answer
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.

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 votes

---
Tags: serial, shields, uploading
---


title: Knowing the Ohms of a Radio Speaker

text:
# Question
Title: 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 ?

# Answer
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.
> 1 votes

# Answer
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 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 or flyback diodes in the circuit to prevent damage from overvoltages.
> 1 votes

---
Tags: arduino-uno
---


title: Function that returns a Structure

text:
# Question
Title: 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){.. }

```

# Answer
> 3 votes
Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:

```
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.

# Answer
> 1 votes
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);
}

```

---
Tags: arduino-mega
---


# Question
Title: 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.

# Answer
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.

How to get HTTPS on Arduino?

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/
> 0 votes

---
Tags: wifi, web
---


# Question
Title: 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...?

# Answer
> 2 votes
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 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 is a great board planner that you can install, or if you would rather, you can use 123D Circuits 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.

---
Tags: arduino-uno
---


# Question
Title: 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!

# Answer
> 1 votes
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.....

---
Tags: arduino-uno, sensors, proximity
---


# Question
Title: 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:

Schematic:

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.

# Answer
> 1 votes
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?

simulate this circuit – Schematic created using CircuitLab

How to make the diagram a bit smaller?

# Answer
> 0 votes
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.

---
Tags: led, mosfet
---


title: Arduino GSM Module with network GPS

text:
# Question
Title: Arduino GSM Module with network GPS
I have looked through the AT command set of Arduino GSM Shield boards. I dont find any AT command that provides network GPS. I wonder what I am missing. Why isn't it possible for GSM module to provide NetworkGPS (the one that is not really accurate) ?

# Answer
> 1 votes
Simple answer is that it is function of cellular network (phone company) instead of the module.

More informative answer is, Position is calculated by network via

1. serving cell base station ID and location
2. when phone on standby, it monitors signal strength from multiple base stations and signal strength is roughly related to distance
3. when phone on transmitting, base station has one more piece of information. It calculates distance through time taken for signal to travel to multiple base stations (called 'time advance' in original GSM)

US E911 utilizes these to locate the phone.

Good technical paper with diagrams https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0CEUQFjAF&url=https%3A%2F%2Fwww.fig.net%2Fpub%2Fcostarica\_1%2Fpapers%2Fts08%2Fts08\_01\_schwieger\_2407.pdf&ei=Ms3bU8-DItfr8AXT7oLQCg&usg=AFQjCNHImn4G34WC0Naw8IH6g1gfLzykuQ&bvm=bv.72197243,d.dGc

http://en.wikipedia.org/wiki/Positioning\_%28telecommunications%29

# Answer
> 1 votes
This is a very complicated situation. In short, the module itself does not provide Assisted GPS without both the handset's help, and the help of the carrier.

Since the module is sold as an OEM or embeddable object, the manufacturer either hasn't included such functionality, or hasn't enabled it, or hasn't documented it.

Even if it were included, enabled, and documented, it has to work with the carrier, and each carrier provides different services for different modules. Some locate solely based on triangulation using cell towers and the module's command channel. Others depend on the module capturing a short sequence of RF from the GPS network, sending it to the carrier's AGPS server to be processed, which then reports back a very accurate position.

At any rate, this is not a standardized function for embedded cellular modules because cellular networks and carriers vary in how they've chosen to implement AGPS.

If you want to use AGPS in an embedded cellular module, you'll need to work with both the module manufacturer and the cellular carrier to enable that functionality. It usually involves additional charges - renting an AGPS server, for instance. These often involve a monthly fee in addition to a per-request fee. Some companies set up their own AGPS servers to do the processing, but the cellular company still has to provide gross location information based on the tower signal reception.

Suffice to say, this is not something that is common or cheap enough for low volume projects. Unless you're going to be working with thousands of these devices it's typically cheaper to integrate a standalone GPS chipset in your device.

---
Tags: gsm, arduino-nano
---


title: What changed in the new Due?

text:
# Question
Title: 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?

# Answer
> 1 votes
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...

---
Tags: arduino-due, bootloader, firmware, revisions
---


title: String operators

text:
# Question
Title: 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?

# Answer
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".
> 1 votes

---
Tags: string, pointer
---


# Question
Title: 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();
}

```

# Answer
> 1 votes
> 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.

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".

# Answer
> 0 votes
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);
  }

```

---
Tags: motor, millis
---