text:
Measuring 12 V via voltage divider: choosing the right resistors
I want to measure a 9 V battery via one of the analog input ports of my Arduino Nano. From all the schemes of this great answer, I choose the simplest one, the voltage divider. Assuming the maximum input voltage to be 12 V (just to be safe) and maximum divider's output voltage to be 5 V, I've solved it against R₂:R₁ proportion. It turns out that R₂:R₁ = 5:7.

simulate this circuit – Schematic created using CircuitLab
With the values above, the input of A0 pin will be exactly 5 V.
The problem is that it could be any values. 5 Ω and 7 Ω or 5 MΩ and 7 MΩ!
I understand, that there should be another equation to take into account that will give me the values of those two resistors. Another brilliant answer demonstrates, that the values depend on the current I want to flow through the branches:

So the point is when determining the resistance of the resistors, we should take into account the input resistance of the load and the two voltage divider resistors should be as small as possible.
On the other hand, let's compare the current going through the divider in the circuit with large resistors on the divider and the circuit with small resistors on the divider. As you can see, the large resistors have current of just 2.5 μA going through them and the small resistors have current of 25 mA. The point here is that the current is wasted by the voltage divider and if this was for example part of a battery operated device, it would have a negative impact on the battery life. So the resistors should be as large as possible in order to lower the wasted current.

9 V batteries are known to have a little of energy canned inside, with the most popular 6LR61 having only about 550 mA·h. I do not want to waste it on heating the resistors, so, probably, I need to use large resistors. But how large? Too large R₁ will let only a little current to flow to the A0 pin and I've read somewhere that small currents may lead to analogRead measurement errors (underestimations?) due to ADC's internal capacitor.
Trying to find the right answer, I've read on the Arduino's forum that:

The ATmega328P datasheet has this info way in the back: Table 28-16 (page 328). The analog input resistance is claimed to be 100 Mohms.
During an actual sample, the input resistance is temporarily a lot lower as the sampling capacitor is charged up so it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy.

And here, I am stuck. I understand that I am connecting a voltage divider to the A/D, but what is it's "output impedance"? It should depend on R₁ and R₂ somehow, and solving that equation (F(R₁, R₂) == 10 000) will give me the exact value…
P.S. I saw some cunning schemes in the Internet with capacitors, diodes and op-amps (everybody say it's super easy and safe to use them for this task), but, please:

I am just trying to understand the basics and making my first steps with electronics.
The device I'm making should be lightweight and compact (although I should be able to compose it without any PCB magic). Two resistors seems to be fine.
I'm going to read the voltage only once when the device is turned on, so I don't actually need super-fast op-amp's speed.
I'll try not to plug negative voltage, so I do not need a protection. Yet.

Wow that's a long question.  I did a quick search and "noise" is not in there. So, here's yet another consideration: If the resistances are too large and the environment is noisy enough, nose may leak into your measurements and cause false readings.  You can mitigate this by using lower resistances. You can also mitigate this in your firmware.  You can also mitigate this by controlling the noise source.  Oh, and chances are that you will always make multiple measurements to mitigate noise.  It is common a 12 bit ADC to not have 12 bits (maybe only 8 bits) of resolution if no averaging is done.

Thanks, @st2000! I indeed read about large resistors "catching" the noise. I thought to mitigate that by reading the value, say, 10 times and averaging it. As I've said, it's only done once and need not be extra-fast.

And, yes, I've tried to put everything I've learned so far in the question, because there is so much information on the Internet and so many parameter. Like your consideration about the noise.

One more advice I saw, is just using ~10 kΩ as R₂ and never bother, but I want to understand the math.

Another general consideration: Never apply a voltage to any pin on a logic chip (microprocessors included) which is higher than the supply voltage.  So, if the micro is actually a 3V3 device, you should not apply a 5V signal to any of its pins.  In fact, many designs have clamping circuits to avoid accidental high voltages.

@st2000, but Nano seems to have 5 V operating voltage. And I am going to apply 9 V (12 V) via a voltage divider, that will drop it to less than 5 V, so I am safe?

Some Arduino processor run at 3v3, others at 5v.  Spot checking, I see schematics where the Nano's processor's VCC pins are connected to 5v.  Fresh batteries are sometimes a little higher than their labeled voltage.  Also, mistakes can happen.  Connecting a 12V battery to a voltage divider designed to convert 9V to 5V.

That's why I'm calculating 12 V divider for a 9 V battery :)

What you are looking for is called the Thévenin equivalent source.
For the schematic you are showing, and assuming you can neglect the
output resistance of the battery itself, the output resistance of the
voltage divider is the same as the two resistors in parallel. If you
want the maximum allowed resistance (minimum current) you have then to
solve:
1/R1 + 1/R2 = 1/(10 kΩ)
R2 / (R1 + R2) = 5/12
which gives:
R1 = 12/5 × 10 kΩ = 24 kΩ
R2 = 12/7 × 10 kΩ ≈ 17.1 kΩ
You can then round the values down to the closest standard values,
taking care that the rounding does not impose more than 5 V on the
analog pin. For example, if you restrict yourself to the E6 series, you
could choose
R1 = 22 kΩ
R2 = 15 kΩ
which would give you a Thévenin equivalent output resistance of
8.9 kΩ, and a maximum output voltage of 4.86 V.

Thank you. So, basically, I need to cross out the batteries and calculate the resistance of the divider between the points I used to attach the Arduino (ground and between the resistors)?

@madhead: Yes. That's basically what Thévenin's theorem tells you.

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


text:
Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P
I have posted this on the Arduino forum also, but I give it more chance if posted here also.
I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.
I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.
First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:
avrdude: Yikes! Invalid device signature
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51
I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.
I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?
I appriciate all the help I can get!

Try a bigger capacitor. Also, putting it between reset and GND sound more logical to me. Looking at the schematic you can also put a jumper between 5V and RST. similar error

This worked for me dude :)
See this:
http://www.instructables.com/id/Bootloading-ATmega328-with-Arduino-Mega2560/?ALLSTEPS

You might want to cite the most interesting parts of your source/link.
In case the link might go dead.
Also, to avoid getting 10's of answers with only links. Which isn't manageable and you'll have to visit each link to check what the good/best answer is.
Read this for more information on single-line or link-only answers: http://meta.stackexchange.com/questions/156941/one-line-answers

source: Stack Exchange

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

sort: votes


text:
How exactly is voltage measured on an Arduino?
How do the analog pins on an Arduino measure voltage?
Do they either measure current and calculate the voltage with Ohm's law? (If so, why can we only read voltage and not current directly?)
Or do they compare the unknown input voltage with a known internal one? (If so, how does that work? What's the known voltage?)

Known voltage is usually provided by a diode or similar reference. The atmega328p chip has a separate aref pin so you can choose your own reference.
An ADC or analog to digital converter http://en.m.wikipedia.org/wiki/Analog-to-digital_converter is a collection of comparators. A comparator is a logic gate that simply tells which of two inputs has more voltage. This aref voltage is divided evenly into 2^10 values (it's a 10 bit ADC). Then the incoming signal is compared against all of these and the largest comparator which triggers is the reading you get in your arduino code.

A flash converter is a collection of comparators. The ADC in the ATmega328/1280/2560 is a successive approximation converter, which uses a DAC and comparator. This is all described in the datasheet.

Thanks! Really satisfying to finally know how it works. Would you mind quickly explaining how comparators are triggered, if you happen to know?

The Arduino uses a 10 bit Analog to Digital Converter(ADC). A good ADC  is made such that it has only as many comparators as is the resolution of the ADC (in BITS) . Therefore the Arduino should have only ten comparators.
More detailed:
Comparator Number      Trigger voltage
        1.(LSB)..............................       (5/1024)V
        2........................................             (5/512)V
        3........................................(5/256)V
       ..........and so on till
        4.(MSB)..............................(5/2)V
So, for a voltage of say 2.75V, you will get a value of 768(11000000 in Binary)
Update:If you choose to give and use a separate Ref Voltage to the Arduino, It replaces the 5V with the new ref voltage.
Update 2: Sometimes a single comparator may be used in exchange of all 10 comparators.i.e., it is used to trigger all the bits .But the voltage at which each bit is triggered remains same.

@PenguinCake The simplest comparator is an Op-Amp.Search Google for more info on Op-Amps.

Op amps make terrible comparators. And the ADC in AVRs only uses a single comparator.

Are you sure? Is it a single comparator or a single device that has 10 comparators?  While it is possible to use a single comparator, it is usually much slower.

It is a single comparator. It is used to compare the input versus the output of a DAC. I can't think of any way of using 10 comparators that would be any faster than using 1.

When using single comparator, it uses 2 cycles per bit, whereas with 10 different ones, it takes one per bit.

The Arduino uses a analog-to-digital converter. For instance on the Arduino Uno there is a 10-bit ADC. Therefore the resolution is 2^10 bits which is 1024 different representations. As the Uno runs at 5V, each step represents 4.9mV.
The actual inner workings of the ADC can be quite complex and I don't exactly know which specific type it uses, but there can be many ways. One example is measuring time to discharge of a known capacitor. Another is comparing the voltage to the running voltage and using a counter.

"The ATmega48A/PA/88A/PA/168A/PA/328/P features a 10-bit successive approximation ADC."

I'm not sure what the answer is or why no one has addressed the second part of your question. To calculate current you need to know voltage and resistance (I=E/R). The ADC is giving you the voltage but I don't know what value to use for resistance in order to calculate the current. I do better with digital electronics but I suspect you might be able to use a resistor divider network to measure the voltage drop across a known resistor to measure current but do not take my word for this.

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


text:
connecting lv maxsonar ez arduino
I am not 100% sure this question relevant here , but question is I have lv maxsonar ez which need 5v. I am powering my uno with  9v battery. And I have few other sensors also connected to 3.3v. But I have neopixel 3 meter LED which is powering with external power source which is 5v 4 amp. So My question is shall I connect my sonar sensor to the external power or keep with my uno 5v power ?
Thanks

Don't cross post on other SE sites.

Sure, I got confused because I was afraid that this question won't be relevant here. But I got the answer :)

I think the question is still relevant.
You should keep the maxsonar powered from Uno power if you don't want to burn it. Even if you use 9v Battery, Arduino Uno have internal 5v regulator. So it would be safer to supply the sensor from Arduino 5V (not Vin) pin.

To be precise, the pin labelled 5V.


text:
Cheap arduino wi-fi TRIGGER
I am looking for cheap way to have very basic wireless communication between an Arduino and a iphone.
I don't need to send complex data, it would be sufficient to "trigger" the arduino: let's say it is reading a certain pin voltage and waiting for it to be up in order to do stuff, my goal is to trigger this pin up by any (wireless and iphone friendly) mean.
I have figured out two solutions: wi-fi shield, cheap RF transceiver. The problem with the latter is that it is not trivial to communicate with a RF transceiver from an iphone. I should add another arduino controlling an RF transceiver on the iphone side and commanding this arduino with an usb.
The wi-fi shield on the other hand is too expensive. Even small routers such as the wr703n (30 euro more or less) is too expensive in my opinion. I just want to send a "bit" of information, so I don't want to spend more than 10 euro.
The third option would be to hack some cheap wi-fi controlled tool, such a lamp or plug: do you know any?
Do you have any other idea?
Thanks!

Does the triggering involve user interaction, eg. pushing a button on the iphone. Or should it be done completely automatic when the phone comes "near" the Arduino?

Button on the iphone

If you are going to need human interaction (button) Then I suggest you get a wifi router with a few ethernet ports in it (if you dont have one already... most homes have one nowadays). And then you connect the arduino via ethernet (ethershield (quite cheap) or ENC28J60 (very cheap) or etherten or other). That way you can connect to your arduino from your iphone.

WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.
RF transceiver you need external circuitry.
The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).
Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.


text:
What does the datasheet information for a switch mean?
I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps.
A project I'm working on now requires turning on an LED using a float switch like this one:
Water Level Switch
The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.

I think that "minimum voltage" must be the "minimum damage voltage", i.e. the switch is guaranteed against damage until 250 Vdc.

It's just a reed-switch, so it should work just fine with any voltage (below 100v). I think the 250V is the "minimal breakdown voltage". I see that term in some reed switch datasheets.

Ah, interesting. I haven't seen that called out in any Arduino materials I've read so far, but I'm pretty new to this. If one/both of you post as an answer, I'll accept.

Thinking about this again, datasheets for these kind of switches don't seem to indicate what the minimum voltage and current are. How might I go about figuring that out?

A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than
20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.

It says "maximum breakdown voltage: 250 V DC". That's maximum, not minimum. Above 250 V DC the arc which is created by an opening contact isn't guaranteed to extinguish. It's defined for DC voltage because then the arc remains; for AC the arc will extinguish automatically when the current crosses zero.

Looks like they changed the data in the listing or the datasheet since I originally posted this, and you're right, now it says maximum breakdown. Either way, I hadn't see anything about arcs and your info is useful and I appreciate the comment.


text:
Where can I find beginner resources on using voltage regulators with Arduino circuits?
I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.
I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics & Arduino. (I'd like to go from there to transistors, mosfets, etc.)

Try reading the datasheet of the regulator you want to use. Most supply a sample circuit with recommended capacitor values. Datasheets can be scary, but you don't need to understand everything. Come time, you'll begin to know the meaning of more and more values inside any datasheet. At least, this is what happened (and is still happening) to me.

My understanding is that the capacitors smooth the signals. This helps the internal workings of the regulator not overshoot when compensating for a change in the input or the output. If the capacitors are not there then there is a chance of oscillation.
A search of google for Voltage Regulator Tutorial will give you quite a few results, here is one that I found (obviously this could change so if it does just do a search and go from there)
regulator basics
The link above is a good explanation that is not too in depth. But as stated in the comments look at the datasheet for specific values needed.
I also did a search for 'what are the capacitors for on a voltage regulator' and found some good info about why they are needed.

You are missing a link or something in your answer. When you update it, please include some valuable information in your answer instead of just linking to another website.

@sachleen, sorry it is not up to your standards but Gregir has asked for links to good tutorials I have supplied him with one. If you click on the words 'regulator basics' you will find the info requested (I hope).

It's not @sachleen's standards, it's common sense. Links change or pages disappear. So a future visitor may not get the information. Including some useful information or excerpts from the link(s) you supply means your post continues to be useful regardless of what happens to external resources. See http://meta.stackexchange.com/questions/72000/should-there-be-a-policy-about-one-link-only-answers and http://stackoverflow.com/help/how-to-answer

Good search suggestions here. Not sure why my Google efforts were so fruitless, but I'm starting to find more info now. Thanks.

In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.

Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.
It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well.
The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.
Part Number     Output Voltage (V)      Minimum Input Voltage (V)
7805            +5                      7.3
7806            +6                      8.3
7808            +8                      10.5
7809            +9                      11.5
7810            +10                     12.5
7812            +12                     14.6
7815            +15                     17.7
7818            +18                     21.0
7824            +24                     27.1

Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.
Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.

Thanks. Calling out the diode and minimum input voltage stuff is helpful. I missed/glossed over that stuff before.


text:
Can I mix 22awg and 26awg hookup wire in the same circuit?
I'm still fairly new to Arduino projects, and am only just now getting into building circuits where I want to cut and place my own hookup wire instead of using the precut jumper wires. I inherited some supplies from a friend who abandoned the hobby, and about half of the wire he gave me is 22awg and the other half is 26awg. All of it is solid core copper. Is it ok to mix wire gauges like this in the same circuit/project?

Assuming you won't ever put more current through it than the 26AWG wire can handle, you'll be safe.

Thanks. Any tips on where to get reliable info on what 26AWG copper (for example) can handle? In searching just now, I found charts & answers that indicate everything from .3 to 6 amps.

It depends on how warm you can let the wire get. I wouldn't let it get above 75degC total, so assuming 20degC ambient, that's a 55K rise. You plug that and the wire gauge into a calculator, and it will spit out the maximum allowable current.


text:
Operating system on Atmel 328 Arduino?
Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?

You can use FreeRTOS on the AVR family:

http://www.freertos.org/a00098.html

I tried it and it works. However, it turned out to be not very useful in the end. The Arduino Due or Arduino Zero with the schedular is a lot more fun.

Here is a portable implementation of the Scheduler https://github.com/mikaelpatel/Arduino-Scheduler.


text:
How To Communicate Three NodeMcu In Access Point Mode
I'm working on project which for example 3 nodemcu connected with eachother in a line(1 connected to 2 and 2 connected to 3) and they are all in access-point mode (they are all server) and now my problem is how to communicate between 1 to 2 and 2 to 3 i have tried tcp but its for server-client
any help would be appreciated


text:
Trouble making TMP102 work with any ADD0 other than ground
I'm trying to get an Arduino Uno to run four sensors (all I2C). The first two are TMP102 temperature sensors. The address is controlled by tying the ADD0 pin to GND, VCC, SDA, or SCL (four possible addresses, without multiplexing). I get it to receive data just fine through the GND setting.
I wrote some code to collect from two, but before I was even talking to the second one, plugging it in causes the data stream from the GND one to stop. Unplugging it from the breadboard makes it work again. Either sensor in either location on the breadboard will work fine, as long as it's addressed as ground. Neither sensor will, even by itself, work with any other address. I tried some other sketches from the net (one attached below that should read from any of four different sensors), but all have the same issue.
#include <Wire.h>
byte res;
byte msb;
byte lsb;
int val;

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

void loop()
{
  res = Wire.requestFrom(72,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "72:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(73,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "73:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(74,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "74:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(75,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "75:");
    Serial.println(val*0.0625);
    delay(1000);
  }
}

Breadboard:
(image link: the forum kept crashing when I tried to upload the image directly)
https://www.sugarsync.com/pf/D333436_95042359_6938296
Thanks!

You see that little solder jumper block on the breakout board labelled "ADD0"?  You need to remove the solder from that.  It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.

Well, that's not obvious :)
Would soldering the other pair of contacts together tie ADD0 to VCC?

Most likely, Yes.

I just used a jumper to set the second address, rather than soldering, but... it works! Thanks for the help!


text:
List of sketches disappears off the bottom of my screen
v 2:1.0.5
The list of sketches disappears off the bottom of my screen and there is no scroll to reach them. This renders the IDE nearly useless.
Is there a solution?

Yes. Install a version of the IDE that isn't 10 years old.

get a bigger screen, or move some into a sub-folder

That issue has been fixed since the Arduino IDE 1.5.5 release, 4 years ago.
The version of the Arduino IDE you get from apt-get install arduino has not been able to be updated for years due to licensing issues. The versions available from various package managers may also be modified in ways that introduce new bugs. For this reason you should always install the official Arduino IDE version downloaded from:
https://www.arduino.cc/en/Main/Software


text:
How can I find the time taken while a function is being called?
I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

micros() is more exact.

Here is a set of macros for benchmarking functions https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/benchmark.h. They can be used like this https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Benchmark/Benchmark.ino

There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())
unsigned long preFunction = micros();
foo();
unsigned long timeElapsed = micros() - preFunction;

The rollover is not an issue as long as foo() executes in less than 71.5 minutes.

Beyond the answer of ratchet freak, I also suggest to (for test only), put it in a loop and divide it to get a better result, like:
unsigned long preFunction = micros();
for (int i = 0; i < 1000; i++)
{
  foo();
}
unsigned long timeElapsed = (micros() - preFunction) / 1000;

The number of repeats depend on the length of foo(), make sure it will not have a value beyond an unsigned long.

The most accurate method would be to toggle a pin high right before the function, and low after.
If you than connect an oscilloscope or logic analyzer to the pin, you can measure the exact time it took for the function to execute.

@LookAlterno: Any oscilloscope would do. Even a cheap pocket scope, like the DSO nano, is likely to be more accurate than micros().


text:
Rfid reader and SD card shield won't work together
I recently encountered a problem that's been bugging me for days. I want to make a project using a RFID reader and log data on an SD card with an Arduino Nano, but apparently no matter what I do, I can't seem to make them work together on SPI. They both work individually, and the SD shield works in parallel with the RFID reader, but the RFID doesn't work in parallel with the SD shield.
I'm absolutely sure that the wiring is correct, slave select on both modules are wired to different digital pins, and both are connected through bidirectional level shifters.
I noticed that the RFID reader works fine when I disconnect the MISO pin from the SD shield. I tried putting a diode between SD MISO and digital pin 12, I tried adding pullup resistors on both SS pins, I tried adding resistors on MISO lines, I tried pulling HIGH the SS i don't use, and low the one I want active. Nothing seemes to work and I'm out of ideas. The last thing I will try is conencting the modules on separate VCC, but I don't have faith that it will make any difference.
I hope someone has some advice for my problem.
Thanks in advance

Show wireup schematics and the code declaring the pin connections.

SD cards (or really their breakout boards) don't tend to obey the rules with regards to SPI. In particular the MISO pin isn't set to high impedance when the slave select is not selected.
You can fix this with a tri-state buffer that you feed the SD card's miso line to and controlled by the slave select. The output from the buffer goes to the arduino's MISO.

I used a tri state  buffer and it worked, thanks a bunch !

The only way I could get it to work was to buy a separate SD logger shield (which contains an SD card via SPI).
When I used the SRAM (SPI) together with the SD card (SPI) it never did work. At least not on an Arduino (Uno or Mega).


text:
How do I connect my Ublox neo 6M GPS Module with arduino mega 2560?
I tried connecting RX of GPS to Pin 18 and TX of GPS to Pin 19 but I get an error that No GPS is detected,check wiring.VCC of GPS to 5V.
I have set baudrate to 115200.I am trying DeviceExample code of TinyGPS++ library.

Have you checked that is the correct baud rate?  Most GPS work at 19200.
If you want more information you need to flesh out the question.  Add a circuit diagram and a link to the GPS datasheet.

The default baud rate for ublox NEO-6M GPS devices is 9600, not 115200.
And try NeoGPS.  It's smaller, faster, more accurate, more reliable and it comes pre-configured to use Serial1 on a Mega.  Be sure to read the Installation instructions.  If it doesn't work, follow the Troubleshooting pages and try NMEAdiagnostic.ino.
NeoGPS has an example sketch (ubloxRate.ino) that can configure the NEO-6M to other baud rates, once you get the basic programs working at 9600.


text:
How does DDRD |= _BV(PD2) differ from digitalWrite(2,HIGH)?
I'm attempting to copycat the work of Louis Frigon's Toyota Aux Enabler. I have (with a lot of help on this site) managed to begin capturing and understanding messages on the AVC-LAN bus, but I can't quite send messages.
Frigon uses the following line to drive output signal to high:
DDRD |= _BV(PD2) | _BV(PD3);

I have more or less no idea what this means. He then 'releases the output' with the following:
DDRD &= ~( _BV(PD2) | _BV(PD3) );

If I copy these lines verbatim I don't get the same results. If I set the output high and then read the bus, I don't even see the signal I'm putting out. I wonder if this is related to the differences between his Atmega8 and my Arduino Nano?
I can't paste my or Frigon's work here due to character count limitations, so here is his github for the project: https://github.com/halleysfifthinc/Toyota-AVC-LAN
The most important files to my question are BigSchematic.jpg and AVCLanDriver.c.
Here is a dump of my current code: https://pastebin.com/NG9U5FuL
Here is my schematic: https://i.sstatic.net/csiVv.jpg

Each port on the ATmega328P (or the ATmega8 for that matter) is
controlled by two registers¹:

DDRx, where x is B, C or D, is the “data direction register”. It is
used to set the pin to either input or output. Writing to this
register is roughly equivalent to calling pinMode().
PORTx is the port's “data register”. It is mostly used in output
mode to set the pin to HIGH or LOW. Writing to this register is
equivalent to calling digitalWrite().

All this is covered by the Arduino tutorial on direct port access.
And, of course, by the datasheet; more specifically by
section 18.2: “Ports as General Digital I/O”.
As you may now notice, the original code does not use anything like
digitalWrite() to write to the bus, relying instead of the equivalent
of pinMode(). This is related to the electrical characteristics of the
bus:

You write a “physical 1” by actively driving AVC+ high and AVC− low
You write a “physical 0” by releasing the bus, in which case the
potentials of those lines are set by the termination resistors.

That's why you see InitMCU() setting PORTD for driving AVC+ high and
AVC− low, but leaving DDRD in its initial state (“leave pins
tri-stated” says the comment). At this point the bus is in the
“released” state. Then pulses are sent by setting the pins to output
mode (“Drive output to signal high” in the comment) and, after an
appropriate delay, setting them back to input mode (“Release output”).

¹ I am leaving away the details that are irrelevant to the code in
question, like the internal pullup or pin toggling via PINx.


text:
Constants within array of structs causes strange compiler errors?
In my sketch I have the following:
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       HU_ADDR, UNKNOWN_ADDR, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

When I compile this, for some reason the Arduino IDE points at the first line and says "expected '}' before ';' token". If I replace the text like so:
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      0x190, 0xFFF, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  0x190, 0xFFF, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       0x190, 0xFFF, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           0x190, 0xFFF, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         0x190, 0xFFF, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

Then it compiles with no complaints.
....what? Why? Aren't these functionally identical? Why does the compiler care if I use HU_ADDR instead of 0x190?


text:
Printing char array from array of structs in progmem to serial
(I apologize if this is a c++ question, I'm too green to know if this is unique to the Arduino IDE)
I've moved an array of structs into my PROGMEM because I was running into memory issues:
#define HU_ADDR                 0x190
#define ALL_AUDIO_ADDR          0x1FF
#define MY_ADDR                 0x360
#define UNKNOWN_ADDR            0xFFF

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEONRARE,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC,
  ACT_PRESSAM,
  ACT_CD,
  ACT_STATIONFOUND,
  ACT_ENABLECD,
  ACT_CD2
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  word Payload[24];
  char Description[20];
};

const MessageDef MessageTable[] PROGMEM = {
  {ACT_POWERON,           HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x00, 0x100, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                    "Tune Knob"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,    {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                       "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,     {0x46, 0x01, 0x11},                                                                                "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,     {0x60, 0x45, 0x01, 0x11},                                                                             "Passive: Strong"},
  {ACT_PASSIVEONRARE,     HU_ADDR, UNKNOWN_ADDR, 4,     {0x100, 0x20, 0x01, 0x11},                                                                            "Passive: Fierce"},
  {ACT_PASSIVEON_0,       HU_ADDR, ALL_AUDIO_ADDR, 16,  {0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x100, 0x80, 0xF1, 0x31, 0x74},    "Vol Knob"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,    {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                                   "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x00, 0x9F, 0x31, 0x62},                                                                             "No DISC available"},
  {ACT_PRESSAM,           HU_ADDR, ALL_AUDIO_ADDR, 24,  {0x00, 0x60, 0x31, 0xF3, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x30, 0x00, 0x58, 0x00, 0x6C, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AM/FM Switch"},
  {ACT_CD,                HU_ADDR, ALL_AUDIO_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x01, 0x30, 0x01, 0xFF, 0xFF, 0xFF, 0x00},                                   "CD switch?"},
  {ACT_STATIONFOUND,      HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                     "FM station found"},
  {ACT_ENABLECD,          HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x77, 0x00, 0x81, 0x00, 0x00, 0xF1, 0x31, 0x60},                       "Enter CD mode"},
  {ACT_CD2,               HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x62, 0x45, 0x01, 0x11},                                                                             "CD message 2?"}
};

const byte MessageTableSize = sizeof(MessageTable)/sizeof(MessageDef);

I've adjusted accordingly in my code segments that reference this data using pgm_read_byte_near() for example. However, I'm not really sure how to get the Description field anymore. When MessageTable was in dynamic memory I could just use:
Serial.println(pgm_read_word(MessageTable[msgid].Description))

But now that seems to be printing... maybe the addresses of the data? Instead of printing out the character array I need to see. How do I parse this more correctly?

You can use the strncpy_P(char* dest, const char* src, size_t maxLen); function which will copy a zero-terminated string of at max maxLen bytes from PROGMEM into RAM. Then print the string from RAM.
Example code:
//We have global buffer in RAM. +1 for 0 termination
char descBuf[20 + 1];

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

    //Copy the description string of the first message in the buffer
    strncpy_P(descBuf, MessageTable[0].Description, 20);
    //Print it
    Serial.print("Description: ");
    Serial.println(descBuf);
}

Together with your code above, that prints on my Arduino Nano as:
Description: Tune Knob

If you don't want to have a 21 byte big buffer in RAM (or there are larger strings you wish to print), you can also use the pgm_read_byte function to read and print the string characters byte-wise. Example:
Serial.print("Description: ");
char c = 0;
for(size_t i=0; i < strlen_P(MessageTable[0].Description); i++) {
    c = pgm_read_byte(MessageTable[0].Description + i);
    Serial.print(c);
}
Serial.println();

For further reference, see the Arduino documentation on PROGMEM: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


text:
Rescuing an Arduino With a Broken Setup()
I may have bricked my Arduino Pro Micro by writing a broken code into the setup() function. When I plug my Pro Micro into my PC, I see it register a COM port for a brief moment before it disappears. Grounding and ungrounding the RST pin causes the device to appear in my control panel again for a brief moment. Attempting to upload the blink example from the Arduino IDE fails, since the COM port disappears before the process can complete.
Is there an alternate way of flashing code to the arduino which I could possibly use to fix this? I have a working Pro Nano I could use if needed.

Try grounding RST twice in quick succession.

When working with any microcontroller it can be good practice to always have a hardware programmer on hand. Bootloaders are all very well, but when they go wrong they leave you stuck. Hit eBay for a USB-ASP (~$2 from China - get the adaptor with it).

After Majenko's suggestion I tried looking into USB ASPs, and then did research about whether you can use an arduino as an ASP. Sort of. I'm not sure if an ASP is exactly the same thing as an ISP, but I used an Arduino Nano as an ISP to program the Arduino Pro Micro.
To do this, I opened the ArduinoISP example sketch and burned it to the Nano (over USB). Then I connected it to a breadboard, along with the Pro Micro. Connected the following pins:
nano pin          micro pin
13                15 (SCK)
12                14 (MISO)
11                16 (MOSI)
10                RST
5v                5v
GND               GND

It is important to connect a capacitor from Nano RST to GND. I was told to use a 10uF capacitor but I had a 1uF on hand that worked just fine. Then I opened up the Blink example sketch, set up the Arduino IDE for programming the Pro Micro, and set programmer to "Arduino as ISP". Hold shift, click upload, problem solved. Pro Micro is running Blink and I can now recognize it and program it over USB.
So I agree with Majenko; someone faced with this problem should buy a hardware programmer. But only if you don't have a spare Arduino ;)

The ASP in USBasp is just part of the name. It probably stands for something like USB Atmel/AVR Serial Programmer. It still uses the ISP protocol.

It's worth mentioning that my Arduino-Arduino programmer has begun to fail me. I'm not sure exactly why, but I'm no longer able to pull this off. More research required. I'm purchasing a USBasp to see what I can salvage.

You can try running the code upload command directly using a precompiled hex file.
Here is how.
Go to preferences in Arduino IDE
Set the Show verbose output during: upload option.
Upload the blink sketch. (arduino does not have to be connected)
After the compilation, check the log window at bottom of the IDE.
You will find a line like this:
E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

That is the actual code upload command.
Copy the command line and paste it into a windows CMD window.
Edit the COM port to match your Arduino.
Reset the Arduino and immediately press Enter to run the command line.
You may get lucky and the upload "squeaks" through.
You can also move the hex file to another folder so that it is always available for doing a quick recovery.
You could also create a BAT file so that double-click on the icon runs the upload.

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


text:
How to pulse a signal at 100ms to 500ms?
Based on this PDF I need to pulse between 100ms and 500ms to record a video (the description is apparently wrong according to this guy). How would I generate such a pulse? The small module has 3 wires I can use, which are positive, ground, and a yellow wire. I assume I need to pulse the yellow wire.
I don't want to hook anything up wrong, but my guess would be using pulseIn(). However, I am not sure at all. Any help appreciated.

According to the pdf you need > 500ms for video...  100 - 500 is photo.

@Majenko That is wrong according to some guy, but that doesn't really matter anyway.

Okay, so pulsing is apparently easy enough. If I just do:
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.
EDIT: Turns out the schematics were right. If I do something as simple as:
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(1000);

It will turn on the video recording and turn off whenever it gets HIGH again.


text:
First Serial.print voltage is wrong, way too low. Ruins average calculation
The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.
https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf
For the average calculation I added:
count = count + 1;
volt_mV = ((count-1)/count)*volt_mV + (1/count)*volt_V;

Please post the exact code you are using, rather than letting us see what source you have started from and then try to guess what you have added or changed to it.

The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.
Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.
Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply exponential smoothing or some other form of smoothing to the readings.
Note, the formula you show for averaging – ((count-1)/count)*volt_mV + (1/count)*volt_V – has a number of problems.  First, if count is an integer, both of ((count-1)/count) and (1/count) will compute to zero values.  Secondly, as count becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a running average, it does not compute a moving average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like movingAverage = (15*movingAverage + newReading)/16.

Your movingAverage formula is a lot better than the one I was using. It quickly fades out the error from the first reading. Its nice to learn the difference between a running average vs. a moving average.

If it is truly only the first reading that is bogus, you could take one or a few readings during setup() whose values you ignore, before your program starts collecting data. Or you could investigate why your first reading is bogus....


text:
How do I change PGA gain in this Arduino program?
Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.
https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

The symbol PGA appears in exapmle.ino (sic) twice, once each in lines 28 and 30:
 #define PGA 1                     // Programmable Gain = 1
 ...
 #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of VFSR, and asVFSR appears only in line 30, that effect is nil.
Looking at the ads1262.cpp file from github, it appears that ads1262::ads1262_Init() initializes register MODE2 to 0x6, via:
ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.
Apparently, if you wish to use some other gain setting, you should define PGA appropriately and put a corresponding setting into MODE2.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in setup() you could say
PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to MODE2.  For example, after
enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
       SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
       SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say
PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.
(Note, enum is a C language element used to define integer constants.  In an enum, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So GainCode1 is 0, GainCode2 is 1, GainCode4 is 2, etc.)
Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.

Yes! Adding   PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8);   did improve the voltage resolution. Thank you for taking the time to look at the linked material. Can you tell me how to set the gain to 32 instead of 16?

@Rico, see edit

I wish I could up vote this wonderful answer! Big help.


text:
Sanity check with potential project. IoT with a dishwasher
So sanity check for a potential project.
We have an old dishwasher at work, a GE QuietPower 3, and being a technology company, we want to connect it to our chat room to notify that the cycle is done, so someone can unload it.
The first iteration of the project we were just going to cover the "finished" indicator light with a photoresistor, so when it lights up, the microcontroller will know it is done.
However, that is not very nice looking, the second approach, after quickly looking at the technical maintenance manual. Is to literally solder the ground and + of the "finished" indicator light to a digital or analog pin, and the ground pin on the micro controller, so the results are more precise.
I suspect the LED is probably less than 12V, (will confirm with a multimeter). I will step it down to 5V.
Then it is just a matter of checking if the pin is high or not on the microcontroller, is this simple enough to solve the problem, or am I overlooking something obvious?

This is enough to solve half the problem - detection. The other half, communication isn't addressed yet (here, anyway) but since you haven't mentioned it I suspect you already have a handle on that part.

Communication was solved by using CC3000 wifi shield.

Use a resistor (10k or something) between the arduino and the diswasher led, in case the voltage is higher that the arduino. The arduino avr chip has internal clamping diode which will protect the chip from possible overvoltages. If the voltage on the led lead is too low (< 0.7*Vcc), you can search for the current limiting resistor that is connected to the led, and tap of the signal before this resistor.

If you want to see your Arduino alive again send $10....... I mean, if you want your Arduino to live, and the people using it to not die semi randomly, then read my answer carefully and consider carefully why you wouldn't do it. Optos cost maybe $1, maybe about free. Keep them away from burning PCBs (ask me how I know) and they will keep the AC mains and similar where it belongs. Non isolated connection to a "looks like it should be OK" device is an invitation to disaster.

If connecting to the wiring, using an opto-coupler will ensure that your Arduino's days will be long on the face of the land. If it is an LED indicator you may be able to connect the opto-coupler LED  input directly across the existing LED, but use of an appropriate series resistor would be wise. Optocoupler LEDs may have about 2 V forward operating voltage which is in the same range as a red LED. Some use lower forwards voltage LEDS (probably IR).
If your opto coupler has low input current requirements then connecting it via a series resistor across the existing LED will allow the indicator to still operate.
R series = (Vsource - V_opto_LED) / I_opto.
eg 12V source, 2V opto_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.
For direct connection across an existing red LED a 100 Ohm series resistor should avert disaster.
V drop in resistor at 1 mA:
V = IR = 0.001 x 100 = 0.1 V
= liable to be OK.
Ask if more information wanted.

More or less. LEDs are often around the 2.something volt range, which won't be enough to power an Arduino. In addition, if you set it to run in parallel with the LED, then the path of least resistance will get most of the current.
I would probably use the led power to turn on a transistor, then use the transistor to signal the Arduino. Be aware that if you want to power it off an external source, you may find that the ground on the washing machine is not the same as the ground on your power supply. If you're powering it off a battery, this won't matter, but otherwise power can flow from one "ground" to another. If you stick a resistor (maybe start with 1kOhm, if that's too much drop it down) between the washing machine led + and the transistor, and the same between the arduino and the transistor.

The Arduino will be powered via the USB port. I am planning to use a digital or analog pin plus ground on the Arduino in parallel with the indicator LEDs.

This is a perfect example of a situation where ground may be different. If you connect the two grounds together (USB ground and washing machine ground), and the grounds are at different levels, you will likely destroy the washing machine or the laptop. Even different USB ports on the same computer may have different ground levels.

Sorry, I should have been more clear, by ground, I meant the ground pin on the Arduino. The Arduino will be powered via a wallwart AC -> USB 1Amp charger.

@Bill seeing that it's an old dishwasher, I would add software denouncing as well.

And as @AMADANONInc. says, use a transistor to step down. It is easily the best way to do this, and if for some reason (bad grounding) the dishwasher misbehaves, the transistor will protect the micro controller, provided its on that supply!

@Bill the problem still applies - if a transformer steps down from 110 to 5, it could use the voltage from 5 to 0, or from 110 to 105 <- This is a gross oversimplification.

@RussellMcMahon's answer of using an opto-coupler would get around all these problems.  In this kind of situation opto-coupling is the normal (and recommended) method.


text:
I/O expander with i2c interface vs Multiplexer
I am wondering where are the difference in between using something like:
CD4067, which selects which pins to read/write from by "selecting" an address with 4 pins by writing to it. Versus the MCP23017 which uses the i2c interface.
I am trying to learn and build a simple application with lots of digital inputs and outputs, and need something that is fast at switching the pins and reading/writing to it.

The MCP23017 gives you 16 extra real IO pins. Each one has facilities such as pull-up resistors, change notification interrupts, etc - the kind of things that you expect from real IO pins. You can read and write to all of the pins.
A multiplexer though just feeds signals through to the existing pins. They're pretty dumb. Only the signal that is currently fed through can have anything done to it. So only one signal can have a value written on it or read from, and pullup resistors and interrupts are non-existent.
However the CD4067 can be used with signals other than digital - as such they are good at being a multiplexer to the analog inputs, something an IO expander can never do. You could, though, use an I2C ADC chip for that.
For high speed IO control you really want to be using the MCP23S17 instead of the MCP23017. It uses SPI instead of I2C and thus is much faster to control.


text:
How to Store the results from a Ping Sensor in a variable
I need your suggestions and help with my Ping Sensor.
I have an Arduino Uno with a Parallax Ping sensor and a motor.
My ping sensor is set to to start the motor when the nearest object is <= 10cm. That works fine.
Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.
I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.
How can I implement this, or if you have any other suggestion, please help me.
Thank you
Here is what i have so far:
/* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;
const int motorPin = 9;
//Yomis code
//int pings[3] = {-1,-1,-1};
//int i;
//bool Increasing(int p1, int p2, int p3)
//{
//  if(p1 < p2 && p2 < p3){
//    return true;
//  }
//}
//
//bool Decreasing(int p1, int p2, int p3)
//{
//  if(p1 > p2 && p2 > p3){
//    return true;
//  }
//}
//
//end of yomis code
void setup() {
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{

  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(1000);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(2000);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(1000);

//        //Yomis code
//        if (cm <= 10)
//        {
//          Serial.println();
//          Serial.println(pings[0]);
//              Serial.println(pings[1]);
//              Serial.println(pings[2]);
//          Serial.println();
//          if(Increasing(pings[0],pings[1],pings[2]))
//          {
//            int Speed1 = 100;  // between 0 (stopped) and 255 (full speed)
//            int Time1 = 3000;  // milliseconds for speed 1
//            analogWrite(motorPin, Speed1);  // turns the motor On
//          }
//        }
//        else
//        {
//          analogWrite(motorPin, LOW);
//        }
//
//        //End of yomis code

  if (cm <= 10) {

    int Speed1 = 150;  // between 0 (stopped) and 255 (full speed)
    int Time1 = 2000;  // milliseconds for speed 1

    int Speed2 = 250;   // between 0 (stopped) and 255 (full speed)
    int Time2 = 3000;  // milliseconds to turn the motor off

    analogWrite(motorPin, Speed1);  // turns the motor On
    delay(Time1);                   // delay for onTime milliseconds
//    analogWrite(motorPin, Speed2);  // turns the motor Off
//    delay(Time2);                   // delay for offTime milliseconds
  }
  else if (cm > 10) {
    analogWrite(motorPin, LOW);  // turn the motor off
  }
  else {
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    delay(100);
  }

}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.m
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

The general idea of your code is fine, but it can be tweaked to make it more efficient.
Firstly, your function increasing(int p1, int p2, int p3) can be simplified to increasing(int *pingArray). This way you pass a reference to the function, rather than three ints. If you decide later that your pings array needs to hold more values you don't have to change the function arguements. However, if you're going to be experimenting with different lengths of the ping array you need to make sure you change the code within the function to reflect this. An easy way to stay on top of it is with #define:
#define MAX_PINGS 3       // Put this at the start of your code somewhere

int pings[MAX_PINGS];     // When you come to declare 'pings'
for (int x=0; x<MAX_PINGS; x++)
    pings[x] = -1;        // Whatever each element is initialised to.

// Your 'increasing' function
//   (... and the same for 'decreasing', if you decide to use it!)
bool increasing(int *pingArray)
{
    // CODE GOES HERE
    // and it doesn't matter how long pingArray / pings is
    // because you have 'MAX_PINGS' defined.
    return true;
}

// You call the 'increasing' function as you'd expect:
if (increasing(pings))
{ /* stuff */ }

Now to the concentrating:
Your initial work is good but from what I've read on ultrasonic sensors, and from experience with any generic sensor, is that the readings aren't going to be perfect. The real world is a noisy place and you aren't going to get nice, accurate distance readings. Finding the average is a simple technique, but you will need to find an optimal solution yourself. Once you have your nice row of average values you can then determine if the distance is increasing or decreasing or neither.
Thus you have two steps:
Average the distance
Create an array (dist, for now) and use it to find the average distance your sensor is from an object.
#define MAX_DIST 5

int dist[MAX_DIST];    // create an array, no need to initialise.
double distAverage;    // average distance, could be 'int' instead.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.

// As you get the distance from your sensor, update 'dist' and
// then calculate the running average.

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAverage = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAverage += dist[x];
distAverage /= MAX_DIST;

I hope you understand the cyclic buffer principle - if you don't you can google it! A key point about the way the code above is constructed is the use of that #define MAX_DIST 5. You can change that single number to anything and your code will change along with it. You will discover that there is an optimum number; I can't tell you what it is (but I recommend it remains odd).
Now that you have a nice reliable distance measurement, you need to find if it is increasing or decreasing...
Average the averages
As you have worked out, you need an array of values to determine if the distance is increasing. Bring in, again, the cyclic buffer.
#define MAX_DIST 5     // these could also be 'const int's
#define MAX_AVRG 3     // but my preference is this way

int dist[MAX_DIST];    // create an array, no need to initialise.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.
int distAvrg[MAX_DIST]; // create an array of averages.
int avrgIterator = 0;  // wwwwoooOOOOooo ? Not this time.

// There's no single 'distAverage' anymore; the result dumps straight
//into 'distAvrg[avrgIterator]'...

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAvrg[avrgIterator] = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAvrg[avrgIterator] += dist[x];
distAvrg[avrgIterator] /= MAX_DIST;
avrgIterator++;
if (avrgIterator == MAX_AVRG) avrgIterator = 0;

Now you have an array of your averages. Winner.
From here you can create your increasing/decreasing function. I'll leave most of this up to you, but consider the following:

The contents of distAvrg may not be perfectly smooth;
The longer any of the arrays, the more reliable the average;
The longer the array, the slower the response of the 'machine';
Using int rather than double for distAvrg may help 'numb' some of the fluctuations in averages;
Because distAvrg is a cyclic buffer, when analysing it make sure you start at the correct element! HINT: If you add your increase/decrease function after all the code above rather than amongst it, avrgIterator will always point to the oldest average value;
If the distAverage array gets beyond three of four elements, you should definitely pass it by reference to the relevant functions; this is what I did in the first codeblock I wrote. It's beyond this answer to explain why you should do it other than "it's more efficient". This is a general rule for any large chunk of data, but you'll learn more as you go along.

The simplest algorithm for determining whether the distAvrgs are increasing or decreasing is to run through from oldest to newest and count how many increases there are and how many decreases there are:
int direction = 0;
for (x=oldest ... x=newest)
{
    if (x > x+1) direction++;
    if (x < x+1) direction--;
}

The above is pseudo-code - you'll have translate it yourself. You end up with a value of direction that is a positive number (increase), a negative number (decrease), or zero. The actual value of direction will help you determine the speed of the increase/decrease, if it's relevant.

A possible solution:

** EDIT ** As pointed out by @EdgarBonet, double and float are 'expensive', in that they take up a lot of computing cycles to be dealt with. The Arduino website recommends avoiding them if you can. The alternative is to use scaled ints. For example, multiplying the return value from microsecondsToCentimetres() by 10 will give you the equivalent of one decimal place's worth of extra precision. No other code needs to change unless you're outputing the value on an LCD or similar and want it in centimeters. Dividing by 10 is conveniently the distance in millimeters, which is why I picked it, but there's no reason you can't scale by a different factor. Just be aware that there is a maximum (and mirrored minimum) value that int can hold, but I doubt you're going to hit it unless you scale by an unnecessarily high factor.

Let's say MAX_AVRG is 6. This gives five changes between distances to look at. The simplest function for determining an increase is:
bool increasing(int * DIST)
{
    int dir = 0;

    for (int x=1; x<MAX_AVRG; x++)
    {
        if (DIST[x] > DIST[x-1])   // change this to < for DECREASE
            dir++;
        else
            dir--;
    }

    if (dir > 0)
        return TRUE;
    else
        return FALSE;
}

The 'decrease' version is identical, save for the single commented line. The for loop starts at the second sample and checks against the previous sample, which is why x starts at 1, not 0 as 'usual'. The return value will be true if distAv has increased more times than it has decreased, and vice versa for decreasing().
Let's say distAve = { 1, 2, 1, 3, 4, 5 }. In the function:
distAve   1   2   1   3   4   5
            ^   ^   ^   ^   ^
start       |   |   |   |   |    dir = 0
increase   -'   |   |   |   |    dir = 1
decrease       -'   |   |   |    dir = 0
increase           -'   |   |    dir = 1
increase               -'   |    dir = 2
increase                   -'    dir = 3

dir > 0 therefore INCREASE.

But what if distAve = { 5, 4, 3, 2, 1, 6 } ? If increasing() will now return false because there are four decreases vs one increase, except the final distance indicates that the sensed object has ended up at an increased distance than when it started.
int distance(int * DIST)
{
    int overallDistance = 0;
    for (int x=1; x<MAX_AVRG; x++)
        overallDistance += (DIST[x] - DIST[x-1]);
    return overallDistance;
}

Now you have an explicit value for the overall distance change.

There is no point in replacing const by #define. 2) float is expensive in the Arduino, better try to use integers, even long if needed.

I agree with @EdgarBonet that it's silly or pointless to replace the const ints by #defines (as noted in his link, “const int constants do not necessarily occupy any storage” and are compile-time constants).  However, I recommend replacing const ints by enum'd constants, eg: enum { pingPin=7, motorPin=9};

@EdgarBonet: (1) I believe #define immediately describes to the reader the fact that you're simply substituting an otherwise meaningless number for a self-descriptive name - it's completely analogous to giving a variable a name rather than having to remember its address. I see your view that there's no point replacing const with #define, but tell me why one shouldn't use #define instead of const in their code. (2) Double-precision may be costly, but it's up to the coder to decide whether it's worth it or not. I agree scaling to utilise unsigned or long is lighter.

@jwpat7: I see no benefit whatsoever of an anonymous enum in place of either const or #define for an arbitrary list of integers such as pin associations or array lengths. Yes, you can save a tiny bit of typing if you have some consecutive pins but that's blisteringly trivial.

chaaarlie2, enum is a specific way of defining integer constants.  #define, on the other hand, is a non-type-checked way of defining textual substitutions.  const int is a slightly-oxymoronic way of defining a "constant variable".

Except in my answer to the OP, I'm talking explicitly about textual substitutions. Who cares if they're non-type-checked? What idiot would attempt to create an array of non-integer length, or try to declare pin 3.141 as an output? And even if they do, the compiler will cast said argument to an int - the same int each time it's referenced.

If the is no point in replacing const with #define, then stop recommending the replacement. The advantage of const is to make it simpler to clearly specify the type of the constants. 2) I am not talking about double precision, which is not supported on the Uno anyway. I am talking about simple precision, which is done by software and can make your program an order of magnitude slower. I would not recommend adding floats to an otherwise floatless program without at least warning about the consequences.

Okay but why is everyone arguing about const and #define. That's clearly not the real problem that the person who posted the question is asking, so i'm kind of lost. @chaaarlie2. What exactly does averaging the averages do, since the distances have already been averaged to find the correct distance.

Say you have six average (mean) distances. If each is greater than the previous then the distance is increasing, and vice-versa. However, if the six mean distances do not immediately indicate a specific direction, you take an average of the five differences between each distance. In this case I am using "average" in the broader sense: you could simply take a count of how many 'increases' vs 'decreases' and use the larger of the two to determine direction, or you could sum the distance-difference between each sample, eg. {5, 4, 3, 2, 1, 20} - five decreases, but an overall increase of 15.

A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively.
Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.

I would use subtraction to find a decreasing series
you can subtract the new ping output from the previous one in every loop this way you can scale to a longer series without allocating more memory for the array
assuming you have defined somewhere:
/*use whatever number you want here*/
#define SERIES_LENGTH 3

declare globally:
int prevPingSample;
int decCount = 0;

than in your loop:
int pingSample = analogRead(sensorPin) //or however else you sample the sensor
if (prevPingSample > pingSample)
{ /*if the new reading is smaller than the previous -  the series is decreasing*/
 decCount = decCount + 1;
}
if (decCount >= SERIES_LENGTH)
{
    //move motor code
}
else
{
    decCount = 0;
}
//and whats left is to update the previous ping sample for the next loop
prevPingSample = pingSample;


text:
D1 Robot... lights up but nothing
I have the Arduino shield described here, I have run the example code compiled to the device, both v1 and 1.1 example, and it shows nothing whatsoever on the screen.
https://www.dfrobot.com/wiki/index.php/Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)
Is there a special trick to initializing this or did I yet again get a lemon that will not display anything?

reduce the code to only the code for displaying something on LCD ..... only this line LiquidCrystal lcd(8, 9, 4, 5, 6, 7); and the code in setup() .... leave loop() empty .... does that display anything?

Like many cheap online shields, this one is a dud, in fact it looks like extended use would fry it if it did work - according to test code this chip is bad.
https://forum.arduino.cc/index.php?topic=96747.0

I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.

"I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display." Thanks


text:
What is the wiring of arduino motor shield to Nano?
I have the basic version of the stepper motor driver and a Nano, I see the pins are set to plug directly in to a Uno or similar Arduino, but according to the documentation it just needs most of the digital pins connected to the arduino - https://learn.adafruit.com/adafruit-motor-shield/faq
As it seems they are the opposite position to plug into a breadboard for testing, I may need to wire and solder them (11 to D11, 3 to D3, 5 to D5, 6 to D6). Is this correct or does the Nano not have the power/amperage/timing or something to run this type of shield, hence the lack of compatibility listed for that shield?

I found that this does work with the Nano - the only reason they don't list it is because it doesn't fit in to the shield I suppose.

Or just another simple version (which is more hardcore such as brute force):
Get expansion shield for nano to uno :)
I think this is just a sandwich version, which just takes additional space and cost.

I believe, though it's not clear, that the shield in question uses a 74HC595 shift register to control the main motor drivers - the other pins are for the servo interfaces (and they are just wired 1:1). Theoretically you can therefore use any pins you like to control the motor drivers themselves.
It's not the same as the Adafruit one which looks to use direct Arduino control of the motor drivers.

Thanks for the answer. Look up the docs for "L293D Motor Drive Shield For Arduin" and it looks like it's the old Adafruit shield, and uses specific pins for each motor... If that's all the difference I guess I'll connect/solder them to the Nano and try.


text:
Which library to use for 23LC1024 SRAM 1 Mbit
I noticed there are quite some libraries for the 23LC1024 SRAM 1 Mbit memory:

SpiRam Extended library
SpiRam library
Direct SPI ?

I tried 1 and 3 so far. What I noticed was that to read 1 byte took around 18 us for the 3th solution and around 25 us for the first library. However, the first has possibilities to read multiple bytes and that considerably speeds up the time.
Also there are other libraries like MQTT and possibly I missed some.
However, in all cases I would expect speeds around just a few us. Since I maybe need to read 100 of different small groups of bytes preferably within 10 us (and process them), it might get problematic in worst case scenarios.
Does anybody know where the speed differences come from or if there are ways to increase the speed or which library is fast?

since they both use the SPI  lib, SPI.setClockDivider matters. a lot on RAM. digitalWrite is slower than the PORTB stuff. there's overhead in sending, so shipping many bytes at once saves "handshake" time. put the tricks together for max speed. might update the code to use https://www.arduino.cc/en/Reference/SPISettings

@dandavis Thanks for that information ... I hope I can get it to work since I also want to connect an SD card via SPI so have to change the settings probably when switching between SD and SRAM (this will only be needed in the first second after startup and only to transfer 128 KB in 512 byte blocks (so 256 times), afterwards I don't need the SD anymore.

SPI RAM has two modes of operation: single byte and "page mode".
In single-byte mode you first send the read or write command followed by the (typically 3-byte) address and then read a byte. That's 5 bytes per transaction, or 40 SPI clock cycles. At the maximum of 8MHz (SPI_CLOCK_DIV2 on a 16MHz MCU) that would be at absolute best (1/8000000*40) 5µS per byte read or written. That's not including the time taken to toggle the CS pin and perform the other software-level parts of controlling the SPI peripheral.
In page mode it is possible to send one start address and then read or write sequential data from that address upwards. Ideal if you need to read a larger number of bytes that are sequentially in memory. For instance, to read 100 bytes sequentially it would take 104 SPI bytes - one for the read/write command, three for the start address, and 100 for the data. That is 832 SPI clocks, or at 8MHz, 104µS.
As you can see, reading 100 bytes within 10µS is not possible on an Arduino with SPI SRAM. There just isn't enough speed. Even 100 sequential bytes. 100 "small groups of bytes" just ain't gonna happen.
There are other technologies that are faster which may be more suited to your use, but they require different peripherals in the chip (namely SQI), and the chips with that in tend to be more powerful and have more RAM anyway, so your 1Mb of external SRAM would be redundant.

Thank you for the very detailed answer ... I don't think I will go for SQI for now, since I'm a beginner, however I will check into the byte versus page modes. I guess I will find in the libraries what is used.  So maybe I have to adapt the manual if I want to use both ways. My idea is to use quite some lookup tables so a smart layout of the memory map in the SRAM might be useful.

Hello! I use Arduino Due and i require external ram to be read/written fast for real time audio. What is SQI?

@user1584421 Serial quad interface. Like SPI but uses 4 data bits instead of 1 for transfers.

Thanks! Are there chipsets like the 23LC1024 that provide external RAM that can be used with arduino DUE for quick r/w? Are you aware of any?

Or do you think 23LC1024 would be suitable for realtime audio? (using the ADCs and DACs).

Depends on the bit depth and sample rate you want. It may be possible, yes. In have done 44.kHz stereo 16 bit from SD card over SPI before.

I am doing fine with the 12 bit ADCs from DUE.. Does that give you a clue on if the 23LC1024 is suitable for me? I just need more RAM. (Also, thanks a lot for your help!)

It's faster than an SD card, so I'd say yes, sure. As long as you code it well. Using DMA would be the best way of doing things, at least for the ADC and DAC access. All my audio work has been on the PIC32MZ using DMA and an external audio DAC chip through I2S.

I have to stick to the DUE due to external libraries. 23Lc1024 supports DMA? Its only today i figured i need more RAM

It doesn't care about DMA. DMA is what the sure does to communicate with it at high speed.

This was an excellent challenge for an SPI bus manager and device driver support library I have been working on. Below are some performance results for the SRAM (23LC1024) device driver (Arduino Uno @ 16 MHz, SPI @ 8 MHz) read/write us per byte, kbytes/s, in benchmark.
write: 9.875 + N*1.4275 us, max. 700 kbyte/s
read: 9.875 + N*1.5 us, max. 670 kbyte/s
where N is the number of bytes transfered

The protocol overhead (9.875 us) is 1) slave select pin handling, and 2) command byte and 24-bit address (four bytes header in total).
Cheers!
Update [2017-09-25]
@MichelKeijzers I recently had time to work on an abstraction of external storage and refactor a number of device drivers to support the new interface. The abstraction includes memory block allocation, caching, handling of large vectors, and streams on external storage. Please see https://github.com/mikaelpatel/Arduino-Storage for more details; benchmarks, example sketches, etc.

I got with my test for 1 byte: 23,49 us/byte, for 8 bytes: 6,70 us/byte, for 100 bytes: 4,06 us/byte, for 1000: 3,86 us/byte. So yours are really faster. However, I decided to not use the 23LC1024 since I want to store some more complicated structures and 'real' RAM (being able to use real variables/pointers etc) is more comfortable. Therefore I ordered a 192 KB STM32 (which causes me a lot steeper learning curve which I'm still busy with).

Actually there is more speed to be gained by interleaving (pipelining) the SPI transfer with data collect. All the SPI wait cycles can be used. The SPI library does some pipelining of the data fetch/store to the buffer. The data access (read/write) and the pointer increments are done while waiting for the SPI transfer. My next challenge is to add a file system/heap on the SRAM and then a Stream binding so that it can work as a ultra fast intermediate Serial for trace etc.

To be honest, I never checked much inside the library itself. Sounds like an interesting project you are doing. It seems like external SRAM is good for continuous regions (and reading less or more bytes from it). Like in your case a file system. To use it as 'real' SRAM is complicated or impossible (meaning to have any kind of variables) to be either using internal SRAM or external SRAM (and even not be aware of the difference as the user of SRAM).


text:
using an ESP8266 shield on my Arduino Uno R3 with an unofficial library
I'm using the following Makefile: https://github.com/sudar/Arduino-Makefile
It works very well and I was able to get my LED to blink.
Now I bought a WiFi Shield which is NOT supported officially by the Arduino WiFi library.
It is the following one I bought: ESP8266 ESP-12E CC3000 UART WIFI Wireless Shield Board Modul für Arduino UNO R3 - you can find this on ebay: http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
What I now am about to do is to include the open source library for the ESP8266 which you can find here: https://github.com/esp8266/Arduino#documentation
Now when I try to upload my sketch it tells me that certain dependencies are not resolved. Like this one here #include <functional> which I was not able to include manually. My main problem here is that the github page of the ESP8266 library isn't providing enough information for me how I can get the working lib to use in my sketch.
I need to know how I can get this library to work in my sketch!

what have you done to interact with your esp through arduino ?

That is not a library for the Arduino. That is a core for programming the ESP8266 directly as if it were an Arduino itself.

Hm that makes me dizzy a bit. So I put that WiFi Shield on my Arduino - how can I use this now? Should I use this makefile: https://github.com/plerup/makeEspArduino - from now on to programm my Arduino because it won't work with my plain Arduino Makefile?

No. You need to find the right library to match the firmware that is on the ESP. If that is the normal aithinker AT firmware then you can just treat it like a normal ESP module. If not then you are on your own. You may be able to flash it with the AT firmware.


text:
Bit Number to Byte Value conversion (AVR Docs)
I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_use_bv.html
I has a macro called _BV that

convert a bit number (usually within a byte register) into a byte value

And the example tells this

_BV(3) => 1 << 3 => 0x08

I am kinda used to bits and bytes etc. But I don't understand what the 3 in this example is? It says it converts a bit number but 3 is not binary it is an integer. And the macro resolves it to 0x08 which is the value of 8 in decimal.
I am very confused. I hope someone can explain to me what is happening here!

when you see 0x08, do not think "decimal" ... think "hexadecimal" ..... hexadecimal numbers convert to binary easily ..... for example, 0x98 is same as 0b10011000

The bits within a byte are numbered 0 through 7 from right to left. The
rightmost (least significant) is bit 0, next is bit 1... and the
leftmost (most significant) is bit 7.
The expression _BV(3) builds a byte where bit 3 is set (is 1) and all
other bits are clear (are 0). In binary it looks like this:
position:   7  6  5  4  3  2  1  0
bit value:  0  0  0  0  1  0  0  0

The macro expands to 1<<3, which takes the integer 1 (0b00000001 in
binary) and shifts all its bits by three positions to the left. The
result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8
in decimal.

and bear in mind @xetra11 that it is only coincidence that in this case, the hexadecimal number and the decimal number are the same. Had bit 4 been set to 1 instead of bit 3, it would have been 0x10 in hexadecimal, and 16 in decimal! It may be useful to consider that decimal numbers are all "base 10" (hence the word DEC-imal). But binary numbers are base '2', and hexadecimal numbers are base 16. The base - 1` is the highest number that can be in a 'digit' before a carry must happen to represent the number. For hexidecimal, in order to have 16 digits, it goes from 0-9 followed by A-F.


text:
Communicate with ESP8266 RX/TX
I just managed to get a unofficial Arduino WiFi shield to work. But the ESP is flashed on its own now - providing only information to the USB->TTL converter and therefore the output goes straight to the Serial Monitor of the Arduino IDE.
Since the ESP is flashed and should be running now - I should be able to disconnected the USB->TTL converter and attach the Arduino RX/TX to the ESP TX/RX right?
Then I should receive Serial Data and should be able to process these in my Arduino Sketch right?
So what do I need to do now? Should I start trying a Serial read from the arduino with the baud rate specified by the ESP Flash (11520)? Or do I have to consider something else as well?

Your analysis is indeed correct, you can communicate between Arduino and ESP using the serial protocol.
Electrically speaking you must ensure the RX and TX pins are crossed:
Arduino RX goes into ESP TX
Arduino TX goes into ESP RX
Also, the two devices MUST have a common ground, the GND pins of the Arduino and the ESP8266 must be tied together.
You don't need level shifters because, even if the ESP8266 runs at 3.3V, its IO ports are 5V tolerant.
Also, as you already pointed out, the two devices must set the same speed (aka BAUD rate) in order to comprehend each other.
In case you decide to transmit binary data please also consider the two devices use a different architecture: Arduino is 8bit, ESP8266 is 32bit, meaning they have different word size (the minimum allocation unit size).
I had to face the word size issue when I first tried to exchange a struct between an Arduino and a RaspberryPI (also 32bit)...

Are you sure the input pins are 5V tolerant? They seemed to be but it was yet confirmed by Espressive.

If you aren't using level shifters will the Arduino be able to read the 3.3v signals transmitted by the ESP8266?

The GPIO pins are all 5V tolerant as stated from multiple sources, even if the Expressf datasheet doesn't state it in a clear way and actually provides contraddictory information.
This DOES NOT MEAN you can power an ESP8266 with 5V and ALSO DOES NOT MEAN you can source or sink any significat current at 5V, but you CAN exchange signals at 5V, provided the 5V side is capable to detect a 3.3V HIGH signal, as the Arduino does.

@Matt yes, Arduino operating at 5V is capable to detect a 3.3V HIGH, the threshold voltages are 3V on the high side and 1.5V on the low side.


text:
message received from GSM contains parenthesis instead of curly braces
the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.

One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.