text:
How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW
The Arduino Uno board has limited RAM which means it has a limited call stack available. Sometimes, recursion is the only quick option to implement a certain algorithm. So, given that the call stack is severely limited, what would be a way to find out that given a certain program running on the board, exactly how many recursive calls can you afford before there is a stack overflow (and bad things happen)?

Can you give an example of an algorithm where the choice between a recursive and non-recursive solution is so clear cut?

@Cybergibbons Most recently, I had to write and test RDP in a short time span, so I went ahead with the recursive implementation. I am not saying that iterative is not possible, just that it may be easier to go ahead with the recursive version.

What does this mean in the question title: How much ca!@#QFSD@$RFW? I'm curious as to why no-one has edited that out to be something more meaningful (in the last 4 years).

The answer is 211 times (depending on many factors) :). See my answer here: https://arduino.stackexchange.com/a/51098/7727. @NickGammon, he is pretend "cursing" I think. It is a play on word for "recurse". Took me a minute to figure that out too. Was pretty confusing at first.

Oh I see. I thought the SE servers might have had a glitch :)

If you really want to recurse (and as @jippie said it is a bad idea; subliminal message:  don't do it) and want to know how much you can recurse, then you will have to perform some calculation and experiments; also you generally will have only an approximation of it as it depends a lot on the memory state at the time your recursive function will be called.
For this, you should first know how SRAM is organized inside AVR-based Arduino (it won't apply to e.g. the Arduino Galileo by Intel). The following diagram from Adafruit shows it clearly:

Then you need to know the total size of your SRAM (depends on Atmel MCU, hence what kind of Arduino board you have).
On this diagram, it is easy to find out ths size of Static Data block as it is known at compile-time and won't change later on.
The Heap size can be more difficult to know as it can vary at runtime, depending on dynamic memory allocations (malloc or new) performed by your sketch or the libraries it uses. Using dynamic memory is quite rare on Arduino, but some standard functions do it (type String uses it, I think).
For the Stack size, it will also vary during runtime, based on the current depth of function calls (each function call takes 2 bytes on the Stack to store the address of the caller) and the number and size of local variables including passed arguments (that are also stored on the Stack) for all the functions called until now.
So let's suppose your recurse() function uses 12 bytes for its local variables and arguments, then each call to this function (the first one from an external caller and the recursive ones) will use 12+2 bytes.
If we suppose that:

you are on Arduino UNO (SRAM = 2K)
your sketch does not use dynamic memory allocation (no Heap)
you know the size of your Static Data (let's say 132 bytes)
when your recurse() function is called from your sketch, the current Stack is 128 bytes long

Then you are left with 2048 - 132 - 128 = 1788 available bytes on the Stack. The number of recursive calls to your function is thus 1788 / 14 = 127, including the initial call (which is not a recursive one).
As you can see, this is very difficult, but not impossible to find what you want.
A simpler way to get the stack size available before recurse() is called would be to use the following function (found on Adafruit learning center; I have not tested it myself):
int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

I strongly encourage you to read this article at Adafruit learning center.

I see peter-r-bloomfield posted his answer while I was writing mine; his answer looks better as it fully describes the content of the stack after a call (I had forgotten the registers state).

Both very good quality answers.

Static data = .bss + .data, and is what is reported by Arduino as "RAM taken up by global variables" or whatever, correct?

@GabrielStaples yes exactly. In more detail .bss represents the global variables with no initial value in your code, whereas data is for global variables with an initial value. But in the end they use the same space: Static Data in the diagram.

@GabrielStaples forgot one thing, technically these are not only global variables going there, you also have variables declared static within a function.

Follow up question: is there such a thing as allocating some ram for stack and some for heap, or is it all available for either? In other words, someone told me that stack size is set in a linker script or something but I thought the entire ram could be used arbitrarily by stack or heap as they need it. What's the truth? Does Arduino use a linker script? If so, where is it?

No, the whole SRAM is dedicated to both Heap and Stack altogether (one is allocated from the top, the other from the bottom). It is developer's responsibility to ensure heap and stack do not collide in each other.

Note that there has been several questions here about Arduino memory, some with very comprehensive answers. It might be worth taking a look at them if you want to know more about this topic.

Note that there are some threading libraries for Arduino floating around. When using these, you do have to explicitly allocate stack space, usually within the heap, for all but the main thread. This, however, is an uncommon situation. The situation you describe is by far the most common.

Recursion is bad practice on a microcontroller as you already stated yourself and you probably want to avoid it whenever possible. On the Arduino site there are some examples and libraries available for checking free RAM size. You can for example use this to figure out when to break recursion or a bit trickier/riskier to profile your sketch and hard code the limit in it. This profile would be required for every change in your program and for every change in Arduino tool chain.

Some of the more high-end compilers, such as IAR (who do support AVR) and Keil (who do not support AVR) have tools to help you monitor and manage stack space. It's really not advisable on something as small as an ATmega328 though.

It depends on the function.
Every time a function is called, a new frame is pushed onto the stack. It will usually contain various critical items, potentially including:

Return address (the point in the code from which the function was called).
The local instance pointer (this) if calling a member function.
Parameters passed into the function.
Register values which need to be restored when the function ends.
Space for local variables inside the called function.

As you can see, the stack space required for a given call depends on the function. For example, if you write a recursive function which only takes an int parameter and uses no local variables, it won't need much more than a few bytes on the stack. That means you can recursively call it far more than a function which takes several parameters and uses a lot of local variables (which will eat up the stack much quicker).
Obviously the state of the stack depends on what else is going on in the code. If you start a recursion directly within the standard loop() function, then there probably won't be a lot on the stack already. However, if you start it nested several levels deep in other functions, then there won't be as much room. That will affect how many times you can recurse without exhausting the stack.
It's worth noting that tail recursion optimisation exists on some compilers (although I'm not sure if avr-gcc supports it). If the recursive call is the very last thing in a function, it means it is sometimes possible to avoid altering the stack frame at all. The compiler can just re-use the existing frame, since the 'parent' call (so to speak) is finished using it. That will mean you can theoretically keep recursing as much as you like, so long as your function doesn't call anything else.

avr-gcc does not support tail recursion.

@AsheeshR - Good to know. Thanks. I figured it was probably unlikely.

You can do a tail call elimination/optimization by refactoring your code instead of hoping the compiler will do it. As long as the recursive call is at the end of the recursive method you can safely re-write the method to use a while/for loop.

The post by @TheDoctor contradicts "avr-gcc does not support tail recursion", as does my test of his code. The compiler did indeed implement tail recursion, which is how he got up to a million recursions. Peter is correct - it is possible for the compiler to replace call/return (as the last call in a function) with simply jump. It has the same end result and does not consume stack space.

I had this exact same question as I was reading Jumping into C++ by Alex Allain, Ch 16: Recursion, p.230, so I ran some tests.
TLDR;
My Arduino Nano (ATmega328 mcu) can do 211 recursive function calls (for the code given below) before it has a stack overflow and crashes.
First off, let me address this claim:

Sometimes, recursion is the only quick option to implement a certain algorithm.

[Update: ah, I skimmed the word "quick". In that case you have some validity. Nevertheless, I think it's worth saying the following.]
No, I don't think that is a true statement. I'm pretty certain all algorithms have both a recursive and a non-recursive solution, without exception. It's just that sometimes it is significantly easier to use a recursive algorithm. Having said that, recursion is very much frowned upon for use on microcontrollers and would probably never be allowed in safety-critical code. Nevertheless, it is possible of course to do it on microcontrollers. To know how "deep" you can go into any given recursive function, just test it! Run it in your real-life application in a real-life test case, and remove your base condition so that it will infinitely recurse. Print out a counter and see for yourself how "deep" you can go so you know whether or not your recursive algorithm is pushing the limits of your RAM too close to be used practially. Here's an example below to force stack overflow on an Arduino.
Now, a few notes:
How many recursive calls, or "stack frames" you can get is determined by a number of factors, including:

The size of your RAM
How much stuff is already on your stack or taken up in your heap (ie: your free RAM matters; free_RAM = total_RAM - stack_used - heap_used, or you might say free_RAM = stack_size_allocated - stack_size_used)
The size of each new "stack frame" which will be placed onto the stack for every new recursive function call. This will depend upon the function being called and its variables and memory requirements, etc.

My results:

20171106-2054hrs - Toshiba Satellite w/16 GB RAM; quad-core, Windows 8.1: final value printed before crash: 43166

took several seconds to crash--maybe 5~10?

20180306-1913hrs Dell high-end laptop w/64 GB RAM; 8-core, Linux Ubuntu 14.04 LTS: final value printed before crash: 261752

followed by the phrase Segmentation fault (core dumped)
took only ~4~5 sec or so to crash

20180306-1930hrs Arduino Nano: TBD---is at ~250000 and still counting---the Arduino optimization settings must have caused it
to optimize out the recursion...??? Yes, that is the case.

Add #pragma GCC optimize ("-O0") to the top of the file and redo:

20180307-0910hrs Arduino Nano: 32 kB flash, 2 kB SRAM, 16 MHz processsor: final value printed before crash: 211

Here are the final print results:
209
210
211  ⸮ 9⸮   3⸮

took only a fraction of a second once it started printing at 115200 serial baud-rate--maybe 1/10 sec
2 kiB = 2048 bytes / 211 stack frames = 9.7 bytes/frame (assuming ALL of your RAM is being used by the stack--which actually isn't the case) --but this seems very reasonable nonetheless.

The code:
The PC application:
/*
stack_overflow
 - a quick program to force a stack overflow in order to see how many stack frames in a small function can be loaded onto the stack before the overflow occurs

By Gabriel Staples
www.ElectricRCAircraftGuy.com
Written: 6 Nov 2017
Updated: 6 Nov 2017

References:
 - Jumping into C++, by Alex Allain, pg. 230 - sample code here in the chapter on recursion

To compile and run:
Compile: g++ -Wall -std=c++11 stack_overflow_1.cpp -o stack_overflow_1
Run in Linux: ./stack_overflow_1
*/

#include <iostream>

void recurse(int count)
{
  std::cout << count << "\n";
  recurse(count + 1);
}

int main()
{
  recurse(1);
}

The Arduino "Sketch" program:
/*
recursion_until_stack_overflow
- do a quick recursion test to see how many times I can make the call before the stack overflows

Gabriel Staples
Written: 6 Mar. 2018
Updated: 7 Mar. 2018

References:
- Jumping Into C++, by Alex Allain, Ch. 16: Recursion, p.230
*/

// Force the compiler to NOT optimize! Otherwise this recursive function below just gets optimized into a count++ type
// incrementer instead of doing actual recursion with new frames on the stack each time. This is required since we are
// trying to force stack overflow.
// - See here for all optimization levels: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
//   - They include: -O1, -O2, -O3, -O0, -Os (Arduino's default I believe), -Ofast, & -Og.

// I mention `#pragma GCC optimize` in my article here: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html
#pragma GCC optimize ("-O0")

void recurse(unsigned long count) // each call gets its own "count" variable in a new stack frame
{
  // delay(1000);
  Serial.println(count);

  // It is not necessary to increment count since each function's variables are separate (so the count in each stack
  // frame will be initialized one greater than the last count)
  recurse (count + 1);

  // GS: notice that there is no base condition; ie: this recursive function, once called, will never finish and return!
}

void setup()
{
  Serial.begin(115200);
  Serial.println(F("\nbegin"));
  // First function call, so it starts at 1
  recurse (1);
}

void loop()
{
}

References:

Jumping into C++ by Alex Allain, Ch 16: Recursion, p.230
http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html - literally: I referenced my own website during this "project" to remind myself how to change Arduino compiler optimization levels for a given file with the #pragma GCC optimize command since I knew I had it documented there.

Note that, according to the docs of the avr-lib, you should never compile without optimization anything that relies on the avr-libc, as some thing are not guaranteed to even work with optimization turned off. I thus advice you against the #pragma you are using there. Instead, you may add __attribute__((optimize("O0"))) to the single function you want to unoptimize.

Thanks, Edgar. Do you know where AVR libc has this documented?

The documentation on <util/delay.h> states: “In order for these functions to work as intended, compiler optimizations must be enabled [...]” (emphasis in original). I'm not quite sure whether any other avr-libc functions have this requirement.

I wrote this simple test program:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  recurse(1);
}

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

}

void recurse(long i) {
  Serial.println(i);
  recurse(i+1);
}

I compiled it for the Uno, and as i write it has recursed over 1 million times! I don't know, but the compiler may have optimized this program

Try to return after a set number of calls ~1000. It should create a problem then.

The compiler has cunningly implemented tail-recursion on your sketch, as you will see if you disassemble it. What this means is that it replaces the sequence call xxx / ret by jmp xxx. This amounts to the same thing, except that the compiler's method does not consume the stack. Thus you could recurse billions of times with your code (other things being equal).

You can force the compiler not to optimize out the recursion. I'll come back and post an example later.

Done! Example here: https://arduino.stackexchange.com/a/51098/7727. The secret is to prevent optimization by adding #pragma GCC optimize ("-O0")  to the top of your Arduino program. I believe you have to do this at the top of each file you want it to apply to--but I haven't looked that up in years so research it for yourself to be sure.


text:
Are there any signal smoothing libraries for Arduino?
I am working on a mobile robot controlled via a wireless 2.4 GHz link.The receiver is connected to the Arduino Uno which serves onboard as the main controller. The most critical (and main) input channel coming from the receiver produces a very noisy signal, which leads to lots of minor changes in the output of the actuators, even though these are not needed.

                    Plot of the input of the Arduino in a 30 second interval.
I am looking for libraries that can perform efficient smoothing. Are there any signal smoothing libraries available for the Arduino (Uno)?

Don't know if you can find this kind of libraries but I'm afraid these might need to much CPU power for an Arduino. I'd rather go with an electronic solution (low-pass filter) if possible.

I am with  jfpoilpret on this. I think you need an electronic solution. I would try a stabilization capacitor, (simple low pass filter). I assume you are using an adc channel, so you should put a cap from this channel to ground. Start with values around 100pf, and work up from there.

Microsmooth is a lighweight signal smoothing library currently being developed by me.
It is still being worked on and the aim is to make it lightweight in terms of memory and fast. The library provides multiple filters for smoothing:

Simple Moving Average
Exponential Moving Average
Cumulative Moving Average
Savitzky Golay Filter
Ramer Douglas Pecker Algorithm
Kalmogorov Zurbenko Filter

To use the library, download and add it to the source directory. Also, add the following line to your source file:
#include "microsmooth.h"

Hi, I'm having trouble using your library. You wouldn't use "Import Library..." to import your library right? I tried just copying the source into my .ino folder, but I'm getting errors about missing automicrosmooth.h, Serial not being defined, and missing ';'. Is this library still working? Thanks

@waspinator Sorry about that. Fixed the errors. Thanks for the feedback!

I think I see a lot of single-sample noise spikes in your noisy signal.
The median filter does better at getting rid of single-sample noise spikes than any linear filter.
(It is better than any low pass filter, moving average, weighted moving average, etc. in terms of its response time and its ability to ignore such single-sample noise spike outliers).
There are, in fact, many signal-smoothing libraries for the Arduino, many of which include a median filter.
signal-smoothing libraries at arduino.cc:

Paul Badger: smooth digital low-pass filter
Paul Badger: digitalSmooth digital low-pass filter with outlier rejection
David A. Mellis and Tom Igoe: Smoothing tutorial
Majenki: Average Library

signal-smoothing libraries at github:

AsheeshR / Microsmooth
jeroendoggen: Arduino-signal-filtering-library
karlward: Arduino data filtering library
sebnil: FIR-filter-Arduino-Library
daPhoosa: MedianFilter
arc12: A Collection of Digital Signal Filters (intended for use with Arduino)
sebnil: Selfbalancing robot in Arduino. Implemented with PID controllers, FIR filters, complementary filter.

Would something like this work in your robot?
(The median-of-3 requires very little CPU power, and hence fast):
/*
median_filter.ino
2014-03-25: started by David Cary
*/

int median_of_3( int a, int b, int c ){
    int the_max = max( max( a, b ), c );
    int the_min = min( min( a, b ), c );
    // unnecessarily clever code
    int the_median = the_max ^ the_min ^ a ^ b ^ c;
    return( the_median );
}

int newest = 0;
int recent = 0;
int oldest = 0;

void setup()
{
    Serial.begin(9600);
    // read first value, initialize with it.
    oldest = random(200);
    recent = oldest;
    newest = recent;
    Serial.println("median filter example: ");
}

void loop()
{
    // drop oldest value and shift in latest value
    oldest = recent;
    recent = newest;
    newest = random(200);

    Serial.print("new value: ");
    Serial.print(newest, DEC);

    int median = median_of_3( oldest, recent, newest );

    Serial.print("smoothed value: ");
    Serial.print(median, DEC);
    Serial.println("");

    delay(5000);
}

Have you tried a low pass filter? I found an example here an another one here.
Both of these libraries have a list of data being read from the analog sensor of your choice which is averaged. Every new sensor value is added to the list, and the last one is thrown out, like this:
List: 3 4 3 3 4 3 5 3 2 3 4 3
new reading added. old one thrown out
      /--                     /--
List: 5 3 4 3 3 4 3 5 3 2 3 4
list averaged

Pretty much what a simple FIR filter does with all tap values set to 1. Fiddling with the taps values can improve the signal further, but requires higher math.

Note: The second link computes the cumulative moving average which is not a practical choice for actuator control, especially one which may involve frequent start and stops. The smoothed signal will always trail the peak value of the actual signal by quite a margin.

You could filter this digitally using a low pass filter:
int valueFilt = (1-0.99)*value + 0.99*valueFilt;

Change the 0.99 to change the cut off frequency (closer to 1.0 is lower frequency). The actual expression for that value is exp(-2*pi*f/fs) where f is the cutoff frequency you want and fs is the frequency the data is sampled at.
Another type of "digital filter" is an event filter. It works well on data that has outliers; e.g. 9,9,8,10,9,25,9 . An event filter returns the most frequent value. Statistically this is the mode.
Statistical averages such as Mean, Mode etc.. can be calculated using the Arduino Average Library.
An example taken from the Arduino Library page referred to :
#include <Average.h>
#define CNT 600
int d[CNT];

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

void loop()
{
  int i;

  for(i=0; i<CNT; i++)
  {
    d[i] = random(500);
  }

  Serial.print("Mean: ");
  Serial.print(mean(d,CNT),DEC);
  Serial.print(" Mode: ");
  Serial.print(mode(d,CNT),DEC);
  Serial.print(" Max: ");
  Serial.print(maximum(d,CNT),DEC);
  Serial.print(" Min: ");
  Serial.print(minimum(d,CNT),DEC);
  Serial.print(" Standard deviation: ");
  Serial.print(stddev(d,CNT),4);
  Serial.println("");
  Serial.println("");

  delay(5000);
}

Note that this will be very slow, since it's doing lots of implicit casts to float and back.

Check out the Arduino Smooth library. It uses absolutely no arrays, no looping over past values, it's fast with constant compute time, and the objects take up 8 bytes regardless of the sample window size.

It would be worth mentioning that this library, like some of the others already cited, implements an exponentially-weighted moving average. The fact that it works in constant-time and constant-size is nothing special: this is how this type of filter is always implemented. There are good use cases for an exponentially-weighted moving average, but the spiky noise of the original question is not one of them: this would be better served by a moving median.

source: Stack Exchange

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

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

sort: votes


text:
Docs for using i2C LCD with Newliquidcrystal_1.3.5 library?
I bought a 20x4 I2C LCD from OddWires. (https://www.oddwires.com/20x4-lcd-display-with-i2c-interface/) It came with ZERO specs or documentation. After some hair-pulling I was able to figure out how to get it working. (I had to use the commands
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address and pin assignments, including the backlight pin and polarity

and
  lcd.begin(20,4);               // initialize the lcd to 20 characters, 4 lines

To get the LCD working (The tricky bit was figuring out the pin assignments. They're not documented.)
I'm assuming this LCD unit is a lot like all the others out there.
It works, and If found the basic commands to clear the screen, position the cursor, and print text.
I've also found commands lcd.cursor() and lcd.noCursor() that let me show/hide the cursor.
I'd like to know if I can do things like blink characters between normal and inverse, underline text, etc using the standard LCD library (I've seen code that uploads custom character maps, so I assume I could upload an alternate underlined character set, but that sounds like a LOT of work for something I'm hoping is built in to the library.)
Can somebody point me to docs on the full suite of commands commonly available for these LCD units in the Arduino Newliquidcrystal_1.3.5 library?
(Sorry to be vague on the specifics of my LCD module. I did not get specs from the vendor, so I have had to guess as to how to use it.)
I'm using the I2C LCD NewLiquidCrystal LCD library. (https://github.com/fmalpartida/New-LiquidCrystal)

https://www.sparkfun.com/datasheets/LCD/HD44780.pdf ..... the link that you posted shows that the controller chip is the HD44780

So it does. (in passing.) I missed that. Thanks. I'm not clear on how I access the features of the HD44780 through the I2C backpack however.

@jsotola So it does (in passing). I missed that. Thanks. That's the datasheet for the LCD driver. It isn't clear to me what I can do from the  I2C "backpack" on my LCD module.

Something might be wrong w/your example code.  The LiquidCrystal_I2C code at github clearly shows a constructor with only 3 arguments (i2c_address, columns, rows).  Can you explain this?

@st2000, Yes, there are at least 3 different versions of the constructor. The one with just 3 arguments assumes default pin assignments, and doesn't work. I had to use the long form that included all the different pin assignments in order to get it to work.

Perhaps I do not understand.  In the link in my comment above is the code by John Rickman on github.com for LiquidCrystal_I2C which I assume you are using.  The only definition for the constructor is on line 47.  I do not see where this is an over-loaded constructor as you are indicating.  Therefore it is difficult to help as we do not know the meaning of the arguments you are using when you instantiate an instance of LiquidCrystal_I2C.

As I say in the title of my question, I'm using the library Newliquidcrystal_1.3.5, which (I think) is an enhancement of LiquidCrystal_I2C. (https://github.com/fmalpartida/New-LiquidCrystal)

There are many many Arduino LCD drivers out there spread on sites such as github and bitbucket.  The one I pointed to was is one of the more commonly used ones.  Please edit your original question to include this important link.  (I've run out of time just now - I think what you need is a link to the commonly used LCD chip specs & perhaps an explanation as to what to expect.  If no one else answers I'll try to form an answer later when I have more time.)

Often in software development, the code is the documentation. The merits of this are debated ad nauseam elsewhere.
As you have provided a link to the GitHub repository of the library you are using, you have all you need, though the provided utility/docs path doesn't fully document the I2C interface.
The function prototype (that is, the function, its return type, and parameters, but without the actual code) is found in header files which usually have the .h suffix.
Since you have an LCD with a I2C interface, you can look at the GitHub repo for the file LiquidCrystal_I2C.h
Within this file, you can see that the class is defined with name LiquidCrystal_I2C and has multiple constructors, each with a different list of parameters. The particular class constructor used is the one that matches the count and type called in your declaration of the object of that class.
The code in the header file is well documented. The first prototype listed includes good commenting:
/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    */
   LiquidCrystal_I2C (uint8_t lcd_Addr);
   // Constructor with backlight control
   LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);

This block shows the first 2 constructor options: With a uint8_t type that defines the I2C address of an I/O expansion module (which is what many "LCD backpacks" are -- that, or shift registers), and one with an I2C address, a backlight pin, and the polarity of the backlight.
Proceeding down, we find the one with 10 parameters, which is what you ended up using:
  /*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d4[in] LCD data 0 pin map on IO extender module
    @param      d5[in] LCD data 1 pin map on IO extender module
    @param      d6[in] LCD data 2 pin map on IO extender module
    @param      d7[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7 );
   // Constructor with backlight control
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
                     uint8_t backlighPin, t_backlighPol pol);

That last constructor is used to override the default pin mappings from the I/O Expander to the LCD. This is tricky -- what were the mappings based on? An I/O expander is basically a way to access multiple pins on an external chip through a single two-wire interface (I2C). How an LCD is connected depends on what pins of the I/O Expander are connected to which pins of the LCD. There is not a formal standard, though there may be convention.
Reading the GitHub page, you see that this is a

Clone of the new liquid crystal library from: https://bitbucket.org/fmalpartida/new-liquidcrystal

Following that link takes us to some kind of documentation, noting that one of the connection types is:

I2C IO bus expansion board with the PCF8574* I2C IO expander ASIC such as I2C LCD extra IO.

A link to that hardware is helpfully provided! We can follow the link to see that the hardware is discontinued, but helpfully documented with some schematics and PCB layouts that tell us which pins of the I/O expander are connected to which pins of the LCD:

P0 is pin 0 of the I/O expander -- the top row are the I/O expander pins. Vo, RS, R/W, etc. are the LCD pins.
LCD Pin  |  I/O Expander Pin
     En  |  P4
    R/W  |  P5
E (rst)  |  P6
     D4  |  P0
     D5  |  P1
     D6  |  P2
     D7  |  P3

(And the backlight is a passthrough pin, not on the I/O Expander. It appears the definition of the backlight pin and polarity refer to I/O Expander pins.)
This is the point where you have to find out if the I/O expander on your purchase has the same pinout as the product for which this library was written.
Your "working" instance is called as (with annotations to the constructor being called)
LiquidCrystal_I2C lcd(
  0x27,       // lcd_Addr
  2,          // En (enable pin)
  1,          // Rw (read/write pin)
  0,          // Rs (reset pin)
  4,          // d4 (data)
  5,          // d5 (data)
  6,          // d6 (data)
  7,          // d7 (data)
  3,          // backlight
  POSITIVE    // backlight polarity
);

This indicates that the I/O expander on your LCD does not have the same pin connections as that for which the library was written, which is why you had success only when remapping them in the constructor.
All that to just re-state the hair-pulling you had to do!
The actual functions available are noted to be:

This library provides the same interface to applications as the LiquidCrystal library sourced by the Arduino SDK.

But to be absolutely sure, you can also see their prototypes in the header file: https://github.com/fmalpartida/New-LiquidCrystal/blob/master/LCD.h
It provides scrolling, blinking, enable/disable, etc.

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


text:
Reading a rotary encoder using digital pins of Mega 2560 directly using port registers?
I'm trying to write an interrupt service routine for an Arduino Mega 2560 to decode a quadrature rotary encoder. I've got an ISR (Interrupt Service Routine) that responds to the falling edge of digital pin 2.
I then need to look at the value of pin 3 and see if it is high or low to tell which direction the encoder is being turned.  I've built a simple debouncing circuit using a couple of resistors and a .01 μF capacitor per line from the encoder, so those signals are clean now.
Based on the reading I've done, it's best to read the pin states directly rather than using digitalRead in an ISR since the digitalRead() function is rather slow.
I am finding it hard to find and figure out the port mappings for the port registers to read the pins.
I believe that I should use
(PIND & (1 << 3) != 0 to read digital pin 3, since I think pins 2-9 are on register PIND?
I found this chart https://www.arduino.cc/en/Hacking/PinMapping2560 that lists the pin mappings for the Mega 2560, but I'm not sure how to read it.
If I use bool  pinBState =  digitalRead(rotaryPinB) == LOW in my ISR it works, but it seems to miss state changes sometimes.
If instead I use the code `bool pinBState = (PIND & (1 << 3)) == 0;
The value of pinBState never changes.
Can somebody tell me what I'm doing wrong?
See the self-answer below. It seems that digital pins 0-7 are read from PINE, not PIND.
However, now I have a new problem:
With the code shown in my answer I am getting readings that increase for clockwise rotation, and decrease for counterclockwise rotation, as expected:
If I rotate it very slowly through a full revolution, I can usually get exactly 12 steps in a rotation. If I rotate my encoder rapidly, or  through several full turns, it gives me values that aren't exact multiples of 12, and rotating it several turns clockwise, and then the same number of turns counterclockwise does not return the value to 0 like it should.
I'm using a simple debouncing circuit as recommended from the spec sheet for the encoder:
https://www.bourns.com/docs/Product-Datasheets/PEC11R.pdf
The circuit looks like this:

Shouldn't that circuit work? I wired it up on a breadboard, and have pretty long leads, and didn't cut the wires on the resistors or capacitors since this is still a test circuit. I wouldn't think this would be sensitive to RF noise though. The only other thing I've got on the project is an I2C LCD display. I've triple-checked my wiring and don't think I've made any mistakes.
I'm stumped as to why an interrupt-driven rotary encoder, with the recommended debouncing circuit,  that reads port registers to read the data from it's PIN B doesn't give reliable results for normal rates of turning on the control.

Are you looking for a complete list? https://forum.arduino.cc/index.php?topic=52534.0

No, I saw that page but can't make any sense of it. I need to know what code to use to read the value of digital pin 2 on my Mega 2560. Some coaching on how to read those tables would be a nice plus, but right now my focus is very narrow: Getting this single read to work.

Digital pin 2 is PE4  ... that is the 5th bit of port E

How is this different than what you asked here?  https://electronics.stackexchange.com/questions/423688/how-do-you-pick-component-values-for-a-debouncing-filter/423695?noredirect=1#comment1052330_423695

Digital pins 2 and 4, both have hardware interrupts on them. Why not use both interrupts? It's kind of overkill, but the mega has them, so why not use them. As to your current problem; You are missing steps, so either your code is too slow, or the debounce filter is to strong. The latter could easily be tested by using smaller capacitors. If rotaryValue and int? Is it defined as volatile?

Why the down-vote?

Gerben, my program can be set up to read just the falling edge of 1 pin (12 steps) the falling edge of both pins (24 steps) or the rising and falling edge of both pins (48 steps). For 12-step decoding, I only put an interrupt on one pin, and read the state of the other pin to figure out rotation direction. For the other cases I do set interrupts on both pins.

Ok, it looks like digital pins 0-7 are read from the PINE (That's PIN E) register, not PIND.
I am setting up my pins as input using normal Arduino code:
#define rotaryPinA 2
#define rotaryPinB 3

void setup() {
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, FALLING);

  pinMode(rotaryPinA, INPUT);
  pinMode(rotaryPinB, INPUT);
  //The rest of the setup function
}

And then my encode method:
void encode() {
  rotaryValueChanged = true;
  //Read my PinB (Digital Pin 3) using port register PINE, 5th bit
  bool pinBState = (PINE & (1 << 5)) == 0;
  //Here is the equivalent code using digitalRead:
  //bool  pinBState =  digitalRead(rotaryPinB) == LOW;
  rotaryValue +=  pinBState ? -1 : 1;
}

That code seems to work, but the value I'm getting from my rotary encoder drifts.

Have you tried some hardware denouncers - like MC14490?
Using Interrupts you can then detect all four phases of each encoder step.


text:
Sound Recognition
I'm looking to recognize a particular sound using arduino uno.
I need to recognize a clap sequence to trigger a relay.
Having given it some thought i need it to be continuous listening mode with out any trigger such as a button press. The background will be quiet.
Is the arduino uno powerful enough to do this and how will i get stated on this? Any help is appreciated.
Note i need to do this entirely onthe Uno itself and not on PC like How do I listen for a sound that matches a pre-recorded sound?
I am thinking i will prerecord the sound and compare with a live sample, is this feasible?

Adding to Michaels answer above which only works for some cases (and  it wont work perfectly even with a sequence of claps). To make it work in more cases you would need to store more information about the clap noise- as Michael points out in his comment above "properly identify" the clap- to make the identification more accurate. There are various ways to do this- you could compare it with live recording as you wrote in your question. I suggest tyou try neural networks to do such a comparision I. I would say you would need a two layer neural network with say a sample of different claps for training it-(its probably quicker to train it not with arduino).
Here is a library for neural networks for arduino
http://robotics.hobbizine.com/arduinoann.html
that you may use. Or you can implement you own neural network. Its well known that sound recognition can be used to analyse sounds.
The built in ADC of Arduino can probably be used to  record and good enough for something like a clap in your case-though it cant be used for high quality sound recordings.

If it's just a clap sound and the background is quiet, then really all you'd need is to sense how loud the sound is.  This can be done using an analog comparator interrupt (this is present on the chip itself but not on the Arduino library).  If all the uno is doing is measuring the sound and maybe setting an output pin when it's loud, then just poll the analogs attached to your microphone and trigger the condition when the output is loud enough.  You'd probably need to amplify the microphone if you haven't already, but yes, the uno can handle that.
Edit: if it's a clapping sequence, then it can still do it.  Again, just measure the time between loud and quiet, don't worry about what the sound is (that is, you don't need to worry about exactly recording and analyzing the sound, you just need to know when it's loud and when it's quiet)

How would it work if work if there  was a clap and another loud sound like a clap (but not a clap)?

It wouldn't, unfortunately.  My answer above really just deals with the case where the only thing that happens is a clap.  Otherwise yes, you'd have to properly identify the sound, which is more complex

If you make a piece of code that detects a short, high volume. It will work better than just a high volume. You could also do two claps (high volume bursts) with an expected time between them. This will filter occasional high volume sounds.

I have not tested it but there is an example for the ArduinoSound library which especially detects claps.
https://github.com/arduino-libraries/ArduinoSound/tree/master/examples/ClapDetector
/*
 This example reads audio data from an Invensense's ICS43432 I2S microphone
 breakout board, and uses the input to detect clapping sounds. An LED is
 togggled when a clapp is detected.

 Circuit:
 * Arduino/Genuino Zero, MKRZero or MKR1000 board
 * ICS43432:
   * GND connected GND
   * 3.3V connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
   * WS connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
   * CLK connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
   * SD connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)

 created 18 November 2016
 by Sandeep Mistry
 */

#include <ArduinoSound.h>

// the LED pin to use as output
const int ledPin = LED_BUILTIN;

// the amplitude threshold for a clap to be detected
const int amplitudeDeltaThreshold = 100000000;

// create an amplitude analyzer to be used with the I2S input
AmplitudeAnalyzer amplitudeAnalyzer;

// variable to keep track of last amplitude
int lastAmplitude = 0;

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

  // configure the LED pin as an output
  pinMode(ledPin, OUTPUT);

  // setup the I2S audio input for 44.1 kHz with 32-bits per sample
  if (!AudioInI2S.begin(44100, 32)) {
    Serial.println("Failed to initialize I2S input!");
    while (1); // do nothing
  }

  // configure the I2S input as the input for the amplitude analyzer
  if (!amplitudeAnalyzer.input(AudioInI2S)) {
    Serial.println("Failed to set amplitude analyzer input!");
    while (1); // do nothing
  }
}

void loop() {
  // check if a new analysis is available
  if (amplitudeAnalyzer.available()) {
    // read the new amplitude
    int amplitude = amplitudeAnalyzer.read();

    // find the difference between the new amplitude and the last
    int delta = amplitude - lastAmplitude;

    // check if the difference is larger than the threshold
    if (delta > amplitudeDeltaThreshold) {
      // a clap was detected
      Serial.println("clap detected");

      // toggle the LED
      digitalWrite(ledPin, !digitalRead(ledPin));

      // delay a bit to debounce
      delay(100);
    }

    // update the last amplitude with the new amplitude
    lastAmplitude = amplitude;
  }
}

The question is tagged “arduino-uno”, which is a board ArduinoSound does not support.

authors: Борис Павленко

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


text:
Read and parse continuous serial stream
I'm trying to read in and parse a message in the form of X123987 continuously streaming into a serial port. There are no new lines or control characters other than the X which marks the beginning/end of the message. The message contains two, three-character components, ex: 123, and 987. I'm trying to copy bytes as their read into a char array, and then on the control character, return the result, but while this compiles, I don't get any output, and it crashes constantly.
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11);

char _byte_received;
char _buffer[10];
char _value[10];

bool OnReceive()
{
  if (RS485Serial.available())
   {
    digitalWrite(13, HIGH);
      _byte_received = RS485Serial.read();
      if (_byte_received == 'X') {
        strcpy(_value, _buffer);
        memset(_buffer, 0, 10);
        return true;
      } else {
        strcat(_buffer, _byte_received);
        return false;
      }
    digitalWrite(13, LOW);
   } else {
    return false;
   }
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(13, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.write(_value);
    Serial.println("");
  }
}

Output:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:

I expect to see value: 123987

You wrote: “while this compiles [...]”. No. The code you posted does not compile.

I updated the code to make it complete so it now does actually compile. I'm very likely using the char array functions wrong, and that's probably my issue. Should I creating a one char string before using strcat? I think I just don't know how to ask my question properly.

Look at the prototype for strcat: char *strcat(char *dest, const char *src );. You are trying to pass a char where there should be a char * for the 2nd parameter.

How much data will be received ? What else is the sketch doing ? The SoftwareSerial takes over the Arduino, and there is not a lot that the Arduino can do any more. The words "continuously streaming" and "SoftwareSerial" rings an alarm bell. You might need an other Arduino board.

the software serial bit is just for testing on an arduino with only a single hardware port. I'll be using one with multiple hardware serial once it's set up. thanks for the warning.


text:
Options for communicating between Arduinos
I'm looking to communicate between ~5-10 Arduinos to send commands and data between them. By "Arduino" I mean the ATmega328 programmed using the Arduino programming framework.
Each of the devices would be on the same PCB.
I know I2C and SPI can communicate to some degree, but that they're really meant for peripherals devices connected to a micro controller rather than connecting multiple micro controllers to each other, and that they usually only send a few bytes of data at a time. On the other hand I know LCD displays can be driven using them, and I'd imagine there's a lot of data being transferred in those cases.
Is there a something like I2C (multi-master, multi-slave, single-ended, serial computer bus) for communicating between micro controllers? Allowing each device to send data to each other device unsolicited. For example, if a switch was pressed on device A, it would tell device B, without having device B ask A all the time if a switch was pressed. and vice versa.
Edit: I found some libraries that may do what I want with RS-485. Is this the only viable option for ~1k bps transmission between 5-10 devices? I would imagine TCP/IP over Ethernet would work as well, but that seems like too much. Are there any I2C libraries that allow sending that amount of data between only master devices?

https://github.com/MichaelJonker/HardwareSerialRS485
https://github.com/MajenkoLibraries/ICSC

Have you looked at serial connection?

do you mean RS-485?

There is a very similar question here: How to interconnect multiple Arduinos with a Rpi to control home-lights/switches - ignoring the Rpi part (it wasn't really relevant to the question) I count that as virtually identical to what you want to do. I made a lengthy response there about doing a "rolling master" system. Please read the other question/answer and see what you think.

You need a physical layer (cabling or board), electronical "standard" like RS-485 but 5V TTL is also good. Then you'll have to choose what type of bus arbitration (round-robin, master-slave or broadcast messages) and probably implement some addressing or error checking.

On a breadboard, I wouldn't use RS485, since it needs transceivers. Just 5v for a logic 1 and 0v for a logic 0. But from that point, possibilities are endless. It will also depend on speed requirements etc.

You haven't stated why you want to create such a thing. If you're short on IO pins, you might use IO-expanders. There might be better solutions. If it's a hobby/proof of concept, you might check out other projects like it and try to "enhance/adjust it".

@Paul I want to have a separation of concerns. I know I could just get a bigger controller with more interrupts and I/O, but I'd rather keep things simple at the device level. It also helps when collaborating with others, as each subsystem can be designed and even constructed independently and connected together later. Also can be easier to unit test and replace/upgrade.

Maybe I did not just find it, but I did not read the fundamental question, which is "what is the topology you need"? Do you need everybody talking to everybody? Centralized access (i.e. everybody speaking to one)? A mixed solution?

@frarugi87 I think a bus topology would work best, with any device communicating with any other device and initiating the connection. So no slaves.

Well, ok for bus topology, but I highly suggest you to make one bus master and all the other slaves. Otherwise you will have collisions, and detecting/preventing collisions is a "difficult" task. If you just have one master you can avoid this, since just him can give permission to talk. You can make a serial (UART) bus, with one wire connecting master's TX to each slave RX, and one wire connecting slaves TX (maybe with a 3-state buffer) to the masters RX. Otherwise you can make a daisy-chain: TX1 connected to RX2, TX2 to RX3... TXn to RX1. This is a bit less efficient, since to talk to

another micro you have to make n hops, but it works. The last solution is what you said, so everybody speaking on the same bus, but you will need collision detection. In this case I suggest you the CAN bus, since it already handles the collisions (but you will have to implement it in your code).

There are a number of concepts that can help you realize your dream. I can't, in the space of this answer, tell you exactly how to implement what you want, but I can show you the concepts that will help you to implement it.
First off there's the concept of the bus master.  This isn't necessarily the device that instantiates communication - instead this is the device that owns and controls the bus.
When a device that isn't the bus master wants to communicate on the bus it first asks permission from the bus master.  The old Z80 (well, I say "old", but they are still in use in many forms today) used this concept to allow other chips to use the data and address buses. It consists of two signals - BUSRQ and BUSACK.  A device first looks to see if either of BUSRQ or BUSACK are active, and if neither are it then activates BUSRQ. If the bus master is willing to give up the bus to the other device (it's not using it at that moment) it activates BUSACK and the other device then knows that it can use the bus.  Nothing else can use it until BUSRQ and BUSACK have both been released.  Nice and simple and elegant.
But not perfect. If two devices both decide to ask for the bus at the very same instant you get a collision.  This is a common problem amongst shared bus systems like this, and causes untold problems unless you know how to handle it properly.
Enter the concept of listen-while-you-talk.  This involves the device that is sending on the bus also listening to what is being sent on the bus through a separate receiver.  It then can know if what it sent on the bus is what actually ended up on the bus.  For instance if two devices talk at the same time and one sends 10011001 and the other sends 11001100 the result that appears on the bus might actually end up as something else, such as 11011101 or maybe 10001000 depending on how the bus signals are created.  So if you know what you sent got corrupted you can now do something about it.
Next concept: backing off.  This is where both the senders wait for a short period and try and send again. As long as they both delay for a different amount of time the first one to try will get the bus and be able to communicate. But how do you guarantee that they will both delay for different times?  You may think the answer is simple: use a random number, like rand() or random().  But that is also problematic:
Another concept: The pseudo random number generator
The Arduino doesn't generate random numbers.  It just uses a complex mathematical formula to create a sequence of numbers that, to us, look random.  They aren't though.  Write a small program to print 10 random numbers through serial and run it multiple times (press the reset button).  You will find the same "random" numbers in the same order every time.  Try it on another Arduino and you get the same numbers again. Always the same.
So what to do?  The answer is called seeding the random number generator.  The next number generated by rand() et al depend on the number that had been generated last.  So change the first number and all the rest of the numbers will change.  However, you have a catch-22 situation. You need a random number to seed the random number generator to make it random to be able to generate a random number to seed the random number generator... ad infinitum.  You see where that's going? You can't seed from rand() since rand() isn't random until you have seeded from a random source. So you need to find a random source.
And that's not an easy task.  The best source of entropy as it's known is white noise. This can be generated in a number of ways with a number of different circuits - from the breakdown of a diode junction to very high gain amplification of the thermal fluctuations in a resistor.
All are quite complex for what you want really, but there is a simpler, if slightly less random, method - read an analog input that isn't connected to anything.  It won't have as much of a range as a proper entropy generator, but it should provide enough randomness to give a reasonable chance of each device getting a different seed.
Another useful concept is the interrupt.
This is good in a situation where you don't want the complexity of a multi-master bus with all the collisions etc. You have a single master that does all the work on the bus, and when a slave device has something important to say it nudges the master with an interrupt. The master then goes "Yes? What do you want?" to which the slave replies "Someone pressed my button".
That way the master isn't constantly polling the slave to see if the button has been pressed.  It is often used in bus arrangements like SPI and there are many chips, such as IO expander chips, that can assert an interrupt when one of their input pins changes state.
But if you have 20 devices does that mean you have 20 interrupt pins?  Not necessarily. New concept: wired OR.
It's perfectly possible to have multiple different slaves all using the same interrupt pin.  The pin is normally held HIGH with a resistor (it could be an internal pullup resistor) and each slave has an open drain output connected to that pin.  An open drain output, when "off", is not connected to anything - it's like the pin is in input mode (in fact it can be emulated on chips that don't have open drain by switching between input and output mode).  When the output is "on" it connects the pin to ground, pulling down the IO pin, just like a button would.
It's then up to the master to make its way round the slaves that it knows are attached to that interrupt to see who needs attention.  You can of course implement a number of different interrupt pins with different groups of slaves on each one - maybe a high priority one with just one device, and lower priority ones with multiple devices on each, for example.
The same concept of wired OR and open drain can be used for allowing multiple devices to all share the same physical wires.  That is exactly how I2C works - the two bus lines are pulled up by resistors and the devices on it use open drain outputs to pull the line low to release it back to high to create the different logic levels. If two devices both pull it low together it will just be low.  Without the open drain method if you had one device outputting a 1 and another outputting a 0 you would basically get a short circuit between the two and you would end up damaging chips.
And then of course you have the concept of synchronous versus asynchronous communication, but that is an entirely different kettle of fish. Simply said though, protocols with a clock, like SPI and I2C, which have a master generating that clock, are synchronous. Protocols like the UART and RS-232, RS-485, etc are asynchronous - they rely on both ends agreeing on how fast data is being sent (baud rate) so they know how to interpret the signals as they arrive.

I would just want to add that I2C is theoretically multi-master capable, and has an arbitration scheme that does not need random numbers. However, there seems to be an issue with Atmel's implementation. C.f. for example TWI module seems buggy in multi-master communications and Multiple Master Problem with Atmel AVR Microcontrollers. Single master + interrupts seems to me like the easiest solution.

@EdgarBonet Pretty much all protocols can be made multi-master if some form of bus arbitration system is implemented. Some are more suited to this than others, and some, such as I2C, have "official" ways of doing it, some of which work better than others. The most reliable way, of course, is to not need a multi-master system at all :)

@EdgarBonet do you know if the wire library supports multi-master? Is it as easy as this https://michael.bouvy.net/blog/en/2013/05/25/arduino-multi-master-to-master-i2c/

@waspinator: I cannot tell, as I have never tried. It would seem the Wire library handles bus arbitration, but I don't know whether it can cope with the issues I pointed to before.

Check out PJON - https://github.com/gioblu/PJON. It's a one-wire alternative.

Please can you elaborate on your answer possibly an example of usage or pros and cons,, as this is really a link only answer at the moment.

Please add some information on why it's better than the alternatives/what makes it stand out. Thanks!

PJON has been made available for multiple platforms, not just Arduino. It's   simpler than I2C/one-wire. It handles noise better. It has multi-master support. Read the wiki from the link.

In addition to @Majenko's excellent answer, you need to have a think about what you are communicating.
It sounds like you want to communicate a single bit - perhaps you can get away with individual pins? If you have a master, and up to 13 slaves, you could have one pin on the master connected to one pin on each of the slaves (via a resistor). If slave A wanted to signal it's signal, it would raise the pin; the master would then be able to poll each pin in turn, to work out who said what.

sorry, that last bit was just an example of how I'd like devices to be able to "push" data to each other instead of polling for it. I, in fact, do want to send more data. ~100 bytes 10 times a second.

Another option is SPI.
SPI can be used with any number of devices, in a ring. It was explained to me as follows: any participant can toggle the clock line 8 times, to move the byte in it's own buffer, into the next device's buffer, in a ring; the device gets a byte from the previous device. If someone else toggles the clock 8 times, you get notified that the new byte is ready (this is done in hardware).
You need to think carefully about a protocol for this - an "address", "length", "command", and then any number of parameters. The sender sends the "address" byte, sets the "length" byte in the buffer, and holds the rest ready. The next device has received the "address" byte, and sees if it is the intended recipient. If it is not, it notes this down, and pushes the chain round, notes the length, and waits until someone ELSE has pushed that many bytes around. If it IS yours, read the rest of the data, pushing the data around, and blanking it as you go (to stop it coming back). A blank address (e.g. 0) would be reserved, meaning "don't do anything with this, wait for someone else to push it around, and read the next byte as the next address". All devices would need to initialize to 0 on startup.
If you need to set addresses dynamically, set a special byte "all stations", with a command which means "your device number is X, and tell the next device it's device number is X+1". Someone would need to initiate this, of course.
You also run the risk of collisions, if two devices start sending at the same time, or if something doesn't relay what it's supposed to (e.g. a chip is powered down). You need to think about how you're going to detect/recover from this.


text:
Sending a struct over i2c
How would you send a struct from an i2c slave when requested by an i2c master?
Slave Struct Respdonder Sketch (Seeeduino Xiao)
#include <Wire.h>

struct TransmitData
{
  int a;
  int b;
  int c;
  int d;
  float e;
  float f;
  float g;
  float h;
};

TransmitData data;

void setup()
{
  Serial.begin(9600);
  Wire.begin(2);
  Wire.onRequest(requestEvent);

  data.a = 1;
  data.b = 2;
  data.c = 3;
  data.d = 4;
  data.e = 5.1;
  data.f = 6.1;
  data.g = 7.1;
  data.h = 8.1;
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("sending ("); Serial.print(sizeof data); Serial.println(" bytes)");
  Wire.write((byte *)&data, sizeof data);
}

Master Struct Requester/Reciever Sketch (Arduino MEGA)
#include <Wire.h>

struct TransmitData
{
  int32_t a;
  int32_t b;
  int32_t c;
  int32_t d;
  float e;
  float f;
  float g;
  float h;
};

TransmitData data;

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

void loop() {
  Serial.print("requesting ("); Serial.print(sizeof data); Serial.print(" bytes)... ");
  if (Wire.requestFrom(2, sizeof data)) {
    Wire.readBytes((byte*) &data, sizeof data);
    Serial.println("done");

    Serial.println(data.a);
    Serial.println(data.b);
    Serial.println(data.c);
    Serial.println(data.d);
    Serial.println(data.e);
    Serial.println(data.f);
    Serial.println(data.g);
    Serial.println(data.h);
  }
  else {
    Serial.println("could not connect");
  }
  delay(500);
}

The serial output on the slave device is:
sending (32 bytes)

The serial output on the master device is:
requesting (24 bytes)... done
1
0
2
0
0.00
0.00
5.10
6.10

You can try the I2C_Anything library by Nick Gammon

int isn't guaranteed to be the same size across platforms. Use fixed width integer types instead.
https://en.cppreference.com/w/cpp/types/integer
struct TransmitData
{
  int32_t a;
  int32_t b;
  int32_t c;
  int32_t d;
  float e;
  float f;
  float g;
  float h;
};


text:
Arduino --> RPI I2C issue
ok, I feel like this should be simple, but I am at a loss
Simple code mock up to send 4 bytes(mimicking a float)  over I2C from Arduino to rpi. I am trying to create a state machine so that I can request certain "registers" containing 4 bytes each. I send a byte from pi to arduino indicating what "register" I want, then read back 4 bytes.  I was attemping to reset the state back to NO_STATE after the end of the switch statement, but it effects the bytes received by the pi, and I dont see how.
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte state = NO_STATE;
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
}

void loop() {
  delay(100);
}

// callback for received data
void receiveData(int byteCount){

  while(Wire.available()) {
    state = Wire.read();
  }
  Serial.print("Got:");
  Serial.println(state);
}

// callback for sending data
void sendData(){
  Serial.println("Sending...");
  byte b[4]={1,1,1,1};

  switch (state){
    case NO_STATE:
      //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      break;
    case GET_BAT_TEMP:
      //send battery temp
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      break;
    default:
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      //send back error code
  }
  //reset state to none
  state=NO_STATE;

}

with this code I receive [3,0,0,0]
if I comment out the line
//state=NO_STATE;

I then receive back [3,3,3,3]
which is what I would expect. But I do not see how reseting the state "after" all the bytes are sent would cause an issue
output from arduino shows entering that function only once, and sending the 4 bytes
Got:3
Sending...
Sending...
Sending...
Sending...

I'm not an expert, but I think I found why it is not working.
The main problem is that you are using always the same byte (0, 3 or 9) for debugging, so you are not noticing that it is not sending four bytes, but only one, and the function gets called four times. This is obvious however from the reply on the serial interface (+1 for adding it in the question, good work).
What you can do is to track how many bytes you sent, and send the successive one. After the bytes are all sent you can reset back the state. The code can be something like
//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte sentData;
byte batteryLevel[4]={3,4,5,6};

byte state = NO_STATE;
void setup() {
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Wire.begin(SLAVE_ADDRESS);
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
}

void loop() {
  // delay(100); // Useless, let it cycle at its max speed
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        state = Wire.read();
        sentData = 0;
    }
    Serial.print("Got:");
    Serial.println(state);
}

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel[sentData]);
            if (sentData < 3)
                sentData++;
            else
                //reset state to none
                state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

I haven't tested it, so forgive any bugs. But I'm sure  you understood the main point.
Just some remarks: the delay is useless (you are not saving energy or other with it, so just remove it); the serial is ok for debugging, but I think you should remove it from the code you will use (not ok to stop the interrupts for such a long time).
And most important: I hope you considered the 5V vs 3.3V voltage problem on the I2C ;)
In any case, I second Look Alterno: good way to ask a question, with all the information needed.
EDIT: as pointed out in the comments, there exist a function to send all the data together. I'm not sure how it behaves in different conditions (e.g. when less bytes are requested), but if you trust the communication the function can be simplified in
// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel, 4);
            state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

(and the sentData variable becomes useless)

@LookAlterno I never used it, so I didn't know it existed ;) in any case the OP was using the single byte version, so I used it too... Thank you for the info, I'll update the answer with this

If the internal pullups on the arduino side are disabled, there is no reason to worry about the voltage mismatch correct?   Arduino only pulls the SDA line low, letting the pi pull it up to rail voltage at 3.3V.

I must have been really tired last night. Didn't put it together in my head that the interrupt was being triggered again before the remaining data was sent. I have not tired any of this yet, but will mark it correct as it seems right. Will edit it with working code once I am done.

@LookAlterno it was perfectly clear that it was a collaboration :) Thank you

@ChadG Just come later to actually write if it is correct ;) in any case, a lot of arduino boards have pullups soldered on the board; moreover even if the high level is 3.3V, it can be misinterpreted by the arduino (the Vih is IIRC 3V, so there is the possibility that the signal is not correct)

Ok, i will keep that in mind, So far I have not seen any "Bad" data that wasn't caused by bad code.   :)


text:
HX711 sporadic wrong values
Am interfacing HX711 with arduino to measure the load of something. However, in my project, I need to continuously monitor the load.
I get fairly accurate values most of the time however, at times I suddenly get a junk value. For example, I call the weight function every 3 seconds and I have placed a 10kg weight, this is what I get. 17.25 is the concern.
10.04, 10.03, 17.25, 10.04, 10.03, 10.03
Am using HX711 library and my process function is a simple call as shown below.
float Processweight()
{
  Serial.print(scale.get_units(40), 2);

  scale.power_down();              // put the ADC in sleep mode
  delay(500);
  scale.power_up();
}

is there something that am missing? What could cause the wrong values?

Actually debugging that would require examining the code and circuitry in detail.  If you don't need answers quickly, you could try a filter; not something that averages but something that rejects rapid change.  Also be aware in your application of the load cell behavior called "creep".

Thanks chris, I will try writing a correlation to reject sudden changes. However, I was curious to understand if HX 711 itself has such issues. I will sure use filtering if I get confident that I have done everything else right.

I get fairly accurate values most of the time however, at times I suddenly get a junk value.

if you use the ebay board, it has the incorrect grounding, which may contribute to the sporadic values you saw.

For example, I call the weight function every 3 seconds

poor quality libraries could be another possibility.
I have used the board quite extensively and aside from its tempco, it is fairly reliable. you can see here: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/
when everything is done right (and in a constant temperature environment), it has very good consistency.

Thanks a lot danny for the input. I will check the same.

Finally I got this right by adding a code to check if 5 consecutive values are fairly close enough and only then respond. That way I was able to flush out sudden changes. However, I still am not sure as to what is causing that jump.

The power down and power up could be an issue.  Probably you should add some delay between the power up and reading attempt.  Also, you may want to examine the wrong values and see if there is any pattern to them.

Thanks for the leads chris, the wrong values had no recognizable pattern. I have tried adding delay, in fact I fully removed the power up and power down cycle (always kept it powered up) and I still saw the issue.


text:
How to implement a priority queue
I was wondering if I would be able to use specific parts of the c++ library for my arduino sketch. For example the arduino library has a queue array but I wanted to use a priority queue for my sketch and I am unsure how to modify the queue header file to do that. Also if I can use the priority queue from the c++ library can you please tell me how I would go about doing that.
Thank-you

There is no priority queue on the Arduino - and for a good reason: these kind of things really aren't suitable for small microcontrollers with limited resources. While it may be possible to roll your own it most likely isn't the right thing to do - instead you should think about what you are actually trying to achieve and consider if this is really the right way to go about it.

Hi Majenko thanks for answering. Do you know if there is an arraylist implementation. I am trying to implement djikistra's algorithm. I was able to do a bfs just with the use of an array, but djikistra's gets a little complicated when using just arrays. I think I can work with an arraylist if arduino has it. @Majenko

It may be time to teach yourself linked lists...

Does the arduino library include linked lists @Majenko

No, they are a basic concept of C, not a library function.


text:
Arduino MEGA 2560 - PWM in case statements not working
So I am using Arduino to control RGB Strip light, the analogueWrite(Pin,Value); Works with the prebuilt AnalogueWriteMega example - on pins 8, 9, and 10.
When I move this into my program, Pin 8 still works but pins 9 and 10 don't work.
Anywhere I write analogueWrite() it only works if the value is 255

Green is pin 8
Red is pin 9
Blue is pin 10

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <LiquidCrystal.h>
// encoder
int val;
int encoder0PinS = 29;
int encoder0PinA = 31;
int encoder0PinB = 33;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;
int MenuPos;
int SubPos;
bool Selected = false;
int Reader = LOW;

// lcd
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//pot
int ASensePin = A0;
double ASenseValue = 0;
double AFixedValue = 0;
int AFixOut = 0;

//randoms
int ranPin;
int ranVal;

//IR

int receiver = 45; // Signal Pin of IR receiver to Arduino Digital Pin 45

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

void translateIR() { // takes action based on IR code received

  // describing Remote IR codes
  switch (results.value)
  {

    case 16195807:
      Serial.println("Red, 0, 255, 0");
      analogWrite(8, 0);
      analogWrite(9, 255);    < ------ works
      analogWrite(10, 0);
      break;

    case 16197847:
      Serial.println("Yellow, 255, 255, 0");
      analogWrite(8, 100);      < ----don't work
      delay(50);
      analogWrite(9, 100);       <----don't work
      delay(50);
      analogWrite(10, 0);
      break;

    case 16228447:
      Serial.println("green, 255 , 0, 0");
      analogWrite(8, 255);
      analogWrite(9, 0);
      analogWrite(10, 0);
      break;

    case 16230487:
      Serial.println("turquois, 0, 255, 255");
      analogWrite(8, 0);
      delay(50);
      analogWrite(9, 100);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16212127:
      Serial.println("blue, 0, 0, 255");
      analogWrite(8, 0);
      analogWrite(9, 0);
      analogWrite(10, 255);
      break;

    case 16214167:
      Serial.println("Purple, 255, 0, 255");
      analogWrite(8, 100);
      delay(50);
      analogWrite(9, 0);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16244767:
      Serial.println("White, 255, 255, 255");
      analogWrite(8, 255);
      analogWrite(9, 255);
      analogWrite(10, 255);
      break;

    default:
      Serial.println(results.value);
  }// End Case

  delay(500); // Do not get immediate repeat
} //END translateIR

void setup() {
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  pinMode (encoder0PinS, INPUT);
  pinMode (8, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (10, OUTPUT);

  lcd.begin(16, 2);
  lcd.print("      Start     ");

  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }
  }
  encoder0PinALast = n;
  if (encoder0Pos == 4) {
    encoder0Pos = 0;
  }
  if (encoder0Pos == -1) {
    encoder0Pos = 3;
  }

  MenuPos = encoder0Pos;

  Reader = digitalRead(encoder0PinS);
  // Serial.println(Reader);

  if (digitalRead(encoder0PinS) == LOW) {
    while (digitalRead(encoder0PinS) == LOW) {}
    Selected = true;
  }

  Serial.println("MenuLoop");
  switch (MenuPos) {
    case 0:
      lcd.setCursor(0, 0);
      lcd.print("     Random    ");
      while (Selected == true) {
        ranPin = random(8, 10);
        ranVal = random(0, 255);
        analogWrite(ranPin, ranVal);

        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;

    case 1:
      lcd.setCursor(0, 0);
      lcd.print("       IR      ");
      Serial.println("IR Receiver Button Decode");
      irrecv.enableIRIn(); // Start the receiver

      while (Selected == true) {
        if (irrecv.decode(&results)) // have we received an IR signal?
        {
          translateIR();
          irrecv.resume(); // receive the next value
          lcd.setCursor(0, 1);
          lcd.print("               ");
          lcd.setCursor(0, 1);
          lcd.print(results.value);
        }
        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }

      break;

    case 2:
      lcd.setCursor(0, 0);
      lcd.print("      Temp     ");
      break;

    case 3:
      lcd.setCursor(0, 0);
      lcd.print("      Pot      ");

      while (Selected == true) {

Not working
        for (int thisPin = 8; thisPin <= 10; thisPin++) {
          // fade the LED on thisPin from off to brightest:
          for (int brightness = 0; brightness < 255; brightness++) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // fade the LED on thisPin from brightest to off:
          for (int brightness = 255; brightness >= 0; brightness--) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // pause between LEDs:
          delay(100);
        }

        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;
  }
}

The problem has nothing to do with your switch code. It's all to do with what you are trying to do, and peripherals conflicting.
Simply put: both PWM on pins 9 & 10, and the infrared library, require exclusive use of Timer 2.
Only one can use it. Either the infrared library, or PWM on those two pins, but not both.
You can modify the IR library to use a different timer instead of Timer 2 - for instance, you can set it to use Timer 1 which will remove your ability to use pins 11 and 12 as PWM.
This is the bit of code that you would need to find and modify on your system to change timers.  This page shows you which timers are used for PWM on which pins.

Thanks this worked, I swapped pins 9 and 10 to 6 and 7 so they where not clashing with the timer from IR.

An other option is a software pwm library. There are a few of those. They require a timer (which is not used by something else). The software pwm can be on any pin, because the pwm is done in software in the interrupt.


text:
'"/dev/ttyACM0": Permission denied' on Ubuntu 18.04
I'd like to say that I'm a noob at both Arduino & Ubuntu (have some command line experience).
I've set port permissions, joined the relevant groups (tty,uucp,dialout & plugdev). I know that the IDE recognizes the board because ttyACM0 only shows up when the board is plugged in. I've searched the Internet and Stack Exchange and Arduino troubleshooting guide and tried all the suggestions. It's not Genuino but a knock-off that's recognized as an Uno. I've got to be missing something.
Are there any relevant logs or a way to monitor whats going on in realtime?
Verbose upload output:
Arduino: 1.8.5 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/snap/arduino-mhall119/5/hardware/tools/avr/bin/avrdude -C/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_241052/Blink500.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/harry/snap/arduino-mhall119/5/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

"and tried all the suggestions". It would be helpful if you listed what you've tried. Did you do this: https://www.arduino.cc/en/Guide/Linux#toc6

Yes I did try that however I'll try it again. I know what port I'm trying to access and I set the permissions for it, I've made sure I'm in all the groups required. I've been at this for 2 days. I've tried installing packages from Ubuntu and Arduino. I could edit my bash history for redundancy and post that if it would be helpful. I've created a rules file (I don't remember the exact path, I could look it up). Thank you for your suggestion, I appreciate it

Please do this: File > Preferences > Show verbose output during: > compilation (uncheck) > upload (check). After the upload fails you'll see a button on the right side of the orange bar "Copy error messages". Click that button. Edit your question and paste the error messages in a code block ({} button on the toolbar).

That is confusing. You installed "arduino-mhall119" version 1.8.5 size 158MB from the snap. There is another snap "Arduino IDE" also version 1.8.5 size 445MB (a lot larger). In the repositories is "arduino", "arduino-core" and so on, I think version 1.05. I don't use any of those. Harry Busk, can you try to remove the snap version and every arduino related thing from the repositories and download the 64-bit linux version 1.8.8 : https://www.arduino.cc/en/Main/Software Unpack it under your home folder and make a shortcut to the 'arduino' file and try that.

Hello jet, thank you for your suggestion. I'm using a 32-bit laptop. Will the 64-bit version still work?

The 64-bit will only work on the 64-bit ubuntu. Use the 32-bit version for a 32-bit ubuntu. Open a terminal and type 'lsb_release -a' I have ubuntu 18.10, type 'uname -a' I have x86_64. Please use @Jot so I will get notified.

I had the same issue with the snap package. Installing the IDE as suggested by @Jot worked for me.

Snaps are pure evil. They cause as many issues with permissions as Windows Store Apps. Ditch the snap and download the IDE properly.  Better still, use UECIDE ;)

Thank you for your suggestion. What is UECIDE?

Also, if you haven't seen it yet, this post probably contains your answer if it's not caused by the snap.

Thank you @Jot, your answer enable to resolve my issue.

As stupid as it may sound but "have you tried turning it off and on again?".
Changes to groups only become effective when you have logged out of your account

LOL, yes I tried that. I was advised of that several times during my searches. There are no stupid suggestions, I really appreciate your input.

Just one more thing: are you sure ttyAMC0 is the correct port? On my ubuntu machine its ttyUSB0

I really believe so. When the board is unplugged my IDE shows only ttyS0. Plugging the board in causes ttyAMC0 to appear


text:
"not declared in this scope" error message
Error message 'dir1PinL' was not declared in this scope. keeps coming up. Any ideas?
#include "Arduino.h"

/*motor control*/
void go_Advance(void)  //Forward
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Left(void)  //Turn left
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void go_Right(void)  //Turn right
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Back(void)  //Reverse
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void stop_Stop()    //Stop
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, LOW);
}

/*set motor speed */
void set_Motorspeed(int speed_L, int speed_R)
{
  analogWrite(speedPinL, speed_L);
  analogWrite(speedPinR, speed_R);
}

//Pins initialize
void init_GPIO()
{
  pinMode(dir1PinL, OUTPUT);
  pinMode(dir2PinL, OUTPUT);
  pinMode(speedPinL, OUTPUT);

  pinMode(dir1PinR, OUTPUT);
  pinMode(dir2PinR, OUTPUT);
  pinMode(speedPinR, OUTPUT);
  stop_Stop();
}

void setup()
{
  init_GPIO();
  go_Advance();//Forward
  set_Motorspeed(255, 255);
  delay(5000);

  go_Back();//Reverse
  set_Motorspeed(255, 255);
  delay(5000);

  go_Left();//Turn left
  set_Motorspeed(255, 255);
  delay(5000);

  go_Right();//Turn right
  set_Motorspeed(255, 255);
  delay(5000);

  stop_Stop();//Stop
}

void loop()
{
}

This is the entire error message:
Arduino: 1.8.6 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Advance()':

smartcar-lesson1:20:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:21:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:22:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:23:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Left()':

smartcar-lesson1:27:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:28:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:29:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:30:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Right()':

smartcar-lesson1:34:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:35:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:36:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:37:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Back()':

smartcar-lesson1:41:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:42:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:43:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:44:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void stop_Stop()':

smartcar-lesson1:48:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:49:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:50:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:51:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void set_Motorspeed(int, int)':

smartcar-lesson1:57:15: error: 'speedPinL' was not declared in this scope

   analogWrite(speedPinL,speed_L);

               ^

smartcar-lesson1:58:15: error: 'speedPinR' was not declared in this scope

   analogWrite(speedPinR,speed_R);

               ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void init_GPIO()':

smartcar-lesson1:64:10: error: 'dir1PinL' was not declared in this scope

  pinMode(dir1PinL, OUTPUT);

          ^

smartcar-lesson1:65:10: error: 'dir2PinL' was not declared in this scope

  pinMode(dir2PinL, OUTPUT);

          ^

smartcar-lesson1:66:10: error: 'speedPinL' was not declared in this scope

  pinMode(speedPinL, OUTPUT);

          ^

smartcar-lesson1:68:10: error: 'dir1PinR' was not declared in this scope

  pinMode(dir1PinR, OUTPUT);

          ^

smartcar-lesson1:69:11: error: 'dir2PinR' was not declared in this scope

   pinMode(dir2PinR, OUTPUT);

           ^

smartcar-lesson1:70:11: error: 'speedPinR' was not declared in this scope

   pinMode(speedPinR, OUTPUT);

           ^

exit status 1
'dir1PinL' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

is that the whole error message?

It doesn't look like you've created any variable with that name in your code.  That's what that error message usually means.  You must create a variable and give it a value before you can use it elsewhere.  Go find any good C++ tutorial and go through the first bit of it and you will learn these sorts of basics pretty quick.
Your code would need a line at the top that looks something like:
int dir1PinL = 2

or whatever number value you want that variable to have depending on what pin you're actually talking about there.  Similar for the other variables you are trying to use.


text:
What is the smallest duration that can be measured using micros()?
What is the least value of time that I could measure(count) using micros()?

What's unclear about the official docs?

Which board? I know you added the arduino-micro tag but I suspect you didn't add that because you're using an Arduino Micro board.

What is the least value of time that I could measure(count) using micro() in Arduino board?

The answer is 64 clock cycles or 4 us @ 16 MHz. Please see the Arduino AVR core[1] for more details.
Cheers!
Ref. [1] https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L25

is there is any other way to count in nano seconds or 0.05 micro seconds?

@krishnamoorthijayakumar yes, by using a Timer and setting the prescaling to 1 (no prescaling). This will give a counter with 62.5 ns per tick @ 16 MHz.

Please accept and mark the question as answered!


text:
AVR+Arduino ADC problem
I  have connected a circuit to analog pin 0 in the Arduino.I have this code ,which I understand partially(online resources).The problem is that it prints nothing neither on Tera Term nor on Cool Term .Where am I mistaking ?(I am new to AVR programming).Here is the code:
  #include<stdio.h>
 void InitADC()
 {
 ADMUX=(1<<REFS0);// For Aref=AVcc;
 ADCSRA=(1<<ADEN)|(7<<ADPS0);
  }

 uint16_t ReadADC(uint8_t ch)
 {

    //Select ADC Channel ch must be 0-7
     ch=ch&0b00000111;
     ADMUX|=ch;

     //Start Single conversion

     ADCSRA|=(1<<ADSC);

      //Wait for conversion to complete
      while(!(ADCSRA & (1<<ADIF)));

      //Clear ADIF by writing one to it
      ADCSRA|=(1<<ADIF);

     return(ADC);
}

int main()

  {

uint16_t adc_value;

InitADC();

while(1)

{

  adc_value = ReadADC(0);
  printf("%d",adc_value);

  }

   return 0;

  }

That doesn't look like Arduino code.  Are you using some other IDE instead of the Arduino IDE?

I don't think printf will output to the serial port. At least not by default.

Your code compiles, but as Gerben said, the printf won't do anything in its current state, as no output handlers are defined for it. Why go to all that trouble when you can do this?
void setup()
  {
  Serial.begin (115200);
  }

void loop()
  {
  uint16_t adc_value;
  adc_value = analogRead (0);
  Serial.println (adc_value);
  delay (100);  // stop output spamming your monitor
  }

You could conceivably make printf work by following the tutorial here: http://playground.arduino.cc/Main/Printf
However I don't really see the point, when what I posted is much easier.

If performance is an issue, you might want to use the "advanced" code.

That "advanced" code above doesn't give you any more performance, because is still blocks. You can do a non-blocking version easily and readably enough:
const byte adcPin = 0;  // A0

bool working;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  ADCSRA =  bit (ADEN);   // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX =   bit (REFS0) | (adcPin & 0x07);  // AVcc
  }  // end of setup

void loop ()
  {
  if (!working)
    {
    bitSet (ADCSRA, ADSC);  // start a conversion
    working = true;
    }

  // the ADC clears the bit when done
  if (bit_is_clear(ADCSRA, ADSC))
    {
    int value = ADC;  // read result
    working = false;
    Serial.println (value);
    delay (500);
    }

  // do other stuff here

  }  // end of loop

Now that code (which admittedly fiddles with the registers) doesn't block so you could be doing other things during the conversion. I don't see any reason you wouldn't use that on a commercial product.
See ADC conversion on the Arduino (analogRead) for more details.

Nice answer illustrating the idea/potential behind Arduino.
The code given by the "Question Asker" would be the somewhat like the underlying code in the arduino analogRead() function.
If performance is an issue, you might want to use the "advanced" code. As it separates the ADC init from the actual reading and is more "tweakable" than the arduino code.
Though the arduino code is many times more readable. But on a commercial product it will be unlikely to use Arduino code.

Thanks! You can quite easily write it without blocking, see amended answer.

I meant that using the Arduino library functions would be unlikely. But indeed you can use it. Much appreciated that you actually took the time to work out a non-blocking function. Though it does have a delay after printing the result? Is it for the ADC to get ready again or just so that it won't spam the serial output?

For simple demos I usually put a delay in something that happens a lot to stop the serial output spamming, yes.


text:
Microphone input into Arduino uno R3
I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .
Is it a correct value?(circuit taken from here http://wiring.org.co/learning/basics/microphone.html)
EDIT: If I put my finger on it the values go up a bit like 792 ,794,800

Please post your code (edit the question to do this).

When does the value "just go down" ?
Have you checked for a dodgy ground connection?
Why have you tied pin2 to ground?
(Your code looks good)

While you may well have circuit problems, before investing in it realize that ADC samples from an Uno reported textually over serial won't be a very meaningful representation of audio.

The amplifier circuit you refer to puts out 2.5 volts even without input from microphone. The LM386 has internal circuitry to make the output 1/2 of the +5 volts. Then, audio signal goes above and below the 2.5 volts.
The amplifier circuit will only be putting out the PEAK of your audio signal (because D1 and C2 is a peak detector)
So, when all is quiet, take that ADC value as meaning zero microphone input.

This schematic contains also the OpAmp stage for a microphone.
You could take it as reference against the design you are using.
The LM386 is basically a more integrated version, iirc.