text:
What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?
I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption).  I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.
First: to run at 8 MHz, do I just need to replace the crystal?  Or is there anything else I have to do?
Second: Do I need to make any code changes to reflect the new speed?  I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.  Will any of these be broken?  Will the code run noticeably slower?
Third: How can I program the chip?  Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?
Fourth: Will power consumption change at 8 MHz?
Thanks!

There are plenty of 3.3V Arduino-compatible boards, Sparkfun Pro mini being one example. It is supported by the IDE so all clock-specific adjustments will be made for you once you pick it from the 'boards' dropdown.

At 8MHz you'll probably be okay using the internal oscillator instead of a crystal. Beware when you compile code that when you for example pick "Pro Mini 328p at 8MHz" that 8 gets applied to code, so I wouldn't suggest compiling for 16MHz and then transplanting or you may find that a delay(1000) takes two seconds as a simple example. And check out power saving/sleep in the H2OhNo code. (Another moment when I suggest you get any programmer at all instead of limiting yourself to serial uploads, search Tindie for "ISP.")

The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.
However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.
Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.
You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.
You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.
How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.
If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.
UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).

Thanks for this response!  I'm a bit baffled by what you said about the brownout detector shutting down below 4.3 V.  I'm running at 3.7 V now and it works fine; didn't have to make any changes to the fuses.

@user40, see "UPDATE" section at the bottom of my post.

First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

No, run on the internal oscillator as suggested by AMADANON Inc.
Alternatively, set the "divide clock by 8" fuse (which would run it at 2 MHz from a 16 MHz crystal) and then in code change the division back up to 2. ie.
#include <avr/power.h>

void setup ()
  {
  // slow clock to divide by 2
  clock_prescale_set (clock_div_2);
  } // end of setup

Or for programming in another Uno leave the fuse alone, program at 16 MHz and then drop the clock down in the target chip, hoping it works long enough at 3.3V to execute that first instruction. The safest thing would be to just install an 8 MHz crystal or resonator on the target board. However if timing is not critical run with the internal oscillator.

Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.

If you tell the IDE you have an 8 MHz processor (eg. a Lilypad) then it should adjust delays, baud rate calculations etc. appropriately.

Will any of these be broken?

I2C and SPI are self-clocked. They can run at a variety of rates. I doubt there will be any problems with them. As for serial, providing the calculations are done right a wide range of baud rates should still be available.

Will the code run noticeably slower?

Well yes, it will run at half speed compared to 16 MHz.

Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

You can do that. Or you could connect up an ICSP header or an FTDI header and program it in situ.
Examples here: http://www.gammon.com.au/breadboard

Fourth: Will power consumption change at 8 MHz?

Yes, it is reduced somewhat.
You can reduce it considerably more by using other techniques as described at http://www.gammon.com.au/power, and referred to by AMADANON Inc.

Thanks Nick!  I've actually read your website before and it helped me cut my power consumption radically.  As a result, AAs and AAAs are now a viable power source for this device, which is a big deal because weight matters.  So thanks for that website too--it's a huge service to the community and really helpful to people like me.


text:
How to detect the absence of an RFID tag?
I have installed an MFRC522 RFID reader in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.
I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.
Do you have any advice or experience in implementing something like this?
Thanks!

I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.
Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.
What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.
The other approach would be to "check out" with your RFID scanner. I did an RFID event management system a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.

Oh Yes it is possible.
I did a project which allows to transmit data from RFID card to a bluetooth device.
You can use below code to identify presence & gone:
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

SoftwareSerial BTserial(0, 1); // RX | TX
int sensorPin = A0;
int sensorValue = 0;
String lastBlock="";
void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin();            // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
//mfrc522.setPassiveActivationRetries(0x9A); // for example
//Serial.println("Scan PICC to see UID and type...");
BTserial.begin(9600);
Serial.println("Scan PICC to see UID and type...");
}
boolean flag=false;
int counter=0;
void loop() {
// Look for new cards
BTserial.println("Scan PICC to see UID and type...");
if ( !mfrc522.PICC_IsNewCardPresent()) {
  if(mfrc522.PICC_IsNewCardPresent()){
    if(!flag){
    byte sector         = 1;
byte blockAddr      = 4;
byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
    0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
};

byte trailerBlock   = 7;
byte status;
byte buffer[18];
byte size = sizeof(buffer);
status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
dump_byte_array(buffer, 16);

    flag=true;
    }
  }
  else{
    if(flag){
    flag=false;
    }
  }
      return;
}
}

void dump_byte_array(byte *buffer, byte bufferSize) {
String a=String((char)buffer[9]);
String b=String((char)buffer[10]);
String c=String((char)buffer[11]);
String d=String((char)buffer[12]);
String str="";
str+=a;
str+=b;
str+=c;
str+=d;
lastBlock=str;
Serial.println(str);
BTserial.println(str);
}

source: Stack Exchange

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

sort: votes


text:
Understanding Digital IMU 6DOF sketch
I am looking at the following code and getting confused by a few elements in it:
1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?
2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?
    #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

any help would be greatly appreciated!

The writeTo functions
The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.
Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.
The Bitwise ops
These don't set the number of bits we are reading per se, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.
(((int)buffer[0]) << 8 ) | buffer[1];
Whats happening here is that buffer[0] is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original buffer[0] are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator |, which will turn on any bits that were set in buffer[1] in the result. Since the bottom 8-bits were 0's from the shift, this just copies buffer[1] in exactly.
The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.

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


text:
How can I open simultaneously 2 client socket connections with GSM shield?
How can I open simultaneously two socket connections with a GSM shield?
It seems that when I try to open the second connection, it is not opened, and additionally the first connection is closed.
Code:
#include <GSM.h>

#define PINNUMBER      ""
#define GPRS_APN       "sm2ms.movilforum.es"
#define GPRS_LOGIN     ""
#define GPRS_PASSWORD  ""

#define SERVER "www.abv.bg"    // some server
#define PORT   80              // some port

static GSM gsm;
static GPRS gprs;
static GSMClient clientControl;    // first connection
static GSMClient clientData;       // second connection

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

    Serial.println("GSM not initialized");

    while (true)
    {
        if (gsm.begin(PINNUMBER) == GSM_READY)
        {
            Serial.println("GSM initialized");

            while (true)
            {
                GSM3_NetworkStatus_t eErrorCode;

                delay(1000);

                eErrorCode = gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);
                if (eErrorCode == GPRS_READY)
                {
                    Serial.println("GPRS initialized");

                    return;
                }
                Serial.print("Not connected to GPRS, error code = ");
                Serial.println(eErrorCode, 1);
            }
        }

        Serial.println("Not connected to GSM");
        delay(1000);
    }
}

void loop()
{
    delay(1000);

    Serial.println((clientControl.connect(SERVER, PORT))
                   ? ("Connected") : ("Couldn't connect"));

    delay(1000);

    Serial.println((clientData.connect(SERVER, PORT))
                   ? ("Second connection succeeded")
                   : ("Second connection failed"));

    Serial.println("Do something here");

    // close the stuff here!!!
    for (;;);
}

The serial dumps:
GSM not initialized
GSM initialized
GPRS initialized
Connected
Second connection failed
Do something here

With other clients I don't have problem supporting two simultaneous connections. Here the first connection succeeds, the second fails.
Regards,
Boyan

Could you post the code you are using to create the connections?

Additionally, it seems to not matter which exactly the server is. The same happens also with other active servers/ports.

It seems like you cannot open a new one because it is already open, you either need to make a new instance or close the old first.

First, clientControl and clientData are already two different instances. Secondly, I cannot close the control connection. I need them both open simultaneously. If I close the control connection, everything will end. If I don't open data connection, I cannot send data. Therefore I need them both.

Could you give us a copy paste of the serial log ?

Serial log added.


text:
Use RFID-RC522 with other Pins
I'm wondering where the pin setting is manifested in the library.
I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.
Where can I change the used ports?
why are two ports user-defineable #define RFID_SS  10 #define RFID_RST 5 while the rest is not?
I am with this Playground-Guide using this library from Github on my Arduino Mega

#define RFID_SS  10

stands for Slave Select on port 10, the SPI is a serial interface, meaning you can connect all kinds of SPI devices to the same wires, as long as slaves have different IO ports.
This is also the reason you don't need to define the other ports because they need to be connected to your SPI.
I suggest you make yourself familiar with this page: http://arduino.cc/en/Reference/SPI
To sum it up. You can change the reset and Slave Select pin out, (those set in the variables) but not the SPI Pins. But you can use the ISCP pins in the middle of the board.

so I can either use ISCP on my board for MOSI MISO SCK. Or I connect the display shield to pins 50-53 and at the same time connect the RFID'sMISO / MOSI / SCK to the same ports 50-53 and the select/reset pins do the rest (choosing where to send data to) for me?

Yes that is correct. Also be aware that some libraries (lib) have the SS pin hard-coded, this is solved by going in to the library and change the value to a variable set through the function.

SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V

Sorry I'm a bit late (5 years late) but hopefully this can help someone who's just now trying to do this!
There's an old obscure Sunfounder library, "rfid1.h" that lets you declare every pin. Like this:
rfid.begin(IRQ,SCK,MOSI,MISO,NSS,RST);

It's a bit hard to find the library online these days, but at the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader) if you download the "RFID-RC522_test_experiment" zip file it will have the library in there. The secret is that this library includes a software SPI which is sort of like a software serial for SPI communication. Letting other digital pins be used as MISO etc...
This library also makes it much easier to use multiple RFIDs reliably since they don't have to share all the same pins.
You can find some example code here: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html

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


text:
Arduino or Raspberry Pi for my project
A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.
My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.
Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.
EDIT: In response to comments below, a greater idea of what I want to do:
I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

Do you already know how to use wifi, Bluetooth, and audio streaming on Linux?

No I do not. I figure I can learn it. I've also heard, however, that programming in Linux can be somewhat dense, and that learning how to program an arduino is much simpler.
EDIT: I'd also like to point out I'm proficient in several programming languages, including Java, PHP, Swift, Ruby, Python, etc. etc. so I imagine I'd be able to pick up any programming knowledge necessary for either of these devices.

Hate to burst your bubble, but the sentence all I really need to do is design a bluetooth / wifi interface is a big task. Can you elaborate on what your other device is? Android Phone?

Revised my question above to further clarify. Sorry about that, hopefully my revisions give a better idea of what I intend to do with this arduino / raspberry pi.

Writing PulseAudio drivers for Windows and OS X might solve it with probably the least overall work.

Thanks, I'll definitely look into that. Would this be an easier job for arduino then?

AFAIK, there is no PulseAudio server for Arduino. At least, not for anything less than a Yún. So, no.

Well, I guess I'm getting a raspberry pi then. Thanks for the help!

This is definitely not an Arduino application.  There are a number of ways in which the actual implementation of the Raspberry Pi is a less than perfect fit, but it is based on the right general idea and not a bad place to start for a prototype.

Yea that's definitely the general idea I'm getting as well. I ended up ordering an arduino (I'm putting this project on hold for a bit) while I learn a little more about embedded computing, then I'll launch into it. For now I'm just starting with an arduino uno and working my way up :)

I'd definitely prefer the Pi for this project.

As mentioned in the comments, a Raspberry Pi would be superior here.
The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a logic level shifter). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.
A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).
For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. Sure, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.

While it might be an interesting project, the overall quality of the sound generated by such do-it-yourself contraption, is likely to be highly disappointing, because of the not-stellar quality of the final analog stage in the audio output.

Can you explain your answer applies to the Arduino vs the R-PI?

I wanted to warn the OP that his expectation about the final result might be incorrect, because the question asked seems to make certain assumption (that the out come will be meeting his expectations in terms of sound quality).
So, if the desire is to make it produce some sound, yes, it will be successful. But in case the expectation is to produce good_quality sound, he will be probably disappointed and might want to spend his time on some other project.


text:
How to check whether my Arduino is working? And how to fix this?
I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.
You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD
If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


text:
error: 'CLASS' does not name a type only when creating object inside another object
I'm trying to use Adafruit's LED Backpack library within a custom class. When I use the Adafruit library directly within a sketch, it compiles fine. When I use an example sketch provided with the library, it compiles fine. However when I create an instance of my custom class with the Adafruit object within it, I get the following error:

In file included from sketch_feb18a.ino:6:
  /Users/lawnmowerlatte/Documents/Arduino/libraries/Bargraph/bargraph.h:18: error: 'Adafruit_24bargraph' does not name a type

All the reasons I've seen for this error stem from the library being missing or otherwise incorrectly installed. However, since I can use it directly, I think something else must be wrong.
Working
#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>
Adafruit_24bargraph bar = Adafruit_24bargraph();

void setup() { }
void loop() { }

Not Working
#include <bargraph.h>
Bargraph bargraph = Bargraph("Test", "api", 0);

void setup() { }
void loop() { }

bargraph.h
#ifndef Bargraph_h
#define Bargraph_h

#include <Adafruit_GFX.h>
#include <Adafruit_LEDBackpack.h>

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class Bargraph {
  public :
    String name;
    String api;
    Adafruit_24bargraph bar;

    Bargraph(String _name, String _api, int _device,
        String _type="Default");

    void set(String _value);
    void setMax(String _max);
    void update();
    void print();

  private :
    int display[24];

    long max;
    long value;
    int device;
    int size;
    String type;

    void format();
    void write();
};

#endif

bargraph.cpp
#define OFF 0
#define RED 1
#define YELLOW 2
#define GREEN 3

#include <bargraph.h>

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

Bargraph::Bargraph(String _name, String _api, int _device, String _type) : bar() {
    name        = _name;
    api         = _api;
    max         = _max.toLong();
    device      = _device;
    type        = _type;
    value       = 0;

    for (int i=0; i<24; i++) {
        display[i] = OFF;
    }

    bar.begin(0x70+device);
}

**Methods Omitted for Brevity**

Can anyone explain what's going on here? I'm pretty certain my class syntax is correct as I have other object-in-object relationships working. I can post code to GitHub if anyone would like to see more context.

I think these lines still need to be in your main sketch file (in addition to being in your custom class file):
#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>

If I remember the Arduino IDE quirks correctly, it uses the #include directives in the main sketch file to determine which libraries to actually link. It's one of those annoying features that was intended to be beginner-friendly but sometimes just makes things more confusing.

Thanks for the answer. I tried this, but then I get a ton of redefinition and previous definition errors. If I wrap the Adafruit library in ifndef blocks, it works! Do you have any ideas why they wouldn't have put that in? It seems like good practice to do so.

@lawnmowerlatte - That's surprising. I can't see any reason that it wouldn't be there already.

If you used the serial port, Arduino sometimes causes confusion.
Close Arduino IDE and
delete files in folder C:/users/[your name]/AppData/Local/Temp/
Its working.
Regards


text:
Arduino interruption (on pin change)
I use the interrupt function to fill an array with values received from digitalRead().
void setup() {
    Serial.begin(115200);
    attachInterrupt(0, test_func, CHANGE);
}

void test_func() {
    if (digitalRead(pin) == HIGH) {
        test_array[x] = 1;
    } else if(digitalRead(pin) == LOW) {
        test_array[x] = 0;
    }
    x = x + 1;
}

That problem is that when I print test_array there are values like: 111 or 000.
As I understand it, if I use the CHANGE option in the attachInterrupt() function, then the data sequence should always be 0101010101 without repeating.
The data changes quite fast since it comes from a radio module.

Interrupts don't debounce the button. Are you using hardware debouncing?

Please post the complete code, including pin, x and test_array definition, and also loop() method; it would enable us to see if this can be a concurrency issue when accessing variables modified by test_func.

You should not digitalRead() twice in the ISR: think about what would happen if you get LOW on the first call and HIGH on the second. Instead, if (digitalRead(pin) == HIGH) ... else ...; or, better yet, this single-line ISR: test_array[x++] = digitalRead(pin);.

@EdgarBonet nice! +1 to that comment. I hope you don't mind I've added something to my answer to include what you've mentioned here. Also if you decide to put up your own answer including this detail then I'll remove my addition and give yours an up vote so you get the rep for it.

@Clayton Mills: I am preparing an (overly long and marginally tangential) answer, but you can keep your edit, it is perfectly fine with me.

Why are you doing this in the first place? The only reasonable expectation is that the array would have 1010101010 in it. Thus if it doesn't that is just measurement error. As Edgar Bonet ably explained, such error could happen with fast sequences.

As a sort of prologue to this overly long answer...
This question got me deeply captivated with the problem of interrupt
latency, to the point of losing sleep in counting cycles instead of
sheep. I am writing this response more for sharing my findings
than for just answering the question: most of this material may actually
not be at a level suitable for a proper answer. I hope it will be
useful, however, for readers that land here in search of solutions for
latency problems. The first few sections are expected to be useful to a
wide audience, including the original poster. Then, it gets hairy along
the way.
Clayton Mills already explained in his answer that there is some latency
in responding to interrupts. Here I will focus on quantifying the
latency (which is huge when using the Arduino libraries), and on the
means to minimize it. Most of what follows is specific to the hardware
of the Arduino Uno and similar boards.
Minimizing the interrupt latency on the Arduino
(or how to get from 99 down to 5 cycles)
I will use the original question as a working example, and restate the
problem in terms of interrupt latency. We have some external event that
triggers an interrupt (here: INT0 on pin change). We need to take some
action when the interrupt is triggered (here: read a digital input). The
problem is: there is some delay between the interrupt being triggered
and our taking the appropriate action. We call this delay "interrupt
latency". A long latency is detrimental in many situations. In this
particular example, the input signal may change during the delay, in
which case we get a faulty reading. There is nothing we can do to avoid
the delay: it is intrinsic to the way interrupts work. We can, however,
try to make it as short as possible, which should hopefully minimize the
bad consequences.
The first obvious thing we can do is take the time-critical action,
inside the interrupt handler, as soon as possible. This means calling
digitalRead() once (and only once) at the very beginning of the
handler. Here is the zeroth version of the program upon which we will
build:
#define INT_NUMBER 0
#define PIN_NUMBER 2    // interrupt 0 is on pin 2
#define MAX_COUNT  200

volatile uint8_t count_edges;  // count of signal edges
volatile uint8_t count_high;   // count of high levels

/* Interrupt handler. */
void read_pin()
{
    int pin_state = digitalRead(PIN_NUMBER);  // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (pin_state == HIGH) count_high++;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(INT_NUMBER, read_pin, CHANGE);
}

void loop()
{
    /* Wait for the interrupt handler to count MAX_COUNT edges. */
    while (count_edges < MAX_COUNT) { /* wait */ }

    /* Report result. */
    Serial.print("Counted ");
    Serial.print(count_high);
    Serial.print(" HIGH levels for ");
    Serial.print(count_edges);
    Serial.println(" edges");

    /* Count again. */
    count_high = 0;
    count_edges = 0;  // do this last to avoid race condition
}

I tested this program, and the subsequent versions, by sending it trains
of pulses of varying widths. There is enough spacing between the pulses
to ensure that no edge is missed: even if the falling edge is received
before the previous interrupt is done, the second interrupt request will
be put on hold and eventually serviced. If a pulse is shorter than the
interrupt latency, the program reads 0 on both edges. The reported
number of HIGH levels is then the percentage of correctly read pulses.
What happens when the interrupt is triggered?
Before trying to improve the code above, we will take a look at the
events that unfold right after the interrupt is triggered. The hardware
part of the story is told by the Atmel documentation. The software part,
by disassembling the binary.
Most of the time, the incoming interrupt is serviced right away. It may
happen, however, that the MCU (meaning "microcontroller") is in the
middle of some time-critical task, where interrupt servicing is
disabled. This is typically the case when it is already servicing
another interrupt. When this happens, the incoming interrupt request is
put on hold and serviced only when that time-critical section is done.
This situation is hard to avoid completely, because there are quite a
few of those critical sections in the Arduino core library (which I will
call "libcore" in the following). Fortunately, these sections are
short and run only every so often. Thus, most of the time, our interrupt
request will be serviced right away. In the following, I will assume
that we do not care about those few instances when this is not the case.
Then, our request is serviced immediately. This still involves a lot of
stuff that can take quite a while. First, there is a hardwired sequence.
The MCU will finish executing the current instruction. Fortunately, most
instructions are single-cycle, but some can take up to four cycles.
Then, the MCU clears an internal flag that disables further servicing of
interrupts. This is intended to prevent nested interrupts. Then, the PC
is saved into the stack. The stack is an area of RAM reserved for this
kind of temporary storage. The PC (meaning "Program Counter") is an
internal register holding the address of the next instruction the MCU is
about to execute. This is what allows the MCU to know what to do next,
and saving it is essential because it will have to be restored in order
for the main program to resume from where it was interrupted. The PC is
then loaded with a hardwired address specific to the request received,
and this is the end of the hardwired sequence, the rest being
software-controlled.
The MCU now executes the instruction from that hardwired address. This
instruction is called an "interrupt vector", and is generally a "jump"
instruction that will bring us to a special routine called an ISR
("Interrupt Service Routine"). In this case, the ISR is called
"__vector_1", a.k.a. "INT0_vect", which is a misnomer because it is
an ISR, not a vector. This particular ISR comes from libcore. Like any
ISR, it starts with a prologue that saves a bunch of internal CPU
registers on the stack. This will allow it to use those registers and,
when it is done, restore them to their previous values in order not to
disturb the main program. Then, it will look for the interrupt handler
that was registered with attachInterrupt(), and it will call that
handler, which is our read_pin() function above. Our function will
then call digitalRead() from libcore. digitalRead() will look into
some tables in order to map the Arduino port number to the hardware I/O
port it has to read and the associated bit number to test. It will also
check whether there is a PWM channel on that pin that would need to be
disabled. It will then read the I/O port... and we are done. Well, we
are not really done servicing the interrupt, but the time-critical task
(reading the I/O port) is done, and it is all that matters when we are
looking at latency.
Here is a short summary of all the above, together with the associated
delays in CPU cycles:

hardwired sequence: finish current instruction, prevent nested
interrupts, save PC, load address of vector (≥ 4 cycles)
execute interrupt vector: jump to ISR (3 cycles)
ISR prologue: save registers (32 cycles)
ISR main body: locate and call user-registered function (13 cycles)
read_pin: call digitalRead (5 cycles)
digitalRead: find the relevant port and bit to test (41 cycles)
digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the
hardwired sequence. This gives us a total latency of 99 cycles, or
about 6.2 µs with a 16 MHz clock. In the following, I will
explore some tricks that can be used to lower this latency. They come
roughly in increasing order of complexity, but they all need us to
somehow dig into the internals of the MCU.
Use direct port access
The obvious first target for shortening the latency is digitalRead().
This function provides a nice abstraction to the MCU hardware, but it is
too inefficient for time-critical work. Getting rid of this one is
actually trivial: we just have to replace it with digitalReadFast(),
from the digitalwritefast
library. This cuts the latency almost by half at the cost of a small
download!
Well, that was too easy to be any fun, I will rather show you how to do
it the hard way. The purpose is to get us started into low-level stuff.
The method is called "direct port access" and is nicely documented on
the Arduino reference at the page on Port
Registers. At this
point, it is a good idea to download and take a look at the ATmega328P
datasheet.
This 650-page document may seem somewhat daunting at first look. It is,
however, well organised into sections specific to each of the MCU
peripherals and features. And we only need to check the sections
relevant to what we are doing. In this case, it is the section named
I/O ports. Here is a summary of what we learn from those readings:

The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the
AVR chip.
We get the whole port D at once by reading a special MCU register called
"PIND".
We then check bit number 2 by doing a bitwise logical and (the C ‘&’
operator) with 1 << 2.

So, here is our modified interrupt handler:
#define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
#define PIN_BIT    2

/* Interrupt handler. */
void read_pin()
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Now, our handler will read the I/O register as soon as it is called. The
latency is 53 CPU cycles. This simple trick saved us 46 cycles!
Write your own ISR
The next target for cycle-trimming is the INT0_vect ISR. This ISR is
needed for providing the functionality of attachInterrupt(): we can
change interrupt handlers at any time during program execution. However,
although nice to have, this is not really useful for our purpose. Thus,
instead of having the libcore's ISR locate and call our interrupt
handler, we will save a few cycles by replacing the ISR by our
handler.
This is not as hard as it sounds. ISRs can be written like normal
functions, we just have to be aware of their specific names, and define
them using a special ISR() macro from avr-libc. At this point it would
be good to have a look at the avr-libc's documentation on
interrupts,
and at the datasheet section named External Interrupts. Here is the
short summary:

We have to write a bit in a special hardware register called EICRA
(External Interrupt Control Register A) in order to configure the
interrupt to be triggered on any change of the pin value. This will be
done in setup().
We have to write a bit in another hardware register called EIMSK
(External Interrupt MaSK register) in order to enable the INT0
interrupt. This will also be done in setup().
We have to define the ISR with the syntax ISR(INT0_vect) { ... }.

Here is the code for the ISR and setup(), everything else is
unchanged:
/* Interrupt service routine for INT0. */
ISR(INT0_vect)
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

void setup()
{
    Serial.begin(9600);
    EICRA = 1 << ISC00;  // sense any change on the INT0 pin
    EIMSK = 1 << INT0;   // enable INT0 interrupt
}

This comes with a free bonus: since this ISR is simpler than the one it
replaces, it needs less registers to do its job, then the
register-saving prologue is shorter. Now we are down to a latency of 20
cycles. Not bad considering that we started close to 100!
At this point I would say we are done. Mission accomplished. What
follows is only for those who are not afraid of getting their hands
dirty with some AVR assembly. Otherwise you can stop reading here, and
thank-you for getting so far.
Write a naked ISR
Still here? Good! For proceeding further, it would be helpful to have at
least some very basic idea of how assembly works, and to take a look at
the Inline Assembler
Cookbook
from the avr-libc documentation. At this point, our interrupt entry
sequence looks like this:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR prologue: save regs (12 cycles)
first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into
the prologue. The idea is the following: reading the PIND register will
clobber one CPU register, thus we need to save at least one register
before doing that, but the other registers can wait. We then need to
write a custom prologue that reads the I/O port right after saving the
first register. You have already seen in the avr-libc interrupt
documentation (you have read it, right?) that an ISR can be made
naked, in which case the compiler will emit no prologue or epilogue,
allowing us to write our own custom version.
The problem with this approach is that we will probably end up writing
the whole ISR in assembly. Not a big deal, but I would rather have the
compiler write those boring prologues and epilogues for me. So, here is
the dirty trick: we will split the ISR in two parts:

the first part will be a short assembly fragment that will

save a single register to the stack
read PIND into that register
store that value into a global variable
restore the register from the stack
jump to the second part

the second part will be regular C code with compiler-generated
prologue and epilogue

Our previous INT0 ISR is then replaced by this:
volatile uint8_t sampled_pin;    // this is now a global variable

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    push r0                \n"  // save register r0
    "    in r0, %[pin]          \n"  // read PIND into r0
    "    sts sampled_pin, r0    \n"  // store r0 in a global
    "    pop r0                 \n"  // restore previous r0
    "    rjmp INT0_vect_part_2  \n"  // go to part 2
    :: [pin] "I" (_SFR_IO_ADDR(PIND)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Here we are using the ISR() macro to have the compiler instrument
INT0_vect_part_2 with the required prologue and epilogue. The compiler
will complain that "‘INT0_vect_part_2’ appears to be a misspelled
signal handler", but the warning can be safely ignored. Now the ISR has
a single 2-cycle instruction before the actual port read, and the total
latency is only 10 cycles.
Use the GPIOR0 register
What if we could have a register reserved for this specific job? Then,
we would not need save anything before reading the port. We can actually
ask the compiler to bind a global variable to a
register.
This, however, would require us to recompile the whole Arduino core and
libc in order to make sure the register is always reserved. Not really
convenient. On the other hand, the ATmega328P happens to have three
registers that are not used by the compiler nor any library, and are
available for storing whatever we want. They are called GPIOR0, GPIOR1
and GPIOR2 (General Purpose I/O Registers). Although they are mapped
in the I/O address space of the MCU, these are actually not I/O
registers: they are just plain memory, like three bytes of RAM that
somehow got lost in a bus and ended up in the wrong address space. These
are not as capable as the internal CPU registers, and we cannot copy
PIND into one of these with the in instruction. GPIOR0 is interesting,
though, in that it is bit-addressable, just like PIND. This will allow
us to transfer the information without clobbering any internal CPU
register.
Here is the trick: we will make sure that GPIOR0 is initially zero (it
is actually cleared by hardware at boot time), then we will use the
sbic (Skip next instruction if some Bit in some I/o register is Clear)
and the sbi (Set to 1 some Bit in some I/o register) instructions as
follows:
sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted
to read from PIND. The sbic instruction takes 1 or 2 cycles to execute
depending on whether the condition is false or true. Obviously, the PIND
bit is accessed on the first cycle. In this new version of the code, the
global variable sampled_pin is not useful anymore, since it is
basically replaced by GPIOR0:
/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    sbic %[pin], %[bit]    \n"
    "    sbi %[gpio], 0         \n"
    "    rjmp INT0_vect_part_2  \n"
    :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
       [bit]  "I" (PIN_BIT),
       [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

It should be noted that GPIOR0 has to always be reset in the ISR.
Now, the sampling of the PIND I/O register is the very first thing done
inside the ISR. Total latency is 8 cycles. This is about the best we can
do before getting stained with terribly sinful kludges. This is again a
good opportunity to stop reading...
Put the time-critical code in the vector table
For those still here, here is our current situation:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could
shorten the latency at this point is by replacing the interrupt vector
itself by our code. Be warned that this should be immensely distasteful
to anyone who values clean software design. But it is possible, and I
will show you how.
The layout of the ATmega328P vector table can be found in the datasheet,
section Interrupts, subsection Interrupt Vectors in ATmega328 and
ATmega328P. Or by disassembling any program for this chip. Here is how
it looks like. I am using avr-gcc and avr-libc's conventions (__init
is vector 0, addresses are in bytes) which are different from Atmel's.
address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

Each vector has a 4-byte slot, filled with a single jmp instruction.
This is a 32-bit instruction, unlike most AVR instructions which are
16-bit. But a 32-bit slot is too small to hold the first part of our
ISR: we can fit the sbic and sbi instructions, but not the rjmp.
If we do that, the vector table ends up looking like this:
address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ sbic PIND, 2    │ the first part...
 0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

When INT0 fires, PIND will be read, the relevant bit will be copied into
GPIOR0, and then the execution will fall through to the next vector.
Then, the ISR for INT1 will be called, instead of the ISR for INT0. This
is creepy, but since we are not using INT1 anyway, we will just "hijack"
its vector for servicing INT0.
Now, we just have to write our own custom vector table to override the
default one. It turns out it is not so easy. The default vector table is
provided by the avr-libc distribution, in an object file called
crtm328p.o that is automatically linked with any program we build.
Unlike library code, object-file code is not meant to be overridden:
trying to do that will give a linker error about the table being defined
twice. This means we have to replace the whole crtm328p.o with our
custom version. One option is to download the full avr-libc source
code, do our
custom modifications in
gcrt1.S,
then build this as a custom libc.
Here I went for a lighter, alternative approach. I wrote a custom
crt.S, which is a simplified version of the original from avr-libc. It
lacks a few rarely used features, like the ability to define a "catch
all" ISR, or to be able to terminate the program (i.e. freeze the
Arduino) by calling exit(). Here is the code. I trimmed the repetitive
part of the vector table in order to minimize scrolling:
#include <avr/io.h>

.weak __heap_end
.set  __heap_end, 0

.macro vector name
    .weak \name
    .set \name, __vectors
    jmp \name
.endm

.section .vectors
__vectors:
    jmp __init
    sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
    sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
    vector __vector_2
    vector __vector_3
    [...and so forth until...]
    vector __vector_25

.section .init2
__init:
    clr r1
    out _SFR_IO_ADDR(SREG), r1
    ldi r28, lo8(RAMEND)
    ldi r29, hi8(RAMEND)
    out _SFR_IO_ADDR(SPL), r28
    out _SFR_IO_ADDR(SPH), r29

.section .init9
    jmp main

It can be compiled with the following command line:
avr-gcc -c -mmcu=atmega328p silly-crt.S

The sketch is identical to the previous one except that there is no
INT0_vect, and INT0_vect_part_2 is replaced by INT1_vect:
/* Interrupt service routine for INT1 hijacked to service INT0. */
ISR(INT1_vect)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

To compile the sketch, we need a custom compile command. If you have
followed so far, you probably know how to compile from the command line.
You have to explicitly request silly-crt.o to be linked to your program,
and add the -nostartfiles option to avoid linking in the original
crtm328p.o.
Now, the reading of the I/O port is the very first instruction executed
after the interrupt triggers. I tested this version by sending it short
pulses from another Arduino, and it can catch (although not reliably)
the high level of pulses as short as 5 cycles. There is nothing more we
can do to shorten the interrupt latency on this hardware.

Good explanation! +1

(For a future edit: 1) "loosing sleep" → "losing sleep" 2) "Skip next" → "skip next". Otherwise excellent writing. The (misleading) indentation in the code in the question could be fixed at the same time.)

@PeterMortensen: Thanks for the correction! I kept the Uppercase “S” in “Skip next” in order to show where the acronym sbic comes from.

...Some say he's still optimizing that interrupt vector to this day...

The interrupt is being set to fire on a change, and your test_func is set as the Interrupt Service Routine (ISR), called to service that interrupt. The ISR then prints the value of the input.
At first glance you would expect the output to be as you have said, and alternating set of high lows, as it only gets to the ISR on a change.
But what we're missing is that there is a certain amount of time that it takes for the CPU to service an interrupt and branch to the ISR.
During this time the voltage on the pin may have changed again. Particularly if the pin is not stabilised by hardware de-bouncing or similar. Because the interrupt is already flagged and hasn't been serviced yet, this extra change (or many of them, because a pins level can change very quickly relative to the clock speed if it has low parasitic capacitance) will be missed.
So in essence without some form of de-bouncing, we have no guarantee that when the input changes, and the interrupt gets marked for servicing, that the input will still be at the same value when we get to reading its value in the ISR.
As a generic example the ATmega328 Datasheet  used on the Arduino Uno details interrupt times in section 6.7.1 - "Interrupt Response Time". It states for this microcontroller the minimum time to branch to an ISR for servicing is 4 clock cycles, but can be more (extra if executing multi-cycle instruction at interrupt or 8 + sleep wake time if the MCU is in sleep.)
As @EdgarBonet mentioned in comments, the pin could also similarly change during ISR execution. Because the ISR reads from the pin twice, it would not add anything to the test_array if it encountered a LOW on the first read and a HIGH on the second. But x would still increment, leaving that slot in the array unchanged (possibly as uninitialised data depending on what was done to the array earlier).
His one line ISR of test_array[x++] = digitalRead(pin); is a perfect solution to this.

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


text:
What kind of Arduino should I pick for a calculator?
I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.
However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 + - / * keys.
I am a real newbie when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.
I want to do something more than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.
P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).

For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.
The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.
That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.
For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.
When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.
If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.

Correction: The Yun does have an AVR MCU.

It has a 32u4 for IO, but the atheros MIPS chip @400 MHz would be used for the calculations.

Any Arduino (I would start with the UNO) will be sufficient to make a calculator similar to the regular HP or TI calculator product line.
For the keypad, you will need to buy an I2C compatible keypad and connect it to the I2C lines. For the screen there is an LCD shield.
You will not need to code anything in assembly. You can write cpp code using the libraries provided with the Arduino.

Much more like a matrix keyboard than an i2c one.


text:
Issue with usbserial for arduino clone
I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5
I have sourced the solution from
http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html
Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"
and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution
This is the board:

I bought the board from this site:
http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html
screenshot from the IDE does now show any usbserial

It looks like the device node for a ch340 on a Mac should be of the form tty.wchusbserial### - at least that is what the screenshot is showing at http://www.codenuke.net/2015/01/nodemcu-install-ch340-usb-to-serial-for-yosemite.html

You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:
sudo nvram boot-args="kext-dev-mode=1"
I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.

This may be better asked on http://apple.stackexchange.com
At the terminal run ioreg -p IOUSB then plug in the Arduino and see what changed.
On my Mac the setting is serial.port=/dev/tty.usbmodemfa131

A genuine UNO with an ATmega16u2 implement USB CDC will have a device node of that form, yes.  But that is not what the poster is connecting.  They are using something based on a ch340 chip instead.

@ChrisStratton and if the OP posted the ouyput of ioreg -p IOUSB we would know which chip.


text:
Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino
I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

Did you include a fixed resistor to form a voltage divider network with the velostat?

You need to use a matching resistance to create a voltage divider.

Could you put some more details on your answer? Maybe the OP does not know what a voltage divider is?

I am using 10k resisrtor to form a voltage divider circuit at the end


text:
How can I obtain the .hex of a file
I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY_USERNAME\Local Settings\Temp".
Where can I obtain the .hex of any file I have compiled, and how?

Have you tried enabling verbose compilation?

@IgnacioVazquez-Abrams - Yes: I know what the build is called and its location whilst I upload, but after I have uploaded, nothing.

Compile the sketch and in log it is shown where the hex is stored. Then you have to copy from there, because its in temporary

As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)
Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file.  Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running.  Change the line
preproc.save_build_files=false

to
preproc.save_build_files=true

so the .hex files in the temporary directory have a better chance of sticking around.
(I'm not able to test this suggestion on an MS-Windows system.  On my Linux system most build files stick around anyway in /tmp/)


text:
Fancy Arduino IDE
Do you know an IDE that is Arduino compatible, with:

Black background; white hurts my eyes.
Some auto completion features maybe?
And also one that lets you minimise brackets. Xcode like.
A better console...
Something to clear the serial console.
A breadboard view.

Something fancy!

You can use any IDE you want; anything fancy as you describe should have a way to define your own build system, so you can just use the makefile or scons or ino or your own shell script. As for the serial console, you will probably just have to deal with it not being built in to a single, monolithic IDE.

Have a look at Fritzing. I don't know how much you can customize there, but it has a whole suite where you can design hardware, write code, and even order PCB if you want to.

I believe Eclipse can do everything you mentioned except for showing hardware layouts. The appearance of editor windows is customizable. If, by minimizing brackets, you mean collapsing them ("just indicate that something is here; I don't want to see the content"), Eclipse does that too. You can clear the console, but I don't know what "better" features you mean so I can't answer that part. It can take some setting up to get it working for you but it's far and away more powerful and feature-filled than the basic Arduino IDE. It is probably the most used IDE by people who look to upgrade from the basic one.
Update:
While it doesn't directly show hardware layouts, it does know about opening files with their default applications. If you put a Fritzing file in your project folder, when you click on it, Eclipse will launch Fritzing. If you put an image file such as a screenshot of the board layout, it will even open that within the IDE.


text:
getting simple socketIO server to work with MRAA library on Edison
I spent the last week working with the CylonJS framework on my edison using a Maxbotix sensor.
Everyting works with a web client on the front end.
However at the last moment I can't get the edison to talk to an existing AIR client which I must use.
Something to do with how socketIO is implemented in Cylon.
The following simple socketIO server works for me. What I need to do is incorporate support for the mraa library and get analogue input from the Maxbotix sensor.
Can anyone please help? I'm up against a deadline!!!
var express = require('express');
    var app = express();
    var server = require('http').createServer(app);
    var io = require('socket.io').listen(server,{transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
     var port = Number(8080);
    server.listen(port);
     app.use(express.static(__dirname + '/'));
     var temp;
     var _this = this;
     io.on('connection', function (socket) {
      console.log('connection '+socket)
     socket.on("data",function(d){console.log('data from flash: ',d);});
      socket.emit("message","wtfwtwftwftwf hello from server");
      socket.on('disconnect', function (socket) {
      console.log("disconnect");
  });

  console.log('_this ='+_this);
  _this.socket=socket;

});


text:
Arduino Ethernet Shield vendor is null
I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with Fing and device Vendor name is null.
Can I change/set device Vendor?
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 106 };

void setup()
{
  Ethernet.begin(mac, ip);
}

The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.
Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.
And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.
Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.
If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.


text:
How do I listen for a sound that matches a pre-recorded sound?
I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.
I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).
The bell sounds kind of like this: bell sound

I would suggest a sound detector module and a timer to measure the length of the sound. If the duration is predictable this might be enough to discriminate from random sounds. Or if the bell is electronic, can you get access to the output wires and just detect a voltage?

I can't get access to the output wires, but I can place the detector within about 10 feet of the bell. Then I can listen for a certain volume level and once it reaches that level, i'll see if the duration remains for three seconds. This wouldn't be fool proof because there's background noise but it may work.

About the simplest starting point is to use an FFT (fast Fourier transform) library (like ArduinoFFT at openmusiclabs.com) to characterize the spectrum of an audio stream.
[Edit: An alternative method (digital bandpass filter) is mentioned below.]
Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.
The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.
The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.
If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• Comparing an audio signal with a previous 'taught/profiled' signal
• How do I compare chords played on a guitar with a known sample?
• How do I compare 2 audio files, returning a percentage of difference
• What does the phase of a FFT bin of an audio signal represent?
• Sound pattern matching using Fast Fourier Transform in Windows Phone
• How do I go about detecting whistles, pops and other sounds in live audio input?
• The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT
An alternative: digital bandpass filter
Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.
For theoretical background see wikipedia's Digital filter article.  Also see Vaseghi, Chapter 5, Digital Filters, (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
ECE438 digital filter design lecture notes
pdf file.
You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like
v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
freqz(v);
v

will compute coefficients for a Constrained L2 bandpass FIR filter, plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) Serial.write(buf, len) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use mkfilter to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.
Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second (1,2,3,4), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.

This is likely too involved an approach for the limited memory and computational resources of an Uno.  Unless the algorithm can be substantially simplified, it is likely the wrong platform for the job.

@ChrisStratton, I don't see Uno mentioned in question.  Also don't know that Uno is too limited for FFT.  But if so, consider an ATmega2560 Arduino board.  However, I plan to mention an alternate method.

@jwpat7 I will be using an Arduino Uno as it's the only one I have. The bell sounds kind of like this sound. Does that mean your second method will work better? Furthermore, would I need to figure out the frequency of the bell and then use the digital bandpass filter on the incomming sound to check for a match?

Ben, I added some paragraphs about development methods at the end, that may help you figure out answers to those questions.

@Chris Stratton's comment is on the mark. This would be a job for a DSP, not an Arduino.

@DaveP, (1) although Arduino floating point performance is pathetic, it probably is good enough to handle 3000-4000 ADC samples per second and then use a digital bandpass filter to detect occurrence of a 332 Hz tone (if the Uno does nothing else).  (2) If the problem is tougher (eg noisy environment, buzzy tone, additional processing needed) or if short development time and elegant methods are important, yes, a DSP board would make sense.  Ref 4 mentioned in last paragraph of answer says so several times.

Onban Arduino you would definitely want to do this with fixed point math.   More importantly though, if contemplating a software approach at all, the algorithm should first be proven satisfactory by running it on a PC using data from the sound card.  Otherwise inordinate amounts of time are likely to be wasted implementing something that may not be a useful solution on any hardware.


text:
How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals
I'd like to use Timer1 to measure the time between rising edges of two input signals.  Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal.  The goal is to measure the time between the rising edges of two input signals.   Is there a Timer1 library out there that alread does this?  Code suggestions welcomed.

What is the minimal expected duration between two consecutive rising edges of your signal?

// ICNC1: Enable Input Capture Noise Canceler // ICES1: =1 for trigger on rising edge // CS10: =1 set prescaler to 1x system clock (F_CPU) TCCR1A = 0; TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10); If I read this correctly (questionable), it looks like the everything is set backwards from what the text says it is supposed to be. Am I reading it wrong? Doesn't "(0<<ICNC1)" put a 0 into the ICNC1 bit? Doesn't that disable the noise canceler? This should be what you WANT for the purposes of catching every rising edge, but the explanation doesn't match the code. Also, doesn't "(0<<ICES1)" catch t

It is not perfect for your simpler task, but here is a link to a sketch that I have used to record pulses, using the Timer1 Input Capture.
In short setup the Interrupt
void initTimer(void) {

  // Input Capture setup
  // ICNC1: Enable Input Capture Noise Canceler
  // ICES1: =1 for trigger on rising edge
  // CS10: =1 set prescaler to 1x system clock (F_CPU)
  TCCR1A = 0;
  TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
  TCCR1C = 0;

  //catchFallingEdge(); // initialize to catch
  { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

  // Interrupt setup
  // ICIE1: Input capture
  // TOIE1: Timer1 overflow
  TIFR1 = (1<<ICF1) | (1<<TOV1);        // clear pending
  TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

  // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
  pinMode(8, INPUT);
  digitalWrite(8, 0);       // leave floating to count 60 Hz etc.
  //digitalWrite(8, 1);         // or enable the pullup
}

Then service it
ISR(TIMER1_CAPT_vect) {
  union twobyte {
    uint32_t word;
    uint8_t  byte[2];
  } timevalue;

  timevalue.byte[0] = ICR1L;        // grab captured timer value
  timevalue.byte[1] = ICR1H;        // grab captured timer value

  // watch for the other edge to catch the half-pulse width
  //rising ? catchFallingEdge() : catchRisingEdge();
  if (rising) {
    TCCR1B &= ~(1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 0;
  }
  else {
    TCCR1B |= (1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 1;
  }
}

For more help and info, and many examples of various detailed aspects of timers, check out Nick Gammon's articles here: http://www.gammon.com.au/interrupts
and here: http://www.gammon.com.au/timers
Under the first link, do a search for "The sketch below times intervals between RISING interrupts," for example, to find one code segment.
Now, important question: what is the minimum time you need to measure between events?  Are we talking milliseconds, microseconds, or nanoseconds?  For the former, you can use pin polling, external interrupts, or pin change interrupts, and the millis() or micros() Arduino functions to grab timestamps. For microseconds resolution, it depends. Even the micros() function only has a 4us resolution, so you'd have to custom-configure the timer if you want better than 4us resolution time-stamps, or you could use the timer2_counter library (http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html), or your own custom timer solution, for 0.5us resolution timestamps.
For nanosecond resolution (down to 62.5ns time steps), youd prob. need to use Timer1's input capture, as the other answer shows. You can also do a search for "Timing an interval using the input capture unit" under the 2nd link above, for another code segment on that.


text:
Arduino UNO + CC3000 Wifi Shield, Reading webpage data
I'm new so I might be making a stupid mistake, but I'm declaring:
char dollars;
at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.
The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.
here is the important part of my code:
unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      dollars = www.read();
      lastRead = millis();
    }
  }

  www.close();
  Serial.println(dollars);

while the www.read is repeating each of the returned characters it works fine Serial.print(c); but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?
I'm planning to show that number from the web page onto my 4 digit screen at the end.

You are going to have to go more in depth with your char variable. I know what you are trying to do, and I have seen it fail before, but I remember there was one solution. The read method needs to be built on and you have to be more specific. It would be amazing if you could post the rest of the code.

Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like Serial.parseInt() does.
You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


text:
Am I Running Out of RAM Or Not?
I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.
However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?
My code:
#include "FastLED.h"
#include <MemoryFree.h>

const byte ledsPin = 3;
const byte sensorPin = A1;

const int numLeds = 300;
const int ledTime = 1000;

const int sensorMin = 0;
const int sensorMax = 512;

const CRGB correction = CRGB(80,255,70); // Cool white
//const CRGB correction = CRGB(160,255,20); // Warm white
const byte hOffset = 170; // baseline hue value
const int8_t hDirection = -1; // 1 or -1, direction of rainbow
const byte s = 255; // saturation (colorfulness)
const byte v = 255; // value (brightness)

const unsigned int arrayLength = numLeds+1;
byte hues[arrayLength];

CRGB leds[numLeds];
byte h = 0; // hue (color)

unsigned long sensorSum;
unsigned int loopCounter;
unsigned int arrayCounterLed;
unsigned int updatesPerLed;
char sp = ' ';
int arrayCounter;

unsigned long time;
unsigned long timeNextLed;
unsigned long timeLeft;
unsigned long time1;
byte route;

void setup() {
  FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
  FastLED.setDither(0);
  pinMode(ledsPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(10);
  time=millis();
  sensorSum += analogRead(sensorPin);
  loopCounter++;
  if(time >= timeNextLed) {
    timeNextLed = (time/ledTime+1)*ledTime;
    arrayCounter = (arrayCounter +1) % (arrayLength);
    hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%256;
    updatesPerLed = loopCounter;
    loopCounter=0;
    sensorSum = 0;
  }
  for(int led = 0; led < numLeds; led++) {
    time1=micros();
    arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
    timeLeft = timeNextLed-time;
    byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
    if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
      h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
    }
    else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
      h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%256; // Causing flashing on red pixels?
    }
    else { // if it crosses through 0 backwards
      h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%256;
    }
    time1 = micros() - time1;
    if(led == 0) {
      Serial.print(dist);
      Serial.print(sp);
      Serial.print(route);
      Serial.print(sp);
      Serial.print(timeLeft);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]*timeLeft);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
      Serial.print(sp);
      Serial.println(h);
    }
    leds[led] = CHSV(h, s, v);
  }
  FastLED.show();
  Serial.print(updatesPerLed);
  Serial.print(time1);
  Serial.println();
}

int pseudoMod(int a, int b) {
  if(a<0) {
    return a+b;
  }
  else {
    return a;
  }
}

You're running out of memory.  An uno has enough memory to drive ~140 RGB LEDs.  Each LED needs 6 bytes. (i.e. Red 0-255, Green 0-255, and blue 0-255.  So to define one LED's color takes 6 bytes (i.e. #000000 thru #FFFFFF)

Wouldn't it be three bytes per LED?

Memfree does not lie. Either not measuring in depest place. Is it possible the object if led is being copied, just temporarily. Doubling used space. Also that chip does not have clock. Any stuttering can cause to string could latch. turn off interrupts. And or show code.

PLease post your code here, otherwise it is difficult to find out what in your program could potentially use more memory than you think, even for a short amount of time.

Alright, added my code. I did some testing to see exactly how many leds it can handle, which is 126. It seems too close to 128 to be coincidence, particularly considering the array to hold my sensor data has numLeds+1 indexes.

Welcome to Arduino SE! Questions that rely on external sites for context are not allowed on Stack Exchange, so I've copied your code into the question for your (and edited your comment to remove the link dependency). Thanks!

I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


text:
AT command XBee from atmega to disable DIO5 (associated led)
I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).
This is a part of my code:
#include <XBee.h>
XBee xbee = XBee();
uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
void setup()
{
delay(30000);
atRequest.setCommand(atdCmd);
xbee.send(atRequest);
}
void loop()
{}

...but it doesn't work!
Thanks guys!

Looks like you are using Xbee API https://code.google.com/p/xbee-api/
Have you tried putting your Xbee module into API mode? The value ATAP must be set to 1 or 2.

Thanks for aswer david! The API mode is set on mode 2 but doesn't work

In case .setCommand() needs a null-terminated string, try adding , \0 after '0' or use uint8_t *atdCmd = (uint8_t *)"ATD50"; to declare it, or char *atdCmd = "ATD50"; if the API allows.

Thank you Jwpat7, I try your recomendations, but it doesn't work, other tipps? ...maybe my command is wrong?

finally I solved the problem with this code:
uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"


text:
Arduino and ATtiny84 w/RF
I'm trying to send data from an ATtiny84 [1mhz] to Arduino Uno using a 433Mhz rf module and Manchester lib.
Now I came across a weird problem, no matter what value I transmit, When I receive it on the arduino and to the Serial monitor, it always shows value of 806,No matter what I have really transmitted.
ATtiny side
void setup()
{
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(transmit_pin, MAN_1200);
}

// And how I transmit
// RGBread is int, I also tried man.transmit((uint16_t)RGBread[i]); same result.
  for(int i=0; i<3; i++)
  {
    man.transmit(RGBread[i]);
  }

Uno
void setup()
{
  man.setupReceive(reciever_pin, MAN_1200);
  man.beginReceive();
}

  if (man.receiveComplete()) {
    Serial.println(man.getMessage());
    man.beginReceive(); //start listening for next message right after you retrieve the message
  }

Thanks to all helpers.

As a test, make your transmit value explicitly count in a loop to rule out problems with the ultimate data source.  Are you sure that man.getMessage() returns something meaningful for printing?  If you don't have a scope to validate the received data waveform, you could try substituting a direct connection for the RF modules.

The values are analogRead's returns.

I did tried to put my own inputs instead of that analogRead, 0 125 and 255 low mid and high, same results its all 806 on the reciever side.

Either substitute a direct connection for the RF modules and test that, or see if you can use a PC soundcard as a crude scope to examine the transmitted and received data signals.

Check what? And if you connect the reciever directly to a led, you can see it blinking all the time, lots of interference, but that's okay. You get what you paid for ;)- Thought it's the lib's job to make the link work right?

The library can't do anything unless there is signal in the noise, something you've yet to prove.  I'm still recommending you try a direct connection to verify that the transmitter and receiver are working, and at the same settings.


text:
Programing other Atmel ARM chips using Arduino
Ok, i know professionals generally hate Arduinos, but I would like to know if it would be possible to program Atmel ARM chips using the Arduino IDE. By which I mean, not needing to modify the source code, just add another entry into the "hardware" folder and that's it.
We already know the Atmel ATSAM3X8EA (Arduino DUE) is compattible, but how about a similar chip, like the Atmel ATSAM3X8CA. Or maybe a Cortex-M4 one, like the Atmel ATSAM4E16EA or the Atmel ATSAM4S8CA.
The Atmel ATSAM3X8CA is the closest one to the Atmel ATSAM3X8EA the Arduino Due uses, a bit smaller and with less I/O.
If it isn't possible without much source code modding, I would like to know what would it take to make it work.
Thanks for your answers.

I haven't use those chips in particular but I thought most of the newer / higher end ATSAM devices already have an in-built serial / USB bootloader. It might be worth taking a further look into that.

Why would Professionals "hate" Arduinos. Or any other system that has a job to do and does it well enough? No doubt a certain (or uncertain) subset of "proFesSionals" 'hate' Arduinos, but their motivations are sketchy and probably make no sense in the greater order of things. || It's a shame that the Arduinos makers chose to present it in a cutesy and hip-speakish manner, but that would be irrelevant to a Professional, who would evaluate the system in terms of aims and achievements and not be deterred by irrelevancies. Correct processing is in order if one is not to get one's wiring crossed.

My point exactly when I Try to explain to people the advantages of the Arduino platform. It has an objective and it accomplishes that objective perfectly, to give people an easy way of programming microcontrollers that doesn't require fiddling around with settings, fuses, pin declarations and so on. I'd like to bring that ease of use to other Atmel SAM chips, without removing the possibility of using, say, Atmel Studio as well to program them.

I'm voting to close this question as off-topic because it requires knowledge of non-Arduino Atmel parts and therefore belongs on EESE where it was originally and properly asked, not here.

@ChrisStratton not quite so: they're basically asking for ports of the Arduino core libraries/etc. for chips not used on a regular Arduino board.

...which is task which requires knowledge found there, rather than here.

Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.
It is fairly involved setup. In short; within each platform there are the following files:

boards.txt, defines the individual boards using the similar processor.
platform.txt, defines the compiler arguments
programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder.
I have not found an complete tutorial on the matter. However, their
Arduino IDE 1.5 3rd party Hardware specification
An overview of the platform architecture proposed for Arduino 1.5
are a great place to start.
I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.