text:
EEPROM endurance and page size
I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.
The datasheet of the ATmega used on many Arduino boards says (page 20):

The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).
But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?

That story goes around, but it appears not to be true.

I'm doing my own test on this right now. So far I am up to a million writes on a single byte, with it reading back correctly. Once I get it to fail (which might be in 7 hours judging by the AVR Freaks posting, I'll see if an adjacent byte fails, or not. Both my own test, and the AVR Freaks one, seem to confirm that you can probably get somewhat more than 100,000 writes from a single address.

Testing a single byte write
I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:
Current count = 11514199
Writes per minute: 17550
....................
Current count = 11538199
Writes per minute: 17550
....................
Current count = 11562199
Writes per minute: 17549
...................
Failed readback!
Expected: FF
Got: 7F
Current count = 11585314
Halted.

So, 11.5 M writes. Still, as pointed out on the AVR Freaks thread, the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)
Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may sometimes get a bad read-back.
On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!
Current count = 14033314
Writes per minute: 17549
....................
Current count = 14057314
Writes per minute: 17549
....................
Current count = 14081314
Writes per minute: 17549
....................
Current count = 14105314
Writes per minute: 17549
....................
Current count = 14129314
Writes per minute: 17549
............
Failed readback!
Expected: FF
Got: 7F
Current count = 14144533
Halted.

Somewhat more quickly the third failure after a further 149,703 writes:
Current count = 14312533
Writes per minute: 17550
....
Failed readback!
Expected: FF
Got: 7F
Current count = 14318236
Halted.

And another failure (in 2.3 minutes) after a further 41757 writes:
Starting.
Current count = 14318236
Waiting for pin 2 to go LOW.
Started.
....................
Current count = 14342236
Writes per minute: 17551
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 14359993
Halted.

Testing the adjacent byte
Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".
Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.
Next morning
The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.
Current count = 12120000
Writes per minute: 17562
....................
Current count = 12144000
Writes per minute: 17562
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 12161565
Halted.

Code
Main sketch
// EEPROM tester

// Author: Nick Gammon
// Date: 22 August 2015

// Connect a jumper from GND to pin D2 when ready to run.
// Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

// Single flash, repeated every half second: ready to go
// Two flashes, stopped on request
// Three flashes, error
// Occasional flash: working

#include <EEPROMAnything.h>
#include <EEPROM.h>

const unsigned int WRITE_COUNT_ADDRESS = 1010;
const unsigned int TEST_ADDRESS = 1020;
const unsigned int ITERATIONS = 200;
const unsigned long MAX_DOTS = 20;
const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
const byte ACTIVATE_PIN = 2;
const byte LED = 13;

unsigned long dots = 0;
unsigned long writeCount;
unsigned long startTime;
unsigned long initialCount;

void showCount ()
  {
  Serial.print ("Current count = ");
  Serial.println (writeCount);
  } // end of showCount

// flash the LED the required number of times
void flashLED (const int times,
               const unsigned long interval = 100,
               const unsigned long delayTime = 500)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (LED, HIGH);
    delay (interval);
    digitalWrite (LED, LOW);
    delay (interval);
    }  // end of for each iteration
  delay (delayTime);  // delay between iterations
  }  // end of flashLED

// check our memory agrees with what we expect
void checkMemory (const byte target)
  {
  byte found = EEPROM.read (TEST_ADDRESS);
  if (found != target)
    {
    Serial.println ();
    Serial.println ("Failed readback!");
    Serial.print ("Expected: ");
    Serial.println ((int) target, HEX);
    Serial.print ("Got: ");
    Serial.println ((int) found, HEX);
    showCount ();
    EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (3);  // three flashes
    }
  }   // end of checkMemory

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

  // get write count from previous run
  EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
  initialCount = writeCount;

  // if all 1 bits, variable was never initialized
  if (writeCount == 0xFFFFFFFF)
    writeCount = 0;

  // tell them we are starting
  Serial.println ("Starting.");
  pinMode (2, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  showCount ();

  // wait for them to unplug pin 2
  Serial.println ("Waiting for pin 2 to go LOW.");
  while (digitalRead (ACTIVATE_PIN) == HIGH)
    flashLED (1);  // one flash

  Serial.println ("Started.");
  startTime = millis ();
  }  // end of setup

void loop ()
  {

  // write to EEPROM, checking each write
  for (unsigned int i = 0; i < ITERATIONS; i++)
    {
    for (unsigned int j = 0; j < sizeof (TESTS); j++)
      {
      EEPROM.write (TEST_ADDRESS, TESTS [j]);
      writeCount++;
      checkMemory (TESTS [j]);
      }  // end of doing each test pattern
    }  // end of loop of x ITERATIONS

  // save the current write count so we can pick up the count next time
  EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
  Serial.print (".");
  dots++;

  // confirming we are working
  flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

  // newline, show counter
  if (dots >= MAX_DOTS)
    {
    Serial.println ();
    dots = 0;
    showCount ();
    unsigned long writes = writeCount - initialCount;
    unsigned long timeTaken = millis () - startTime;
    float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
    Serial.print ("Writes per minute: ");
    Serial.println ((int) writesPerMinute);
    }  // end of needing a newline and counter output

  // check if user wants us to stop by disconnecting the jumper from Gnd to D2
  if (digitalRead (ACTIVATE_PIN) == HIGH)
    {
    Serial.println ();
    Serial.println ("Stop request detected.");
    showCount ();
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (2);  // two flashes
    }
  }  // end of loop

EEPROMAnything.h
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

Error correction
If the concern is that the EEPROM reads may deteriorate, once could use Reed Solomon error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).
My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.
Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.

See edited reply. The second byte failed after 12.16 million writes, so it appears that even bytes in the same 4-byte page have individual lifetimes.

In the arduino forum
http://forum.arduino.cc/index.php?topic=293472.0
someone states that is 1 byte size (each "page") - each write writes and spends a cycle for a single byte.
There it also says that SPI access to eeprom uses a 4 bytes page size.
I did not went further reading since my doubt was same as here, writing a byte to arduino eeprom.


text:
"write" function in sd card is not working
I have recently started working with arduino UNO and the "write" function in sd Card library is not working. Below is my code. I have tried with "println" which is working fine. Any help regarding this is welcome.
void loop()
{
     byte b=10;
     File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.write(b);
     }
}

How is the SD card reader connected? Is it part of a shield? It might also be helpful if you show us the complete program. Are you calling SD.begin() anywhere?

@peter Hi,I have called the SD.begin() in setup(). The issue is "write" function is not working. When I am using "print", I am able to write to the file. Thanks!

How do you know it's not working? What's actually happening?

I am writing the byte b to the text file. When I am reading the SD card, I can't see the byte in it which I am able to see when I use "print" function instead of "write". I desperately want "write" function to operate so that I can directly write arrays without any "for loops", which I will not be able to achieve if I use "print" function. Thanks!

The problem is that print() and write() behave differently when you give them numerical data, such as a byte.
When you pass your byte to print(), it converts it to text which is convenient for humans to read. For example:
byte b = 10;
dataFile.print(b);

This will result in the following ASCII characters being written to the file:
10

That's actually two bytes: one byte with the value 49, which represents ASCII character 1, followed by a byte with the value 48 representing character 0.
However, write() does not convert numbers into text. It writes them in their raw binary form. For example:
byte b = 10;
dataFile.write(b);

When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.
For comparison, try this instead:
byte b = 65;
dataFile.write(b);

ASCII value 65 corresponds to the letter A (uppercase), so that's what you should see in the file.
The write() functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.
In your case, print() is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the print() functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.

Thanks Peter, but I want to store large chunks of data as fast as possible so that I can sample incoming data at high rates and using of loops slows the speed. Is there a way to achieve this?

@Naresh If speed is critical then it's preferable to use write() to output binary. However, you can't read raw binary files using a text editor. You would need some other program on your computer to load it or convert it into a useful format. I don't know of a general purpose program which would do that for you automatically. You'd probably have to write something yourself.

It is typical of file devices that an output file must be closed when the application is through writing to it - datafile.close(), using your variable names. Their drivers or libraries typically buffer output data in memory and may not write it to the device until the buffer fills or the application flushes the buffers or closes the file.
See the read/write SD card example at the Arduino site. Especially note the uses of the calls to:
begin
open
print or write, ...
close

Failing to close an output fail might leave unwritten data in memory buffers rather than flushing the last few bytes (all of the data, in the case of your one-byte-write example).
It is also possible that there is another fault - incorrect mapping of I/O pins to the card reader/writer, incorrect wiring, faulty device or card, but I think the programming sequence is the most likely culprit.

Hi, the issue is "write" function is not working. When I am using "print", I am able to write to the file. Thanks!

I would still make sure I used the whole {begin; open; write; close;} sequence, then examine the resulting output file with a hex-editor on your computer to confirm that does or does not contain what you expect it to.

source: Stack Exchange

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

sort: votes


text:
16Hertz Uno R3 Board vs Arduino Uno R3 Board
I bought a 16Hertz Uno R3 Board. When I installed the driver and the Arduino IDE,  in the IDE`s menu I saw:

Tools -> Board -> Arduino Uno

was selected by default which is great, but...

Tools -> Port -> COM3(Arduino Mega or Mega 2560)

was selected by default which I think might be some kind of misunderstanding...
When I chose:

Tools -> Board -> Arduino Mega or Mega 2560

On that tools menu appeared new menu "Processor" with two options:

Tools -> Processor -> ATmega2560 (Mega 2560)

which was selected by default and there was another option

Tools -> Processor -> ATmega1280

When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!
If you take my board and look at the Microcontroller there is written:

ATMEGA328P-PU

Also on that board is written:

16HzUNO

I need to know:

What does 16Hz mean? Does it mean the clock or frequency of this
Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the rs-online site, there is written:

ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
  kB RAM, I2C 28-Pin PDIP

Why was there "COM3(Arduino Mega or Mega 2560)" written on the
Port's menu?
Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
is better? When one of those is better?
Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
Microcontroller?

You need to have a look at the Arduino comparison table. This shows that all Arduino Uno boards run at 16 MHz. It seems that you have fallen for the marketing on the page for the Uno kit that you provided.
Also, which version of the IDE are you running? You should upgrade to the latest version, which is currently, at the time of writing, version 1.6.1.
To answer your questions in turn:

"16Hz" is the brand name and has nothing whatsoever to do
with the speed, which is actually 16 Mega Hertz. "Clock" and
"Frequency" refer to the same thing. 16 MHz is the clock frequency
of the board, and is the speed at which the ATmega328 runs at.
The RS Online link does indeed state 20 MHz, but that is merely the
maximum speed at which the ATmega328 can run at. The Uno under clocks it at 16 MHz.
The Ports menu will show you a number of possible devices, Arduino Uno should be one of them (which is the one you should select) and three items below that will be Arduino Mega or Mega 2560 (which you should ignore, you do not have a Mega board1). Unfortunately the Arduino site only shows the Mac menu, even on the Windows guide

which is no help to you, assuming that you are running the Arduino IDE on Windows. You should actually see this in the Board menu:

and this in the Port menu:

As you can see, there should be no mention of the microcontroller in the Port menu.
The 16Hz branded Uno and the Arduino Uno are to all intents and purposes the same and as I state in the first line, the 16 MHz Uno is exactly the same as a regular Uno, it is just marketing.
Both the 16Hz and the Arduino Uno have a ATmega328 and the Mega board has a ATmega2560. Again, check the Arduino comparison table to see the variety of the boards and their respective microcontrollers.

I hope that answers your questions.

1 If you do chose the Arduino Mega or Mega 2560 option, in the Board menu, then indeed there will be an additional Processor menu. However, this is irrelevant in your case, as you do not have a Mega board, and so you need to chose the Uno in the Board menu. If you do so, then the Processor menu will disappear, as it is not needed for the Uno.

Every Arduino is using a quartz crystal in order to get the frequency needed. ATmega328 can handle up to 20 MHz
??
Yes. You can't run the microcontroller by itself. It has an internal oscillator but none is using it. So basically you will have a 16 MHz crystal.
Pretty much the Arduino Uno, Nano, Mini and few others have the ATmega328P.
Note that the -PU -AU at the end defines the package. So they're the same.

Arduino Mega, Leonardo, Micro, Due use other chips.

Just a theory for 2:
The text that shows up in the Tools > Port list after the COMx
eg Tools -> Port -> COM3(Arduino Mega or Mega 2560)
is simply what the IDE thinks the board is based on the USB ID (VID/PID) of the board's USB interface chip. For some clones, this is blank because they don't even use the same chip as an authentic Uno. In your case, I would suspect that they have used the USB chip from a Mega board on your Uno board.
So the IDE thinks a Mega is attached because it is seeing a USB chip from a Mega, even though it is an Uno (clone).

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

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


text:
Arduino unstable analog reading when using power supply
As soon as I unplug my Arduino from USB and only use the VIN pin with my 9 V power supply, the analog readings from my Arduino start to get unstable, which means the value fluctuates much more than with USB connected. When I reconnect USB again, the readings are stable again.
I'm trying to build a load scale using a load cell, an INA125P and the Arduino, using this setup here: Instrument Amplifier Calibration.
Therefore I need stable readings. For example, I wrote some code to convert the analogRead() value to grams. While USB and VIN (9 V) connected, I get a stable reading of about 8.3 to 8.7 grams when I put a weight of 8.5 grams on the scale. As soon as I unplug USB, the LCD shows values from 7.8 grams up to 9 grams.
Unfortunately, I don't have any other power supply which I could use to test. I've already tried to use a 9 V battery with the same results. Do I maybe need some additional de-coupling capacitors?

Hard to say without checking ripple with an oscilloscope. It definitely sounds like some sort of a reference issue. The AVR controllers use an analog reference pin that is used to compare against the ADC input lines. That said, it sound either like a reference ripple or insufficient capacitive bypassing at the AREF pin. If you have access to an oscilloscope I would first check the supply and then the voltage present at AREF, which I think is pin 8 on the UNO. There is already a 100nF bypass present, so it's likely the supply.

It's more likely that you need a beefier regulator. The on-board regulator on an Arduino can only supply a tiny amount of current (a few tens of mA) at 5V to external circuitry (beyond what the Arduino itself needs). When the USB cable is plugged in, the USB host can supply at least 500 mA (probably more) at 5V without any problem.

First of all what is your board? 'cause different boards have different regulators. And then... If you need precise values, avoid using the supply voltage as reference: it is really noisy and unprecise. Use the internal analog reference if it suits your needs, or otherwise use an external voltage reference. Use the power supply reference only when you don't need precision or you have a ratiometric sensor (e.g. a potentiometer)

I got the same issue where too much ripple from power supply, I saw this article bit late where I used an digital sensor to get away with analog read.

I solved a similar issue by adding a pin from supply to AREF and it's now stable. This fixed a frustrating pH meter issue on my Mega that every time I plugged USB in it would be right, but as soon as I dropped the USB cable it changed the readings.

This answer was reported as "not an answer", I find that false. He just provided an example before his solution (rearranged that now). If his answer is not useful, please use the This answer is not useful button instead of the Flag button.

OK @Avamander. Understood.

Does your arduino have a switch-mode regulator when converting 9V to 5V? If that's the case, then you must have some voltage ripple on your 5V power line. I'm guessing you are probably using analogRead which uses that 5V reference. If there is a ripple in your reference voltage, you will get a ripple in your readings.
Can you use the internal 1.1V reference of Atmega328p chip? That reference voltage is (as far as I know) the most stable you can provide for ADC.
If that doesn't work, then you need to find a very stable 5V adapter for your 9V sources.

Load cell signals are very small and without proper shielding are be susceptible to noise. The USB power connector is likely earth grounded (the clue was battery operation is noisy, exact opposite of expectations!) I suggest testing this hypothesis:

Check with ohm meter if exposed metal on USB connector is connected to earth (chassis on your PC is usually earth connected).
Touch an earth grounded conductor to the signal ground of the load cell amplifier and see of the readings become more accurate.

The final solution is to use properly shielded signal wires between the load cell and the amplifier. Also the signal wires between load cell and amplifier should be a 'twisted pair' to further reduce noise.

I would say that this may be related to the analog reference. Try AnalogReference and see if it helps.

Without much information (software, schematic, hardware, measurements ...) It is hard to tell.
My guess would be that you used vcc as a dc reference and the circuit draws too much current from the battery than it can deliver so bcc dips, leading to a rise and instability in the reading.
Good luck debugging it.


text:
Ethernet shield not getting IP
I am just running the below DHCPAddressPrinter sketch in Arduino example to setup EthernetShield with MAC and IP
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}

void loop() {

 }

After uploading the sketch to arduino,below is the output shown in console
Sketch uses 13,614 bytes (42%) of program storage space. Maximum is 32,256 bytes.
Global variables use 539 bytes (26%) of dynamic memory, leaving 1,509 bytes for local variables. Maximum is 2,048 bytes.

And there is nothing shown in Serial monitor
This is the image of Ethernetshield's some leds glowing after connecting to Router.
My router is Binatone Wireless ADSL2+ Router.

I checked arp -a,
C:\Users\Radhamani>arp -a

Interface: 192.168.1.6 --- 0x3
  Internet Address      Physical Address      Type
  192.168.1.1           6c-fd-b9-24-c6-fe     dynamic
  192.168.1.255         ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static
  255.255.255.255       ff-ff-ff-ff-ff-ff     static

Interface: 192.168.198.1 --- 0xe
  Internet Address      Physical Address      Type
  192.168.198.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Interface: 192.168.234.1 --- 0xf
  Internet Address      Physical Address      Type
  192.168.234.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Complete result of ipconfig:
Wireless LAN adapter Wi-Fi:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::901:3297:48ad:9e7d%3
   IPv4 Address. . . . . . . . . . . : 192.168.1.6
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
Ethernet adapter VMware Network Adapter VMnet1:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::c954:40b2:c8c1:de0%14
   IPv4 Address. . . . . . . . . . . : 192.168.198.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
Ethernet adapter VMware Network Adapter VMnet8:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::2837:7e01:c799:d627%15
   IPv4 Address. . . . . . . . . . . : 192.168.234.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Serial.println in the program is not printing anything.Looks like Ethernet shield is not getting IP.I am not sure where I am wrong.Please help me to fix this issue

Based on the image .. i see that the programmer pins at the back of the shield and the arduino aren't connected properly.. That might be the error or at least happened with me.
Apart from that, certain network need to identify the mac address from a look up table and if the shield mac address matches, then only network transactions are allowed.
Also i suggest you to drop the virtual machine mac address and networking protocols and try upon the base OS which you have on your computer.

The SD might need disconnecting. Add below to setup().
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);

Also check the pin assignment for the W5100 (in the Ethernet library).
Cheers!

check the DHCP service of your router is active or not :)

I had the same problem with my project in which I was using Arduino Ethernet schield 2. I suppose to get the IP address in serial moniter using simple sample program but later I found that when we use Arduino Ethernet schield 2 we need to use the library "<Ethernet2.h" instaed of Ethernet.h

I had the same problem and it had two causes:
1) I couldn't fully insert pins of my shield into the board (ArduinoMega), because if its USB connector. So I connected them with cables. To check for this error, use this code to initialize your Ethernet shield:
   Ethernet.begin(mac, ip);
   if (Ethernet.begin(mac) == 0) {
     Serial.println("Failed to configure Ethernet using DHCP");
     Ethernet.begin(mac, ip);

     if (Ethernet.hardwareStatus() == EthernetNoHardware) {
       Serial.println("Ethernet shield was not found.");
     } else if (Ethernet.linkStatus() == LinkOFF) {
       Serial.println("Ethernet cable is not connected.");
     }
   }

If this is the case, it will print "Ethernet shield was not found."
2) I'm using this Chinese W510 shield too (the same as on the photo above). Apparently, there's a known bug. Here is the solution: https://forum.arduino.cc/index.php?topic=351477.45
In short: You have to solder 2 resistors between pins 1-2 and 3-6 of the shield's Ethernet connector. No need to unsolder anything.
Works great!


text:
Receive multiple data from arduino using String builder
I am working on a small project where I have to read data from different hardware and display it on android app. I am using arduino Uno to get the values from a sensor and a motor and I use a bluetooth module to send the data to the android device. I know how to read data from motor only but not from motor AND sensor. The data displayed on the arduino can be assumed as follows:
Motor: 132
Sensor: 258
Motor: 259
Sensor: 992
So first, we will read the value of the motor then the sensor then the motor and so on. Here is part of the code where I used handler and string builder to read data from the motor. How to modify the code in order to read from BOTH the motor and sensor and keep the updating the values?
Code:
Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        motor.setText(sbprint);             // update TextView
                    }

                    break;
            }
        };
    };

You can convert each value to string before sending to bluetooth using string.contain("string"), like this:
if (sbprint.contains("C"){
    temptv.setText(sbprint);}
if (sbprint.contains("H")){
    humidtytv.setText(sbprint);}


text:
Analog Input not going to Zero
Arduino Uno user here
I am building a project with 4 analog inputs A0 dose not work. A1 A2 and A3 work perfectly fine! But for last input when I connect to A4 or A5, then they do not go to zero. They are stuck between 400 to 900. Even when connected to arduino ground it gives 400 instead of 0.
Am I missing something here cause the circuit for A4 connected to A3 gives perfect input value. They both work fine as output. Same situation with A5.
Is there another way to get one more Analog Input without multiplex?
Thank you!

Circuit is simple... Just 4 potentiometer and 4 pwn leds.

I mean the circuit on the Arduino board.

A 0 is a normal pin. A 4 & 5 are also the i2c data and clock, but that only depends on if a shield is connected

What do A4 and A5 report when you connect it directly to GND? What sensors are you using?

A1 to 3 gives zero... A4 and A5 give 440 approx... All input connect to diff RC pass filters..

there is no shield connected to Uno.

You haven't set the pins to "Input Pullup" by any chance? And you haven't done a "digitalWrite(pin, HIGH);" ?

I did not... I used digitalWrite(pin, LOW) though.

Connect A3 and A4 together, then put a 1 kΩ resistor between A3 and GND, then analogRead() both A3 and A4. If they both give high values, this means A4 is trying to output something, maybe through its I²C interface, or maybe it has its internal pullup enabled. If only A4 reads high, then you have a really weird problem. You may have fried a portion of the input mux of the ADC.

Please edit your question and post your code.


text:
Arduino on attiny85 driving 4-digit 7-segment using two 74HC595N shift register not alternating fast enough
I am using a port of the Arduino libraries on an AtTiny85 (1MHz) to drive a 4-digit 7-segment LED (common cathode, 12-pin). I'm just counting from 0 to 9 and alternating between the first two digits (pin 12 and 9) as a test. I am driving from two 74HC595N shift registers in series, the first of which will trigger S9018 NPN BJT transistors to turn on/off the digit I want and the other to light the segments.
The code seems to work fine, functionally, to alternate the two digits, but they don't alternate fast enough to make the LED show two solid digits, instead you can clearly see them flashing/alternating. Not sure what the bottleneck is but here's the code (please ignore my wiring for the 7 segments)
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const long output_interval = 10000; // Time to change each output
const int T_digit = 2; //period on one digit (4 digit 7-segment only)
const int duty_digit = 1; // duty cyle of a digit shown

// States
unsigned long outputT_last = 0; // Holds the last time output change was checked
unsigned long outputT_now = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  checkOutput();
}

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = (int)(outputT_now - outputT_last);
    digits = 0;
    if(digitON%T_digit < duty_digit){
      //bitwrite led 0
      bitWrite(digits, 0, 1);
    }
    else{
      //bitwrite led 1
      bitWrite(digits, 1, 1);
    }
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

void clearMemory(){
  leds = 0;
  updateShiftRegister();
}

void checkOutput(){
  outputT_now = millis();
  float timeleft = (int)((outputT_now - outputT_last)/1000);
  if (outputT_now - outputT_last >= output_interval){
    outputT_last = outputT_now; // output_interval set to 10000, because LED counts 0 to 9, and then needs to reset
  }
    // clearMemory(); // Uncomment this if you want 1 LED lit at time, all others turned off
    leds = sevenSegment1D(timeleft);
    updateShiftRegister();
    // output_count++;
  // }
  // Check if we reach the end, then do 1 more iteration for 0x0 (all turned off)
  // if(output_count > 8){
    // output_count=0;
    // clearMemory();
  // }
}

byte sevenSegment1D(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}

I tried to mod a float but it seems to require an int, so that's why I stopped at 2%1. I also converted the code from a single-digit 7-segment LED so please ignore anything that doesn't make sense in lighting up the segments.
I am not sure if the bottleneck is my code, the 1MHz AtTiny85, or the shift register.
EDIT: switched over to micros() instead of using millis() for more resolution. Still not solid.

Did you pick a board entry that specifies 1MHz?

I am unsure how to check this.

Did you try looking at the board entry?

Can't you just lower T_digit? Better would be to use a timer to update the digits every X ms. That way the main loop doesn't interfere with the display update. 1mHz should be fast enough to get at least 60hz update speed.

Turns out there is something wrong with my mod calculation. I did a test with to shift out the first digit, reset, then shift out another with delay(2) and it's solid.

Unless you really, really need something unique about the '85, such as the pll, this design just does not make sense.  Don't use an '85 with an external shift register, rather use a micro with a decent number of pins like an ATmega.  There's also little reason to run your clock so slowly - in theory doing so could save power, but if you have a 7-segment display your need a decent power source anyway.

The original idea was to divide up a specific period into segments where each digit on the 4-digit 7-segment would light up. I would use a mod(%) and divide it up to make the function call more generic for future extensibility (and also make it more asynchronous). What I learned is that it would probably take more work doing the calculations then just calling a function to reset and light up the next digit one after another. Here's the updated code:
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const int countdown = 60; // amount of time to countdown from in seconds
const long reset_interval = countdown*1000000; // interval before reset in microseconds, i.e. if countdown is set to 60s, every 60 seconds will reset display to countdown start

// States
unsigned long last_display_update_time = 0; // Holds the last time output change was checked
unsigned long curr_time = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  updateResetTimer(); // checks what the countdown is at
  int timeleft = countdown - (curr_time - last_display_update_time)/1000000;
  leds = getSevenSegmentFormation(timeleft/10);
  updateShiftRegister(0);
  leds = getSevenSegmentFormation(timeleft%10);
  updateShiftRegister(1);
}

void updateShiftRegister(int digit)
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = micros();
    digits = 0;
    bitWrite(digits, digit, 1);
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

//Turns off all 7 segments of a digit, will need to specify digits 0 to n
void clearMemory(int i){
  leds = 0;
  updateShiftRegister(i);
}

//Updating timer for resetting countdown
//Will take absolute current time and compare it to the last time checked, if it is greater than countdown value, we reset
void updateResetTimer(){
  curr_time = micros();
  if (curr_time - last_display_update_time >= reset_interval){
    last_display_update_time = curr_time; // reset_interval set to 10000000, because LED counts 0 to 9, and then needs to reset // actually set to 60*1000000 to countdown 1 minute
  }
}

byte getSevenSegmentFormation(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}


text:
Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line?
I have a SwitchDoc Labs DS3231 Real Time Clock Module that I am using with an Arduino Mega.  It's connected to 3.3V and the SDA(20)/SDL(21) pins.  I'm also using SwitchDoc's RTC_SDL_DS3231_ARDUINO library (see link to the example sketch below).
I can compile and run the example provided with the library just fine.  However, I'm running into a very bizarre compilation problem when I remove the Clock set function calls in the setup.
Rather than take up the space and copy the code that works I'll just link to it on github: 100% working for me example.
The problem I am running into happens when I remove (or comment out) the section in the setup function that sets the time:
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Removed code
  // Start the serial interface
  Serial.begin(9600);
}

Then I get the following error when I try to compile/verify the sketch:
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/../
lib/gcc/avr/4.3.2/../../../../avr/lib/avr6/crtm2560.o: In function `__vector_default':
(.vectors+0x90): relocation truncated to fit: R_AVR_13_PCREL against symbol `__vector_36'
defined in .text.__vector_36 section in core.a(HardwareSerial.cpp.o)

If I add back just one single clock set call it will compile:
void setup() {
  // Start the I2C interface
  Wire.begin();
  Clock.setYear(15);  //Set the year (Last two digits of the year)
  // Start the serial interface
  Serial.begin(9600);
}

However, the truly strange thing is that if I simply add a Serial.println() line to the setup function, the sketch compiles too!
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  // Adding the following line allows the sketch to compile
  Serial.println("Why does this work now???");
}

Thanks for any help.

Ponderings: (1) Initialising or altering / clearing/setting a variable that is common to all routines?  (2) This sounds nasty and worth knowing more about -> "relocation truncated to fit"

Update: This seems to be a linker bug. Quick fix: upgrade your
Arduino installation. See the end of this answer for details. What
follows is the first version of this answer, with a detailed explanation
of the error message.

You have a problem linking the interrupt vector table with your program.
I quite understand what the error message means, but I do not understand
how in the world you can possibly have this error. This should not
happen. I will try to explain the error anyway.
The Arduino Mega is based on an AVR chip. The AVR instruction set has
“jump” and “call” instruction that come in two flavors:

“absolute” jumps and calls (opcodes: jmp and call) can address the
whole flash memory, which means you can branch from any part of the
program to any other part, without restrictions.
“relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: rjmp and
rcall) have limited range: they can only bring you to nearby places,
no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus
better if the destination is close enough. On the smaller AVR chips
(up to 8 K of flash), they can access the whole flash, then these
chips lack the absolute flavors.
How the vector table is normally linked
Every program you build for an AVR starts with an “interrupt vector
table”. This is a series of jump instructions that are automatically
executed whenever an interrupt triggers: if the n-th supported
interrupt triggers, then the hardware automatically loads and executes
the n-th jump instruction, which will jump the execution of the
program to the corresponding ISR (interrupt service routine). The
table is chip-specific: on the smaller AVRs (up to 8 K), it's a
table of rjmp, whereas on the bigger ones it's a table of jmp. This
table is part of the CRT (C run time) provided by the avr-libc library
in a file named crtXXX.o, where XXX is a code identifying the chip. The
Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.
I disassembled my own copy of crtm2560.o and found this vector table:
00000000 <__vectors>:
   0:   0c 94 00 00     jmp 0
   4:   0c 94 00 00     jmp 0
   8:   0c 94 00 00     jmp 0
   ...
  e0:   0c 94 00 00     jmp 0

You can see these are all jmp instructions (absolute flavor), as
expected for any AVR with more than 8 K of flash. The address of
the jump, however, is always 0, which is obviously wrong. This is
because the proper addresses cannot be known until the program is fully
built. When you build your program, the linker will put all the pieces
together. It will then know where the ISRs are, and it will patch the
vector table to make it correct. This kind of patching is known as
“relocation”, and the linker performs this based on some “relocation
records” included in the CRT. Here are the relevant records from my copy
of crtm2560.o:
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_CALL        __init
00000004 R_AVR_CALL        __vector_1
00000008 R_AVR_CALL        __vector_2
...
00000090 R_AVR_CALL        __vector_36  [*]
...
000000e0 R_AVR_CALL        __vector_56

The record I marked with [*] means: “at offset 0x90 into the vector
table there is an absolute jump or call instruction, and the instruction
should be modified to point to __vector_36”. This tells the linker
how to fix the table when building the program.
If I instead disassemble a CRT for a smaller chip, I get a smaller table
made of rjmp (instead of jmp) instructions, and the relocation
records look like this:
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_13_PCREL    __init
00000002 R_AVR_13_PCREL    __vector_1
00000004 R_AVR_13_PCREL    __vector_2
...
00000032 R_AVR_13_PCREL    __vector_25

These records mean “at offset XXX into the vector table there is a
PC-relative jump or call instruction, and the instruction should be
modified to point to __vector_XXX”.
Your error message
Your error message provides the following information:

“crtm2560.o”: this is your CRT, where the vector table and the
relocation records live.
“.vectors+0x90”: this means the problem is at offset 0x90 into the
vector table.
“R_AVR_13_PCREL against symbol `__vector_36'”: this means there
is a relocation record of type R_AVR_13_PCREL (PC-relative jump or
call) referencing __vector_36. Here seems to be the problem.
“defined in [...] core.a(HardwareSerial.cpp.o)”: this __vector_36
is part of the serial port code from the Arduino core library.
“relocation truncated to fit”: __vector_36 is too far to be reached
by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type
R_AVR_13_PCREL, which is what you expect on smaller chips but not on
your ATmega2560. You normally expect R_AVR_CALL.
Now, about the strange behavior: the exact point where the ISR lands
when the program is built is difficult to predict. Add or remove a few
lines in your code and the linker may bring the pieces together in a
different order. Then, the infamous __vector_36 may end up being in
range or out of range of a relative jump. Given the nature of the error,
the behavior you find “strange” is actually quite normal.
Further debugging
The root of the problem seems to be an incorrect relocation record in
your CRT. You can try to disassemble the CRT to see what is wrong:
search your computer for a file named crtm2560.o, probably in
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6
or a similar place. The tool needed for disassembling is called
“avr-objdump” and should be hidden somewhere in your Arduino
installation folder. Once you find the files, start a terminal and type
/path/to/avr-objdump -d /path/to/crtm2560.o

with “/path/to” replaced by the actual paths. You should see something
very much like the first listing of my answer, with lots of jmp
instructions. If you have rjmp instructions instead, then something is
already wrong at this level.
To see the relocation records, type:
/path/to/avr-objdump -r /path/to/crtm2560.o

The output should look like my second listing, with lots of R_AVR_CALL
records. If you have R_AVR_13_PCREL instead, the records are wrong.
If this is the problem, then the obvious fix would be to replace the
broken CRT with a sane one. You may try to reinstall the whole Arduino
package. If you still have a corrupted CRT, you should report the error
to the Arduino folks. Then you may try to fetch a fresh copy of the
avr-libc and replace the relevant
parts of your Arduino installation. Replacing just the CRT may or may
not work: I don't know whether the last version of the CRT has
incompatibilities with older versions of the rest of the libc.
Update: this is a linker bug
I did some research, and I now believe you have hit a linker bug. There
is a gcc option called -mrelax that allows some link-time
optimizations. One if them is to have the linker replace some absolute
jumps and calls by the smaller and faster relative ones. Obviously, this
is only possible if the target address is within reach of the relative
jumps or calls. There was a bug in old versions of the GNU linker (up to
2.22) where, under some obscure circumstances, it would erroneously
believe the target was reachable, only to find out later that it was
not. This bug mainly affected the interrupt vector table, producing the
kind of error message you are seeing now.
Here is a partial timeline of this bug and its fix:

November 2011: this is filed as
bug 13410
on the bug tracker for the GNU binutils package.
January 2012: Vidya Praveen, from Atmel, publishes a fix.
February 2012: the fix is committed to the development version of
binutils.
October 2012: GNU binutils 2.23 is released, including the fix.
The same month, the bug is reported again as
issue 1071
on the Arduino issue tracker.
June 2013: Paul Stoffregen links this new issue to the old bug.
June 2014: Arduino gets an updated
toolchain
including binutils 2.23.2, which fixes the bug in the development
version of Arduino.
July 2014: Arduino 1.5.7 beta is
released including the
updated toolchain.
September 2014: Arduino 1.0.6 is released with the old toolchain.

A workaround for the bug has been
published by Mark Anderson on stackoverflow. The real fix, however,
would be to upgrade to the latest Arduino package (1.6.1 as of this
writing).


text:
Analog Input not going zero
Arduino Uno user here
I am building a project with 4 analog inputs A0 dose not work. A1 A2 and A3 work perfectly fine! But for last input when I connect to A4 or A5, then they do not go to zero. They are stuck between 400 to 900. Even when connected to arduino ground it gives 400 instead of 0.
Am I missing something here cause the circuit for A4 connected to A3 gives perfect input value. They both work fine as output.  Same situation with A5.
Is there another way to get one more Analog Input without multiplex?
Thank you!


text:
Can anyone suggest me a software timer library that does not use polling but timer ISR instead?
There are many software timer libraries available in Arduino.
A library called SimpleTimer http://playground.arduino.cc/Code/SimpleTimer is really good with many functions, but it uses polling.
If anyone is familiar with a really good library that uses Timer ISR of Atmega instead of polling, please suggest me as i am using ultrasonic sensors and i can't afford polling.

If it used the hardware timer then it wouldn't be a software timer library.

ultrasonic sensor is using the pulseIn() function. But i need software timer for another purpose.

Yeah, I have the same problem.
The only solution I found is to rewrite  a lot of the code. Still ongoing, though.
For you, Timer1 is probably the best candidate, unless you have already some use for it, like in my case.
A quick hack is to free Timer0: it is currently (ab)used by the wire library, which provides the typical arduino timing.
But you can remove/rename the file wiring.cpp to something that will not be identified as source (ex: wiring._cpp) and comment out the init() function call from the main() function in the main.c file.
Normal Arduino stile time functions will not work, of course.
Unfortunatelly Arduino SW really lacks the structured design that would allow it to be useful in more complex cases and most of the libraries make exclusive use of resources that could be shared, timer being the most prominent example.
Port ISRs is another.
Btw, if you happen to use a SW serial library, it's already game over, as it busy loops inbetween bits, in interrupt context (!), rather than using a timer.

Correct me if i am wrong: the first line of timer1 library page says : "This library is a collection of routines for configuring the 16 bit hardware timer called Timer1"  Can it be used to generate software interrupts?

I decided to ignore the library and write my own, as I didn't like the style used by the library.
Here's my (GPLv2) work:
https://github.com/igor-stoppa/pem
Check
https://github.com/igor-stoppa/pem/tree/master/src/pem_Arduino
you can look at hw-adaptation-uno.cpp for a very simple exampel of how to use the timer.

Thanks! I don't intent to use your entire work, but it will surely help me write my own code. thanks.

Yes, I wasn't proposing that :-)
But it shows in few lines how to use directly the timer interrupt. For more details, you can refer to the fine manual, but it shouldn't be necessary.
The slightly trickier part is to calculate the value to use.

What you do, is:
check your main clock (20/16/8MHz), choose a divider for the prescaler, then calculate the scaled clock (main/prescaler) and multiply it by the period you want to use. The result must be subtracted from the max value that the timer register can assume (256 for 8bit, 65536 for 16bit register).
This will cause the Overflow interrupt to trigger once  the max value is reached.
Then you can rearm or not, depending if it's periodic.
Remember to rearm as first thing, so that the period is stable, regardless of what else you do in the isr.

Can you help me with this? http://arduino.stackexchange.com/questions/6860/error-function-not-declared-in-the-scope

done, please remember to upvote my answers if they are useful ;-)


text:
Simulation of Arduino Mega 2560 with GSM Module using Proteus
I have really been suffering with my simulation! Tried connecting my arduino mega 2560 to COMPIM (used as GSM Module) in my circuit and also loaded sample code but damn! In vain! I wanted to view the data sent in virtual terminal but am getting nothing! and its also complaining of excessive CPU usage.
This is the circuit as seen below in Proteus.

And thereafter, the log messages are displayed as shown below.

Someone please help me out. Am I making a mistake oh? Infact the arduino code for displaying in the simulation is also giving me hard time. The one am using is as shown below.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    mySerial.println("Hello, world?");
  if (Serial.available())
    mySerial.println("Hello, world?");
}

Will b every grateful for any help offered.

Generally speaking, circuit-driven simulation should be used when you have circuit details to work out; connecting two pieces of software is better done on the hardware itself, or by porting at least one piece to run on your PC.

You should download this GSM Library for Proteus . You can use this library to simulate your GSM module in Proteus software. You should also check this example where they have discussed Hoe to Send SMS with GSM module in Proteus ISIS. I hope it will help you out.
Thanks.

Hello I had the same problem as you, but I managed to solve it.
Use the TinyGSM library. Open the library folder, locate the Tinygsmcommon file.
Open the file, line 75 changes the value from Baud 9600 to 2400. That is the minimum speed of my module.
In proteus work with the same speed 2400.
It worked here. Proteus can not handle so much speed.
And do not forget to also change the speed of GSM, place 2400.

I'm sorry to say that answers need to be in English (see Quality Standards and [answer]). Please edit your answer to be in English otherwise it will be deleted.

I have used Google translate. Please edit it if there are any errors in translation.


text:
Why does timer ISR not execute?
This is my code which I have written as a library
#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
     //TIFR1 |= _BV(OCF1A);

    TCCR1B = 0X00;
    //TIFR1 = 0X01;
    digitalWrite(13,!digitalRead(13));
    Serial.print("I printed");
    TCNT1 = 0X0000;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    //sei();
}

 void AllTimer::setTimer(void)
 {
    TCNT1 = 0x0000;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
 }

ISR (TIMER1_OVF_vect)
{
     AllTimer::dofun();
}

Code in Arduino IDE:
 #include <AllTimer.h>

 AllTimer mytimer;

 void setup()
 {
     pinMode(13,OUTPUT);
     Serial.begin(9600);
 }

 void loop()
 {
     mytimer.setTimer();
    //delay(200);
  }

But I am not getting anything on the serial monitor. What is the error I have made?

Using Serial.print inside an ISR is asking for problems. Does the led blink? Also, there is no need to write TCCR1B and TCNT1 inside doFun.

The Arduino main() calls loop() continuously, in a tight loop. Thus
your AllTimer::setTimer() is called continuously, and each time it
resets the counter (TCNT1 = 0x0000;). Thus the counter can never
overflow.

So put mytimer.setTimer(); inside setup instead of loop.

also, in TCCR1B |= (1<<CS12) && (1<<CS10); shouldn't it be | instead of the logic &&?

@SimSon: Indeed! I hadn't spotted that. Good catch.


text:
Can I use relays with 10A125V~ for my 220V~ applications, safely?
I am using the TinkerKit Relay Module and recently they changed the relay mounted on the board from a white one with 10A250V~ to a black one with 10A125V~.
In my country the voltage is 220V~. Can I use the black relay in my application, safely? May be there problems that I have to be careful?

Definitely no!!!

Though it will most likely work, safely is wrong. If it is rated at 125V, it will work safely up to 125V only :)

In fact the answer is maybe. It all depends on the detailed relay specifications. Many relays have a current rating at one voltage, and a lower rating at a higher voltage. There is, of course, a maximum voltage, independent of current and vice versa.

The link is not good. Are you using this T010010 model? http://uk.rs-online.com/web/p/processor-microcontroller-development-kits/7485360/

The part is obsolete now according to Mouser.  The simple answer is no, you cannot use a 120 volt part at 220 volts.  The higher voltage can breakdown the lower voltage rated parts.  It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay.  The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.


text:
Arduino Uno R3 USB is not working
I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is on and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.
I tried lsusb and I checked /dev/ ports. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.
I thought it was a bootloader problem, and I got a new ATmega328P chip board. It is getting power on and the LED is blinking, but the port is not mounted. I tried with lsusb and also ls /dev/ttyACM* with no result.

You could try to flash the firmware of the USB controller.
General steps for Arduino R3 are:

Put the Arduino in DFU mode (the R3 does not require soldering for that)
Flash the firmware using:
dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).
Useful links for that:

Resetting your Uno R3's default firmware
Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU

A useful search term for that is Arduino R3 DFU-programmer.

Maybe you need to "reflash" the FTDI firmware. Sorry, I'm very bad in Linux. To do this, you'll need some software and a HEX file. Check this video on YouTube:
ARDUINO- Upgrading USB FIRMWARE using FLIP
And download the arduino_usbtoserial.hex file.
If it doesn't work, and if your Arduino Uno has the ATmega328P chip as DIP, try to change the ATmega328P chip in the board. Remove this chip carefully. Put another chip in with the bootloader and test.

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


text:
UNO analog input voltage reading not accurate
My loop code is this:
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(float(sensorValue*5000.0/1023));
delay(1);        // delay in between reads for stability

When I read 5V it gives 5000 mV. When I read 3.3V pin it gives 3211 mV. When I read 1442 mV battery it gives 1392. What do you think about this situation?
NOTE: There is no any additive circuit. Just wires.

How do you know your 1442mV battery is actually at 1442mV? Using a Voltmeter? Also, if you measure a 3.3V pin, it is usually off a bit, and I wouldn't be surprised to see 3211mV (or 3400mV) from a 3300mV regulator

Btw it is not necessary to use float(...) to print the number over the serial line, it will accept any data type :)

Both your measurement (e.g. using a voltmeter) and the ADC of the Arduino have a limited accuracy (cf.  table 28.7 in the datasheet of the ATmega328). Therefore you should never expect them to agree to all given digits.

All comments are true but it gives 5V correctly, why? And my voltmeter is not corrupted. I also read a voltage refence IC's output, there is a 40-50 mV error still.

Your question contains a number of errors and misconceptions.
Firstly the maximum output of a successive approximation ADC (here 0x3ff) corresponds to Vref - 1 LSB
The voltage will thus be sensorValue*5000.0/1024. Note this error is less than the error of ±2LSB.
Measuring your 5V is futile, as this is the default analog reference, so the result must be 0x3ff.
Measuring the 3.3V pin will give a relative value to the 5V reference. Both are produced from commercial grade regulators with a accuracy of ±5%.
You are also confusing the precision of the reading (10 bit) with accuracy which is a best ±5% ±2LSB.
If you really want to measure voltage you should use the internal 1.1V bandgap reference. You would of course need to reduce the 5V and 3.3V to less than 1.1V. This introduces another potential error (even if you use 1% resistors), but would give more accurate results which are directly comparable.

Is there 1.1V ref. exists in UNO?

Are you sure its not 1023 but 1024?

And note 5V pin is not at 5V, its 5.15 V. I think the problem is this.

@user30878 for 1.1V ref see http://arduino.cc/en/Reference/AnalogReference re 1024 see http://arduino.cc/en/Reference/AnalogRead (or read the Atmega data sheet)

Yes, if the 5V pin is 5.15 then the reference voltage will be high. Thus you need to multiply by 5/5.15 = 0.97 to correct the results. This gives figures which roughly agree with what you got. (3.20 instead of 3.3, and 1398 instead of 1442). Plus what the others said about accuracy.

Both your measurement (e.g. using a voltmeter) and the ADC of the Arduino have a limited accuracy (cf. table 28.7 in the datasheet of the ATmega328). Therefore you should never expect them to agree to all given digits.
Concerning the points raised in your comment:

All comments are true but it gives 5V correctly, why?

analogRead returns a value between 0 and 1023. For all voltages above an (unknown) threshold close to 5 V, it will saturate and always return 1023, no matter what the actual input voltage is. This value is then converted to 5.000 V in your code. What you are probably seeing is just the maximum value your code can return, not an accurate measurement of a 5 V input voltage.

And my voltmeter is not corrupted.

It doesn't have to be corrupted. It will still be off. Have a look at the manual to find the nominal accuracy. (Also note that accuracy and precision are two different things and different from the number of digits of the display, assuming your voltmeter is digital.)

Thanks for clear my mind for maximum voltage. I already know it but I was confused a bit.

I mean voltmeter is working correctly.


text:
Can I safely connect my original Arduino Uno to a 19V adapter?
I have an original Arduino Uno R3. According to the specifications the recommended input voltage is 7 to 12 Volt.
However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.
I don't want to damage the Arduino or the DFRobot 2A Motor Shield I'm using. Can I safely plug in the adapter and will it still work correctly?

Input Voltage (limits) 6-20V. What kind of motors do you have, because these have to be able to handle 19v too.

The motors need to handle 19v if powered separately via PWRIN, but not if they use the 5v regulated supply from the Arduino via VIN. See my answer below for more details.

19V is too close to the absolute maximum rating (20V) for comfort. Any voltage surge could kill the regulator. And you'll have thermal problems as well. So I'd say powering the Uno at 19V is very bad advice! Stick to the recommended input voltage range instead!

It's often better to supply separate power to high-current applications (such as motors) rather than taking power off the Arduino. This avoids problems with current and thermal limits of the Arduino on-board power regulator.
Looking at the manual for your board, the motors can be powered by a separate power supply hooked up directly to the motor shield. There's a six-pin header on the board marked VIN and PWRIN. When the jumpers are on the VIN side Arduino-supplied power is used to drive the motors; when the jumpers are on the PWRIN side the motors are supplied with power from the terminal block next to the jumper. (The rest of the board remains powered from the Arduino, but that's usually a negligible amount of current compared to your motors.) A photo in the manual demonstrates the pins set to PWRIN and an external power supply hooked up.
The documentation says you can supply any voltage between 4.8 V and 35 V DC, but be careful! What they don't make clear in the documentation (but is clear from the schematic and the L298N datasheet) is that this power is supplied directly to power side of the L298N and the motors without further regulation. The chip can handle up to 50 V DC, so it would be fine with a 35 V input, but you'll want to check that your motors can handle the voltage you want to give them.
If the motors can handle 19 V input, and your 19 V power supply is reasonably well regulated itself (which a laptop computer power supply generally would be), you can use that to power the motors directly through the motor shield and continue using your current power supply to power the Arduino.
(The ST L298 page has further information, including a slightly less readable copy of the data sheet and application notes.)

According to the page you linked:

The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

So, yes. You can use the 19V external power supply to power the board. However, be aware that the voltage regulator can overheat over time and damage the board.

If someone has a way of calculating how hot the voltage regulator would get, I'd greatly appreciate the knowledge. I'm also not sure if the regulator will get hotter quicker depending on how much current is being pulled through it (for the motor driver shield)

Also, there may be current issues - I found an analysis that says the current limit of the Uno is 1A ( http://electricrcaircraftguy.blogspot.com/2014/02/arduino-power-current-and-voltage.html#.VQcm2UJ6nOQ ). TheDFRobot 2A Motor Shield might try drawing more than the Arduino can handle. I don't know how to calculate that

yes, the more current, the more heat. to calc the temp, you need to know the junction-to-ambient rating of the regulator in watts. To calc watts, subtract 5 from 19 (14) and multiply by the current. If we assume, say, 200ma; 14*.2=2.8w; way too much. divide watts by J2A to get deg C.

I agree with @dandavis. Here's the datasheet for the regulator: https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF. A dissipation of 2.8W would raise the junction temperature by 188°C. If ambient was 25°C, then the junction temperature would be 213°C, far above the 175°C limit at which the regulator internally shuts off. So it won't work at that current (200 mA).

Also, 19V is too close to the absolute maximum rating (20V) for comfort. Any voltage surge could kill the regulator. So I'd say powering the Uno at 19V is very bad advice! Stick to the recommended input voltage range instead!

throwing an LM7812/7809 between the 19v and the MCU would solve the heat issue.


text:
Reading I2C sensors with a timer interrupt
I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.
Step I: testing the timer
I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!
200
201
200
201

CODE
// Timer variable
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Step II: Reading values from the sensor in the ISR
Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.
CODE
// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  calcBias():
  Serial.print("Readings take: (us)");
  Serial.println(samplingTime);

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  Serial.println("Enabling interrupts..");
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  Serial.println(z);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  // Update x, y, and z with new values 2.5ms
  getGyroValues();
  cont++;
}

void getGyroValues()
{

  //starting samplingTimer
  samplingTime = micros();

  // Gets the angular velocity from the sensor
  byte zMSB = readRegister(L3G4200D_Address, 0x2D);
  byte zLSB = readRegister(L3G4200D_Address, 0x2C);
  z = ((zMSB << 8) | zLSB);

  samplingTime = micros()- samplingTime;
}

void calcBias()
{
  Serial.println("Bias");

  // Reads sensors and display three values
  getGyroValues();

  [...]

  Serial.println(bx);
  Serial.println(by);
  Serial.println(bz);
}

void writeRegister(int deviceAddress, byte address, byte val)
{
    Wire.beginTransmission(deviceAddress); // start transmission to device
    Wire.write(address);       // send register address
    Wire.write(val);         // send value to write
    Wire.endTransmission();     // end transmission
}

int readRegister(int deviceAddress, byte address)
{
    int v;
    Wire.beginTransmission(deviceAddress);
    Wire.write(address); // register to read
    Wire.endTransmission();

    Wire.requestFrom(deviceAddress, 1); // read a byte

    while(!Wire.available())
    {
        // waiting
       // Serial.println("No Data");
    }

    v = Wire.read();
    return v;
}

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.
Here is the output:
starting up L3G4200D
Bias
4.00
0.00
-3.00
Read

Try putting sei(); at the start of the ISR. Also avoid using Serial.print inside an ISR.

Grande Gerben! It works, please write your an answer. Why do I need to enable interrupts again?

By default interrupts are disabled inside ISRs.

Try putting sei(); at the start of the ISR. I think I2C needs interrupts enabled to work.

To explain why it's necessary to (re)enable interrupts, this is what the ATmega328P datasheet says: "When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user
software can write logic one to the I-bit to enable nested interrupts."

Also, note that Arduino defines an interrupts() "function" that can be used as a more readable alternative to sei() (on AVRs, it's defined as a macro that is directly equivalent to sei()).

I2C requires interrupts to work, however enabling interrupts inside an ISR is not recommended. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one.
Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.
As an example, your main loop could be rewritten as:
unsigned long lastReading;
unsigned long lastDisplay;
void loop()
{
  if (millis () - lastReading >= 5)   // 200 Hz
    {
    lastReading = millis ();
    // Update x, y, and z with new values 2.5ms
    getGyroValues();
    cont++;
    }

  if (millis () - lastDisplay >= 1000)  // one second
    {
    lastDisplay = millis ();
    Serial.println(cont);
    Serial.println(z);
    cont=0;
    }
}

Now you don't need the timer, and you are interrupt-friendly. :)
More information about interrupts: http://www.gammon.com.au/interrupts

Thank you, with your code this solution is perfect. But in my case, there is a SerialRoutine in the loop() which sometimes takes a long time to send /receive data over the serial. If the getGyroValues is placed in the main loop, it will be delayed by the other running task and its reliability compromised


text:
Good button debouncing/stateChange library
I need debouncing/stateChange for a push button configuration. Is there a good library for debouncing/stateChange buttons in Arduino (without delay)?

I usually check the button state every few milliseconds, and store the state in an array. Next I check if the stored values are all HIGH or all LOW.

"Best", especially without offerimg any (or enough) criteria, would elicit entirely subjective answers and so is not a good fit for stackexchange.com. If you can re-word your question make it more objective, it will get more useful results (not to mention, it will remain open!)

There is no such thing as debouncing without delay. Some small amount of delay by definition needs to be introduced for the input system to be sure that the event is not a false positive.

The Button library in the Arduino playground works perfectly.

This library is great! BUTTTT dosn't work with the ESP8266 because meanwhile the Arduino has an internal Pull-up resistor the ESP doesn't (in all pins)!!!

This link is now broken

I think what you need is an interrupt-based detection of the button. This way, your Arduino can do what it needs to do without stalling for the delay function.
// Example code usage

int pin = 13; // LED on board
int interrupt0pin = 2; // pin attached to int0 if you're using Uno
int buttonState;

void setup()
{
  pinMode(pin, OUTPUT);
  pinMode(interrupt0pin, INPUT);
  attachInterrupt(0, buttonUpdate, CHANGE); // calls buttonUpdate() when button input changes (you can also use high-to-low or low-to-high)
}

void loop()
{
    if (buttonState)
        digitalWrite(pin, HIGH);
    else
        digitalWrite(pin, LOW);
}

void buttonUpdate()
{
  buttonState = digitalRead(interrupt0pin);
  delay(50); // 50ms works for most switches - adjustable
}

Find out more here: http://arduino.cc/en/Reference/AttachInterrupt
Good luck!

You can use my library
https://github.com/anlgncr/Buttons
This library lets you use buttons as many as you wish with only one instance of class.
You can also call a function when button is pushed or released.

I'm on this subject right now and I'll use this to note my findings.
I found many libs on this, and this is my wishlist:

support many buttons
support toggles or switches
support debouncing and maybe de-glitching
non-blocking functions
support long-press, double-click

Candidates:

Switch from avandalen: tutorial - github - lib ref@arduino - @platformio
EasyButton from Evert Arias: tutorial - github - lib ref@arduino - @platformio
JCButton from JChristensen: github - lib ref@arduino - @platformio
ezButton from ArduinoGetStarted: tutorial - github - lib ref@arduino - @platformio

Here are my findings for each lib:
Switch

it's really easy to use
you can use it as a switch or a button, same class handles both
supports callbacks
supports many buttons
supports debouncing and de-glitching
supports double click and long press
most configs have defaults, and you define them at the Button setup
as I use PlatformIO, some warnings from this lib are shown while compiling my project

EasyButton

it's really easy to use
very good docs
supports callbacks
supports many buttons
does not support toggles/switches, although you can simulate it by checking the wasPressed and wasReleased properties
supports debouncing
supports double click, triple click, or a given number of clicks
you may have a different action for single, double or triple click for the same button
supports multiple times of long press, if needed
most configs have defaults, and you define them at the Button setup

JC Button

easy to use, not as easy as Switch and EasyButton tough
you can use it as a Button or a switch (ToggleButton), different class for each
supports many buttons
does not support callbacks
supports debouncing
supports multiple times of long press, if needed
most configs have defaults, and you may define them at the Button setup, but long press time is something you define while querying it's status rather than defining it once at the button setup

ezButton

easy to use, not as easy as Switch and EasyButton tough
supports many buttons
does not support toggles/switches, although you can simulate it by checking the isPressed and isReleased events
does not support long press
does not support callbacks
supports debouncing, does not debounce by default (you must call setDebounceTime on setup)
supports an easy way to count button clicks

Veredict
I chose avdweb/Switch. Reasons:

in terms of debouncing AND de-glitching, it did better according to my tests
I need a solution for Buttons and Switches, and it provides them in the same class

I can receommend the following library:
http://log.liminastudio.com/itp/physical-computing/arduino-a-new-improved-button-library-with-some-handy-features
https://github.com/virgildisgr4ce/Button
On the website you will find some examples on how to use it. I have implemented this library already in several sketches and it works very reliably.

You can put a capacitor in parallel with the switch - 100nf should do the trick. Some capacitors have a minus on the packaging, next to one of the pins - if so, make sure that side is to negative (ground).

I put this together for a guy the other day. Its not a library but it achieves reading and debouncing all of your buttons and works very well maybe it could help you
const byte numbuttons = 15;                                                     // DEFINE HOW MAY DIGITAL INPUTS TO MONITOR(NUMBER OF BELOW PINS TO USE)
const byte digitalpin[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16 };   // DECLARE ALL DIGITAL INPUT PINS WHICH CAN BE USED IN THE ORDER IN WHICH THEY WILL BE PHYSICALLY USED(DONT INCLUDE ANY PINS USED FOR OTHER THINGS
const byte debouncetime = 50;                                                   // THIS VALUE IS THE TIME TO WAIT BEFORE RECHECKING (FOR DEBOUNCE
byte readstate[numbuttons];                                                     // READ ARRAY
byte laststate[numbuttons];                                                     // HOLDS THE BUTTON LAST STATE FOR STATE CHANGE DETECTION
byte NumBut;                                                                     // THIS IS THE VARIABLE FOR DIGITAL FORLOOP COUNTER
unsigned long checktime;                                            // RECORDS THE TIMES (IN MILLIS() TO RECHECK THE STATE FOR EACH BUTTON. FOR DEBOUCING

byte CURRENT_SETTING;
void setup() {

  // SET INITIAL STATES FOR DIGITALS
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {
    pinMode(digitalpin[NumBut], INPUT_PULLUP);
    laststate[NumBut] = digitalRead (digitalpin[NumBut]);
    checktime = 0;
  }
}

void loop() {
  //call the read button method
  READBUTTONS();
  PROGRAM_OUTPUT();
}

void READBUTTONS() {
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {

    readstate[NumBut] = (digitalRead (digitalpin[NumBut]));                                                                   // READ DIGITAL INPUTS INTO ARRAY

    if (readstate[NumBut] != laststate[NumBut] && millis() >= checktime )   {
      if (readstate[NumBut] == 0 && laststate[NumBut] == 1) {
        checktime = millis() + debouncetime;
        CURRENT_SETTING = NumBut;
      }
      laststate[NumBut] = readstate[NumBut];
    }
  }
}

void PROGRAM_OUTPUT(){
    switch ( CURRENT_SETTING ) {
    case 0:   //do something to turn off output break;
    case 1:   //do something with setting 1 break;
    case 2:   //do something with setting 2 break;
    case 3:   //do something with setting 3 break;
    default:    break;
}
}


text:
Arduino/C++ byte manipulation
Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.
Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.
eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.
01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1
What would be the most efficient way to accomplish this?

Could you explain a bit more? Is it always the same bits that are moved to the same new location? What values do the underscores (_) get?

Yes, the same bits are moved to the same new locations and the underscores are filled with bits which are calculated from the rest of the bits present in the received byte. (After performing a few simple operations on them)

Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:
int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 0x08) retval |= 0x800;
   return retval;
}

On most microprocessors, this will compile into just a few instructions per statement.
This is also arguably more maintainable than a complex series of shift and mask operations.

Assuming the incoming bytes are guaranteed to come in even numbers, and
your output is in little-endian order, you could do something like this:
void process_and_send_bytes(uint8_t data_in)
{
    uint16_t some_12_bit_function(uint8_t);  // processing function
    void send_byte(uint8_t);                 // sending function
    static uint8_t data_on_old = 0;
    static bool has_data_on_old = false;
    uint16_t processed_data = some_12_bit_function(data_in);
    if (has_data_on_old) {
        send_byte(processed_data << 4 | data_on_old);  // two pieces
        send_byte(processed_data >> 4);      // high 8 bits
        has_data_on_old = false;
    }
    else {
        send_byte(processed_data);           // send low 8 bits
        data_on_old = processed_data >> 8;   // save higher 4 bits
        has_data_on_old = true;
    }
}

Basically, when you get the first byte, this function outputs one byte
and keeps 4 bits on hold. When you get the next byte, this outputs the
4 bits that where on hold, together with the new 12 bits, as two
8-bit packets.

It looks like we each picked a different part of the question to answer! :-)

I haven't tested this in any way whatsoever, but you could use a 32-bit integer as a buffer to store the bytes as you process them.  Then, any multiples of 8 bytes that end up in the buffer can be passed on to wherever they are needed.
The first byte that comes in you process and push all 12 bits into the 32-bit integer - increment a counter by 12.  You now have 12 bits in the buffer variable.
Then while the number of bits in the buffer is at least 8 bits you grab the upper-most 8 bits and pass them on to wherever they are going.  Decrement the counter by 8 for each iteration.  You have now sent 1 byte and you have 4 bits left in the buffer.
The next byte that comes in you push the new 12 bits into the buffer.  The counter, increased by 12, is now 16.
16 is greater than or equal to 8, so send out the upper 8 bits of the 16 and decrement the counter by 8.
8 is greater than or equal to 8, so send out the upper 8 bits of the 8 and decrement the counter by 8.
Counter is now 0, so nothing else to send.  Back to the beginning again.
Something like:
void processByte(uint8_t in) {
    static uint32_t buffer = 0;
    static uint8_t validBits = 0;
    buffer <<= 12; // Make room for 12 new bits.
    buffer |= (first processed bit << 11);
    buffer |= (second processed bit << 10);
    buffer |= ((in & 0x80) << 2);
    buffer |= (third processed bit << 7);
    buffer |= ((in & 0x70) << 1);
    buffer |= (fourth processed bit << 4);
    buffer |= (in & 0x0F);
    validBits += 12;

    while (validBits >= 8)
        validBits -= 8;
        executeByte((buffer >> validBits) & 0xFF);
    }
}


text:
Connect 5V DC Fan to Ardumoto
I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, https://www.sparkfun.com/products/9649) to Ardumoto (https://www.sparkfun.com/products/9815).
Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?
Thanks.

If you look at the schematic on the product page it shows that the Vin from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.
With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that it cannot be made to reverse, therefore you should always give the direction pin a high signal. The Sparkfun hookup guide has a example code which shows how to control the motor shield, and some explination.


text:
Generating a PWM frequency greater than 125 kHz using Arduino Uno

I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
  delayMicroseconds(900);
}

Update
On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.
My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.
Second sketch:
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output (but cro measures only 125 kHz)
   TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
   TCCR2B = _BV(WGM22) | _BV(CS20);
   OCR2A = 63;
   OCR2B = 0;

  // Set up the 8 MHz output
   TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
   TCCR0B = _BV(WGM02) | _BV(CS00);
   OCR0A = 1;
   OCR0B = 0;

  // Make the 250 kHz rolling
  while (1) {
    _delay_us(5);
    if (OCR2B < 63)
      OCR2B += 5;
    else
      OCR2B = 0;
  }
}

The rolling part made it difficult to see on my scope, getting rid of that and setting OCR2B to 30 I seem to get a 250Khz waveform. Strange.

I made it and it works, what i noticed is that there is no 0 % duty cicle available. How can i make 0 % duty cicle?

It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM

I fully agree with your advice, but I would consider this kind of timer programming perfectly within the "normal Arduino capabilities".

microtherion, what I meant was it's outside the "Arduino language" set of functions that will work across many varients of AVR (such as delay, digitalWrite etc.) and instead delving into registers that will likely be specific to a given AVR chip.

My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

According to my measurements, it is. Using this slightly modified version of your code:
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5 µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output
  TCCR2A = bit(COM2A1) | bit(COM2B1) | bit(WGM21) | bit(WGM20);
  TCCR2B = bit(WGM22) | bit(CS20);
  OCR2A = 63;
  OCR2B = 31;

  // Set up the 8 MHz output
  TCCR0A = bit(COM0A1) | bit(COM0B1) | bit(WGM01) | bit(WGM00);
  TCCR0B = bit(WGM02) | bit(CS00);
  OCR0A = 1;
  OCR0B = 0;
}

I get the predicted 8 MHz output on pin 5:

And the 250 kHz output on pin 3:

To your original question: You can reduce the delay, but there's a limit to how small the delay can be.
Two reasons: Firstly, the loop() function does have some overhead, and secondly the code that you write takes time to execute. This is why the hardware PWM timer is valuable - it generates the pulses without much software intervention.

I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation).

This is really just to add to Nick's answer...
(To understand what's going on, you need to refer to the datasheet. Based on your questions, I'm assuming you haven't stared at it long enough.)
In the first case: 125 kHz.
I am not sure if you're aware, but you're using a special mode of "Fast PWM" which is slightly different from the analogWrite() provided in Arduino.
In this mode, your PWM period is determined by the time it takes your timer counter to match the value in OCR2A register. This means that with a 16 MHz clock, and your output is toggled at a rate of 16 MHz/63 = 250 kHz (roughly).
So far so good, but what does the CRO see? The CRO considers a period to be made up of both high and low signal. It takes TWO 250 kHz cycles to toggle the signal up and down. Hence, the reading shows 125 kHz.
As to why the rolling would make your reading difficult: Think what kind of wave will appear when OCR0B = 0. ;-)
Case 2: 8 MHz
The same applies in the seccond case, and you should expect a 16 MHz cycle that toggles the signal up and down (which gives a 8 MHz reading on the CRO). As to why you are getting 1.6 MHz - that's an odd case. Can you post your CRO reading?

The CRO considers a period to be made up of both high and low signal. - indeed. The original code had such a short pulse that a scope might have interpreted each pulse as half a period, and thus halved the reported frequency. It might have missed the very short on cycle, which is why I adjusted the duty cycle up to 50%.

Yes, you can reduce the delay.
From the documentation:

This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times.

Note that, there are a few cycles between the delays, so as you get shorter timeperiods, you will get less and less accuracy.
You could hand-code the delay. I would imagine you could get up to 1 MHz, but with little control over the duty cycle (at that frequency).You would need to disable interrupts, and you could do nothing else at all.
If you want still more, you could set a fuse on the ATmega, and get your native clock speed out on of pin 14 CKO (this shows up as digital pin 8 on the Arduino board) - I would expect a 50% duty cycle; you will have NO control over - you can't switch it on or off, or affect the duty cycle. It can be used to run multiple chips off the same clock.