text:
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);

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 () { }

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;
}

Nice answer. I like the way you address the complexity of the various methods. :) The linear approach will be faster, although at the cost of RAM. If the OP wanted to average more numbers (eg. the top 100) then RAM might start to become an issue.

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.

Comment  “// arrSize - 1 lets us ignore the previous max values”  should instead refer to arrSize - i


text:
Empty char variable
How do I empty all the values inside a variable char array[256];?
I tried a for loop assigning an empty value at each iteration, but it doesn't compile.

Please post this loop.

You can't "empty" an array, you can only fill it with meaningless values.

char array[256];

...

int i;
for( i=0; i<256;i++ ) {
    array[i] = 0x00;
}

There is a single-line command you can use:
memset(array, 0, 256);

Or memset(array, 0, sizeof array); preferably.

@NickGammon Assuming you are using "array" directly, and not in a function which has a pointer passed to it.  Better is to use a #define or a const int for both the array size and the memset length.

Quite right, for a pointer that is correct.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arrays and Functions
How can I return a char array from a function?
char c[] = getFloat(val, valid);

char getFloat(float val, bool valid){
      if(valid){
        char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
      } else Serial.print("No Float");
    }

Allocate it in the heap. Don't forget to free it after.
#include <stdlib.h>
#include <string.h>

 ...

char *c = getFloat(val, valid);
use(c);
free(c);

 ...

char *getFloat(float val, bool valid){
  if(valid){
    char stringFloat[16], *ret;
    dtostrf(val, 10, 8, stringFloat);
    ret = strdup(stringFloat);
    return ret;
  } else {
    Serial.print("No Float");
    return NULL;
  }
}

An alternative method would be to allocate the string statically inside the function, like this:
const char * getFloat(float val, bool valid){
      if (valid)
        {
        static char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
        }
      else
        return "No Float";
    }

Now we can use that string:
const char * c = getFloat(24.5678, true);

However note that this is only good for one use at a time!
This would not work properly, for example:
const char * c1 = getFloat(24.5678, true);
const char * c2 = getFloat(42.7654, true);

Now c1 and c2 both point to the same piece of memory, so only the last one would be correct. However this restriction may not matter to you. And it saves you having to free memory afterwards, and possibly saves you from heap fragmentation.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
SD Library writing char in a file
I'm trying to write into a file using this code from the example of the library:
String dataString = "";
int sensor = 0;
dataString += String(sensor);
dataString += ",";
sensor +=1;

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

I have a char array that I want to write in the file, but it works only with String objects apparently. What can I do?

Try using dataFile.write(arrayName);
https://www.arduino.cc/en/Reference/FileWrite

You can write char arrays? What makes you think you can't? Example:
char dataBuffer [80];
strcpy (dataBuffer, "Hello, world");

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataBuffer);
  dataFile.close();
}

Do C++ strings still need the '\0' char at the end?

Depends on the type of string you are talking about. The strings manipulated by the standard library (eg. strcpy, strcmp, strcat) expect strings to have a 0x00 byte at the end.


text:
Nokia 5110 Screen Pixel by Pixel
I have got this LCD screen

I'd like to be able to decide every pixel status of the screen. Do I need to work directly with the buffer or is there another method?

Create a byte buffer where you draw everything (and check pixel values) and flush it to the display after changes. This way you can also implement double buffering to avoid any flickering during animations.

The 5110 Nokia LCD display is based on PCD8544. It is not possible to read the device display memory. The controller has only serial data input.
Typically a graphical device driver for that display will use an offscreen bitmap (buffer). To check the pixel status you would need to check the status in the offscreen bitmap.
Some device drivers use only text and copy font bitmap directly to the display memory. In that case you cannot check the status of the pixel (if the text is not buffered).


text:
deprecated conversion from string constant to 'char*'
What does this error means?
I can't solve it in any way.

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

This question should be on StackOverflow, not Arduino :)

As is my wont, I'm going to provide a bit of background technical information into the whys and wherefores of this this error.
I'm going to inspect four different ways of initializing C strings and see what the differences between them are.  These are the four ways in question:
char *text = "This is some text";
char text[] = "This is some text";
const char *text = "This is some text";
const char text[] = "This is some text";

Now for this I am going to want to change the third letter "i" into an "o" to make it "Thos is some text".  That could, in all cases (you would think), be achieved by:
text[2] = 'o';

Now let's look at what each way of declaring the string does and how that text[2] = 'o'; statement would affect things.
First the most commonly seen way: char *text = "This is some text";.  What does this literally mean?  Well, in C, it literally means "Create a variable called text which is a read-write pointer to this string literal which is held in read-only (code) space.".  If you have the option -Wwrite-strings turned on then you get a warning as seen in the question above.
Basically that means "Warning: You have tried to make a variable that is read-write point to an area you can't write to".  If you try and then set the third character to "o" you would in fact be trying to write to a read-only area and things won't be nice.  On a traditional PC with Linux that results in:

Segmentation Fault

Now the second one: char text[] = "This is some text";.  Literally, in C, that means "Create an array of type "char" and initialize it with the data "This is some text\0". The size of the array will be big enough to store the data".  So that actually allocates RAM and copies the value "This is some text\0" into it at runtime.  No warnings, no errors, perfectly valid.  And the right way to do it if you want to be able to edit the data.  Let's try running the command text[2] = 'o':

Thos is some text

It worked, perfectly.  Good.
Now the third way: const char *text = "This is some text";.  Again the literal meaning: "Create a variable called "text" that is a read only pointer to this data in read only memory.".  Note that both the pointer and the data are now read-only.  No errors, no warnings. What happens if we try and run our test command?  Well, we can't.  The compiler is now intelligent and knows that we are trying to do something bad:

error: assignment of read-only location ‘*(text + 2u)’

It won't even compile.  Trying to write to read-only memory is now protected because we have told the compiler that our pointer is to read-only memory.  Of course, it doesn't have to be pointing to read-only memory, but if you point it to read-write memory (RAM) that memory will still be protected from being written to by the compiler.
Finally the last form: const char text[] = "This is some text";.  Again, like before with [] it allocates an array in RAM and copies the data into it.  However, now this is a read-only array.  You can't write to it because the pointer to it is tagged as const.  Attempting to write to it results in:

error: assignment of read-only location ‘*(text + 2u)’

So, a quick summary of where we are:
This form is completely invalid and should be avoided at all costs.  It opens the door to all sorts of bad things happening:
char *text = "This is some text";

This form is the right form if you are wanting to make the data editable:
char text[] = "This is some text";

This form is the right form if you want strings that won't be edited:
const char *text = "This is some text";

This form seems wasteful of RAM but it does have its uses.  Best forget it for now though.
const char text[] = "This is some text";

It is worth noting that on the Arduinos (the AVR-based ones at least), string literals live in RAM, unless you declare them with a macro like PROGMEM, PSTR() or F(). Thus, const char text[] does not use more RAM than const char *text.

Teensyduino and many other more recent arduino-compatibles automatically place string literals in code space, so it's worth checking to see whether or not F() is needed on your board.

@Craig.Feied In general F() should be used regardless. Those that don't "need" it tend to define it as a simple (const char *)(...) casting. No real effect if the board doesn't need it, but a big saving if you then port your code to a board that does.

To elaborate on Makenko's excellent answer, there is a good reason why the compiler warns you about this. Let's make a test sketch:
char *foo = "This is some text";
char *bar = "This is some text";

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  foo [2] = 'o';     // change foo only
  Serial.println (foo);
  Serial.println (bar);
  }  // end of setup

void loop ()
  {
  }  // end of loop

We have two variables here, foo and bar. I modify one of those in setup(), but see what the result is:
Thos is some text
Thos is some text

They both got changed!
In fact if we look at the warnings we see:
sketch_jul14b.ino:1: warning: deprecated conversion from string constant to ‘char*’
sketch_jul14b.ino:2: warning: deprecated conversion from string constant to ‘char*’

The compiler knows this is dodgy, and it is right! The reason for this is, that the compiler (reasonably) expects that string constants don't change (since they are constants). Thus if you refer to the string constant "This is some text" multiple times in your code it is allowed to allocate the same memory to all of them. Now if you modify one, you modify all of them!

Holy Smoke! Who would have known... Is this still true for latest ArduinoIDE compilers? I just tried it on an ESP32 and it causes repeated GuruMeditation errors.

@not2qubit I just tested on Arduino 1.8.9 and it is true there.

The warnings are there for a reason. This time I got: warning: ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings]
char bar = "This is some text"; - FORBIDS is a strong word. Since you are forbidden to do that, the compiler is free to muck around and share the same string over two variables. Don't do forbidden things! (Also, read and eliminate the warnings). :)

So in case you come across crappy code like this, and want to survive the day. Would an initial declaration of *foo and *bar using different string "constants", prevent this from happening? Also, how is this different from not putting any strings at all, like: char *foo;?

Different constants might help, but personally I wouldn't put anything there, and put data there in the usual way later (eg. with new, strcpy and delete).

Either stop trying to pass a string constant where a function takes a char*, or change the function so that it takes a const char* instead.
String like "random string" are constants.

Is a text like "random characters" a constant char?

String literals are string constants.

Example:
void foo (char * s)
  {
  Serial.println (s);
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  foo ("bar");
  }  // end of setup

void loop ()
  {
  }  // end of loop

Warning:
sketch_jul14b.ino: In function ‘void setup()’:
sketch_jul14b.ino:10: warning: deprecated conversion from string constant to ‘char*’

The function foo expects a char* (which it can therefore modify) but you are passing a string literal, which should not be modified.
The compiler is warning you not to do this. Being deprecated it might turn from a warning into an error in a future compiler version.

Solution: Make foo take a const char *:
void foo (const char * s)
  {
  Serial.println (s);
  }

I don't get it. Do you mean can not be modified?

Older versions of C (and C++) let you write code like my example above. You could make a function (like foo) that prints something you pass down to it, and then pass down a literal string (eg. foo ("Hi there!");)
However a function that takes char * as an argument is allowed to modify its argument (ie. modify Hi there! in this case).
You might have written, for example:
void foo (char * s)
  {
  Serial.println (s);
  strcpy (s, "Goodbye");
  }

Unfortunately, by passing down a literal, you have now potentially modified that literal so that "Hi there!" is now "Goodbye" which is not good. In fact if you copied in a longer string, you might overwrite other variables. Or, on some implementations you would get an access violation because "Hi there!" might have been put in read-only (protected) RAM.
So the compiler-writers are gradually deprecating this usage, so that functions to which you pass down a literal, must declare that argument as const.

Is it a problem if I don't use a pointer?

What sort of problem? That particular warning is about converting a string constant into a char* pointer. Can you elaborate?

@Nick: What do you mean "(..)you are passing a string literal, which should not be modified". I don't get it. Do you mean can not be modified?

I modified my answer. Majenko covered most of these points in his answer.

I have this compilation error:
TimeSerial.ino:68:29: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   if(Serial.find(TIME_HEADER)) {

                         ^

Please replace this line:
#define TIME_HEADER  "T"   // Header tag for serial time sync message
with this line:
#define TIME_HEADER  'T'   // Header tag for serial time sync message
and compilation goes well.

This change changes the define from a one character string "T" to a single character with the value of the ASCII code for the letter capital T.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
USB and UART simultaneous power to Arduino?
I am connecting an Arduino Mega (Crius) to a Intel Embedded processor (Minnowboard) via the following to Peripherals:

Minnowboard USB            -> Arduino      (to flash the micro-controller)
Minnowbaord Highspeed UART -> Arduino UART (to communicate)

Now both the peripherals are supplying +5V Vcc to the Arduino from the Minnowbaord but via different ports. Both the channels shall always remain connected.
Is it safe to power +5V from different ports to the Arduino (because i am technically bypassing all the voltage regulators available on board) ?
Will this cause any problems for the Arduino in regards to difference in voltage levels?

A UART connection does not normally provide power.  Some particular cables like those often found on FTDI USB converters might, but that's not actually part of the UART connection, but rather something passed through from the USB.

That's perfectly fine.  As it's the same 5V source the voltage should be the same and it'll just combine them together as if you had 2 wires in parallel.  However, if there are things like diodes in the path of one connection that causes the voltage to be slightly lower then the increased voltage imposed on the lower voltage side would reverse bias those diodes and end up cutting off that one source, so only one would be used.
So no, it's nothing to concern yourself over.


text:
Arduino communication with ROS via UART
I am trying to program an Arduino Mega(Crius) from a Minnowboard Max A2 via an UART (Hardware Flow Control Off) interface.
I can successfully communicate with the ROS (robot Operating System) on the Ubuntu 12.04 installed on the Minnowboard Max via the UART1 port available on the Minnow Board.
The Crius UART has a FTDi compatible port with a DTR pin.
Unfortunately the MinnowBoard does not have any DTR pin to communicate with the Arduino (Only CTS/RTS pins for 1 of the 3 UART ports). Thus I cannot upload any sketch to the Arduino via the Minnowboard over the UART. I must always connect to the onboard FTDi-USB chip of the crius and upload the sketch.
Is there any workaround to upload the sketch to the Arduino via the UART from the Minnowboard ?

Have you tried the RTS pin? The FTDI header usually asserts RTS to reset the Arduino.

You can use any GPIO you like on the Minnow to trigger a reset of the Mega to initiate the bootloader.  The Yún does just that to program the on-board ATMega chip through a script they have chosen to call "run-avrdude":
#!/bin/sh

echo 1 > /sys/class/gpio/gpio21/value
avrdude  -q -q -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U efuse:r:/tmp/efuse:d
read EFUSE < /tmp/efuse
rm -f /tmp/efuse
if [ "x$EFUSE" = "x203" ] # 203 = 0xCB
then
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m -Uflash:w:$1:i $2
else
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xFB:m -Uflash:w:$1:i $2
fi
echo 0 > /sys/class/gpio/gpio21/value

You could do something similar to initiate the bootloader on the remote board - connect any GPIO pin to the RESET line of your Mega board, then perform the following logical actions:

Set the GPIO to OUTPUT
Set the GPIO to LOW
Delay a few ms
Set the GPIO to INPUT
Run avrdude.

By setting the GPIO to INPUT you are emulating an open-drain output.  If you were just to drive the GPIO HIGH it would hold the RESET pin HIGH and you wouldn't be able to use the USB interface, nor the RESET button.  By setting it to INPUT it is then effectively disconnected from the RESET pin so won't interfere.
The Yún again has a script that works in that way, "reset-mcu":
#!/bin/sh

echo 18 > /sys/class/gpio/export
echo "high" > /sys/class/gpio/gpio18/direction
echo 1 > /sys/class/gpio/gpio18/value
echo 0 > /sys/class/gpio/gpio18/value
echo 18 > /sys/class/gpio/unexport

I have a similar setup to you but using a BeagleBone Black and a PONTECH Quick240 PIC32 based controller.  In my IDE UECIDE I set up a special board definition with the following programmer added to it which performs the manual reset through GPIO and runs the upload program (pic32prog) all in one operation:
upload.local.name=Local upload
upload.local.using=script
upload.local.script.0=__builtin_bullet::Entering programming mode...
upload.local.script.1=__builtin_gpio::7::low
upload.local.script.2=__builtin_delay::100
upload.local.script.3=__builtin_gpio::20::low
upload.local.script.4=__builtin_delay::100
upload.local.script.5=__builtin_gpio::20::hiz
upload.local.script.6=__builtin_delay::100
upload.local.script.7=__builtin_gpio::7::hiz
upload.local.script.8=__builtin_delay::100
upload.local.script.9=__builtin_bullet::Uploading sketch...
upload.local.script.10=${core.root}/tools/linux_arm/pic32prog::-S::-d::${port}::-B::${upload.maxbaud}::-p::${build.path}/${filename}.hex
upload.local.script.11=__builtin_bullet::Resetting board...
upload.local.script.12=__builtin_delay::100
upload.local.script.13=__builtin_gpio::20::low
upload.local.script.14=__builtin_delay::100
upload.local.script.15=__builtin_gpio::20::hiz

sketch.upload=local

That one is a little different in that you have to hold a second GPIO LOW while you reset the board to initiate the bootloader, hence the two GPIOs in use there.


text:
Individually addressing LEDs in a multiplexed matrix
I have created my first LED project with a hand made 4X4 LED matrix. The cathodes are joined horizontally to make the rows and the anodes are joined vertically to make the columns the columns. It is controlled by a shift register with the cathodes (rows) connected to pins 0-3 and the anodes (columns) connected to pins 4-7 of the register controlled from an Arduino Nano.
It all works but I have hit upon a limitation that I have not seen in the various videos and tutorials about making LED matrices so I suspect I am missing something.
This code will light up the bottom left LED which I will call position (0,0).
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
digitalWrite(latchPin, HIGH);

This code will light up the LED at position (1,1), so one up and one to the right.
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
digitalWrite(latchPin, HIGH);

If I then combine the two as below:
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00111100 );
digitalWrite(latchPin, HIGH);

it of course lights up 4 LEDs: (0,0),(0,1),(1,0) and (1,1).
This feels like a limitation of wiring the LEDs in this way because once you power a row in a given column, you cannot unpower it in subsequent columns or vice versa. i.e. lighting (X,Y) and (A,B) means that you cannot have (X,B) and (A,Y) unlit.
However, in the videos I have seen that accompany tutorials on how to make similarly constructed matrices, I can see them lighting up in ways I can't replicate.
How can I light up an LED at positions (0,0) and (1,1) without also lighting up (0,1) and (1,0)?
Is this possible with this configuration?

You are looking for "switching between 0,0 and 1,1 fast enough, that eye can't see it's not lit at the same time, but slow enough it's visible" - Multipexing

You need in principle at least 50 Hz to trick your eyes (or actually brains).

@KIIV Thanks that seems to work well.

Thanks to KIIV in the comments I figured it out. Apparently the trick is to rapidly switch between columns or rows without ever having two on at the same time.
With the below code running in the main loop it appears that (0,0) and (1,1) are lit at the same time even though they are actually switching rapidly.
void loop()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
  digitalWrite(latchPin, HIGH);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
  digitalWrite(latchPin, HIGH);
}

Yup. That is a common issue with matrixed displays. Note that it's possible to light your LEDs one row or one column at a time. You shift in the states of all the LEDs in 1 row, then turn those off and turn on the LEDs in the next row, etc.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to control one Mosfet with another mosfet
I've got 4x 12V 6a peltiers and some 3d printer mosfet controllers to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A (this page seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

simulate this circuit – Schematic created using CircuitLab
R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.
However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that the output is normally on and you have to actively turn it off.
Again a pullup resistor can help:

simulate this circuit
Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.
To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.

Brilliant, thanks for your help Majenko!


text:
Why is there a third connection to the host in this 3 wire current output sensor diagram?
I've got a 3 wire 4-20mA current output sensor, externally powered by 12V, which I want to read from an Arduino Uno (5V). The sensor connection diagram is below, but I don't understand why it says to connect the sensor power out (12V) to the host as well?
Below that is how I think I should connect it (i.e. with the power out from the sensor simply connected back to itself). Will this work? Could I damage my board or, far worse, the sensor itself this way?
Thanks alot!

If the sensor outputs 12V I wouldn't advice connecting it directly to an Arduino GPIO.

where did the diagram come from? Try it with a DMM and see what your ranges are

@dandavis Hi, try what with a DMM? The voltage across +UB and ground on the sensor? The diagram came from the datasheet for the sensor

@MichelKeijzers Hi, I know. I thought 3 wire sensors you can simply connect a 250Ohm shunt resistor to the current output, and measure the voltage drop across that, which should then only be 0-5V. But I don't understand why the diagram says connect the power supply to the host as well?

Digital Multi Meter; you can use it to tell if your setup works w/o frying your uno

The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.
All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

simulate this circuit – Schematic created using CircuitLab
In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good.  RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does).  D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.


text:
Can I monitor data of variables while simulating Arduino on Proteus?
I simulate Arduino UNO on proteus 8 Pro. I use Arduino software for writing a program.
Is it possible to trace or know the data that are stored in valuables while running the code on Proteus?
I would like to know how the code is running step by step so that I can find logical errors.
Thank you,

It is possible. By using several tools on "Virtual Instruments Mode" such as SPI-Debugger, I2C-Debugger, Virtual Terminal, or Logic Analyser.

I would like to know how the code is running step by step so that I can find logical errors.

For example, you can use Virtual Terminal and print the value of variables you want to examine


text:
How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code?

I am attaching my code below :
int cwled=9;
int wwled=10;
int button=8;
int buttonpress;
long startTime=0;
long endTime;
long holdTime;
boolean previous = LOW;
boolean current;
int state=0;
int pot = A0;
boolean cwState = HIGH;
boolean wwState = LOW;
int brightness;
int counter = 1;
boolean pressB;

void setup(){
  pinMode(cwled,OUTPUT);
  pinMode(wwled,OUTPUT);
  pinMode(button,INPUT);
  Serial.begin(9600);

}

void loop() {
  if(state == 0){
    brightness= map(analogRead(pot),0,1023, 0, 255);
        analogWrite(cwled,brightness);
       // analogWrite(wwled,0);
        Serial.println("Initialized");
  }
  current= digitalRead(button);
  if(current == HIGH){
  pressDetection();
  state =1;
  }
}

void pressDetection(){
  pressB=digitalRead(button);
  if(pressB==HIGH && previous == LOW)
  {
    state =1;
    startTime = millis();
  }
  while(digitalRead(button) == HIGH){
    endTime = millis();
    Serial.println("Inside loop");
  }
  previous = LOW;
  holdTime = endTime - startTime;
  if(holdTime> 500){
    longPress();
  }
  else{
    shortPress();
  }

  }

void shortPress(){
  cwState = !cwState;
  wwState = !wwState;
  //brightness= map(analogRead(pot),0,1023, 0, 255);
  if(cwState == HIGH && wwState == LOW){
   brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
   Serial.println("cwState");
   return;
  }
  if(cwState == LOW && wwState == HIGH){
  // brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,LOW);
   Serial.println("wwState");
   return;
  }
 /*else if(cwState == HIGH && wwState == HIGH){
   //brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
  }*/
}

void longPress(){

   cwState =wwState = HIGH;

   //if(cwState == HIGH && wwState == HIGH){
 //  brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,HIGH);
  cwState = !cwState;

 //}

}

I understand there are so many variables unused, this program needs a lot of improvising.
My question is:

How do I improve this code?
How do I add dimming via pwm in this code?
And if I have to add one more type of LED or say n number of LEDs and want to toggle between them what should be the algorithm.

My aim is to use a push button to switch between different types of LEDs (in my case between warmwhite LED and coldwhite LED, if Arduino registers long press off the push button all the LEDs light up, in my case both warmwhite and coldwhite LEDs turn on, and short press of push button toggles between warmwhite and coldwhite LED. The program by default switches on coldwhite LED first and after a long press, shortpress sets default LED to high which is coldwhite.
I am not a hardcore programmer but I have more than basic knowledge of OOPS programming. I am an ECE Engineer and I believe I have slightly more than basic understanding of OOPS and procedural programming. I am aware of C++, C and JAVA only. Any advice or help would be highly appreciated.

Since you never set state back to zero, it looks like your initial stuff (under the if) might as well be in setup as it will only be done once.

I deliberately did that. initially only coldwhite LED turns ON( which can be dimmed). I can remove that part but It's purpose is to initially start the system with coldwhite LED ON.

"Improving you code" is too general of a question to ask here.  I won't do it, but, unless you rephrase your question to something more specific, someone will likely down vote your question.  (At the very least, you could add comments.) As for adding dimming, you are already using "analogwrite()".  However, I'm not sure why, you later forsake the dimming feature and use "digitalwrite()".  If you want to add LED I don't see what is stopping you.  There are only some pins on an Arduino Uno which support PWM.  Other than that you can add as many LED as you want.  Just use normal low current LEDs.

That analogWrite wasn't working properly. That is: it was not dimming in real-time, what I mean by that is suppose I switched to coldwhite Led, then when I'd change my potentiometer to set pwm to say 80 percent it'd not change the brightness , however when I'd toggle again to the warmwhite led it light up with 80% brightness and so on.
By improving I mean can I use classes for it too? I want to make my code changeable, such that if I make amendments it'd not affect the previous performance

Just want to clarify, your intention is add "dim" effect for transition?

Yes, what i want is when I push the button coldwhite LED changes to WarmWhite LED and then I should be able to control its brightness(should be able to do dimming), then when I push the button again it changes back to ColdWhite again and I should be able to control its brightness too. Now when I press and hold the button for greater than half a second both the LEDs should light up and I should be able to control their brightness. and then when I again short-press the button ColdWhite LED should come on with me being able to control the brightness again as previously.

Well thanks a lot everybody, just did some minor changes, it is now working as I wanted. I appreciate everybody's advice and time you took out to help me. Thank you all

How do you improve your code?
Firstly there is nothing disastrously wrong with you code, it could do with a polish, but who's code couldn't?
In the dim and very distant past I was told "you write code once but read it many times" so try and make your code readable and clear.

If the values aren't going to change then they should be constants or #defines.
ALWAYS initialise variables.  (Doesn't matter on an Arduino because the compiler does it for you, but its good practice).
Boolean should be true or false.
You are writing C/C++ not Java.  Opening braces { should be on a new line.  It makes the code easier to read and match up the braces.
Unless your space bar is broken, put spaces after commas and either side of equals.
Using function parameters and less global variables will make you code more reusable.  Imagine the day when you start a new project and copy and paste functions from previous projects and finish the code in 15 minutes.
One statement per line.  cwState = wwState = HIGH;.  In this case its not a problem, but you can get into states where side affects screw everything up.  Also its easier to read.
Comment the code as you go, because you'll never go back.
Explain what each function does, because you'll have forgot by
tomorrow.

I hope that helps you write better code and none of it has caused offence.

That was so helpful man. why would knowledge and/or advice cause offence. Very practical advice. yeah I was opening braces like they do it in JAVA. Thanks a lot. #define or constant thing is very helpful too. will definitely keep all these points in mind from now on.

Putting aside the long press vs. short press, alternating the pwm generation is fairly simple.

Use an adc interrupt to periodically read the pot and update a variable that holds the duty cycle.
Use an interrupt to track the button input. In the isr, use a static variable to track which pwm pulse train is running. Upon button presses, update the variable and then use it to steer pwm output.

With this structure, your loop() is entirely empty and the functionalities (reading the pot, pwm generation and output steering) is done entirely in the background.
As to the long pushes, you can use a timer to track the button hold time and it returns not just the state of the button but also long vs. short presses.


text:
L298 works only when touched
The following image is my connection of l298 with Arduino.

This is the program.
int ENA = 10; // MCU PWM Pin 10 to ENA on L298n Board
int IN1 = 9;  // MCU Digital Pin 9 to IN1 on L298n Board
int IN2 = 8;  // MCU Digital Pin 8 to IN2 on L298n Board

int ENB = 5;  // MCU PWM Pin 5 to ENB on L298n Board
int IN3 = 7;  // MCU Digital pin 7 to IN3 on L298n Board
int IN4 = 6;  // MCU Digital pin 6 to IN4 on L298n Board

void setup()
{

pinMode(ENA, OUTPUT); //Set all the L298n Pin to output
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
void DRIVEONE()
{
// Run the motors on both direction at fixed speed
digitalWrite(IN1, HIGH); // Turn HIGH motor A
digitalWrite(IN2, LOW);
analogWrite(ENA, 200); // TO set the turning speed to 200 out of possible
range 0 to 255

digitalWrite(IN3, HIGH); // turn HIGH motor B
digitalWrite(IN4, LOW);  // To set the turning speed to 200 out of possible
range 0 to 255
analogWrite(ENB, 200);
delay(2000);  // Delay to 2 seconds
void loop()
{
DRIVEONE();
delay(100);
}

The program seems to work fine but the motors run only when I touch all the 15 pins in L298 as shown in the second image.
I don't understand why the motors aren't running without touching those 15 pins.

I have connected the L298 to a 12V rechargeable battery and Arduino to a 9V battery.
Please help me understand what is wrong here.
Thank you.

Your schematic does not show a connection from the ground line of the 12V battery to the GND connection on the Arduino.  This is required.


text:
I2Cdev #include weirdness
I am using Jeff Rowberg's MPU6050 library, and I simply don't understand what is going on in the following lines of the first example (MPU6050_raw.ino):
#include "I2Cdev.h"
#include "MPU6050.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE
// implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include <Wire.h>
#endif

So, what I got from that is, if I2Cdev is using Wire instead of some alternative I2C library, I should include Wire.h. I really don't see why that's necessary, so I removed the line in which Wire.h is included, and got this error:
C:\Users\Franco2500k\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:26: fatal error: Wire.h: No such file or directory
     #include <Wire.h>

So, apparently, I2Cdev.h already tries to include Wire.h, but somehow fails? And another #include a few lines later goes back in time and fixes everything? Can someone explain what is going on?

The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.
But of course, there's something missing from that list. The IDE doesn't copy libraries used by other libraries. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.

Indeed. I describe this process here: http://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them/13182#13182

Weird. So, if I understood that right, I2Cdev.cpp is not compiled, waiting to be linked; it is instead compiled with the entire project every time I build it, and the IDE knows which sources to compile by scanning the my source for #includes. Is that right?


text:
for loop reads pots, passes value to PWM pins, can this be in the same for loop?
In the code below I am using a for loop to iterate over analog pins (potentiometers) and pass their value, after being mapped, to PWM enabled analog output pins (currently controlling LED brightness). While this works as is, I am curious about the following: would it be better to split the analogRead and analogWrite lines into separate for loops, or would that simply be redundant from a code standpoint? My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.
The code:
static const uint8_t analog_pins[] = {A0, A1, A2, A3};
static const uint8_t digital_pins[] = {3, 5, 6, 9};
int pot_vals[] = {0, 0, 0, 0};
int val[] = {0, 0, 0, 0};

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

  // setup inputs, outputs
  for ( int i = 0; i < 4; i++ ) {
    pinMode( analog_pins[i], INPUT );
    pinMode( digital_pins[i], OUTPUT );
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    val[i] = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map( val[i], 0, 1023, 0, 255 ));
  }
  delay(2);
}

Analogue pins are configured as input by default. It is unnecessary to declare them in setup.

Having both the analogRead() and analogWrite() in the same loop is
perfectly fine. That would be be my preferred choice if only for one
reason: less RAM consumption. If you split them in two loops, you have
to store somewhere the readings of the four channels, either before or
after mapping. If you keep them in the same loop, you don't need the
pot_vals[] nor val[] arrays. You would use a local variable instead,
which consumes no RAM:
void loop() {
  for (int i = 0; i < 4; i++) {
    int val = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
  }
  delay(2);
}

My concern is accidentally mixing up the pot values due to
  difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead.
You have no risk of “mixing” any values here. Maybe, if you can
elaborate on the kind of issues you imagine you could have, we could
help you clear some misunderstanding about how the microcontroller
executes your code.

Edit: To expand on Andrew's comment, the for loop can be optimized
as
for (int i = 0; i < 4; i++) {
  unsigned int val = analogRead(analog_pins[i]);
  analogWrite(digital_pins[i], val / 4);
}

Dividing the value by 4 is the best way to map the input range to the
output range. It gives a more uniform mapping than the map() call
above, as every output value is mapped to exactly 4 input values. It
could be noted, though, that map(val, 0, 1024, 0, 256) gives the same
uniform mapping.
The division by 4, however, is optimized by the compiler into a bit
shift, which is orders of magnitude faster than map(), and likely to
consume less stack space. There is one caveat to be aware of: this
optimization is only possible if val is unsigned. If it is signed,
then it is compiled into a call to a division routine, which is quite
expensive.
One could be tempted to go even further and get rid of the temporary
val variable, like:
for (int i = 0; i < 4; i++) {
  analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
}

However, there is zero benefit from doing so: from the point of view of
an optimizing compiler, this form is exactly equivalent to the previous
one. I prefer the former which I deem more readable.

If you want to really simplify the code and minimize memory usage then you could even do: for (int i = 0; i < 4; i++)      analogWrite(digital_pins[i], analogRead(analog_pins[i])/4);

@Andrew: Your comment is both right and misleading: a naive reader may wrongly think that your not using the intermediate val variable is what reduces the memory footprint.

Obviously you can. Except that in most cases your loop execution is much faster than your own period so that you end up changing the duty cycles multiple times in one period.
Not an advisable aporoach. If you have to do it think about configuring the pwm center aligned.


text:
Arduino Uno + USB Host Shield + Motor Shield
We have an obstacle avoiding robot, and we decided to upgrade it by controlling it with a PS3 controller, so I am asking if above the Arduino UNO we can attach the USB host and above the Host attach the motor shield where the motors are connected to?

Read the documentation for both shields and see which (if any) pins they share, then decided if these pins can be shared.

You need to check the I/O used by each shield to make sure there is no conflicts.


text:
Can I test if something is connected to analog pin?
In my sketch I have a potentiometer connected to A0.  The value of the pot is used to adjust the speed of a connected item.
I have set the speed to have a default value, but doing analogRead() on a pin with nothing attached gives random values rather than using the default value.  The docs state "If the analog input pin is not connected to anything, the value returned by analogRead() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to the board, etc.)."  https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
How can I test whether something is connected to A0 and if not, use the default value?

Not in any general way, no, but it's unclear why this is a problem.

instead of connecting the pot between Vcc and Gnd, connect it between two data pins ... setting both the data pins to LOW should result in analog reading of near 0 V ... then set both to HIGH ... etc etc

@DaveNewton it is as a fallback value if pot doesn't exist.

In my sketch I have a potentiometer connected to A0 ... but doing analogRead() on a pin with nothing attached gives random values rather than using the default value. - Why is this an issue? - you say you have something connected, but you are asking how do you detect if nothing is connected. Do you, or do you not, have the pot connected to A0?

@NickGammon it makes the sketch more generic and acts as a fallback value if pot doesn't exist.

I agree with Boggyman's answer. A large-value resistor between A0 and Gnd would at least tend to give zero readings consistently. Although you wouldn't know then if the pot was just turned to its lowest setting. I don't know that there is any really reliable way to achieve what you want. There is no "default value" absent a pull-up or pull-down resistor. Possibly you could conclude that if you got lots of random values in a short time that there was nothing connected.

@NickGammon: Your last sentence is a summary of JRobert's answer. In practice, analog readings of floating inputs are not as random as you may expect, unless you have a strong capacitive coupling with a powerful noise source. You can artificially force the readings to have strong fluctuations though, as described in my answer.

Your last sentence is a summary of JRobert's answer - true, and being a comment it was not intended as an answer per se. I was commenting that there were a few different ways you could go about it. Stating the obvious, perhaps? :)

The input stage of the analog-to-digital converter is a sample-and-hold
capacitor. When you take an analog reading, the capacitor is connected
to the input pin, it is charged to the voltage you want to measure, then
it is disconnected from the input and it “holds” the voltage while the
conversion is in progress.
You can leverage this capacitor to detect whether your input pin is
floating. If you try to take an analog reading from a floating pin, the
sample-and-hold capacitor will not be able to charge or discharge
through it. You should then get a reading that is close to the
previous reading you took, although not exactly the same, as floating
pins a very prone to noise. Thus I suggest the following algorithm:

take a reading from a pin tied to GND, and discard this reading
take a reading from your input pin and record it
take a reading from a pin tied to +5V and discard it
take and record a second reading from your input pin

If the input pin is floating, the first recorded reading should be close
to zero, and the second one close to 1023.
Here is a test sketch demonstrating this approach. It uses
digitalWrite() to tie the required pins to GND and +5V, thus no
external connections are needed:
const uint8_t pin_input = A0;  // the one we are interested in
const uint8_t pin_low   = A1;  // will be tied to GND
const uint8_t pin_high  = A2;  // will be tied to +5V

void setup() {
    Serial.begin(9600);
    pinMode(pin_input, INPUT);
    pinMode(pin_low, OUTPUT);
    digitalWrite(pin_low, LOW);
    pinMode(pin_high, OUTPUT);
    digitalWrite(pin_high, HIGH);
}

void loop() {
    analogRead(pin_low);  // take a reading and discard it
    Serial.print(analogRead(pin_input));
    Serial.print(" ");
    analogRead(pin_high);  // take a reading and discard it
    Serial.println(analogRead(pin_input));
    delay(200);
}

And here is a sample output from an Arduino Uno:
167 710
271 748
287 753
287 751
284 748
281 746
279 741
271 736
268 733
264 732

It looks like the capacitor does not hold its charge very well across
consecutive readings. This is presumably caused by the parasitic
capacitance of the input pin, which partially charges and discharges the
sample-and-hold. Yet, the difference between consecutive recorded
readings (about 460) is still very high, and this very clearly shows
that the input pin is not connected to a stable voltage.

Take some number of analog readings over some period of time and look at the variation among the samples. Do this both with, and without, a potentiometer connected. You should see very stable readings with it connected, ranging over a few counts or less. Without it connected, the readings are likely to cover nearly the entire range A/D range.
A simple way to detect the pot would be to look at the difference between the highest and lowest readings. Pick a range that covers the "pot is connected" case. If the difference falls within that range, assume the pot is connected. Otherwise, assume it is not.
You could improve on this a number of ways, but a simple way would be to take, say, 50 readings, sort them by value, average the lowest 5 or 10 of them, and average the highest 5 or 10. Subtract those averages, and proceed as above.

The ADC input has a really high impedance (100 Meg).  All you need to do to get a consistent reading (of zero) is to connect it to ground through a suitable resistor.  100K will probably be fine, and you might be able to get away with 1 Meg.  It should be at least 10x bigger than your pot to avoid loading it when connected.

You are quite right, although such an arrangement would not distinguish between nothing connected and the pot turned to its lowest setting.


text:
Do I need a transistor if my relay has an optocoupler?
I'm looking to use this relay  with my arduino. It has an optocoupler and correct me if I'm wrong but this should prevent any back EMF from affecting my arduino. Do I still need to use a transistor?

I'm not sure why everyone wants to close this question as off-topic. But driving relays (especially relay boards) with an Arduino is, in my opinion very on topic.

I'm voting to close this for inactivity. Since it has been two weeks after a good answer and we haven't heard anything of the (relatively new) person who asked the question. So the question is likely to be abandoned.

That isn't just a relay you are linking to. That's an entire board that, among others, contains a relay (blue box). This board already has a transistor to drive the coil inside the relay. It also has a diode to handle back EMF.
It even has a opto-coupler, thought that isn't that useful as in most cases both sides of the opto-coupler are powered by the same 5V coming from the arduino.

Gerben is right. That is a complete board, not a relay. I have used some of these and they do not require a transistor to drive them (although you could use one if power output from the ports are a concern).
I beg to differ from Gerben, as the optocoupler isolates the pin from the driving circuit (even if it does not isolate the regulator) it still retains much of its safety characteristics.


text:
Battery Solution for ESP8266 and HC-SR04
I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.
I'm trying to keep costs down as well as make a system that works reliably and has good longevity.
I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.
Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.
Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.
Looking for any advice or affirmation that I'm on the right path. Thanks!

You can probably reconfigure a boost converter for 3.3v, and definitely find one intended more for the sort of thing you are trying to do, though perhaps not as a discount module.  You may however need to put some thought into the enable input for the boost converter, what it may draw when inactive, what you are going to cause the timed wakeup, and what that is going to run on.

You could use a 5v boost converter, and then use a voltage regulator to bring it down to 3.3v. I'd probably use a higher voltage battery and go with a buck converter. I think those are a bit more efficient. Also take a good look at the quiescent current of those voltage converters. As the quiescent alone can drain your battery pretty fast with nothing attached.

A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply here. Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like  MCP1825S (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.


text:
Sending "Blink" to pin 12 is causing on-board led to blink?
I recently picked up an Uno clone and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.
Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?
Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.
Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.
int ledPin = 12;
int delayPeriod = 100;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(delayPeriod);
  digitalWrite(ledPin,LOW);
  delay(delayPeriod);
  delayPeriod = delayPeriod + 100;
}

Is there a schematic available anywhere? This behavior is not expected, and certainly not characteristic of an Arduino.

Good question. I'm not sure. I've just emailed the company asking them if a schematic is available. I've also let them know about this unexpected behavior. I'm curious if this has happened to anyone else.

After some digging I came up with this pdf on their website. The second to last page, pg.121, may be it.

Those are the reference schematics, for the 2009 and Uno r1.

Ok, I thought maybe 2009 was AVMicrotech's internal name for their clone. I didn't realize it was an official board. Hopefully they'll get back with me soon.

Try measuring the resistance between the two pins using a multimeter, if you have one. Could be some flux residue or something between the solder joints on the underside, between pins 12 and 13. This residue is slightly conductive.

I checked and yes I was getting a measurement of around 150 ohms checking those two pins. Then again i checked the pairs of 8 and 9, 10 and 11, etc. and most of them read something in the same range. Is that level expected?

See Have I bricked my Arduino Uno? Problems with uploading to board
As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:
 pinMode(13, OUTPUT);
 digitalWrite (13, LOW);

See if that changes the behaviour.

Yes, adding that stopped the blinking.
So what should I do next?

According to this answer. The onboard led might turn on if you leave the pin floating and in input mode.  So you need to leave it in output mode, or make sure it's not floating. A pull-down or pull-up resister may help if you need it in input mode for some reason.

Thanks all for the help. You've given me some insight into the behavior I witnessed as well as more knowledge about this device.
Also, Nick, you're page that you linked to is an excellent resource, that I'm sure I'll refer to again in the future.


text:
Can a ESP8266 and a HC-SR04 be friends?
I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.
The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.
duration = pulseIn(echoPin, HIGH);

Any idea on how I can change the pulseIn function with interrupts or something else?
Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

This may be helpful, I have come across a library - newping.h that doesn't use pulseIn (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home). The code fails to compile when I include that whole library. I just want to be able to use the part to bypasses pulseIn and haven't figured that out yet.

Can a ESP8266 and a HC-SR04 be friends? Have you tried food, wine, candles and romantic music?

pulseIn() is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.
Also, I don't know which implementation of the ESP8266 plugin you are using, but the one I use has pulseIn available.

I'm using the same version of ESP8266 plugin as you are, thanks for letting me know that pulseIn() is already supported! I didn't see any mention of it in the reference documentation - http://arduino.esp8266.com/versions/1.6.5-947-g39819f0/doc/reference.html. I was also told that my code will compile even if all the functions aren't supported.

I had trouble with pulseIn() until the proper initializing code was put in setup().
As follows:

  pinMode(TRIGGER, OUTPUT);
  digitalWrite(TRIGGER, LOW);
  delay(2);
  pinMode(ECHO, INPUT);

TRIGGER and ECHO were initially defined at top of code with other variables as follows:
  #define TRIGGER 13 // Data pin D7
  #define ECHO    12 // Data pin D6

My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.

Project was a 'Tide' reporting system. A work in progress.
Also found HC-SR04 board was  unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.


text:
Arduino Mega as a USB device
My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?
Thanks,
Alexander

Not directly, no.  You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like.  It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.
That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part.  You will need to:

Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection
Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined
Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.

What the destinations on the PC end can be is a bit of a wooly area.  If you want to make it look like serial ports in /dev then you can use a pty pair, which is a master/slave pair of pseudo TTY devices that you can use to pass data through.  On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.
The function openpty(...) creates and opens a pty pair for you to use in your program.  You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.
For instance, here is a bit of code I use to open a pty pair:
struct termios options;
openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
fcntl(_masterfd, F_SETFL, 0);
tcgetattr(_masterfd, &_savedOptions);
tcgetattr(_masterfd, &options);
cfmakeraw(&options);
options.c_cflag |= (CLOCAL | CREAD);
if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
    fprintf(stderr, "Can't set up PTY\n");
}

That makes it appear to almost be a serial connection in style.  Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).
In that snippet you talk internally to the _masterfd with normal read() and write() functions as you would any other device or file.  Some other piece of software would open the other end of the pty pair (the _slavefd), the name of which is placed in _dev when the pty pair are opened.  You could use that _dev name to then create a symbolic link to a better named device instead of using the /dev/pts/x name that could change without warning from one run to the next.


text:
Can't able to detect Square wave from 74HC14
In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.
For that, I made Square wave with help of Arduino.
Here, it's code.
int kPinSqrOut = 13;

void setup()
{
   pinMode(kPinSqrOut, OUTPUT);
}

void loop()
{
  digitalWrite(kPinSqrOut, HIGH);
  delay(1000);
  digitalWrite(kPinSqrOut, LOW);
  delay(2000);

}
This is just simple HIGH and LOW one pin of arduino and we get Square wave.
Oscilloscope output :

Now based on this, I'm getting Square wave which length can be able to vary.
Here, it's code.
const uint8_t button_pin = 2;
const uint8_t kPin = 3;

void setup()
{
   pinMode(button_pin, INPUT_PULLUP);
   pinMode(kPin, OUTPUT);
   Serial.begin(9600);
}

void loop()
{
   static int last_button_state = LOW;
   static unsigned int push_count;
   static unsigned long last_press_time;
   int button_state = digitalRead(button_pin);
   unsigned long now = millis();

  // Record when the button is pressed.
  if(last_button_state == LOW && button_state == HIGH)
  {
    push_count++;
    last_press_time = now;

    digitalWrite(kPin, HIGH);
    delay(20);
    digitalWrite(kPin, LOW);
  }

  // Report when the button is released.
  if(last_button_state == HIGH && button_state == LOW)
  {
    unsigned long push_duration = now - last_press_time;
    if (push_duration < 10)   // discard bounce
    {
        push_count--;
    }
    else
    {
       Serial.print(F("pushes: "));
       Serial.print(push_count);
       Serial.print(F(", duration: "));
       Serial.print(push_duration);
       Serial.println(F(" ms"));
    }
  }

  last_button_state = button_state;
}

And Serial Monitor output :
pushes: 1,    duration: 1001
pushes: 2,    duration: 1000
pushes: 3,    duration: 1001
pushes: 4,    duration: 1002
pushes: 5,    duration: 1001

ve
So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.
Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.
Oscilloscope output :

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.
Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

So, give me some suggestion.

The main thing that's different between your two signals is the frequency. An incredibly low frequency signal works. A higher frequency signal doesn't. Maybe that's a clue to your problem? Maybe you should look at frequency counting and duty cycle measurement techniques that don't use digitalRead().

Oh, and using delay() in generating your output waveform is going to kill the reading of the input waveform completely.

@Majenko Ok, that means I have to replace delay() with something else which work same like delay means provide square wave with desired ms.

Personally I would use either interrupts or Input Capture to measure the incoming duty cycle in the background, and also write a non-blocking square wave output routine using millis() (or micros() if you want faster).

@Majenko Yes, I think that is also one solution. Just using interrupt, detect HIGH state of Square wave and when it detect just write non-blocking square wave output using millis() because I need readings on milliseconds. Thanks for this suggestion, let me try it out.

For your code use of Interrupt will solve your problem.

The only issue in your code is due to the delay in the pin control. You can solve it this way:
void loop()
{
    static int last_button_state = LOW;
    static unsigned int push_count;
    static unsigned long last_press_time;
    static bool kPinPressed = false;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if(last_button_state == LOW && button_state == HIGH)
    {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        kPinPressed = true;
    }

    if ((kPinPressed) && ((now - last_press_time) >= 20))
    {
        digitalWrite(kPin, LOW);
        kPinPressed = false;
    }

    ...
}

So you turn on the output, then after 20ms you turn it off.
There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?
And most important... What is the time scale? Is it really 10ms/div?

In last picture, Lower one waveform mean yellow trace is RPM waveform from auto rickshaw. And Upper one mean pink trace is waveform which filter out by RC circuit & passed through 74HC14. So as an output from 74HC14, I got this pink trace mean upper one waveform.

I think may be some noise present on that. That's why.

In serial interface, the reading you see is length of square wave which is generated by arduino. Length is in ms.

10 ms/ div ? I can't understand what this mean.

@Hasan ok, so there is an RC + 74HC14. Show the actual circuit, and please show also WHAT you expect from as output and what you get

Your code. Is designed to work with slow inputs and you are feeding it a much faster input than it can handle.
Solution 1. Use interrupts.
Solution 2. Speed up the main loop execution if you insist on polling.


text:
Vary the length of square waveform

Here in figure,  we can see two waveforms.
Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).
As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.
Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?
Here, I want to use Arduino because I have to vary the length of square wave with help of programming.  For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.
If possible then please give me some suggestion how to do this.

You should probably try to filter out the spike before it gets into the Schmitt triggers.

@EdgarBonet I already tried out Low pass filter and then output of that going into 74HC14.

needs by bypass caps. tiny ones; less than 100 puff.

The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD  1602 keypad shield will be enough for this.


text:
pulseIn() function not working

I want to find the length of upper one signal (purple one). So for that, i used pulseIn() function for that. But i just get 0 as a result in serial monitor.
int pulsepin = 8;
int value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Here, above is my arduino code which i used. I don't know why I don't get any reading except 0.

Looks like the voltage is too low to be read as a HIGH

@Gerben means pulseIn() not working for this ?

If digitalread doesn't work on this signal then pulseln won't work either.

@Gerben Too low to be read as a HIGH, or too high to be read as a LOW...? Looks like it's a ~2V pulse with a ~3V offset. Hard to work out from that trace, it doesn't give much information.

pulseIn() returns an unsigned long (32 bits) not an int (16 bits), so you may have some truncation occurring in your program leading to a 0 value.
Hence you should modify your program as follows:
int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Also beware that pulseIn() has a timeout (it will not wait forever).
This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get HIGH, then waiting for it to get back LOW. If no pulse is detected and complete (LOW -> HIGH -> LOW) within this time, then pulseIn() will return 0.
Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an unsigned long:
e.g. if you need 10 seconds, then:
  value = pulseIn(pulsepin, HIGH, 10000000UL);

I am not sure why you use delay(1000) in your loop(), I would remove it as a pulse may occur during that time and it would not be seen by your program.
Here is a suggested update (I also used const where it made sense but that won't change program behavior):
const unsigned long PULSEIN_TIMEOUT = 10000000UL;
const int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  Serial.println(value);
}

You may also want to avoid printing 0 values since they mean no pulse was detected:
void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  if (value > 0)
    Serial.println(value);
}

Thank you for explanation. Here, i used delay(1000) because every time whenever readings are serially printed in serial monitor, it's very hard to identify the changes between those readings. So, delay(1000) used only for my convenient purpose, so i can see every readings after every 1 second,nothing else.

And as you say, value = pulseIn(pulsein, HIGH,10000000UL ) that mean pulseIn() function wait for 10 seconds until signal goes LOW or gets that 10 second long pulse. I can't understand. Can it possible to get 10 seconds or any seconds pulse means length of pulse is 10 seconds or any seconds length with help if this line of code.

The timeout is global this means in these 10 seconds, the signal must first go HIGH then go LOW. If you call pulseIn() at t0, and the signal gets HIGH at t1, then gets back LOW at t2, then you must have t2 - t0 < timeout (10s), then pulseIn() will return t2 - t1; if ever t2 - t0 > timeout, then the pulse will not be recognized and pulseIn() will return 0.

It works strange anyway. It works for 10s and doesn't for 1s. It's always returning zero... pulseIn(buttonPin, HIGH, 1000000UL); - 1s.


text:
Find the time between HIGH state & LOW state of push button(switch)
I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.
const int  buttonPin = 2;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long finalMillis = 0;

int buttonPushCounter = 0;

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

   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH);
}

void loop()
{
  if (digitalRead(buttonPin) == LOW)
  {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);

    while(digitalRead(buttonPin) == LOW)
    {
      currentMillis = millis();
    }

    finalMillis = currentMillis - previousMillis;
    Serial.println(finalMillis);

    previousMillis = finalMillis;
    //finalMillis = 0;
  }
}

Here, it is my serial monitor output.
on
number of button pushes:  1
0
on
number of button pushes:  2
775
on
number of button pushes:  3
873
on
number of button pushes:  4
1425
on
number of button pushes:  5
1496
on
number of button pushes:  6
2073
on
number of button pushes:  7
2010
on
number of button pushes:  8
2643
on
number of button pushes:  9
3052
on
number of button pushes:  10
3195
on
number of button pushes:  11
3396
on
number of button pushes:  12
3575
on
number of button pushes:  13
3737

TL;DR make sure you keep switch-bounce in mind.

While the previously given answers should work for you, they share a
couple of problems with your original code:

they do not debounce the button
they block while waiting for the button to be released

Blocking the program is not a big deal if you do not have to do anything
else. However, chances are you are showing us only a fraction of what
will ultimately be a larger program. In this case, doing a busy wait
(like while (digitalRead(buttonPin) == LOW) ;) will block the whole
program, not only this particular feature. Then, I suggest you get
immediately in the habit of writing non blocking code:

when the button is pressed, record that fact and the current time
when the button is released, report to the user

The important notion is that you never wait for anything. Instead, you
check whether something has to be done right now and, if so, you do
it.
Here is a non-blocking version of your program, with some debounce
added:
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}

Thank you for your suggestion. It's works great. Yes, you're right. Previous answers gives me result which I expected but sometimes it's provides garbage value even if I pressed button for same time.

First of all, frarugi87 is right.
Second, why not use this:
finalMillis = millis() - previousMillis;
previousMillis = millis();

Instead of what you wrote.
if (digitalRead(buttonPin) == LOW) {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);
    finalMillis = millis() - previousMillis;
    previousMillis = millis();
    Serial.println(finalMillis);
    while(digitalRead(buttonPin) == LOW){}
  }

It works great.
Hope it helps.
Yoav

You wrote
previousMillis = finalMillis;

This means that you store the duration of the pulse, not the last time it was pressed.
Change it with
previousMillis = currentMillis;

and you will be able to detect the high + low time.
By the way, constantly reading the millis function is useless. You can change your code to
while(digitalRead(buttonPin) == LOW);
currentMillis = millis();

which reads only once.


text:
is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together?
I am lakshman a mechanical engineer,i have a question that is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together???
so that i can take the output value from Accelerometer so that to make a call to a preprogrammed number???
Plz help me.
Thank you.

Please provide links to the devices you have in mind, or is this just a very general question?

Yes, it is possible.

Yes, that is perfectly possible.  Typically:

Accelerometer is either an analog, SPI or I2C interface.
GSM is usually a UART interface
The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.

A little too much jargon, @Majenko. I had to Google what SMOP meant. ;) (And some of the results probably were not what you meant).

@NickGammon Just a "Small Matter of Programming" - i.e., if you have to ask this then you have a lot of learning to do before you can write the software, and while it would be simple for us, for someone that doesn't even know if you can connect these things together it's not going to be a simple task


text:
Is it possible to use Adafruit's Circuit Playground Express's 2MB storage in Arduino IDE?
I understand that the extra 2MB of memory is for circuit python.  However, I wouldn't mind having access to 2MB of storage and using the Arduino IDE/low level C to access it.  Is that possible?  If so, how?

please provide all available information in your post ... there is no reason why people would have to do internet searches for a datasheet and for any applicable libraries before being able to answer your question

You may be interested in Adafruit's FRAM breakout board: https://www.adafruit.com/product/1895 They have an SPI version too, and both support 256Kbit's of persistent storage. Plus, they're super easy to use.

https://github.com/adafruit/Adafruit_SPIFlash

What is Adafruit's Circuit Playground Express's 2MB storage?

@Majenko, a board by Adafruit a well known and established company with a good web site. Circuit Playground Express is the only one not Arduino board in Arduino SAMD boards package. you could ask what is Neopixels or Feather Huzzah or MKR

@Juraj Yes.... I know who Adafruit are. But what is the "2MB storage"? Is it a physical device? If so what is it? Or is it some online service provided by Adafruit? It's not clear, and I shouldn't need to google these things.

So... it's just a run-of-the-mill 16Mb SPI flash chip. Big whoop. Wanna fight about it? Also Cypress list that model as obsolete now...

@Majenko, as I saw the question I opened the Adafruit site for the board and there it is: "2 MB of SPI Flash storage, used primarily with CircuitPython to store code and libraries.".

In their guided tour of the Adafruit Circuit Playground Express, it specifically states:

You can use this in Arduino or CircuitPython to store files.

So yes, it is possible. As far as the how, according to this guide (also from Adafruit), that they have also made a library, Adafruit SPI Flash, which has a bunch of examples showing how to read from, write to, and format the SPI flash whilst retaining compatibility with CircuitPython, among other things.


text:
Can I force a function to live in the boot sector without overwriting the bootloader?
Not for any practical purpose but just out of curiosity, I want to abuse the flash memory and write it dynamically at run-time.  This is, in a sense, what the bootloader does.  If I understand it, the only way to modify flash is to do so from instructions written to the boot sector.  Is it possible to stick a simple function in there that writes to flash memory, and call it from running code?  If so, how do I put it there?  I have no issue with calling functions from function pointers, so I don't think I'll have an issue actually calling the function once I get there, but I need to know how to stick into flash in the first place.

The Optiboot version 8 has a do_spm function which can be called from application. The Optiboot repository contains an example for the use of this function.
SPM is the AVR CPU instruction to write to flash memory. The Optiboot wraps this in a function. A pointer to this function is put in a 'vector table' at the beginning of the bootloader. The first pointer jumps to main, the second pointer jumps to do_spm. The optiboot.h then has the function as (version for small Optiboot)
typedef void (*do_spm_t)(uint16_t address, uint8_t command, uint16_t data);
const do_spm_t do_spm = (do_spm_t)((FLASHEND-511+2)>>1)

I made an enhancement of this, a copy_flash_pages function with reset option to bootload an AVR from its own flash. It is added as third entry in the 'vectors table' of Optiboot. It is used in my ArduinoOTA library for AVR MCUs.
typedef void (*copy_flash_pages_t)(uint32_t dest, uint32_t src, uint16_t page_count, uint8_t reset);
const copy_flash_pages_t copy_flash_pages = (copy_flash_pages_t)((FLASHEND-1023+4)>>1);

That's very interesting, thanks.  I will check it out


text:
EEPROM library throwing errors
I've included  in my sketch and am trying to run a simple sketch that just does EEPROM.write(0,4); followed by a println of EEPROM.read(0);  However, it won't compile.  It keeps telling me there is an error, and that I'm making a "request for member 'write' in something that is not a structure or a union".  I'm using the Mega ADK.  What am I doing wrong?  I've also tried to go to sketch->include libraries and include the EEPROM library directly, still no joy.  This is Arduino 1.6.13 on Windows 8, if it matters.

You need to list your program ("sketch") for us to help.  Guessing, (this is actually C++ so it's going to sound more complex than it really is, but) did you instantiate an instance of the EEPROM class?  Did you include the header file for this class in your program?

Actually I figured it out.  I was using the wrong data types (my sketch wasn't quite what I had shown).  I was sending in an unsigned int to the read/write as the address, but it requires an int and the data type is important.

This will sound odd, but in C++ passing the wrong data type is just like calling a totally different method.  The up side, you can, for example, write a number of identically named methods that can handle different data types in unique ways.  Obviously, the library authors could have done this, but did not.  Maybe that is an improvement you can implement.

I suggest you create an answer to your question. It can then (in a couple of days IIRC) be accepted as the right answer and other people can be helped by it.

The problem had to do with data types.  I was using an unsigned int as follows:
unsigned int addr = 0;
EEPROM.write(addr,5);

However, EEPROM.write requires an int, not an unsigned int, and this caused a compiler error.

Also same error if you try to compile eeprom.h (C++) into a C program