# Question
Title: How to add data without pre-defining variables?
I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.

What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello `w`, your ID number is `xxx xxx xxx xxx xxx`.

So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?

Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

# Answer
Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.

As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

---

## For those who don't know

In C, data relevant to an object can be stored in a structure, or `struct`. You can put all sorts of different types of data in a struct, like so:

```
struct personalProfile {
    char    firstName[8];
    char    lastName[8];
    uint    cardID;           // 'uint' is an unsigned int...
    bool    accessAllowed;
};

```

You can then use that structure to create a 'personal profile' for however many people you want:

```
// within your main program:

struct personalProfile Person1;
struct personalProfile Person2;

// Now you can directly access individual aspects as so:

Person1.firstName = "John";
Person1.lastName = "Brown";
Person1.accessAllowed = TRUE;

Person2.firstName = "Dodgy";
Person2.lastName = "Dave";
Person2.accessAllowed = NOT_A_HOPE_IN_HELL;

```

You can use the *members* of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.

The best way to store multiple instances of a particular variable type is in an array:

```
struct personalProfile listOfPeople[5];

```

You now have an array of five (blank) `struct`s, which can be accessed by `listOfPeople[n].firstName = Potato;`, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.

An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five `struct`s in it you can't add or remove any. One solution is to create a massive array, and set all the values in each `struct` to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.

Next comes containers. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

---

## EEPROM basics

The EEPROM library that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.

Using the function `EEPROM.put(address, data)` you can put ANY data type - an `int`, `char` or - you guessed it - a `struct` into the EEPROM, starting at the byte specified by *address*. Of course there has to be enough space so you can't put an `int`, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)

So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.

```
// within main program

struct personalProfile Person1;
struct personalProfile Person2;

// fill in the details for Person 1...
// fill in the details for Person 2...

// ...then put Person1 in the EEPROM at address 0.
EEPROM.put(0, Person1);

// Done. Now put in Person2. But where?
// You need to make sure you put them AFTER Person1.

int AddressJump = sizeof(personalProfile);

// AddressJump now equals how many bytes are need to store one person.

EEPROM.put(AddressJump, Person2);

```

Simple as that.

If you create a Person3, you're going to need to put them `sizeof(personalProfile)` bytes AFTER Person2, i.e. `EEPROM.put(AddressJump*2, Person3);`. So, you add Person*N* to address `AddressJump * (N-1)`.

Retrieving data is the same principle, except you use `EEPROM.get()`:

```
// provided you've used the above snippet somewhere to actually
// populate the EEPROM with something!

struct personalProfile personA;

EEPROM.get(0, personA);

Serial.print("Person A is called:");
Serial.println(personA.firstName);

```

Again, you're going to need `sizeof(personalProfile)` to read the second, third, or *N*th person. If you 'send `EEPROM.get()` to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't `put` one person on top of another (you could get in trouble for that) and you don't want to `get` someone that isn't there.

---

## List management

This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.

Your first task is to determine what sort of array you want. Inevitably it's going to be a Linked List. This is an array of `structs`, where each `struct` element in the list *contains the memory address of the following element*, thus the list is **linked**. You need to consider:

1. How the array will be linked (if at all);
2. Whether or not the array is space-critical (does it have to be as small as possible);
3. Where the array is going to start;
4. How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!
> 2 votes

# Answer
The "key" is creating a means to access a table of IDs that you can search through for a given name or a given ID number. There are various ways of doing this and if you are unclear on these that can be discussed in due course. But, to start, I'll assume that making and searching some form of table or array is not a problem for you.

You obviously MUST have enough storage space for the maximum number of simultaneous IDS that you wish to store at any time. Call this "IDCount".

You can allocate IDCount ID storage locations by whatever means suits you.
In unused locations you store a dummy or null ID number.
eg ID 000 000 000 000 000 is probably invalid so can be used as an 'empty' indicator.

To add a new ID either search through your table of IDs for an empty location and store the new ID there. To find a given ID match you search the table for the ID and , if it exists, retrieve the matching name.

---

**"Improvements":**

**To reduce access times** when the potential entries are large you can store all entries "at the bottom" and have a pointer to the 1st free location. New entries are added "at the end". If an entry is removed, all entries above it are moved down by one. eg if entry N is removed:
for (entry \>= N and entry \< end\_pointer)
...move entry N + 1 into location N
...and step N by 1.

Another method is to use a "**linked list**" where each entry has a pointer to the next entry in the list. New entries take an address from the empty\_locations list and add their address to the used\_locations list. Removed entries do the opposite. This can be fast and effective but also mind blowing for beginners and, when it goes wrong it can go VERY wrong. Best avoided initially.

The simple "search for 1st empty entry" method will usually work very well.
> 1 votes

---
Tags: arduino-uno, c++, rfid, variables
---


title: Shortening large chunks of code

text:
# Question
Title: Shortening large chunks of code
Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.

```
long turn1;
long turn2;
long turn3;
long turn4;
long turn5;
long turn6;
long turn7;
long turn8;
long turn9;
long turn10;
long turn11;
long turn12;
long turn13;
long turn14;
long turn15;

```

#################

```
  turn1 = random(sizeof(turns) / sizeof(char*));
  turn2 = random(sizeof(turns) / sizeof(char*));
  turn3 = random(sizeof(turns) / sizeof(char*));
  turn4 = random(sizeof(turns) / sizeof(char*));
  turn5 = random(sizeof(turns) / sizeof(char*));
  turn6 = random(sizeof(turns) / sizeof(char*));
  turn7 = random(sizeof(turns) / sizeof(char*));
  turn8 = random(sizeof(turns) / sizeof(char*));
  turn9 = random(sizeof(turns) / sizeof(char*));
  turn10 = random(sizeof(turns) / sizeof(char*));
  turn11 = random(sizeof(turns) / sizeof(char*));
  turn12 = random(sizeof(turns) / sizeof(char*));
  turn13 = random(sizeof(turns) / sizeof(char*));
  turn14 = random(sizeof(turns) / sizeof(char*));
  turn15 = random(sizeof(turns) / sizeof(char*));

```
\#
```
if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

```
\#
```
lcd.print(turns[turn1]);
lcd.print(turns[turn2]);
lcd.print(turns[turn3]);
lcd.print(turns[turn4]);
lcd.print(turns[turn5]);
lcd.setCursor(0, 2);
lcd.print(turns[turn6]);
lcd.print(turns[turn7]);
lcd.print(turns[turn8]);
lcd.print(turns[turn9]);
lcd.print(turns[turn10]);
lcd.setCursor(0, 3);
lcd.print(turns[turn11]);
lcd.print(turns[turn12]);
lcd.print(turns[turn13]);
lcd.print(turns[turn14]);
lcd.print(turns[turn15]);

```

# Answer
> 6 votes
Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.

You can read good information on arrays **here**, and 'for loops' **here** (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the **tutorial series** that the two aforementioned links are part of.

I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you *still* don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.

To declare an array of *N* variables, all of which are the same type, you use:

```
<type> <name_of_variable> [<number_of_elements>];

or:

long turns[15];

```

Now you have an array of 15 `long`s. Ta da!

You now have to set the values of each turn. As your values are all the same (if you ignore the fact that `random()` ultimately leaves you with different values) you can use a **for loop**:

```
for (int x=0; x<15; x++)
{
    turns[x] = random(sizeof(turns) / sizeof(char*));
}

```

I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.

That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your *if* statement, I don't actually know what you plan to do if any two adjacent `turn` elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to *N-1* th element, where *N* is the total number of elements:

```
for (int x=0; x<14; x++)
{
    if (turns[x] == turns[x+1])
    {
        turns[x+1] = random(sizeof(turns) / sizeof(char*));
    }
}

```

You need make sure that `turns[x+1]` is not outside of the array, which is why the for loop runs for one iteration less than there are elements.

The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:

```
for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,2);
for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,3);
for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
    lcd.print(turns[x]);

```

All done.

---
Tags: code-optimization
---


# Question
Title: How do I know how many memory that Arduino is use after my code is running for a few time
When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.

How do I know the current size of memory that Arduino is use?

I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.

Note: I am using the Board: Arduino Mega 2560.

I read the question and the answer for Measure SRAN usage

In the question @fuenfundachtzig ask:

***Can I determine how much SRAM I have left in the live system?***

In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.

I am tryin to know in an specific time what is the size of my memmory.

### example...

```
void setup() { //doing some configuration };

void loop() {  // invoke some functions and evil function  };

// in other place a evil function

void evil(){
MyClass * instance = new MyClass();
//play with the instance and it class create other instances....
//and a dynamic memmory is used but not deleted.
}

```

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

# Answer
Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.

You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).

You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.
> 1 votes

---
Tags: arduino-mega, memory-usage
---


title: Cleaning up code? Removing repetition?

text:
# Question
Title: Cleaning up code? Removing repetition?
I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.

Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code.

Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.

In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!

Any suggestions are welcome.

Thanks in advance.

Example code:

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>

boolean runMotor1 = false;
boolean Motor1Running = false;
unsigned long Motor1StartMillis;
unsigned long Motor1RunTime = 5000;

boolean runMotor2 = false;
boolean Motor2Running = false;
unsigned long Motor2StartMillis;
unsigned long Motor2RunTime = 10000;

//etc etc etc up to 10 Motors

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1);
Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2);

void setup()
{
  Serial.begin(9600);
  AFMS.begin();
  runMotor1 = true;  // set condition to true for testing
  runMotor2 = true;
}
void loop()
{
/// Motor1 START
  if (runMotor1 == true) {
     Serial.println("Run Motor 1!");
     runMotor1 = false;
    MotorMotor1->setSpeed(255);
    MotorMotor1->run(FORWARD);
    Motor1StartMillis = millis();
    Motor1Running = true;
  }

  if( Motor1Running && (millis()-Motor1StartMillis > Motor1RunTime) )
  {
    Serial.println("Motor1 Time Elapsed!");
    MotorMotor1->setSpeed(0);
    MotorMotor1->run(RELEASE);
    runMotor1 = false;
    Motor1Running = false;
  }

  /// Motor 2
    if (runMotor2 == true) {
     Serial.println("Run Motor 2!");
     runMotor2 = false;
    MotorMotor2->setSpeed(255);
    MotorMotor2->run(FORWARD);
    Motor2StartMillis = millis();
    Motor2Running = true;
  }

  if( Motor2Running && (millis()-Motor2StartMillis > Motor2RunTime) )
  {
    Serial.println("Motor2 Time Elapsed!");
    MotorMotor2->setSpeed(0);
    MotorMotor2->run(RELEASE);
    runMotor2 = false;
    Motor2Running = false;
  }

}

```

Thanks for reading, and thank you for any input you may have. Steve

# Answer
> 2 votes
You are perfectly right, a class would help simplify your code. Here is a tentative class that should work for what you are doing:

```
class Motor
{
public:
    Motor(const char *_name, Adafruit_DCMotor *_motor,
          unsigned long _runTime)
    : name(_name), startNow(false), running(false),
      runTime(_runTime), motor(_motor) { }
    void start() { startNow = true; }
    void update();
private:
    const char *name;
    boolean startNow;
    boolean running;
    unsigned long startTime;
    unsigned long runTime;
    Adafruit_DCMotor *motor;
};

```

Most of this is almost copy-paste from your actual code, except for your `runMotorX` variables that I renamed `startNow`, which seemed more appropriate.

Beware that the name of the motor is copied as a pointer. Thus you should better call the constructor with a literal string (like `"the name"`) as a first parameter. Otherwise it would be more appropriate to allocate memory and copy the characters themselves, but I like to avoid dynamic memory allocation on an Arduino if I can.

Now, all the code that you have in `loop()` for each motor would be the Motor's `update()` method:

```
void Motor::update()
{
    if (startNow) {
        Serial.print("Run ");
        Serial.print(name);
        Serial.println('!');
        startNow = false;
        motor->setSpeed(255);
        motor->run(FORWARD);
        startTime = millis();
        running = true;
    }

    if (running && (millis()-startTime > runTime))
    {
        Serial.print(name);
        Serial.println(" Time Elapsed!");
        motor->setSpeed(0);
        motor->run(RELEASE);
        running = false;
    }
}

```

With this class, your code would now look like:

```
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor m1("Motor 1", AFMS.getMotor(1),  5000);
Motor m2("Motor 2", AFMS.getMotor(2), 10000);
//etc etc etc up to 10 Motors

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    m1.start();
    m2.start();
}

void loop()
{
    m1.update();
    m2.update();
}

```

Of course, when you get to 10 motors, this would still be annoying repetition. You can simplify further by putting the motors in an array and looping through it:

```
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor motors[] = {
    Motor("Motor 1", AFMS.getMotor(1),  5000),
    Motor("Motor 2", AFMS.getMotor(2), 10000)
    //etc etc etc up to 10 Motors
};
#define NUM_MOTORS (sizeof motors / sizeof motors[0])

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].start();
}

void loop()
{
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].update();
}

```

---
Tags: code-optimization
---


# Question
Title: Call a class method from inside the same class
If i have file cSpeedOfSound.h:

```
#ifndef cSpeedOfSound_h
#define cSpeedOfSound_h
#include "Arduino.h"
#include "math.h"
class cSpeedOfSound{
    public:
        cSpeedOfSound(float *i,float *C);
    private:
        float *C;
        float *a;
        float *i;
    };
#endif

```

and file cSpeedOfSound.cpp:

```
#include "cSpeedOfSound.h"
cSpeedOfSound::cSpeedOfSound(float *i,float *C){
    //some code...
    *C =roundto(*C,2);}
float cSpeedOfSound::roundto(float x,float dp){
return (round(x*pow(10., dp)) / pow(10., dp));}

```

where i want to run function roundto inside class, but it doesnt seems to work. So what im making wrong and how to do it properly?

Ps: Im begginer to arduino (want it to learn robotics + C language) and know python (learnd for about 1+ year), so pls do not hate me if i made crucial mistakes.

# Answer
You need to include `roundto()` in your class declaration, e.g. something like this:

```
class cSpeedOfSound {
public:
    cSpeedOfSound(float *i,float *C);

private:
    float roundto(float x, float dp);

    float *C;
    float *a;
    float *i;
};

```

In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.

---

As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called `i` and `C`, **and** you have totally separate function parameters called `i` and `C`. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.
> 3 votes

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


# Question
Title: Power source for Arduino uno, sparkfun usb shield and adafruit motor shield
I'm having trouble powering my boards altogether. Right now, I'm using 8x AA batteries to power everything. Running my arduino with one shield runs fine, but not with both shields stacked on top of my arduino. I've even tried powering it with an extra 4x AA batteries on my motor shield, but it still won't run. The way it's stacked is; arduino uno board, usb host shield then motor shield.

# Answer
> -1 votes
Its a very bad idea to power everything from the same battery source. Most motors, especially ESP, generate large current spikes, rather than draw a small current throught. AA batteries are not designed for this.

You can get away with using AA batteries for micro-controllers, shields. However, keep motors on a sweater power supply. There are batteries for specific motor types, and these will typically have a high current rating. Of course, without a circuit diagram, I cannot go into details. I'll update my answer when you do.

---
Tags: arduino-uno, power, motor, shields, battery
---


title: Storing and parsing data with Arduino

text:
# Question
Title: Storing and parsing data with Arduino
I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:

```
client.println("GET http://ramp.local/api/actions?");

```

The response I get is:

```
[{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
{"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
{"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
{"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

```

How to collect a data in a string variable and parse it to get `action_status`?

# Answer
> 0 votes
Ideally, you would use a proper recursive JSON parser, like the one suggested in prakharsingh95's answer. However, if code speed and size are critical considerations, and if the format of the response is narrowly constrained, then you can build a fast special-purpose parser.

Here is a simple example. It assumes the response has been stored in the `response` char array:

```
static const char key[] = "\"action_status\"";
const char *p, *q;
char action_status[16];

for (p = response; ; p = q) {
    p = strstr(p, key);    // find key
    if (!p) break;         // not found
    p = strchr(p, ':');    // find ':' between key and value
    p = strchr(p, '"');    // find opening quotes for the value
    q = strchr(p+1, '"');  // find closing quotes

    // Report finding.
    strncpy(action_status, p+1, q-p-1);
    action_status[q-p-1] = '\0';
    Serial.print("Found action status: ");
    Serial.println(action_status);
}

```

Of course, in production code you would check that every `strchr` call returns a non-NULL pointer. And you would check that the status you found fits in your buffer.

**Edit** about the pros and cons of this method:

Compared to a proper JSON parser, this approach will give you smaller and faster code, the drawback is it being more *fragile*. For example, this will not detect a corrupted JSON, and it will return garbage if the action\_status happens to be a number instead of a string, or is a string with embedded double quotes, or if the string "action\_status" appears as a value of some other field... A full JSON parser should correctly handle all these cases.

On a non-embedded computer, a proper JSON parser would probably be the only appropriate answer. On a constrained microcontroller environment, you sometimes have to make trade-offs. In this particular instance, the “best” answer depends on how much you weight speed and size vs. robustness against unexpected input.

# Answer
> 0 votes
I would recommend a JSON parsing library. Checkout https://github.com/bblanchon/ArduinoJson

```
var response = [] ; // get response here
int response_length = 4; //Put length of the response array here
StaticJsonBuffer<200> jsonBuffer;

String action_ids[] = new String[response_length];
String action_types[] = new String[response_length];
String action_statuses[] = new String[response_length];
String ramp_ids[] = new String[response_length];
String user_ids[] = new String[response_length];

for (int i=0; i < response_length ; i++) {
    JsonObject& data = jsonBuffer.parseObject(response[i]);
    // Note the '&' above

    action_ids[i] = data["action_id"];
    action_types[i] = data["action_type"];
    action_statuses[i] = data["action_status"];
    ramp_ids[i] = data["ramp_id"];
    user_ids[i] = data["user_id"];
}

```

Of course, you only need to extract those fields that you need.

# Answer
> 0 votes
Try this on for size.

This is an arduino based, open source, JSON processor.

---
Tags: arduino-uno
---


# Question
Title: What is the difference between file.print() and file.write()
From here I think I understand the difference between Serial.write and Serial.print, but is it the same when writing to a file in a SD card for example. Does it mean that File.write saves bytes in the file instead of text?

# Answer
The File class inherits from the Stream class, which in turn inherits from the Print class.

The Serial class inherits from the Stream class, which in turn inherits from the Print class.

`print()` and `write()` are defined by the Print class.

So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().
> 3 votes

---
Tags: sd-card
---


# Question
Title: Sketch stops working after ~40 minutes. Overflow?
I have this simple sketch I use on Arduino Micro:

```
int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
unsigned long prevMicros = 0;        // will store last time LED was updated  +
unsigned long interval =  7000000;           // lunghezza della pausa in secondi
unsigned long intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
 pinMode(fan, OUTPUT);
 pinMode(led, OUTPUT);
 prevMicros = micros();
}

void loop() {
  unsigned long currMicros = micros();

  // manage overflow? BOH
   if (ledState == HIGH && (((unsigned long)(currMicros  - prevMicros)) >= intervalON)){
     prevMicros = currMicros;
      ledState = LOW;
    }
    else if (ledState == LOW && (((unsigned long)(currMicros - prevMicros)) >= interval)){
      ledState = HIGH;//riparte
      prevMicros = currMicros;
    }

    digitalWrite(led, ledState);
    digitalWrite(fan, ledState);
}

```

I could use `millis()` instead of `micro()`, but I decided to keep this to shorten the overflow rate (should be 72 minutes). I shall go back to `millis()` once my issue is fixed.

The sketch works as expected, turning on the LED for a second every 7, but **the sketch hangs after 40 minutes**. Can you tell me why, and how to manage overflow properly? Why is it hanging after 40 and not 72 minutes? Thanks

# Answer
When comparing time intervals, use unsigned long instead of long.

```
if ( ... (((unsigned long)(currMicros - prevMicros)) >= intervalON) )

```

The time counter overflows at some point -- micros() overflows after 70 minutes, milis() overflows after nearly a month -- but these are unsigned values.

When an unsigned value is interpreted as a signed value -- `(long)` instead of `(unsigned long)` -- then half of the values are interpreted as negative numbers. So after 40 minutes, the micros() value looks like a negative number, and the (curr-prev) \>= interval comparison returns false. After 70 minutes, the micros() overflows back to 0, and the signed comparisons work as expected.

The solution is to use unsigned long for all delta-time comparisons.

This is easier to see if you consider a smaller, 3-bit number: there are 8 values for a 3-bit number. If the 3-bit number is unsigned, then the values are 0, 1, 2, 3, 4, 5, 6, 7. But if the 3-bit number is signed, then those same binary code numbers are interpreted as 0, 1, 2, 3, -4, -3, -2, -1. Same principle for int and long values, just a larger range of values.

EDIT:

Based on your comment below, I did some testing on my own hardware (Sparkfun "red board" Arduino UNO R3 clone), and added some code to help make it more testable. Some highlights:

1. Added a diagnostic LED on Arduino pin 9, to indicate when the timer overflow has happened (i.e. new time is less than previous time).
2. Added a mask to force the timer overflow to happen sooner, so I don't have to wait an hour to verify whether the code had any effect.
3. Calculated timeSinceLastChange and applied mask, to handle overflow.
4. Added TIMER\_DATATYPE based on jippie's comment

The complete code:

```
//--- based on comment from jippie about using C++ standard width integer types
// #define TIMER_DATATYPE unsigned long
#define TIMER_DATATYPE uint32_t

//--- MarkU: diagnostic LED to indicate that timer overflow happened.
// Comment out this line for normal operation.
#define DIAGNOSTIC_LED_TIME_OVERFLOW 9
//---

//--- MarkU: diagnostic: force timer overflow to happen sooner.
// This must be significantly longer than the intervals being measured.
// Must be a binary all-1's bitmask.
// 0x3FFFFFF overflow after approximately 1 minute
// 0xFFFFFFF overflow after approximately 5 minutes
// 0xFFFFFFFF overflow after approximately 70 minutes
#define DIAGNOSTIC_TIMER_OVERFLOW_MASK 0x3FFFFFF
//---

int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
TIMER_DATATYPE prevMicros = 0;        // will store last time LED was updated  +
TIMER_DATATYPE interval =  7000000;           // lunghezza della pausa in secondi
TIMER_DATATYPE intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);

  //--- MarkU: diagnostic LED indicate that timer overflow happened
#if DIAGNOSTIC_LED_TIME_OVERFLOW
  pinMode(DIAGNOSTIC_LED_TIME_OVERFLOW, OUTPUT);
  digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, LOW);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
  //---

  prevMicros = micros();
}

void loop() {
  TIMER_DATATYPE currMicros = micros();

  //--- MarkU: diagnostic: force timer overflow to happen sooner
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
  currMicros = (TIMER_DATATYPE)(currMicros & ((TIMER_DATATYPE)DIAGNOSTIC_TIMER_OVERFLOW_MASK));
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK

  //--- MarkU: consolidate time delta calculation
  TIMER_DATATYPE timeSinceLastChange;
  if (currMicros < prevMicros) {
    //--- MarkU: handle timer overflow
#if DIAGNOSTIC_LED_TIME_OVERFLOW
    digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, HIGH);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & DIAGNOSTIC_TIMER_OVERFLOW_MASK;
#else // DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & 0xFFFFFFFF;
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK
  } else {
    timeSinceLastChange = currMicros - prevMicros;
  }
  //---

  // manage overflow? BOH
  if (ledState == HIGH && (timeSinceLastChange >= intervalON)) {
    prevMicros = currMicros;
    ledState = LOW;
  }
  else if (ledState == LOW && (timeSinceLastChange >= interval)) {
    ledState = HIGH;//riparte
    prevMicros = currMicros;
  }

  digitalWrite(led, ledState);
  digitalWrite(fan, ledState);
}

```
> 1 votes

---
Tags: arduino-micro
---


# Question
Title: How to int variables with similar names without tons of code?
I'm using `int` with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:

```
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int led8 = 9;
int led9 = 10;
int led10 = 11;
int led11 = 12;
int led12 = 13;
int led13 = 45;
int led14 = 46;

```

is there any way to not do this? Also, to define them as output, is there any way to avoid using `pinMode(***, OUTPUT)` 14 times as well?

# Answer
The word you are looking for is *array*.

An *array* is like a list of values all of the same type. For instance, your LED pins could be specified as:

```
int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

```

You can then access the LEDs by number. Note that arrays *start counting from zero* not from one, so you would have:

```
leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

```

It's great for using them in an array:

```
for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

```

If the values are never going to change, as in this case since they are pin numbers, the array should be declared *const* so it doesn't take up any of your precious RAM:

```
const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

```

Also you should get into the habit of tailoring the data types to the expected values. If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8\_t".

```
const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

```

An *int* takes two *bytes*, so using *int* when you can get away with *uint8\_t* means you're wasting half the memory.
> 4 votes

---
Tags: code-optimization
---


# Question
Title: IDE to program Arduino Uno especially internal interrupt vectors
I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?

What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.

Suggestions?

# Answer
> 1 votes
You can do all you need to do in the Arduino IDE. It doesn't "block" you from doing any low-level operations. Any other IDE will also allow you to do what you want.

All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.

http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p\_datasheet.pdf

---
Tags: arduino-uno, arduino-ide, interrupt, ide, atmel-studio
---


# Question
Title: Why are LED's receiving different voltages connected to Arduino
I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:

```
  digitalWrite(blue1, HIGH);
  digitalWrite(green1, HIGH);

  digitalWrite(blue2, HIGH);
  digitalWrite(green2, HIGH);

```

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

Why is this happening and how do I get them all to light up the same?

# Answer
> 3 votes
After trying another Arduino I realized the problem. I did not use `pinMode` in the setup for all of the pins. Darn.

---
Tags: arduino-uno, led
---


# Question
Title: Serial.println Sensor Value and text in one line
**How do I put the sensor value and text on the one line in the serial monitor.**

I just want Pot Value 30 to show in the serial console. What am I doing wrong?

```
Serial.println("POT value ")(sensorValue);

```

# Answer
> 1 votes
You just do two Serial prints:

```
Serial.print("POT value ");
Serial.println(sensorValue);

```

The `.print` prints without moving to a new line, the `.println` moves to a new line.

If you want to be more fancy and don't mind the processing and memory overhead, you can use `snprintf` to format the string:

```
char temp[15];
snprintf(temp, 15, "POT value %4d", sensorValue);
Serial.println(temp);

```

You can read more about `sprintf` and formatting here:

**Note that there is no floating point support in the standard library for the Arduino - so you can't use %f etc.**

---
Tags: arduino-uno, serial, arduino-ide
---


# Question
Title: control Arduino board using Android sensors and wifi?
i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control ) so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ??

# Answer
Is it possible? Yes, it's certainly possible. You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB. The Arduino can be programmed to respond to what it gets through the serial.

Is it easy? Well, that depends on how good you are at Android programming.

One good place to start might be the ArduinoFirmata-Android project. Don't worry about programming the Arduino, just install Firmata on it. Then it's all down to how you program the Android device. The Arduino just becomes a peripheral to your phone.
> 0 votes

---
Tags: sensors, wifi, android
---


# Question
Title: What is the most memory-friendly way to declare integer literals?
I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:

```
for(byte i=0;i<16;i++) buf[i]=(char)ap1[i];

```

Would it make any difference if I declared the integer literal 16 as a constant?

```
const byte BUFSIZE=16;

```

Or using the preprocessor:

```
#define BUFSIZE 16

```

There's also the macro `PROGMEM` which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.

```
const byte BUFSIZE PROGMEM=16;

```

AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.

This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use

# Answer
> 2 votes
Well, it's easy to just try and see... Let's try the following program:

```
#ifdef USE_CONST
const byte BUFSIZE = 16;
#else
#  define BUFSIZE 16
#endif

char buf[BUFSIZE], ap1[BUFSIZE];

int main(void)
{
    for (byte i = 0; i < BUFSIZE; i++)
        buf[i] = ap1[i];
    return 0;
}

```

I compiled this for an Uno both with and without `#define USE_CONST`, and it doesn't make any difference! avr-size reports the same sizes for both versions, and the generated assemblies are identical: the optimizer transformed the loop into something like

```
byte *Z = ap1;
byte *X = buf;
do {
    *X++ = *Z++;
} while (Z != ap1 + 16);

```

where X and Z are two of the CPU's pointer registers, and `ap1 + 16` is an *immediate* constant, i.e. part of the instruction itself, c.f. the AVR addressing modes.

It is worth noting that, in C++, `const` implies internal linkage. Thus a const global variable is very much like a preprocessor constant.

This is unlike C, where you would need to qualify the variable as `static const` in order to get the same behavior. Otherwise the compiler would need to allocate storage to `BUFSIZE`, just in case it is referenced as `extern` from another source file, even though it can replace occurrences of `BUFSIZE` *in the same file* with its immediate value.

On the other hand, the Arduino IDE compiles your code with -ffunction-sections -fdata-sections and links it with --gc-sections, which means the linker will eventually get rid of the unused reserved storage.

# Answer
> 3 votes
I'm not familiar with the Atmel megaAVR microcontrollers or Arduino. But generally speaking, your memory optimization ideas are misguided.

For example, it's likely that the compiler implements local loop variables within a register so that they don't consume any RAM at all.

And the integer literal constants, such as 16 from your example, also likely don't consume any RAM. The compiler likely incorporates these constants into the code.

Whenever you optimize something it's best to go after the big fish first. You're focusing on the tiniest fish. To find the big fish, look at the \*.map file produced by the linker. The map file should show how much RAM and Flash memory is used by your program. The RAM sections might be labeled "bss" and "data" in the map file. Hopefully the map file will also detail how much RAM is used by each compilation unit. Find the compilation units that are using the most RAM and focus on them. Maybe there are large buffers or arrays defined in those compilation units that can be reduced in size or redesigned.

The map file is also where you could check to see if your optimizations have made any difference. For example, try some of the optimization you described and see whether the map file changes significantly.

# Answer
> 2 votes
Yes, defining "const byte bufsize" would make a difference - it'll use one additional byte of SRAM. All variables are stored in RAM unless they're annotated as being PROGMEM.

A #define gets translated into its value by the preprocessor, and so looks the same to the compiler.

Your constant '16' isn't taking up any SRAM in the first place; look elsewhere (at actual variables) if you need to optimise.

String literals are treated the same way as arrays of any numeric type: they're copied to SRAM on startup because the code has to be able to dereference the pointer (which is what myarray\[x\] does) and find the location in RAM. Single numeric constants do not have this issue - they're value types - and so don't get copied into RAM.

---
Tags: sram
---


# Question
Title: Arduino compatible's serial port not showing Mac OSX
I bought an Arduino-compatible Freaduino board atmega8 (I selected the board type as Arduino ng or older atmega8). I installed the Arduino IDE on Mac OS X and the FTDI drivers. But my serial port looks like this when I connect the board:

And when I try to upload the program, this is the error I get:

Can someone tell me what is the mistake? I am clueless.

**UPDATE**: the problem was I had not installed the driver properly (I guess). I uninstalled and reinstalled them and it worked perfectly. Also made a YouTube tutorial regarding the same. http://youtu.be/BwatajQO\_88

# Answer
> 8 votes
From the OSX System Report we learn that your board is based on an SiLabs CP2102 converter (or workalike), but according to your question you installed the drivers for an entirely different product from FTDI

(Arduino.cc has used FTDI in the past and CDC/ACM today, I don't believe they have ever used SiLabs so their instructions probably don't cover that, but other vendors obviously have)

Install the CP2102 drivers and it should work if you use the /dev/tty.XX device which then appears when you plug in the board.

SiLabs appears to provide the drivers at

http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx

Just for sake of completeness, there are *at least* 5 distinct protocols/chips in use for serial-like USB communication with embedded devices:

* FTDI
* CDC/ACM Virtual Com Port
* SiLabs CP210x
* Prolific PL-2303
* ch340

(Additional possibilities could include actual RS232 serial or serial-over-bluetooth)

# Answer
> 5 votes
just to add to the list - some cheaper boards use **CH340** chipset

here is a blogpost on how to install the drivers on OSX http://javacolors.blogspot.ie/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html

From that post:
You can find drivers for this chip on the web site of the chinese manufacturer, here :
http://www.wch.cn/downloads.php?name=pro&proid=5

# Answer
> 0 votes
http://arduino.cc/en/guide/macOSX

That link should almost definitely get it working for you. Ensure (as in Step 7) that the board you have is the same one that is selected in Tools-\>Board.

And in step 8, since you have connected via a USB cable, it should be one of the USB named options.

# Answer
> 0 votes
If you still have problems, like me after following the above, this might help: From this thread: http://forum.arduino.cc/index.php?topic=292284.msg2229300#msg2229300

> the problem is in the spaces of the device name. To fix that you have to manually edit two (2) txt files of the arduino installation.
>
> Go where you have installed it. In my case the path is:
>
> /Users/MY\_USERNAME/Downloads/Arduino.app/Contents/Java/hardware/arduino/avr
>
> Inside this directory you can see files platform.txt & programmers.txt.
>
> Inside these files replace -P{serial.port} with "-P{serial.port}". So you simply have to add the quotes.

Then restart.

---
Tags: uploading, arduino-ide, avrdude, avr, mac-os
---


title: What's wrong with my Arduino board?

text:
# Question
Title: What's wrong with my Arduino board?
When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?

# Answer
Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.

When you disconnect the board, the fuse will reset.

So either the board is faulty of the connection you made to it are.
> 0 votes

---
Tags: arduino-uno
---


title: Aduino 7 segment dice project

text:
# Question
Title: Aduino 7 segment dice project
I am struggling with the code that I should write for my project. I finished my breadboard but I have never learnt programming before so I cannot write the program for the dice. My project is to make the dice output random numbers when the button is pressed. This is what I have completed already. I just want to know how to complete the program to make it work for my arduino.

This is the code so far:

```
int leda = 2;
int ledb = 3;
int ledc = 4;
int ledd = 5;
int lede = 6;
int ledf = 7;
int ledg = 8;
int ledh = 9;
int leda1 = A0;
int ledb1 = A1;
int ledc1 = A2;
int ledd1 = A3;
int lede1 = A4;
int ledf1 = A5;
int ledg1 = A6;
int ledh1 = A7;

void setup()
{
    Serial.begin(9600);
    pinMode(leda, OUTPUT);
    pinMode(ledb, OUTPUT);
    pinMode(ledc, OUTPUT);
    pinMode(ledd, OUTPUT);
    pinMode(lede, OUTPUT);
    pinMode(ledf, OUTPUT);
    pinMode(ledg, OUTPUT);
    pinMode(ledh, OUTPUT);
    pinMode(leda1, OUTPUT);
    pinMode(ledb1, OUTPUT);
    pinMode(ledc1, OUTPUT);
    pinMode(ledd1, OUTPUT);
    pinMode(lede1, OUTPUT);
    pinMode(ledf1, OUTPUT);
    pinMode(ledg1, OUTPUT);
    pinMode(ledh1, OUTPUT);

    pinMode(12, INPUT);

    digitalWrite(12, HIGH);
}

if (number == 1)
{
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
}

else if (number == 2)
{
    digitalWrite(3, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    delay(200);
}
else if (number == 3)
{
    digitalWrite(3,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(200);
}

else if (number == 4)
{
    // do number 4
}

else if (number == 5)
{
    // do number 5
}

// ... etc
// Additional 'numbers' have been removed for brevity

```

# Answer
> 2 votes
## About random numbers

What you are trying to achieve is actually not that easy. An Arduino is basically a computer, and as any computer, it is designed to execute instructions in a very *deterministic* fashion. Computers are not good at randomness and, unless fitted with dedicated hardware, they *cannot* generate random numbers. Given this, you are left with two options:

1. pseudo-random number generators
2. entropy gathering

The first is the easiest:

```
int first_dice  = random(1, 7);  // 1 (inclusive) to 7 (exclusive)
int second_dice = random(1, 7);

```

and voilà! You have two random-looking numbers. They are random-looking in the sense that you will find no obvious pattern in any sequence of numbers you draw. However, if you reset your Arduino, either with the reset button or by power-cycling it, it will give you the *exact same sequence* as in the first run. Thus, pseudo-randomness in useless unless you commit to never unpower your circuit. It is a good starting point, however, if your main goal is to get started with Arduino programming.

Entropy gathering means getting some randomness from outside the Arduino: you would connect it to some source of randomness and perform some measurement that has unpredictable outcome. A human being is a good source of randomness: if you require the user to press a button before displaying the dice value, the timing of the button press is a good random source. The `micros()` function can be used to get the current time with 4 µs resolution, which is more than enough for this purpose. Entropy gathering is usually used in tandem with pseudo-random number generators, as a way to *seed* them, like this:

```
wait_for_the_user_to_press_a_button();
randomSeed(micros());
int first_dice =  random(1, 7);
int second_dice = random(1, 7);

```

If you cannot have human interaction, you could try to get some electromagnetic noise by performing an `analogRead()` on a floating pin. Ideally you would connect that pin to an analog noise source. See the first comment to this answer for more information on this option.

## About arrays and loops

You should definitely try to find a good tutorial about arrays and loops. Whenever you find yourself writing tons of almost-identical lines of code, you should wonder whether you can replace that repetition with a loop. For example, for displaying the digit `1`, you may write:

```
if (number == 1) {
    digitalWrite(leda,  LOW);
    digitalWrite(ledb, HIGH);
    digitalWrite(ledc, HIGH);
    digitalWrite(ledd,  LOW);
    digitalWrite(lede,  LOW);
    digitalWrite(ledf,  LOW);
    digitalWrite(ledg,  LOW);
}

```

(I am using the "canonical" A–G letter assignments, and yes, you should also take care of setting to `LOW` the segments you want to be off). This code is an obvious candidate for being replaced by a loop:

```
if (number == 1) {
    for (int segment = 0; segment < 7; segment++)
        digitalWrite(leds[segment], digit1[segment]);
}

```

This requires that you first define the following arrays:

```
//                A     B     C     D     E     F     G
int leds[]   = {  2,    3,    4,    5,    6,    7,    8 };
int digit1[] = { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW};

```

This logic can be pushed one level further by using a two-dimensional array (an array of arrays): instead of defining six arrays `digit1`, `digit2`... `digit6`, you create an array of arrays like this:

```
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         ...
};

```

and you use `digits[number]` instead of `digit1`, etc. This way you get rid of the whole `if () ... else if ()` chain, replaced by:

```
for (int segment = 0; segment < 7; segment++)
    digitalWrite(leds[segment], digits[number-1][segment]);

```

Take care though that in C++ arrays are indexed from zero, which is why you need to use `number-1` as the index in `digits`. If you have more than one die (which is your case), you can also put their pin assignments in a two-dimensional array. Then all the dice updating code would be wrapped inside a loop indexed by the die number. Putting all this together you end up with something like this:

```
// Pin assignments.
int leds[][7] = {
   /*                A     B     C     D     E     F     G  */
   /* 1st die */  {  2,    3,    4,    5,    6,    7,    8 },
   /* 2nd die */  { A0,   A1,   A2,   A3,   A4,   A5,   A6 }
};

// 7-segment "font".
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         /* 3 */  {HIGH, HIGH, HIGH, HIGH,  LOW,  LOW, HIGH},
         /* 4 */  { LOW, HIGH, HIGH,  LOW,  LOW, HIGH, HIGH},
         /* 5 */  {HIGH,  LOW, HIGH, HIGH,  LOW, HIGH, HIGH},
         /* 6 */  {HIGH,  LOW, HIGH, HIGH, HIGH, HIGH, HIGH}
};

void setup()
{
    for (int die = 0; die < 2; die++) {
        for (int segment = 0; segment < 7; segment++) {
            pinMode(leds[die][segment], OUTPUT);
        }
    }
}

void loop() {
    for (int die = 0; die < 2; die++) {
        int number = random(1, 7);
        for (int segment = 0; segment < 7; segment++)
            digitalWrite(leds[die][segment], digits[number][segment]);
    }
    delay(200);
}

```

This is still lacking the entropy gathering phase discussed above.

# Answer
> 1 votes
I made it so at least it compiles. It should loop through the numbers.

As for the circuit; you really should add a resistor to every segment, instead of just one the the common cathode. Otherwise the brightness will be different if more segments are on.

```
int number = 1;
int number1 = 1;

int leda = 2;
int ledb = 3;
int ledc = 4;
int ledd = 5;
int lede = 6;
int ledf = 7;
int ledg = 8;
int ledh = 9;

int leda1 = A0;
int ledb1 = A1;
int ledc1 = A2;
int ledd1 = A3;
int lede1 = A4;
int ledf1 = A5;
int ledg1 = A6;
int ledh1 = A7;

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

    pinMode(leda, OUTPUT);
    pinMode(ledb, OUTPUT);
    pinMode(ledc, OUTPUT);
    pinMode(ledd, OUTPUT);
    pinMode(lede, OUTPUT);
    pinMode(ledf, OUTPUT);
    pinMode(ledg, OUTPUT);
    pinMode(ledh, OUTPUT);

    pinMode(leda1, OUTPUT);
    pinMode(ledb1, OUTPUT);
    pinMode(ledc1, OUTPUT);
    pinMode(ledd1, OUTPUT);
    pinMode(lede1, OUTPUT);
    pinMode(ledf1, OUTPUT);
    pinMode(ledg1, OUTPUT);
    pinMode(ledh1, OUTPUT);

    pinMode(12, INPUT);
    digitalWrite(12, HIGH);
}
void loop() {

    // turn off all leds
    digitalWrite(leda, LOW);
    digitalWrite(ledb, LOW);
    digitalWrite(ledc, LOW);
    digitalWrite(ledd, LOW);
    digitalWrite(lede, LOW);
    digitalWrite(ledf, LOW);
    digitalWrite(ledg, LOW);
    digitalWrite(ledh, LOW);

    digitalWrite(leda1, LOW);
    digitalWrite(ledb1, LOW);
    digitalWrite(ledc1, LOW);
    digitalWrite(ledd1, LOW);
    digitalWrite(lede1, LOW);
    digitalWrite(ledf1, LOW);
    digitalWrite(ledg1, LOW);
    digitalWrite(ledh1, LOW);

    if (number == 1)
    {
        digitalWrite(leda, HIGH);
        digitalWrite(ledf, HIGH);
        delay(200);
    }
    else if (number == 2)
    {
        digitalWrite(ledb, HIGH);
        digitalWrite(leda, HIGH);
        digitalWrite(ledd, HIGH);
        digitalWrite(ledh, HIGH);
        digitalWrite(ledg, HIGH);
        delay(200);
    }
    else if (number == 3)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(leda,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        delay(200);
    }
    else if (number == 4)
    {
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(leda,HIGH);
        digitalWrite(ledf,HIGH);
        delay(200);
    }
    else if (number == 5)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        delay(200);
    }
    else if (number == 6)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        digitalWrite(ledh,HIGH);
        delay(200);
    }

    if (number1 == 1)
    {
        digitalWrite(A4, HIGH);
        digitalWrite(A1, HIGH);
        delay(200);
    }
    else if (number1 == 2)
    {
        digitalWrite(A5, HIGH);
        digitalWrite(A4, HIGH);
        digitalWrite(A7, HIGH);
        digitalWrite(A0, HIGH);
        digitalWrite(A2, HIGH);
        delay(200);
    }
    else if (number1 == 3)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A4,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 4)
    {
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A4,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 5)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 6)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A0,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }

    number = (number%6) + 1;//show next number the next loop
}

```

---
Tags: programming, led, atmega328
---


# Question
Title: analogRead-ing Potentiometer Values in void setup()
I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button \[indicating the beginning of the loop()\], and the speedometer would begin measuring and displaying his or her speed.

This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.

Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.

Thanks!

# Answer
You presumably know that: The easiest and usual way to read a potentiometer is to connect the "track" between V\_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.

The use of analogRead() is valid in setup.

However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

---

eg

void setup() {

... boolean initialised = false ; ... }

void loop() { if (initialised == false) {
// initialise speedo
// .... initialised = true; }

...

} // end of loop()

}
> 1 votes

# Answer
If you really want to use this feature in the setup() then you can do like this:

```
#define BUTTON 2
boolean not_done = true;

void stopDiameterSetup() {
    // some button debounche code
    ...
    // we are done with setting up the diameter.
    not_done = false;
}
void setup() {
    ...

    // POT reading
    interrupts();
    attachInterrupt();
    while(not_done) {
       attachInterrupt(BUTTON, stopDiameterSetup, CHANGE);
    }
}
void loop(){
// your loop code
}

```

If you can't or afraid to use interrupts then just check for a button pressed inside the while loop.
> 1 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Connecting battery and LED to Arduino Due
I am brand new to Arduino/robotics and am trying to take baby steps. First I'd like to just power an Arduino and an LED from a 9V battery like so:

No programming, just simple circuitry. The battery powers the Due, and the Due in turn powers the LED.

A few concerns here:

* Will the 9V battery fry the Due, which I *believe* is expecting 3.3V? If so, what can I do to reduce the voltage/amps?
* Will the 9V battery fry the resistor and/or LED?
* As you can see by my question marks, I'm not real sure *where* to connect the battery to the Due (both positive & negative terminals) as well as the *where* to connect the breadboard to the Due (again, both terminals).

Any ideas?

# Answer
> 4 votes
What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield):

My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one. You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).

It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.

In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do. I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.

In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.

As a next step, you could load the sample sketch Examples-\>01Basic-\>Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).

Edit (to specifically address your concerns):

* The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.
* The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.
* Only connect the battery through the power socket. If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended. Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.

Additional edit: You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket. Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.

---
Tags: led, power, arduino-due
---


# Question
Title: Will writing to serial when no serial is available cause problems?
I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?

# Answer
No, that will not cause any problem.

What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected *and* the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.

This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.
> 0 votes

---
Tags: serial, debugging
---


title: Microcontroller controlled power supply

text:
# Question
Title: Microcontroller controlled power supply
Can anyone assist me to make a power supply whose output voltage will be controlled by an Arduino, with the latest voltage setting automatically saved in non volatile memory?

I am in an OJT (On the Job Training Scheme). I was given a task to make a Arduino controlled voltage variable power supply whose outputs can be switched between several preset values using pushbutton control. It's like switching between two different outputs when a designated button is being pushed.

Here is what I have done so far. I made an LM317 based power supply with the output voltage controlled by a potentiometer. I followed **this youtube tutorial**. It works well but I was ask to upgrade it.

Instead of using a potentiometer to adjust the voltage, I wish to use switching buttons to choose between two or more preset voltage levels. Each switch buttons have their corresponding voltages.

This link may also be relevant.
Code is given below the circuit diagram.
ARDUINO AS A POWER SOURCE ALTERNATOR

# Answer
If you want to output preset voltage levels in distinct steps, rather than an 'analogue' range from X volts to Y volts, then the answer is in the datasheet for the LM317:

Connect each of the INPUTS through a 1k base resistor to your Arduino pins. Selecting different values for all the resistors will of course allow you to vary Vout by turning each transistor on or off, by themselves or together. You can use any standard transistor: 2N3904, 2N2222, BC548, etc., but I might elect to use a (low power) MOSFET like a BSS138 instead (and omit the base resistor). Of course you can use add more resistor/transistor lines if you want more output options. I recommend using R2 so that Vout is always limited, otherwise - if Vin is quite high - you may damage whatever Vout is powering due to some runaway voltages.

Calculating resitor values is your mathmatical challenge. If you really apply some brainpower you can change Vout in linear steps with minimal Arduino pin usage:

```
'Input' states            Vout
  A  B  C  D            (/volts)
  0  0  0  0              5.00  [Vmax set by R2]
  0  0  0  1              4.75
  0  0  1  0              4.50
  0  0  1  1              4.25
  0  1  0  0              4.00
   ...  ...                ..
  1  1  1  0              1.75
  1  1  1  1              1.50

```

This shows that with *N* Arduino pins you can have *(N^2)-1* levels. Using R2 gives your final level whne all INPUTs are off.

If you want to be able to drop Vout down to 1.25V, add transistor/MOSFET that connects R1/ADJ straight to ground. Turning this on will drop Vout to 1.25V, irrespective of the state of the other INPUTS.
> 5 votes

# Answer
I am wary about providing a complete answer without knowing what is expected of YOU - is this like an assignment where you are being tested on understanding and what you have learned. The following will be useful to you. You need to give some more details if you want more assistance with these circuits.

Here is an existing stack exchange question. I see that I answered it in 2011 :-).
How does this power supply circuit work? (MCU + LM317)
The circuit and my previous answer should help greatly.
In your case you apply PWM using analog.Write to R1.
You MUST understand how the circuit works and not just apply it.
The original appears to be **here** with circuit description, with diagram **here**

---

On **this page** from EDN magazine is a similar circuit. The pot between pins 1 & 5 would not usually be used.

---

In another stack exchange question there is a very useful caution about the opamp's load limits in a similar circuit.
**Problems controlling an LM317 with an op-amp** \- 2013

---

You can get many possible ideas here - search = lm317 voltage controlled power supply \- this is an immensely powerful way of finding information - IF a picture is worth a thousand words then this is priceless. Note the terms used.

---

Bad designs:

There are some bad designs around which can look OK but behave badly.
Despite the detailed writeup, This poor design uses "open loop control" and the output voltage varies with load and is only "sort of controlled".

I was asked why I think this circuit is "open loop". I could not find a complete circuit diagram on the page but this diagram was shown of the output stage. If this is NOT the actual circuit used it would be "good" to have the complete circuit easily accessible.

**IF** this is the actual circuit used, then:

Call the transistors Q1 Q2 Q3 Q4 in left to right order.
Call intended output voltage = Vset = Vdac x (R6 + R7)/R7.
Vdac is applied to Q1 base and amplified by Q1 & Q2 to form the desired output voltage, appearing at Q2 collector. A lesser voltage appears as Vout due to the Vbe drop in Q3 & Q4. As load current increases Vout will "droop" thereby increasing the drive to Q4. This in turn increases the load on Q3 and Q3 emitter voltage will droop increasing Q3 drive. The actual Vbe voltages will depend on the beta (current gain) of Q3 and Q4, their temperatures (which depends on heat sinking, load and ambient temperatures) and manufacturing variation. At no or very low loads Vout will be about 1 Volt below Vset. At heavy loads Vbe\_Q3 will be in the 0.6-0.8V range and Vbe\_Q4 will be 0.8V+. So Vout will be around 1.5+ Volts below Vset and variable with (at least) the factors mentioned above.

This is still a usable design, but Vout could 'easily enough' be made far more stable with load by feedback from Vout to the Q1-Q2 amplifier - essentially forming a comparator that compares Vset and Vout.

**Update:**
**This** \[reference provided by NilsB\] MAY be the actual circuit diagram or close to it. It's an earlier 2005 design which presumably is much the same as the later version.

It appears not to be open loop in the broad sense. The Vout is still decoupled from Vset, with the software feedback allowing him to adjust the Vset to make Vout what he wants on a "nudge it and see" basis. ie Vset is not a fixed ratio wrt Vout so he can never set it and have it "just track". So it does not automatically stabilise for load or temperature changes and there is a variable drp between k x Vset and Vout.
Software is fastish but not as fast as a closed loop in hardware which allows Vout to track Vset within mV in a time delay as short as you provide an error amp loop for.

That's a 2005 circuit diagram so an earlier version than the originally cited V3 - one assumes he has not 'gone backwards' in design concept. It's strange that he does not include the whole circuit diagram or a good discussion of the provided current and voltage feedback. He may have wanted to sell kitsets rather than give away his final design. The link to the kitset sales is now broken so he now manages neither.

I'd consider it preferable to add a simple hardware error amplifier so Vout = k x Vset and THEN measure Vout and Iout with ADCs (as he does). Vout is then essentially "set and forget" with the added ability to check that Vout is what it should be (which allows eg heavy overload to be detected.
Constant current mode operation is still "nudge and see" but 'not too bad'.
Also, Vout includes the Vdrop across the current sense resistors - about 0.5V/A. Measuring with 2 x AD C channels as he does allows this to be compensated for. If the Isense resistors were in the "high side" feed before the regulator this would remove this variation but make current sensing somewhat harder.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Light sensor acting up when used with other code
I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:

```
const int lightSensorPin = A0;
int lightSensorValue = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);
}

```

Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000.

Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:

```
int trigPin1 = 5;
int echoPin1 = 6;
int blue1 =  7;
int green1 = 8;

int trigPin2 = A3;
int echoPin2 = A4;
int blue2 =  A2;
int green2 = A1;

int redLED = 10;
int greenLED = 3;
int yellowLED = 9;
int blueLED = 4;

const int lightSensorPin = A0;
int lightSensorValue = 0;

int securityLength1 = 28;
int securityLength2 = 28;

int frontEyes(11);
int backEyes(12);

const char* front = "front";
const char* back = "back";

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

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(blue1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(green2, OUTPUT);

  pinMode(frontEyes, OUTPUT);
  pinMode(backEyes, OUTPUT);

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);

}//end setup

void loop(){

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(blueLED, HIGH);

eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front);
eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back);

  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);

}//end loop

void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  long distance = (duration/2) / 29.1;

  Serial.println(distance);

 if (distance >= securityLength || distance <= 0) {
  digitalWrite(green,HIGH);
  digitalWrite(blue,LOW);
  if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);
  }//end else
  }//end if

  else if(distance < securityLength) {
  digitalWrite(blue,HIGH);
  digitalWrite(green,LOW);

  if (frontOrBack == "front") {
    digitalWrite(frontEyes, HIGH);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, HIGH);
  }//end else

 }//end else if

}//end function

```

# Answer
I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had `Serial.println(distance);` in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.
> 2 votes

# Answer
There's no `pinMode(lightSensorPin, INPUT);` in either of your codes. In the original code this probably doesn't matter because you set no other pins to In or Out.

As a side note, instead of declaring all your pin number as `int` then defining them, make use of *preprocessor directives*:

```
#define trigPin1  5;
#define echoPin1  6;
#define blue1     7;
#define green1    8;

```

When you hit Verify or Upload the *preprocessor* sweeps through your code and replaces all instances of a defined term with whatever comes immediately after it in the definition. You can't use it for variables of course, but it's perfect for designating pins.

This will cut down on unnecessary memory usage. Not a huge saving in your case, but I don't see why people don't do it more often.
> 1 votes

---
Tags: sensors, arduino-nano, code-optimization
---


title: Coding Debugging

text:
# Question
Title: Coding Debugging
This program is supposed to act as a Decimal To Binary Converter, the LeD's acting as output. The problem is that this function returns Garbage Value

```
const int LED1 =1, LED2 =3, LED3 =5;
void setup()
{
  Serial.begin(9600);
  pinMode (LED1, OUTPUT);
  pinMode (LED2, OUTPUT);
  pinMode (LED3, OUTPUT);
}
void loop()
{
  int x = 0;
  x = Serial.read();
  x = x-48;
  switch(x){
    case 0:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
    case 1:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
      case 2:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 3:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 4:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 5:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 6:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
      case 7:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
  }
 Serial.write(x);
}

```

# Answer
> 7 votes
That massive program can be compressed into just a handful of lines:

```
const int LED1 = 1,
          LED2 = 3,
          LED3 = 5;

void setup() {
    Serial.begin(9600);
    pinMode (LED1, OUTPUT);
    pinMode (LED2, OUTPUT);
    pinMode (LED3, OUTPUT);
}

void loop() {
    if (Serial.available()) {
        int x = Serial.read();
        x = x - '0';
        digitalWrite(LED1, x & 0x01);
        digitalWrite(LED2, x & 0x02);
        digitalWrite(LED3, x & 0x04);
        Serial.print(x);
    }
}

```

Note the use of Serial.print() not Serial.write(). If you use Serial.write() then it prints the ASCII character associated with the number you feed it - in your case characters 0 to 7 (none of which are printable).

Also, unless you check for there actually being something available for you to read from the serial you'll only get a brief flicker of something meaningful (too fast for the eye to see) and then it will just return -1, which with 48 subtracted from it would be -49, which would be "complete garbage".

# Answer
> 0 votes
There are a couple of issues:

* The function `loop()` doesn't return anything, by definition. Functions that do return a value return it with a statement like \`return(someValue); Did you mean to say that it *prints* garbage on the terminal?
* If you want to print a value on the terminal, you need to use the the `Serial.print(someValue)` function; `Serial.write()` sends a binary value and that is probably not what you wanted. The binary values 0 - 9 represent non-printing characters so I'm not surprised that the terminal printed some odd graphic characters.

\-

---
Tags: arduino-uno
---


# Question
Title: Leonardo Serial1 enable internal pull-up for removable Bluetooth module
I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.

My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.

I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.

I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?

# Answer
> 1 votes
Yes, what you have done is good.

It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs. When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.

As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.

UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter. By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.

The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART. If that happens then you want to add an external stronger (lower resistance) pull up.

Another thing to think about with your disconnected pins is to protect them from ESD. You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.

---
Tags: serial, arduino-leonardo
---


# Question
Title: How to communicate with arduino uno when arduino motor shield connected to arduino uno?
I'm using this Dual Motor Shield

when I plug Arduino Dual Motor Shield into Aruino uno can't seen any way to communicate with Adruino uno.how can I communicate with uno ?

# Answer
Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and D1) If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.
> 1 votes

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: Is there such a thing as an "Always" loop?
I seem to remember somewhere somebody making an "Always" loop between Setup() and Loop().

But I can't find any documentation on it. Does such a thing exist, or am I imagining it?

# Answer
There's nothing officially called an "always" loops as such. However, you can make a loop which goes on forever like this:

```
while (true)
{
    // this bit repeats forever
}

```

A `while` loop checks the condition before every iteration of the main body. If it detects that the condition equals boolean `false` then it will stop the loop and move on to the next bit of code.

Normally, the condition would be some kind of expression, like `(x < 10)`. However, in the example above, the condition is hard-coded as `true`, meaning it will never be `false` so it will never stop.
> 1 votes

# Answer
You *might* be thinking of the *Serial Event* system.

This is a specially defined function which runs whenever `loop()` finishes *if there is anything to read from the serial port*.

Basically it is implemented as a function call after `loop()` in the `main()` function, which looks like this:

```
setup();

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

```

As you can see there is only `setup()`, `loop()` and the *serial event* system.
> 1 votes

---
Tags: c++, arduino-ide
---


title: Arduino IDE / Teensy 3 on Ipad

text:
# Question
Title: Arduino IDE / Teensy 3 on Ipad
Does anyone know a good IDE for Ipad to write Arduino code and compile it for teensy 3 ?

Answers with different alternatives would be appreciated

# Answer
> -1 votes
I don't know of any way to *compile* it on an iPad, but Textastic should do the trick for writing the code if you set the syntax highlighting to `C++`.

---
Tags: programming, arduino-ide, teensy
---


# Question
Title: Controlling 2WD car chassis with PS3 controller
I'm having trouble with controlling my car with the PS3 joystick, and there hasn't been any example codes out there. I'm using;

This is my code;

```
include <PS3USB.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nPS3 USB Library Started"));
  pinMode(motora1, OUTPUT);
  pinMode(motora2, OUTPUT);
  pinMode(motoraspeed, OUTPUT);
  pinMode(motorb1, OUTPUT);
  pinMode(motorb2, OUTPUT);
  pinMode(motorbspeed, OUTPUT);
  delay(5000);
}

void loop() {
  Usb.Task();

  if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

    //go forward
     if (PS3.getAnalogHat(LeftHatY) == 0) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
         digitalWrite(motora1, HIGH);
          digitalWrite(motora2, LOW);
          digitalWrite(motoraspeed, 255);
        digitalWrite(motorb1, HIGH);
        digitalWrite(motorb2, LOW);
        digitalWrite(motorbspeed, 255);
}

//go backward
if (PS3.getAnalogHat(LeftHatY) == 255) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
           digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 255);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 255);
}

//turn left
if (PS3.getAnalogHat(RightHatX) == 0) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
           digitalWrite(motora1, HIGH);
  digitalWrite(motora2, LOW);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 200);
}

   //turn right
   if (PS3.getAnalogHat(RightHatX) == 255) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
          digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, HIGH);
  digitalWrite(motorb2, LOW);
  digitalWrite(motorbspeed, 200);
}

```

As of now, when I look at my code in the serial monitor, I get the following;

```
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127

```

The numbers adjust as I'm moving the joystick around but just keeps going even though I'm not moving the joystick around. Any help would be appreciated, thanks

# Answer
> 1 votes
I found three issues:

1. You don't have a `#` before the include on line 1.
2. There is no `}` at the end of the `void loop()`.
3. You forgot to include an if statement for when the joystick is idle.

Try this code:

```
#include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
                  //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
    Serial.begin(115200);
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
    }
    Serial.print(F("\r\nPS3 USB Library Started"));
    pinMode(motora1, OUTPUT);
    pinMode(motora2, OUTPUT);
    pinMode(motoraspeed, OUTPUT);
    pinMode(motorb1, OUTPUT);
    pinMode(motorb2, OUTPUT);
    pinMode(motorbspeed, OUTPUT);
    delay(5000);
}

void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
        } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 255);
        } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 200);
        } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 200);
        } else { //stop moving
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 0);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 0);
        }
    }
}

```

---
Tags: arduino-uno, programming, motor, shields
---


title: Use of Resistor in PinWheel Exercise

text:
# Question
Title: Use of Resistor in PinWheel Exercise
I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.

Here is the schematic:

(if img not showing: https://goo.gl/tqZmKD)

My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?

Thank you!

EDIT\**: Additional help from the arduino forums: The resistor is needed so when the switch is closed you don't short the supply to ground. Switch open the resistor pulls the signal to ground and no current flows, when the switch is closed it forms a resistive divider with the 10k (switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.

Replace the 10k with a wire and you'd simply overload the supply completely and perhaps weld the switch contacts shut. Arduino Forums

# Answer
It's a pull-down resistor.

A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).

With the switch open and no resistor present, the Arduino pin is neither high nor low. It will *probably* read as low if you tried `digitalRead()`, but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.

However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) *until you press the switch*, at which point the Arduino pin switches state.

If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?

Think about it...

One side of the switch connected to Vdd.

The other side is connected to the Arduino and GND.

Close the switch, *I dare you.*

**Vdd is now connected to GND**
> 1 votes

---
Tags: resistor
---