# Question
Title: Do I need a bubble sort or something easier?
I'm using an Arduino Leonardo and a GPSTiny++ library to parse NMEA strings from my GPS receiver. In this chunk of code I'm averaging all satellite SNR numbers for satellites which are locked (Being used for navigation). The avg value provides some general information on overall performance but I'm also really looking for the avg Top 4 values.

I believe I would need to do some sort of sorting algorithm. Increment through the top 4 and average those values.

Here's a snippet of my output window: 12/13 0.92 SNR=17 10 27 27 30 29 25 27 33 0 0 0 31 25.60 0.00

The second to last number is the average.

How do I get started?

```
int totalSNR = 0;
    float avgSNR = 0;
    int count = 0;
    Serial.print(F(" SNR="));
    for (int i = 0; i < MAX_SATELLITES; ++i)
      if (sats[i].active)
      {
        if (sats[i].snr > 0) {
          count++;
          totalSNR = totalSNR + sats[i].snr;
        }

        Serial.print(sats[i].snr);
        Serial.print(F(" "));
      }

    avgSNR = float(totalSNR) / float(count);
    Serial.print(avgSNR);

```

# Answer
You could do a **qsort**. You haven't posted any data types so it is hard to answer with your specific code, however here is a sample of sorting numbers:

```
const int COUNT = 10;

int someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
int myCompareFunction (const void * arg1, const void * arg2)
  {
  int * a = (int *) arg1;  // cast to pointers to integers
  int * b = (int *) arg2;

  // a less than b?
  if (*a < *b)
    return -1;

  // a greater than b?
  if (*a > *b)
    return 1;

  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

```

Output:

```
-5
3
18
21
30
42
54
998
999
7342

```

---

## Generic compare function with a template

Interestingly, you can make the compare function be a *template* which lets you compare *any* type -- that is, any type that supports direct comparisons. Change the compare function to:

```
// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

```

This change removes the reference to "a" and "b" being "int" and replaces them with T, which is the template type.

Now we can change the qsort line to be:

```
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction<int>);
  // -------add this----------------------------------------^^^^^

```

That gives the same results, but now we can also compare float, long, unsigned long, byte, all that sort of thing.

---

## Compare floats

For example to compare floats:

```
const int COUNT = 10;

float someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (float), myCompareFunction<float>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

```

The only change there was changing the word "int" to "float" (in two places) on the qsort line, and on the data declaration itself.

---

## Compare String objects

You can even compare **String** objects (not C strings), for example the data is:

```
String someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

```

And the sort is:

```
  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (String), myCompareFunction<String>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);

```

---

## Compare C strings

We need to use `strcmp` in this case, but most of the work is done in that. We just have to dereference the pointer so `strcmp` gets the pointer to the string (not the pointer to the pointer to the string).

```
char * someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

int myCompareFunction (const void * arg1, const void * arg2)
  {
  return strcmp (*(char **) arg1, *(char **) arg2);
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (char *), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);
  }  // end of setup

void loop () { }

```
> 5 votes

# Answer
I assume that by

> I'm also really looking for the avg Top 4 values.

you mean that you will find the largest four numbers and report their average.

If so, you can sort all the values (as in previous answer) and then average the last four numbers (or first four, depending on sort order) from the sorted array. This has complexity *O(n lg n)*, that is, sort time grows with array size *n* as the product *n* times logarithm of *n*.

Or, you can keep track of the largest four values as you iterate through the array, via technique illustrated in code at the end of this answer. This has complexity *O(n lg k)*, that is, sort time grows with array size *n* and number *k* of high values as the product *n* times logarithm of *k*.

---

In using `qsort`, I prefer (in this edit) to write the comparator function more compactly, although possibly less transparently, by using `*(int*)a` to reference the value that `a` points to. For example:

```
// Comparator function for integers
int compareInt (const void *a, const void *b) {
  // Return -, 0, or + if first value is <, =, or > second value.
  return *(int*)a - *(int*)b;
}

```

You can make the comparator sort descending (so that the largest four numbers appear in array's first four slots) by using `return *(int*)b -*(int*)a;` instead of the `return` that's shown.

---

Templated, the function looks as follows.

```
template<typename T>
// Comparator function for Numbers
int compareNumber (const void *a, const void *b) {
  // Return -, 0, or + if first value is <, =, or > second value.
  return *(T*)a -*(T*)b;
}

```

I called the routine `compareNumber` because it uses subtraction to find out which operand is larger. But as explained in arduino.cc's String Comparison Operators page, for Arduino `String`-type objects, subtraction is bound to string comparison, so the above templated function works with `String` objects as well as numbers.

For C-type strings, which are character arrays terminated by a null character, *ie* of `char*` or `char[]` type, the `strcmp()` function can be used directly as `qsort()`'s comparator function:

```
qsort(arrayOfPointersToCStrings, elementCount, pointersize, strcmp);

```

That is, there is no reason to write a separate comparator function with a call to `strcmp()`; just reference `strcmp()` directly.

---

When you have a small, fixed number of values to process, just doing a sort is reasonable. The algorithmic complexity is `O(n*lg n)`, and if `n` is fixed, this is basically `O(1)`. If, however, you were processing extremely large data sets and wanted to identify the largest four numbers without storing all the other numbers, you can track the largest four by keeping the four largest numbers so far seen in an array. This has algorithmic complexity that is `O(n*k)` at worst, where `k` is the number of elements tracked; and for fixed `k`, this is `O(n)`. If `k` is large or variable, a tree method can be used to get complexity `O(n*lg k)`.

Anyhow, suppose the array is `int largestSoFar[4]`. Initialize each entry in that array to some number smaller than any valid data item; eg, to `INT_MIN` from `<limits.h>`.

As each new data item arrives, compare it to `largestSoFar[0]`. If it's less or equal, go get the next data item.

Else, the new value is one of the largest values so far seen. Store it in `largestSoFar[0]`, then have a loop to do compare-and-swap steps to ripple the new number up to its appropriate level. That is, compare elements \[0\] and \[1\]; break if `largestSoFar[0]<largestSoFar[1]`, else swap\[0\] and \[1\] and go on to compare-and-swap for elements \[1\] and \[2\], etc.

The code below (shown as a standalone C program, rather than as an Arduino sketch) illustrates the technique. Here is what it prints out:

```
Linear result:   2654  2720  2815  2961  2968  9662    Total: 23780
Sorting result:  9662  2968  2961  2815  2720  2654    Total: 23780

```

Here is the standalone C program illustrating a linear (`O(1)`) method:

```
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

// Comparator function
int intCompare(const void *va, const void *vb) {
  const int a = *(int*)va, b = *(int*)vb;
  // (a>b) is 1 if a>b, else 0.  (b>a) is 1 if b>a, else 0.
  // So the following expression has value 1, 0, or -1.
  return (b>a) - (a>b); // To sort descending
}

int main () {
  int someNumbers [] = { 481,  1041, 107,  279,  809, 2052,  2961, 557,
             2534, 2968, 89,   839,  2720,  85,  2115, 898,
             1931, 655,  2631, 1897, 2322, 1115, 2815, 674,
             2259, 176,  598,  525,  600,  1088, 1885, 313,
             1175, 2654, 915,  536,  978,  2052, 798, 1979,
             2571, 2154, 1138, 259, 9662  };
  enum { NumTop = 6, NumNum = (sizeof someNumbers)/sizeof(int) };
  int i, j, tot, largestSoFar[NumTop];

  for (i = 0; i < NumTop; ++i)
    largestSoFar[i] = INT_MIN;  // Init. largestSoFar[] to smallest numbers

  // Process all the numbers
  for (j = 0; j < NumNum; ++j) {
    if (someNumbers[j] <= largestSoFar[0])
      continue;
    // Install number into largestSoFar[] and bubble it up
    largestSoFar[0] = someNumbers[j];
    for (i = 1; i < NumTop; ++i) {
      if (largestSoFar[i] < largestSoFar[i-1]) {
        int t = largestSoFar[i];
        largestSoFar[i] = largestSoFar[i-1];
        largestSoFar[i-1] = t;
      }
      else break;
    }
  }
  printf ("Linear result:  ");
  for (i = tot = 0; i < NumTop; ++i) {
    printf ("%5d ", largestSoFar[i]);
    tot += largestSoFar[i];
  }
  printf ("   Total: %d\n", tot);

  // sort the array descending, for comparison
  qsort (someNumbers, NumNum, sizeof(int), intCompare);
  printf ("Sorting result: ");
  for (i = tot = 0; i < NumTop; ++i) {
    printf ("%5d ", someNumbers[i]);
    tot += someNumbers[i];
  }
  printf ("   Total: %d\n", tot);
  return 0;
}

```
> 3 votes

# Answer
Since you only need to know the 4 largest values in the array you don't need to sort the array, you just need to iterate through it and find the four largest values. This can be done in `O(n*k)` which is faster than any sorting algorithm you could use. However there is an issue of space since you would use an array to hold the previous largest numbers. Fortunately we can get around this by swapping the current largest value to the end of the array and ignoring it. So you can find the `k` largest values in an size `n` array in `O(n*k)` time complexity with `O(1)` space complexity. For fixed values if `n` and `k` the time complexity is `O(1)`.

```
 #include <stdio.h>

    void swap (int& a, int& b);

    int main () {

        int sum = 0;
        int max = -1; // I'm assuming your array will have non-negative numbers
        int maxIndex;
        int nums = 4; // we want the top "num" values in the array

        const int arrSize = 9;
        int arr[arrSize] = {36, 33, 19, 42, 47, 26, 50, 37, 38}; // random numbers

        for (int i = 0; i < num; ++i){
            // arrSize - i lets us ignore the previous max values
            for (int j = 0; j < arrSize - i; j++){
                if(arr[j] > max){
                    max = arr[j]; // store current max
                    maxIndex = j; // store the current max's index
                }
            }
            sum += max; // running total
            max = -1;   // reset max
            swap(arr[maxIndex], arr[arrSize-1-i]); // move current max to the end
        }

        float top4Avg = sum / 4.0;
        printf("\nTop 4 average: %f\n", top4Avg);

    }

    // swaps a and b without a temp variable
    void swap (int& a, int& b){
        a = a ^ b; // ^ is the bitwise xor
        b = a ^ b;
        a = a ^ b;
    }

```

First iteration: `{36, 33, 19, 42, 47, 26, 38, 37, 50}`

Second iteration: `{36, 33, 19, 42, 37, 26, 38, 47, 50}`

Third iteration: `{36, 33, 19, 38, 37, 26, 42, 47, 50}`

Fourth iteration: `{36, 33, 19, 26, 37, 38, 42, 47, 50}`

Also this was a really fun question I'd upvote but my rep isn't high enough.
> 3 votes

---
Tags: arduino-leonardo, tinygps
---


# Question
Title: Reading analog signal from digital pin #6
Is it possible to use digital pin 6 (PD6\_PCINT22/AIN0) to read an analog voltage with analogRead()?

According to the ATMega datasheet, this should be possible.

If yes how is it done ? (pin configuration)

# Answer
That is not possible. AIN0 is an input to the analog *comparator*, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.
> 3 votes

# Answer
Maybe. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega) and the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega).

As you can see in the image below the pin PD6 is not an analog input. To be an analog pin it should be write ADCx, like the PC0..5.

So, if you are not using and Arduino Uno you can't use PD6 as analog input but you can use PC0..5.

To read an analog value using analogRead() method you can do like this:

```
int analogPin = 3;
int val = 0;           // variable to store the value read

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

void loop()
{
  val = analogRead(analogPin);    // read the input pin

  Serial.println(val);             // debug value
}

```
> 1 votes

---
Tags: analogread
---


# Question
Title: How is LED powered when PIN 2 is disconnected?
Using the Arduino tutorial "Button", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.

I am trying to understand HOW this happens. Is it simply due to being a floating ground?

# Answer
> 1 votes
The `pinMode(buttonPin, INPUT);` line tells the board to set the `buttonPin` in high impedance mode.

When you disconnect the wire the state of that pin becomes unknown; usually it oscillates. Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".

The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as `pinMode(buttonPin, INPUT_PULLUP);` and invert the logic (i.e. `buttonState = !digitalRead(buttonPin);`). This way it will never oscillate again.

---
Tags: arduino-uno, button
---


# Question
Title: Can I use this cheap GPS module with arduino
For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.

Here is the link-- http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

# Answer
> 1 votes
After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: http://arduiniana.org/libraries/tinygpsplus/. You may have to use the protocols in this data sheet: https://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual-Rev2.1-Dec07.pdf.

All of this information was taken from this thread: https://www.linkedin.com/grp/post/4573843-5806249757395406852.

# Answer
> 1 votes
Yes. You can tell that from two entries in the specification:

> TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

> Output SiRF binary system OR **nmea0183 V3.0**(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.

---
Tags: arduino-uno, gps
---


# Question
Title: Using an Arduino Nano, how many LEDs can I safely power?
I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: http://www.instructables.com/id/Sleek-word-clock/ and this one: http://www.instructables.com/id/Personalised-Word-Clock/ A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: http://www.amazon.com/gp/product/B00SGMEH7G.

I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.

The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?

Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.

# Answer
If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.

If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply. My immediate guess is "not enough".

64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs. That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.

So you can reduce your current requirements by not having the LEDs as bright. Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all. At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.

So you can come up with a compromise between the brightness you desire and the current consumed by each LED.

Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED. When all LEDs are on that would be (5 × 64) 320mA. That's reasonable for a linear regulator, but still will generate more heat than is really advisable.

So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator. You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.

Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip. There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.
> 4 votes

---
Tags: power, led, arduino-nano
---


# Question
Title: Looking for a game application oriented display for Arduino Mega
I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.

I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:

```
*(0x12)=0x34 // Sends 0x1234

```

However, I couldn't find where to buy that specific one.

I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!

The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).

It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).

It should be either:

* Monochrome
* Color display with MS Paint colors if it has equal to or less than 256 colors
* Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.

If anyone knows where to buy it, please comment.
Thank you for your time.

# Answer
> 1 votes
I'd suggest, if you haven't done it already, to take a look at what is supported by uGFX.

If you find any HW meeting your needs, you can at least be sure that it is supported.

# Answer
> 1 votes
> I was using displays with serial communication (SPI) ...

Personally I regards serial and SPI as different things:

SPI is somewhat faster than serial.

---

> ... sending bytes to draw a tile-based picture was way too slow ...

How slow was it? What was your target speed?

---

> The resolution it needs to have is minimum 128x64 ... It should be no bigger than 2.5"

Something like 2.2" 18-bit color TFT LCD display ?

---

> fast bandwidth to receive fast pictures at a speed at least 10FPS ...

See Toorum's Quest II - Retro video game and console

That guy made a sideways scrolling game outputting to video with a display resolution of 104x80 with 256 colors. He also had sound generation and managed input from a NES controller.

See video of it in operation on YouTube.

---
Tags: arduino-mega, display
---


# Question
Title: I want a couple of servos to listen for P.C. input (data from OSC protocol), can I bypass having to use an Arduino?
...and whack a stripped usb cable straight into a prototype board?

by bypass having to use an arduino I mean any kind of sheild? polulu would be perfect but im trying to avoid needing any of this.

My issue for finding tutorials and documentation on the subject is not quite knowing what keywords to search for, could someone point me in the right direction?

# Answer
If I understand your question correctly you're asking if you can control servos with OSC and no microcontroller.
OSC is a protocol used for networking and communication between synthesizers, similar to midi in that, but totally different in the way OSC sends data which looks a bit like XML.
There's a couple of problems here:
**1.** *Servos will not respond to OSC-signals. You could use MAX/MSP to generate servo-pulses from the OSC. The problem arises whan you are going to send this to the servos using usb.*
**2.** *USB, a fast data-transmission technology, is not suitable to be connected straight into a servomotor.*

Arduino uses an atmega16u to transform the data from usb to serial (called a usb to serial programmer) for programming and communication. Then the microcontroller (atmega168/328) takes this and creates a pulse and a signal for the servo-motors.

**To control servos without a micro-controller using USB is impossible.**

It is be possible to control electronics using the serial-port and low-level coding. Used to do stuff like that on a Commodore 64 a time ago. Before these affordable, stable, reliable avr, arm and pic programming cards came out.

*A tip*: It is possible to load a program onto an atmega168/328 using a Arduino UNO or similar. Take the chip off of the programming card(ie. the Arduino UNO) and create a stripped down version, containing the micro-controller chip, 16kHz crystal, some capacitors and an usb to serial converter/ftdi-cable.

Regards
Krister Borge
> 1 votes

# Answer
A build-your-own-duino isn't hard to do and it is quite inexpensive. It will make your life (or the part it you're about to spend creating custom hardware) much, much easier! I have built Joao Alves' CSE-duino for example and it has everything an UNO has except for:

* on-board USB (use an FTDI cable that has USB \<-\> Serial in the cable head)
* a 3.3v power supply; and
* an ISP (high-voltage programming) connector;

, none of which you should need to drive a servo.
> 1 votes

---
Tags: programming, servo, usb
---


title: Alternative to delay function

text:
# Question
Title: Alternative to delay function
I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.

Here is the link to the example:

https://www.arduino.cc/en/Tutorial/AnalogWriteMega

Here is my code:

```
int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i <= 13; i++)
  {
        pinMode(i,OUTPUT);
  }
}//Setting the pins to output and allowing serial communication.

void loop (){

  for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
  {

    for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness >= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

```

Thank you

# Answer
```
// You don't need to return anything since it's just a delay
// also I changed the parameters to long ints because millis()
// returns a long int
void timeLoop (long int startMillis, long int interval){ // the delay function

    // this loops until 2 milliseconds has passed since the function began
    while(millis() - startMillis < interval){}
}

// Your call for a 2 millisecond delay would be
timeLoop(millis(), 2);

```

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.

If you really want it to return something you could use this:

```
long int timeLoop (long int startMillis, long int interval){ // the delay function

    while(millis() - startMillis < interval){}
    return millis() - startMillis;
}

```

But it really isn't needed.
> 1 votes

# Answer
What's the point? Why rewrite `delay()`?

Anyway:

```
int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

```

In every iteration of that loop you are updating `prevmillis`. So you will never reach the wanted delay interval.

Apart from the fact that you may as well use the inbuilt `delay` rather than writing your own, and getting it wrong.

---

> I am trying to make a workaround for the delay function

Why?

The XY Problem
> 0 votes

# Answer
Depending on what you want the alternative function to do, there are a megaton of timer libraries at the Arduino playground. One of them is likely to provide what you need.
> 0 votes

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


# Question
Title: error: expected primary-expression before ',' token
I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?

```
const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180};

```

# Answer
Two things:

1. You have a comma missing: `1260,12601635,1635,`
2. You have an extra comma: `1180,1180,,1255,1255`

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.
> 3 votes

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


# Question
Title: Can I run ESP8266 via Arduino using the PWM pins?
First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?

Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

# Answer
> First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws *far* too much current (in excess of 200mA) to use anything other than a proper supply.

> Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.

You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.
> 2 votes

---
Tags: esp8266
---


# Question
Title: Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P
I have posted this on the Arduino forum also, but I give it more chance if posted here also.

I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.

I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.

First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:

avrdude: Yikes! Invalid device signature avrdude: stk500\_getsync(): not in sync: resp=0x00 avrdude: stk500\_disable(): protocol error, expect=0x14, resp=0x51 I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.

I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?

I appriciate all the help I can get!

# Answer
> 1 votes
This worked for me dude :)

See this:

http://www.instructables.com/id/Bootloading-ATmega328-with-Arduino-Mega2560/?ALLSTEPS

---
Tags: arduino-mega, attiny, atmega328, avr, isp
---


# Question
Title: Arduino Interface with Serial device and LCD display
I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.

My questions are:

1. Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
2. The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

# Answer
> 1 votes
1. If the device *is* serial and you want to connect it to the Arduino *serial* port, why would you use a usb-to-serial converter? For a serial to serial connection, you have to connect TX, RX and GND. This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.
2. it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.

---
Tags: arduino-uno, serial, lcd
---


title: Multiple If statements

text:
# Question
Title: Multiple If statements
I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages. my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?

```
#include <LiquidCrystal595.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal595 lcd(7,8,9);
void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

void loop() {
   // put your main code here, to run repeatedly:
   char c;
   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }
      while(c=sms.read())
         if(c=='motoroff'){
            analogWrite(Enable_m, 0);
            digitalWrite(Control_2,LOW);
            digitalWrite(Control_7,LOW);

         }
      if(c=='motoronclockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='motoronanticlockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      if(c=='speedhalf'){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speedquarter'){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speed75'){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(c);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

```

# Answer
> 1 votes
```
#include <LiquidCrystal.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6);

void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

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

   // I chose 160 since that is max size for sms
   char message [160];
   // this fills message with null characters
   memset( message, '\0', sizeof(char)*160 );

   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      // you used single qoutes properly here
      // single qoutes denote a char which is a single character
      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }

      // this will add the characters to messages[]
      for(int i = 0; message[i] = sms.read(); i++){}

      // I changed this to double qoutes since you need double
      // qoutes to denote a string literal
      if(strcmp(message, "motoroff") == 0){
         analogWrite(Enable_m, 0);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "motoronclockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "motoronanticlockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "speedhalf") == 0){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speedquarter") == 0){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speed75") == 0){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      // This else will only be executed if the previous if and else if statements are false
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(message);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

```

So I've made some edits to your code. For example this code `'motoronanticlockwise'` isn't correct. Single quotes are used for `char` data types and double quotes are used for string literals. You should use double quotes since there are multiple characters `"motoronanticlockwise"`. Also as Majenko said you would have to use `strcmp()` in order to compare `c-strings` c-strings are `char` arrays that have a null terminator `'\0'`. Also `strcmp()` returns `0` if the two strings are equal.

Your last `else` statement will only executed if the previous `if` statement is `false`. It seems like you only want it to execute if **all** of the previous `if` statement are false. To do this you make the first `if` statement and then make a chain of `if else` statements followed by a single `else` statement. You can have a single `if` statement with no `else` or `if else` statements however, if you want `else` or `if else` statements then you need to have an `if` statement. I've made the necessarily edits to your code already.

Lastly, this part of the program is the biggest problem `while(c=sms.read())` This is because `sms.read()` returns a `char` so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by `sms.read()` in it. This can be done like this

```
char message [160]; // I chose 160 since that is max size for sms
memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters
// this will add the characters to messages[]
for(int i = 0; message[i] = sms.read(); i++){}

```

I am using a `for` loop to iterate through `message[]`.

Try the above and get back to me if there are any problems with it.

# Answer
> 1 votes
Two things:

1. The `else` will only be subject to the last `if` being false, the rest of the `if` statements are completely separate and can affect the `else` in no way whatsoever. To chain them you need `if (...) { blah blah } else if (...) { blah blah }` etc.
2. You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.

Some tips:

* Use `strcmp()` to compare strings.
* If reading strings from serial store them in character *arrays* not a single character.

You might find this useful:

# Answer
> 0 votes
If you intend each `if` statement to be executed, regardless of the whether the prior one(s) did, then yes, they do not require `else` clauses.

If you mean to try each condition until you find one that is true, and execute that one and only that one, then the second and subsequent `if`s need to be `else if`s. The final one may be just an `else`, if you want a catch-all clause; or an `else if` if it is possible that none of the clauses might need to be run.

Update: To execute at most one clause, you need to use `if`, some `else if`s, and maybe a final `else`.

If you're trying to match strings, you can use an array of strings or use literal strings as you've tried to do. Strings have to be enclosed in double-quotes (`"`) however, not the single quotes you've used. And the variable `char c;` you tried to use to hold the SMS message is really only one character. You'll need to make it an array of characters such as `char c[140+1];`, the size of the longest SMS message + one more for a zero-character string-terminator. C doesn't directly compare strings as simple variables so `==` and `!=` won't work here. You'll need to compare them with strcmp().

---
Tags: arduino-uno, gsm
---


# Question
Title: How does this code move the bird sprite in this sketch?
I'm teaching this sketch in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.

Here is the code for both:

Bird

```
class Chym {

private:
  int frameCount;
  int x;
  int y;
  int deltaIde;
  int delayFrame;

  int jumpCount;
  int maxJumpCount;
  int moveSpeed;

  bool _isDead;
public:
  void respawn() {
    x = 24;
    y = 20;
    deltaIde = -1;
    moveSpeed = 1;
    jumpCount = 0;
    _isDead = false;
  }

  Chym() {
    frameCount = 0;
    delayFrame = 0;
    maxJumpCount = 20;
    respawn();
  }

  void render() {
    if (frameCount < ANIM_FRAME / 2) {
      display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
    }
    else {
      display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
    }
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {
      y += deltaIde * moveSpeed;
      delayFrame = 0;
    }

    if (y > 35) {
      _isDead = true;
    }

    frameCount++;
    if (frameCount >= ANIM_FRAME) frameCount = 0;
  }

  bool isDead() {
    return _isDead;
  }

  void die() {
    _isDead = true;
  }

  void cancelJump() {
    jumpCount = 0;
    flyDown();
  }

  void flyUp() {
    if (jumpCount < maxJumpCount) {
      deltaIde = -1;
      moveSpeed = 3;
      jumpCount++;
    }
    else {
      flyDown();
    }
  }

  void flyDown() {
    deltaIde = 1;
    moveSpeed = 1;
  }

  int getX() {
    return x;
  }

  int getY() {
    return y;
  }

};

```

Pipe

```
class Bar {

private:
  int x;
  int y;
  int delayFrame;
  int moveSpeed;
public:
  Bar() {
    delayFrame = 0;
    x = 0; y = 24;
    moveSpeed = 2;
  }

  void setPos(int sx, int sy) {
    x = sx; y = sy;
  }

  void render() {
    display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
    display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {

      x -= moveSpeed;
      if (x < -10) x = 95;

      delayFrame = 0;
    }
  }

  int hitTest(int tx, int ty) {
    int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
    int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
    if (hitX != 0) {
      return hitY;
    }
    return 0;
  }

};

```

https://www.youtube.com/watch?v=04cY78Y2d3g

# Answer
This part of your code is what changes the sprite's y-value.

```
y += deltaIde * moveSpeed;

```

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your `render()` method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).

As for the bars, if you watch closely in the video you can see that they aren't actually randomized.

**Compound Assignment Operators**

`+=` is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators\_in\_C\_and\_C%2B%2B#Compound\_assignment\_operators

```
int x = 5;
x += 2; // equals 7; equivalent to x = x + 2;
x = 5;
x = x + 2; // also equals 7; equivalent to x += 2;

```
> 2 votes

---
Tags: programming, c, sketch
---


# Question
Title: Arduno Uno voltage in via VIN pin or DC power?
I have an Arduino UNO. It has VoltageIN on a pin. Is there any difference between powering my UNO through VIN or powering it through the DC port?

The docs only say this,

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So it seems to imply VIN/USB/DC in all go through the voltage regulator? Is there any difference then?

Is there any advantage to running a variable power supply through an adapter like this:

Or should I just go through VIN?

# Answer
> 5 votes
DC Jack has a Reverse Protection Diode, that drops 0.7V at usable currents. The VIN does not. Both go through the on board LM7805 or similar linear regulator. The USB does not, but it does go through a P-Channel Mosfet used to switch between USB and DC/VIN power before connecting to the 5V rail. The 5V pin bypasses the regulator, Diode, and P-Channel Mosfet completely.

The advantage of the DC jack is that the Reverse Protection Diode is used, preventing reverse voltage problems if you wire it wrong.

# Answer
> 0 votes
If you have a "variable power supply" just set it to 5.00v and connect to the 5v pins. Eg like the this http://blog.unixbigot.id.au/2015/10/make-5-volt-battery-supply-for-any.html?m=1

---
Tags: arduino-uno, power
---


# Question
Title: How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)?
On my Arduino Yun (openwrt-yun, updated to latest version), I have a bluetooth dongle in the usb port; I have installed bluez-libs and bluez-utils (and python-bluez). They show up as version 5.13. hciconfig and hcitool work properly. There does not seem to be any utility installed to pair with a device, nor can I figure out how to get pairing to work by editing config files.

I can find the device with hciconfig and hcitool, but rfcomm can't connect without the pin. If I try the same sequence on my Linux laptop after pairing with the gui, rfcomm is able to connect, so I know the device is working properly (JY-MCU HC-06 on another Arduino).

All the recommendations I can find on the web indicate I should be able to use simple-agent or bluez-simple-agent, but they are not installed with these packages (there is no bluez-tools package for this distro). If I manually copy the python script for the agent to the device and run it, it fails, saying that org.bluez can't be found with dbus. There is no bluetoothd running, and no init script for any bluetooth demon. None of the bt\* tools are available.

I also found a description of how to set a pin code in /var/lib/bluetooth/\[bt-addr\]/pincodes (where bt-addr is my dongle address) containing a line of the form:

\[device-addr\] \[pincode\]

but this seems to have no effect.

I have also tried settings in /etc/bluetooth/main.conf and /etc/bluetooth/rfcomm.conf, but I think they may only be for incoming connections.

Any help would be greatly appreciated.

# Answer
> 1 votes
It takes me some time to make it work :

1) update drivers

```
opkg update

opkg install kmod-bluetooth bluez-libs bluez-utils

```

2) add configuration files in directory /etc/bluetooth

```
root@Arduino:~# cat /etc/bluetooth/hcid.conf

options {
  autoinit yes;
  security auto;
  pairing multi;
  passkey "0000";
   }
device {
  name "OpenWrt";
  class 0x000100;
  lm accept,master;
  lp rswitch,hold,sniff,park;
  }

root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

rfcomm0{
 bind yes;
 device 00:1B:C1:02:B0:F5;
 channel 1;
 comment "Holux M-1000";
 }

```

3) Reboot the card

4) test if all is OK

```
hciconfig

```

5) put the interface up

```
hciconfig hci0 up

```

6) Search for devices

```
hcitool scan

```

7) Look for Serial Port capability on the devices

```
sdptool search SP

```

8) bind the serial dev

```
rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

```

9) see the information comming from the device (bluetooth GPS in my case)

```
cat /dev/rfcomm0

```

# Answer
> -1 votes
Bluetooth support on OpenWRT is broken, simply does not work.

---
Tags: arduino-yun, bluetooth
---


# Question
Title: Why does my analogRead work on Teensy but not Arduino Uno?
I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.

Basically:

```
int timer = 100;
int ColA = 0;
int Output;

// Setting digital pin functions

void setup()
{
  Serial.begin(38400);
  pinMode(0, OUTPUT);

}

// Program

void loop()
{
  digitalWrite(0, HIGH);
  delay(timer);
  Output = analogRead(A0);
  Serial.println(Output);
  delay(timer);
}

```

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.

Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

# Answer
If you're still using D0 as your output on the Uno then yes you are doomed to failure.

D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.

Pick a different IO pin to be your voltage source.
> 1 votes

---
Tags: arduino-uno, analogread, teensy
---


# Question
Title: Can Arduino libraries be compiled for ARM MCU's?
I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs.

I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.

IridiumSBD Library

Gecko Zero MCU

# Answer
> 1 votes
Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be mbed Gecko development boards so the task is, to port the Rockblock-IridiumSBD Arduino library.

The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.

The Rockblock-IridiumSBD Arduino library won't compile 'out of the packet' on mbed.

However, the Rockblock-IridiumSBD Arduino library appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.

The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.

---
Tags: compile
---


title: Arduino constant clock output

text:
# Question
Title: Arduino constant clock output
I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino. Is there any way that I can have a constant clock output from one of the Arduino pin ?

Thanks,

Liam

# Answer
This outputs 8 MHz on pin 9:

```
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

```

---

> How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.

Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

---

> you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:

```
#define <avr/io.h>

```

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:

```
#define TCCR1A _SFR_MEM8(0x80)

```

The \_SFR\_MEM8 basically generates a pointer to a `volatile` address (because it might change without the compiler knowing it) and then dereferences that variable.

Notice that the number 0x80 in that define agrees with the number shown on my chart.

Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:

```
#define TCCR1A _SFR_MEM8(0x80)
#define WGM10 0
#define WGM11 1
#define COM1B0 4
#define COM1B1 5
#define COM1A0 6
#define COM1A1 7

```

---

> Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which *processor* pins are connected to which *board* pins.

### Atmega328P datasheet snippet:

### Uno datasheet snippet:

---

> Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

---

> What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.

Edit by Edgar: OCR1A values and frequencies

```
Value, MHz
 0 8.00
 1 4.00
 2 2.67
 3 2.00
 4 1.60
 5 1.33
 6 1.14
 7 1.00
 8 0.889
 9 0.800
10 0.727
11 0.667
12 0.615
13 0.571
14 0.533
15 0.500

```
> 9 votes

# Answer
You can use one of the PWM pins on Arduino to output a PWM signal. If you want a constant clock, you need to set the duty cycle of the PWM to be 0.5, i.e. 50%.

Syntax: analogWrite(pin, value) where the parameter "value" is the duty cycle ranges from 0 (always off) to 255 (always on) since it is a 8-bit PWM generator inside Arduino.

If you need a PWM wave with duty cycle of 0.5, you need to set the "value" above to be 127, which is exactly in middle of 0 and 255:

```
analogWrite(clkpin, 127);

```
> 3 votes

---
Tags: frequency, oscillator-clock, adc
---


# Question
Title: Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot
I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!

I can't figure out how to parse strings in Arduino like c++/java/python! I tried this, If the first letter is L, set the next value to left motor, same for R

but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.

Any ideas on what I should do?

EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option

Update: This is how it works now: L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)

# Answer
> 0 votes
A state machine is the right way to go if you are sending multibyte commands.

However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees? If not I would consider encoding the dAta into a single byte. You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.

Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.

---
Tags: arduino-uno, bluetooth
---


title: Separate Timer Instance

text:
# Question
Title: Separate Timer Instance
I'm trying my best attempt here after failing in Googling the answer, but here goes:

I'm trying to get a separate instance to start running *in the background* when a pin goes HIGH. How should I attempt this? PLEASE explain your answer, so that I can learn as well. I'm using an Arduino Uno R3 with a Commercial Ir RX-Tx.

**Basically:**

Sensor -\> Low -\> Loop
Sensor -\> High -\> Start Other Event for 5 min -\> Loop while Counting down to reset state.

My thoughts here are:
Do this via 555-timer OR get some functional coding (anyone maybe want to share here what solutions they have found?)

Thanks.

# Answer
Arduino Uno has two interrupt pins: 2 and 3, and by hooking up the output of your IR, which goes from LOW to HIGH, it will trigger the function that you defined in the code.

For example this is a piece of code that runs when the pin 2 RISING:

```
void setup() {
    attachInterrupt(0, doSomething, RISING);
}

void loop() {
}

void doSomething() {
    //Do your stuff
}

```

Look here for further information link
> 1 votes

---
Tags: arduino-uno, timers, ir
---


# Question
Title: using more than 8 temperature probe of DS18B20 on Arduino
I am trying to use more than 8 temperature DS18b20 on one bus. Is there any problem to make it work?

# Answer
> 2 votes
As far as I can see there is no limit on the number of sensors you can have on a bus.

So if you are having problems does your code work with less sensors? Try one and work up.

Is it a current issue are you pulling to much from the board?

Is the problem with the one wire library?

Have you got 4.7k pull ups on each sensor?

# Answer
> 0 votes
As long as you connect each sensor on a different pin, you should be able to collect the data without any problems.

Otherwise try to search for a I2C temperature sensor and use a demux to control 8 sensors.

---
Tags: arduino-ide
---


# Question
Title: Sending SMS once with arduino GPRS SIM900 if an input is HIGH
I faced a problem to send 1 SMS if an input is HIGH and if it is LOW no SMS will be sent. The code not working, just sends SMS when I turn the GPRS on and after that nothing happens.

Please check this link to see the code : the code

Thank you for helping in advance.

# Answer
You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.

Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.
> 1 votes

---
Tags: arduino-uno, gsm, c
---


# Question
Title: Interfacing accelerometer LSM303DLH with Arduino UNO using I2C
I am trying to connet a tri axis accelerometer LSM303DLH to arduino UNO using the libraries taken from the following links (https://github.com/adafruit/Adafruit\_LSM303DLHC and/or https://github.com/ryantm/LSM303DLH) but none of them work. Using the following connection: SCL on A5, SDA on A4, Vin on 5V, Gng on Gnd.

I should be able to see the values of the accelerometer but the serial monitor is empty.

I've tried inserting a few print in the libraries to understand where the execution stops, basically after a Wire.endTrasmission() the program doesn't go forward. How can I connect the accelerometer using I2C?

# Answer
Are you using one module bought from Adafruit?

Make sure the connection is correct between the sensor and Arduino, then make sure that the script doesn’t get stuck when the Wire is begun.

Another thing that you need to make sure, is to have the correct address, it depends from board and each one can have a different one or a selector.

This can be helpful to figure out what the wiring is
> 1 votes

---
Tags: arduino-uno, i2c, accelerometer
---


# Question
Title: Sending Something to Serial and Writing it Returns a Correlated but Strange Number
I have an indescribable bug where read and write commands give back an array of numbers that are the digits of the input number except +48. Kinda hard to explain. Basically if I type 0 into this code:

```
    void setup(){
      Serial.begin(9600); //Begin serial connection
    }
    void loop(){
      if(Serial.available()){ //If serial available...
        double ser = Serial.read(); //Read serial value and write it to 'ser'
        Serial.println(ser); //Print 'ser'
      }
    }

```

I receive 48. 1 means 49, 2 means 50, 3 means 51... And then two digit numbers, which are the same except for each digit. 10 returns 49 48, 33 returns 51 51, 22 returns 50 50.

# Answer
> 1 votes
Serial.read returns a character. The **character** '0' is 48 in decimal. So this is doing what you expect (or what I expect, anyway). I suggest not using `double` there, eg.

```
    char ser = Serial.read(); //Read serial value and write it to 'ser'

```

---
Tags: serial, c++
---


# Question
Title: Safely enabling voltage divider on a 12V battery
I'm planning to monitor voltage of a 12V battery with an Arduino's ADC pin connected via a voltage divider. Since I don't want the circuit itself to drain the battery when not in use, I want to use a transistor to "enable" it via an Arduino DIO pin like:

Is this a safe circuit to use?

If I set EN low to disable the divider, will that risk putting 12V directly on the ADC pin and burn it out? I've found alternative designs, but they seem overly complicated.

Edit: The battery is a Lipo which is also powering the Arduino through a step-down DC converter.

# Answer
> 5 votes
I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.

The trick, though, is to do the exact opposite of what you are doing. Instead of isolating the ground (*which leaves the battery then directly connected to the Arduino*) you need to completely isolate the battery from the divider.

This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

The theory is, when the Arduino DOUT is either LOW or not connected (*pulled low by 10K resistor*) the N channel MOSFET is turned off. That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.

When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.

When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.

You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the *impedance*) which is placed in parallel to the lower resistor of the divider. If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly. Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.

Note that it is important to use a P-channel MOSFET for this, not a PNP transistor. A P-channel MOSFET, when on, looks like a very small resistor. A PNP transistor is seen as a fixed voltage drop skewing your results. The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.

As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.

# Answer
> 4 votes
I'd use some very large resistors (e.g. 1 and 2 Mega Ohm), and add a small capacitor to the center, to stabilize the value during sampling. Using 1 and 2 MOhm would result in 10uA of current loss, which is probably negligible in your cases.

---
Tags: analogread, voltage-level
---


# Question
Title: How to change the usb name of Atmel 32u4?
I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.

I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.

On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.

# Answer
> 2 votes
The Arduino '32U4 bootloader, Caterina, can be found under `hardware/arduino/bootloaders/caterina`. It requires LUFA in order to build.

With the technical part aside, note that you are not allowed to use the USB IDs assigned to Arduino LLC with products you intend to distribute under another name. You will need to acquire your own vendor ID from the USB-IF if you want to do so.

---
Tags: usb
---


# Question
Title: Arduino snake on 5110 screen - some help needed
I'm trying to make a snake game using the u8g lib. But for now, only the second body part of the snake follows the head, where I want the whole body to follow the snake's head and I don't understand why it doesn't work. Here is the code:

```
#include "U8glib.h"

U8GLIB_PCD8544 u8g(13, 11, 10, 9, 8);    // SPI Com: SCK = 13, MOSI = 11, CS = 10, A0 = 9, Reset = 8

const int SNAKEMAXSIZE = 10;

bool title = true;
bool gameRunning = false;

enum direction {HAUT, BAS, GAUCHE, DROITE};

int snakeDirection = GAUCHE;

class snakeCell
{
  private:
  int x;
  int y;

  public:

  snakeCell(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  snakeCell()
  {
    x = 42;
    y = 24;
  }

  void setX(int x)
  {
    this->x = x;
  }

  void setY(int y)
  {
    this->y = y;
  }

  int getX()
  {
    return x;
  }

  int getY()
  {
    return y;
  }

  void draw()
  {
    u8g.drawBox(x, y, 5,5);
  }
};

class Pomme
{
  public:
  int x;
  int y;

  Pomme(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  Pomme()
  {
    x = 42;
    y = 24;
  }

  void randomSpawn()
  {
    x = random(48);
    y = random(84);
  }

  void draw()
  {
    u8g.drawCircle(x, y, 5);
  }
};

snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(52,39)};

Pomme pomme = Pomme();

void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.setFont(u8g_font_6x13);
  //u8g.setFont(u8g_font_osb21);
  u8g.drawRFrame(0, 0, 84, 48, 0);   //Screen frame
  printTitle();
  game();
}

void setup(void) {
  // flip screen, if required
   //u8g.setRot180();

  // set SPI backup if required
  //u8g.setHardwareBackup(u8g_backup_avr_spi);

  // assign default color value

  randomSeed(analogRead(0));

  if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }

}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

  // rebuild the picture after some delay
  delay(50);
}

void printTitle()
{
  if(title == true)
  {
    u8g.setFont(u8g_font_6x13);
    //u8g.drawStr( 26, 30, "SNAKE");
    delay(2000);
    title = false;
    gameRunning = true;
  }
}

void moveSnake()
{
  //move head accordingly to movement
  if(snakeDirection == GAUCHE)
  {
    snake[0].setX(snake[0].getX() - 1);
  }
  else if(snakeDirection == DROITE)
  {
    snake[0].setX(snake[0].getX() + 1);
  }
  else if(snakeDirection == BAS)
  {
    snake[0].setY(snake[0].getY() + 1);
  }
  else if(snakeDirection == HAUT)
  {
    snake[0].setY(snake[0].getY() - 1);
  }

  //tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }
  delay(100);
}

void restart()
{
  //snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(47,34)};
}

void drawSnake()
{
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    snake[i].draw();
  }
}

void spawnApple()
{
  pomme = Pomme();
  pomme.randomSpawn();
}

void checkCollision()
{
  // detect if apple eaten
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() == pomme.x) && (snake[i].getY() == pomme.y))
    {
      pomme.randomSpawn();
    }
  }
  // detect if snake hit wall
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() >= 84) || (snake[i].getX() <= 0) || (snake[i].getY() >= 48) || (snake[i].getY() <= 0))
    {
      //gameOver();
      restart();
    }
  }
}

void gameOver()
{
  gameRunning = false;
  //u8g.setFont(u8g_font_6x13);
  //u8g.drawStr( 14, 30, "GAME OVER");
  //delay(1000);
  restart();
  gameRunning = true;
}

void game()
{
  if(gameRunning == true)
  {
    checkCollision();
    moveSnake();
    drawSnake();
  }
}

```

Thanks in advance.

# Answer
There might be a problem with going through your snake array from the back. I'm not sure if you're filling it from front or back, but you should read it from there aswell.

And, every time you re-draw your snake, you're creating a new snakeCell?

```
//tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }

```

You should differentiate between a snakeCell that is active or not. And just re-position and draw it when it's active.

Be sure to check if you're not placing them ontop of eachother. You should put each piece of the tail in the previous position of the preceding part.

Also: You shouldn't really be mixing up French and English naming in your code.
> 1 votes

---
Tags: arduino-uno, c
---


# Question
Title: avrdude: usbdev_open(): did not find any USB device "usb"
I was programing the arduino and things were going great. Then I plugged in another chip, and went to burn a boot loader. (New chips) now, I get:

```
avrdude: usbdev_open(): did not find any USB device "usb"

```

when I try to upload code to old chips, I get:

```
avrdude: usbdev_open(): did not find any USB device "usb"

```

ten times. I have tried reseting, and it doesnt do anything. when I plug the device in,

dmesg shows that the device responds to my PC

```
[526199.130716] usb 3-1: new full-speed USB device number 7 using xhci_hcd
[526199.149422] usb 3-1: New USB device found, idVendor=2341, idProduct=0043
[526199.149427] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[526199.149430] usb 3-1: Manufacturer: Arduino (www.arduino.cc)
[526199.149433] usb 3-1: SerialNumber: 649343332353518022F0
[526199.149579] usb 3-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[526199.149766] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

```

IDE settings: board: Audruino Uno serial posrt /dev/ttyACM0 Programer: AVRISP mkII

I also tried AVR ISP

in the command line, I tried:

```
   avr-gcc -DF_CPU=16000000UL -mmcu=atmega328 -o Balls.out Balls.c
   avr-objcopy -O ihex -R .eeprom Balls.out  Balls.hex
   sudo avrdude -V -F -c stk500v1 -p m328 -b 19200 -P /dev/ttyACM0 -U flash:w:Balls.hex

```

each time, I get:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

```

How can I troubleshoot the Arduino Uno? Is this thing broken?

# Answer
> 6 votes
# Generated from IDE

Because this is a generic error, I'll answer it. I was getting this on STDERR when using the IDE:

> avrdude: usbdev\_open(): did not find any USB device "usb"

This is because in the IDE I was using

* Sketch → **Upload Using Programmer \[`Ctrl` \+ `Shift` \+ U\]**

However, I should have been using

* Sketch → **Upload \[`Ctrl` \+ U\]**

---
Tags: arduino-uno
---


# Question
Title: Help making LEDs blink like blinkers in a car
I am trying to make blinkers and hazards lights for a car. I can get the left and right blinkers to work. I cannot figure out how to get the lights to blink simultaneously like hazard lights would.

What I think I want is that when both inputs are HIGH then Both LEDs will blink together at the same time.

I left the garbage and comments in the code so you can see what I have tried.

Thanks for your help.

```
/*
 Blinkers and Hazard Lights

 Simulates a vehicles blinkers and Hazard Lights
 left button connected to pin 2 using a pushdown resister
 right button connected to pin 3 using a pushdown resister
 left LED connected to pin 9
 right LED connected to pin 10
 Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

 When left button is pushed Left LED will Blink
 When Right Button Is pushed Right LED will Blink

 If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

 created 2015
 by thomsl41@gmail.com

*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPinLeft = 2;     // the number of the pushbutton pin
const int buttonPinRight = 3;
const int buttonPinHazard = 2 && 3;
const int ledPinLeft = 9;      // the number of the LED pin
const int ledPinRight = 10;
const int ledPinHazard = 13;

// variables will change:
int buttonStateLeft = 0;         // variable for reading the pushbutton status
int buttonStateRight = 0;
int buttonStateHazard = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinLeft, OUTPUT);
   pinMode(ledPinRight, OUTPUT);
   pinMode(ledPinHazard, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinLeft, INPUT);
  pinMode(buttonPinRight, INPUT);
  pinMode(buttonPinHazard, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonStateLeft = digitalRead(buttonPinLeft);
  buttonStateRight = digitalRead(buttonPinRight);
  buttonStateHazard = digitalRead(buttonPinHazard);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonStateLeft == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
  }
 else {
    // turn LED off:
    digitalWrite(ledPinLeft, LOW);
  }

if (buttonStateRight == HIGH) {
    // turn LED on:
  digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second

}
  else {
    // turn LED off:
    digitalWrite(ledPinRight, LOW);
  }
}

/*if (buttonStateHazard == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, LOW);
  digitalWrite(ledPinRight, LOW);
  digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);              // wait for a second
  digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
  //}
 //else {
    // turn LED off:
   // digitalWrite(ledPinHazard, LOW);
 }

}
*/

```

# Answer
> 2 votes
It looks like you need to do something like:

```
if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
    digitalWrite(ledPinRight, HIGH);
    digitalWrite(ledPinLeft, HIGH);
}
else if (buttonStateRight == HIGH) {
    digitalWrite(ledPinRight, HIGH);
}
else if (buttonStateLeft == HIGH) {
    digitalWrite(ledPinleft, HIGH);
}
//One delay for all
delay(500);
//Shut anything off that might be on after the delay
digitalWrite(ledPinRight, LOW);
digitalWrite(ledPinLeft, LOW);

```

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.

---
Tags: led
---


title: VC0706 card failed, or not present

text:
# Question
Title: VC0706 card failed, or not present
I'm trying to follow this tutorial here:

https://learn.adafruit.com/ttl-serial-camera/using-the-camera

Here's what my serial log is printing-- I've added a few commands for logging:

```
Arduino version is: 10605
Chip Select is: 4
VC0706 Camera snapshot test
Card failed, or not present

```

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite

it works just fine. What am I messing up?

I'm using an arduino uno with wifi shield.

Thanks!

# Answer
> 1 votes
Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.

```
//#if !defined(SOFTWARE_SPI)
//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
//#else
//  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
//#endif
//#endif

```

---
Tags: sd-card
---


# Question
Title: Driving multiple LED arrays with shift registers
The project I'm building requires multiple LED arrays. I'm going to wire these LEDs in parallel and then connect the arrays to individual pins on a shift register. In addition to the LEDs running in parallel I've connected resistors in series to each LED. I've been prototyping this on a couple of breadboards and I've noticed my parallel LEDs are much more dim then my LEDs I have in series. The resistors I'm using are around 550 OHMs and I'm powering the registers through my arduino uno. I think this may be part of the reason why they're so dim, as the arduino is only providing 5V. My question is, can I/should I have my registers connected to my arduino via the data connections and power them using an external source? Will this provide me with brighter LEDs? I don't want to dump the resistors, and I have around 21 arrays, if it matters, each with a varying number of LEDs

# Answer
You haven't provided enough information to allow definitive answers to your questions, but you can apply LED resistor calculators and formulas to determine how much current is available to drive LEDs of various voltages.

Here is an example: Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA. Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground. Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.

If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin. If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.

Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.

Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.

Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages. Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents. Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.
> 1 votes

---
Tags: arduino-uno, power, led, resistor, shift-register
---


# Question
Title: How can program/arduino restarted by IDE?
I wrote my custom sketch, where I am printing some greeting text inside `setup()` method.

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. `setup()` method running again.

How can this happen? I was thinking `setup()` method run once, when Arduino is powered up by connecting to the USB socket?

If it is possible to restart it already connected, then how this can be done?

**UPDATE**

Code is follows:

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

Adafruit_BMP085 bmp;

String command;

String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

void awaiting() {
  Serial.println(awaitingMessage);
}

void help() {
  Serial.println("Temperature and pressure sensor commands:");
  Serial.println("temp\t- output temperature in degrees Celsius");
  Serial.println("press\t- output pressure in Pascals");
  Serial.println("wait\t- print awaiting message");
  Serial.println("help\t- output this text");
}

void temperature() {
  Serial.println(bmp.readTemperature());
}

void pressure() {
  Serial.println(bmp.readPressure());
}

void unknown() {
  if( command.length() > 0 ) {
      Serial.println("Unknown command was \'" + command + "'");
    }
}

void setup() {
   Serial.setTimeout(50000);
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  else {
    awaiting();
  }
}

void loop() {
  command = Serial.readStringUntil('\n');

  if( command.startsWith("temp") ) {
    temperature();
  }

  else if( command.startsWith("press") ) {
    pressure();
  }

  else if( command.startsWith("wait") ) {
    awaiting();
  }

  else if( command.startsWith("help") ) {
    help();
  }

  else {
    unknown();
    //awaiting();
  }

}

```

Video is here: https://youtu.be/-QBleGVxaus

# Answer
When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted. This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.

Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.

There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.

There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.

Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.

Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.
> 4 votes

# Answer
This means your Arduino or ATmega328 is restarting due to another issue. Usually the Arduino will reboot when there is too much amperage draw which is called a brown-out.

It can also mean there is a bug in your code.

Please also note as you mentioned

> I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again

The Arduino will reboot when opening the serial monitor.
> -1 votes

---
Tags: arduino-uno, ubuntu
---


# Question
Title: Can i run brushless ESC from any digital pin of arduino
{assume arming is done} Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.

# Answer
> 1 votes
It should work.

The Servo library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.

---
Tags: arduino-uno, pwm
---


title: How to connect Arduino device to Linux?

text:
# Question
Title: How to connect Arduino device to Linux?
I wrote Arduino sketch and it works. It waits for a command and answers text on response.

Simultaneously, I can't get any response with command line tools.

For example, I have the following code to get temperature:

```
#!/bin/bash
tty=/dev/ttyUSB0
exec 4<$tty 5>$tty
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
#stty -F $tty 9600 -echo
#printf "temp\n" >&5
echo temp >&5
read reply <&4
echo "$reply"
#tail -n 1 - <&4

```

It returns empty or hang under different circumstances.

Also, if I run built-in `Serial Monitor`, I can see responses on command lines like:

```
echo temp > /dev/ttyUSB0

```

But I see nothing with commands like `tail -f /dev/ttyUSB0`

What I am doing wrong?

# Answer
Add the flag `-hupcl` to your `stty` command. That will disable the assertion of DTR which is resetting the board.

```
 hupcl (-hupcl)
             Stop asserting modem control (do not stop asserting modem
             control) on last close.

```

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset. So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.

You can do that with the `sleep` command: `sleep 3`

Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with

```
stty -F $tty hupcl

```

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board. So in summary try this:

```
#!/bin/bash
tty=/dev/ttyUSB0
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
sleep 3
echo temp >$tty
read reply <$tty
echo "$reply"
stty -F $tty hupcl

```
> 1 votes

---
Tags: arduino-uno, serial, linux
---


# Question
Title: Doesn't Arduino reports DSR (Data Set Ready) correctly?
I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.

This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data

And computer should wait for it.

Does it happen so?

# Answer
> 3 votes
No, this doesn't happen.

DTR is used purely for resetting the board. Personally I would have chosen the RTS signal instead, but the wise guys at Arduino decided on DTR.

The Arduino has no knowledge of the DTR signal, it only knows that it has been rebooted. Whether that reboot came from DTR, or from the reset button, or wherever, it has no knowledge.

So the DTR is being (in my opinion ab-) used to perform the resetting in order to make uploading a sketch easier and that is all.

# Answer
> 3 votes
No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.

Generally host software / serial driver configuration ignores DSR.

On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.

None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.

---
Tags: serial
---


title: Concatenate string constants

text:
# Question
Title: Concatenate string constants
Please take a look at following example (I have Java background):

```
const char* BT_ADDRESS = "abcd,ef,ghijkl";

void bar(const char* string) {
  ...
}

void foo() {
   bar("AT+BIND=" + BT_ADDRESS);
   bar("AT+LINK=" + BT_ADDRESS);
}

```

How to achieve this with "Arduino-C++" so BT\_ADDRESS only has to be entered at one location?

# Answer
There is, as you may expect with C, many different ways of doing this.

The simplest is probably to use, instead of a const variable, a preprocessor macro.

In C you can concatenate string literals like this:

```
print("AT+BIND=" "abcd,ef,ghijkl");

```

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.

Now you can, of course, replace one of those with a preprocessor macro:

```
#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);

```

The preprocessing replaces BT\_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.

Other options, depending on what `print` does, is to expand it to take two `const char *` parameters and deal with them both separately. For instance, you might have:

```
void print(const char *command, const char *data) {
    Serial.print(command);
    Serial.println(data);
}

print("AT+BIND=", BT_ADDRESS);

```

If you don't know how many parameters you may want to pass you could use *variadic* arguments:

```
#include <stdarg.h>

void print(int count, ...) {
    va_list args;
    va_start args, count);

    for (int i = 0; i < count; i++) {
        const char *arg = va_arg(args, const char *);
        Serial.print(arg);
    }
    va_end(args);
}

print(2, "AT+BIND=", BT_ADDRESS);

```

Yet another option is to pre-format the data into a single string using the various string operators. For example:

```
int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);

```

I could go on all night with different options... The first one using the preprocessor is probably easiest though.
> 4 votes

# Answer
Get rid of strange `print()` and use standard `stdout`, `fprintf()` and `%` format tokens.

```
#include <stdio.h>
#include <Stream.h>

// printf to file support http://arduino.cc/playground/Main/Printf
// we need fundamental FILE definitions and printf declarations
// apparently it eats 1k FLASH by saves to much copy&paste and hopefully even FLASH

// create a output function
// This works because Serial.write, although of
// type virtual, already exists.
static int stream_putchar (char c, FILE *stream) {
    ((Stream*)(stream->udata))->write(c);
    return 0;
}

void SetupFileStream(FILE* file, Print* stream) {
    fdev_setup_stream(file, stream_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = stream;
}

#ifdef UDRE0
// non interrupt transmit function
static int uart_putchar (char c, FILE *stream) {
    volatile byte *ucsrna = (byte*)(stream->udata);
    while ( !bitRead( ucsrna[0], UDRE0) ) {;}  // wait for transmit buffer is empty
    ucsrna[&UDR0-&UCSR0A] = c;
    return 0;
}

void SetupUartStream(FILE* file, volatile byte *ucsrna) {
    fdev_setup_stream(file, uart_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = (void*) ucsrna;
}
#endif

#define INFO(fmt, args...) \
    fprintf_P(stderr, PROGSTR("INFO: " fmt), ## args);

// create a FILE structure to reference our UART output function in main project file
static FILE myStdOut = {0};
void setup() {
....
    Serial.begin(19200);
    SetupUartStream(&myStdOut, &UCSR0A);   // when debugging in AvrStudio then debugger is saturated by debug messages in user data empty interrupt handler if used buffered stream output
    // The uart is the standard output device STDOUT
    stdout = &myStdOut;
    stderr = stdout;
...
}

....
const char* BT_ADDRESS_RAM = "abcd,ef,ghijkl";
const char* PROGMEM BT_ADDRESS_FLASH = "abcd,ef,ghijkl";

INFO("AT+BIND=%s", BT_ADDRESS_RAM);
INFO("AT+BIND=%S", BT_ADDRESS_FLASH);

```
> -1 votes

---
Tags: c++, string
---