text:
NeoPixel Ring Usage Without Arduino
I am looking at purchasing a NeoPixel Ring for a project, but need it to work without an Arduino. Once the NeoPixel has been programmed by the Arduino, will it function when powered without the Arduino? I am not looking at changing colors or anything, I want to set the LEDs to solid red and not change.
I have found in the Adafruit website that it says "NeoPixels don’t just light up on their own; they require a microcontroller (such as Arduino) and some programming." But is this only to get them working initially, or do they require an microcontroller permanently?

No, the settings for the colors are stored in RAM on the individual devices so they need to be reprogrammed every time they are powered on.
On the other hand, it is possible to use a much smaller device such as a surface-mount ATtiny85 to program them, and light_ws2812 runs on said device just fine. And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power.

"And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power." -- Why bother when the MCU running flat out consumes about 0.0001% the power of the average ws2812 chain?

I recently completed a project using one of these LED rings. I knew these were normally used with an arduino for control, but at the time I was still testing things, so I decided to buy one and mess with it.
I soldered a standard 3-pin ARGB cable to the 5v, GRN, and Data In to the ring and connected it to one of the argb headers on my PC. The results were as follows:

The ring did light up and stayed illuminated with the PC.

The ARGB header was connected to a splitter which came from a ASUS motherboard header.

Armoury Crate (ASUS’s argb software) was already set up on my computer and this software was what was sending signal to the ring via a splitter.

There were SOME LEDs on the ring that behaved as expected based on the colors and pattern set up in Armoury Crate. However, some LEDs although we’re illuminated, we’re flashing various colors that didn’t match to how it was set up in Armoury Crate.

Take aways:
These NeoPixel rings DO work without an arduino in terms in terms of receiving voltage and lighting up. However, because of how these are programmed they may not behave as expected or intended if connected to a non-arduino controller.
For my application, the multi-color pattern ended up looking nice, so I decided to keep it as is.


text:
How can I make my Arduino code work?
I am trying to make an automatic lock which stays open during different times and on different days. I want the door open Monday through Friday 8am to 5pm. On Saturdays and Sundays I want the door locked. I will be using an electric lock strike the + wire to pin 9 and - to ground on arduino. I am using an LED for development purposes for now because I don't have the lock yet. The code I have now works (stays open) for 8am to 5pm through the whole week but i want the door locked for Saturdays and Sundays. This is my code so far:
#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if (hour()>=8 && hour()<=17){
  digitalWrite(doorPin, HIGH);
}
else if (weekday()==1 || weekday()==7){
  digitalWrite(doorPin, LOW);
}

This is what's happening: it's still between 8 AM and 5 PM on the weekend, so it unlocks it. Since you use an else if, it terminates the if statement and never checks the day between 8 and 5. I'm almost positive that if you checked it another time in the day, it'd be "locked."
Fixed code:
#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if ((hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7)){
  digitalWrite(doorPin, HIGH);
}
else {
  digitalWrite(doorPin, LOW);
}

Note: ! means "not." Thus, the door is locked only if it's not a weekend and it's between 8 and 5.
Additionally, you might want to get a lock that is the other way around: unlocked only with power applied so someone can't unplug the Arduino to get access. EDIT: miscommunication, ignore this part paragraph...

I'm sorry I meant open from Mon - Fri 8-5, locked on Sat - Sun. (The lock is unlocked with electricity)

@user the code should stay the same, just with a [slightly] different explanation.

Adding to Annonomus Penguin's answer, it might be cleaner and easier to understand if you extract the variable:
bool doorOpen = ( (hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7) );

Or in my eyes even nicer if you unnegate the last part, ymmv:
bool doorOpen = ( (hour()>=8 && hour()<=17) && (weekday()!=1 && weekday()!=7) );

And then use them directly in the code without the if statement:
digitalWrite( doorPin, doorOpen ? HIGH : LOW );

This way you make sure that the doorPin always gets set and you din't forget a path like in your if-elseif-nothing version.
Another benefit is you can test independently if the doorOpen variable is correct and if the functionality that is triggered by it is correct.

In that last Boolean expression, all of the parentheses other than the function calls are redundant and distracting. bool doorOpen = hour() >= 8 && hour() <= 17 && weekday() != 1 && weekday() != 7; is much clearer.

[As for the boolean statement change]: It's pretty much a personal preference, I personally think it flows better the way in my answer, but I'm pretty quirky! :-) However, a boolean directly is a good idea, +1 for that.

source: Stack Exchange

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

sort: votes


text:
How do I know the sampling frequency?
I am beginning to get a bit confused about sampling rates and baudrates etc. I have this Arduino code:
#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

Since there is no delay interrupt, what is the sampling rate/frequency? Is it based on the Arduino ADC speed? When I increase the baudrate am I increasing the sampling frequency or just the rate at which I send data over the serial port?

The Arduino ADC clock speed is set in ..arduino-1.5.5\hardware\arduino\avr\cores\arduino\wiring.c
Here is the relevant part
#if defined(ADCSRA)
    // Set A/D prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
    sbi(ADCSRA, ADPS1);
    sbi(ADCSRA, ADPS0);

    // Enable A/D conversions
    sbi(ADCSRA, ADEN);
#endif

For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz.
That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
Since you read the result and send it through the serial port, you are getting a delay that increases as the baud rate decreases. The lower the baud rate the longer it will take to send the same length of data and the longer it will take to call the next ADC conversion.
The actual sampling rate in your application can be determined with the use of a debugger or a simulator, but an easier solution is to toggle a digital pin every time you execute a conversion and measure the frequency that the digital pin toggles at.

Also, the time between my time stamps increases from ~1300 all the way up to ~16400, surely they should stay the same? That is at 9600, at 115200, they increase only to about 1500 after a lot of time.

@user3284376 regarding your time stamp code, I think it cannot work at all times (can be biased by some interrupts at the wrong time). I'd suggest you post a specific question about how to get high precision timing on Arduino and put the relevant part of your code there.

I also wanted to get a high sampling rate, for a project. turns out that the ADPS2,ADPS1,ADPS0 bits of the ADCSRA register can be configured to get a sampling rate of 76923 s/s or 76.8 ks/s. But, beware that I am running my arduino's ADC in free running mode, the following lines worked for me.
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup() {
// Set the Prescaler to 16 (16000KHz/16 = 1MHz)
// WARNING: Above 200KHz 10-bit results are not reliable.
//ADCSRA |= B00000100;
sbi(ADCSRA, ADPS2);
cbi(ADCSRA, ADPS1);
cbi(ADCSRA, ADPS0);

// Set ADIE in ADCSRA (0x7A) to enable the ADC interrupt.
// Without this, the internal interrupt will not trigger.
//ADCSRA |= B00001000;
sbi(ADCSRA,ADIE)
}

At this frequency the usual 10-bit results are not reliable. It means that increasing the sample rate will decrease the precision of the results. So I only use the upper 8 bits because at this prescalar the upper 8-bits are reliable. You can go into more detail on this page, this dude rocks! he made a high sample rate oscilloscpe using UNO http://www.instructables.com/id/Girino-Fast-Arduino-Oscilloscope/

I'm on an ATMEGA 2560, but I figured I'd copypaste in case this worked.  Once I replaced the calls to sbi and cbi with their definitions (my compiler didn't like them), AND commented out the last line, the quality of my stupid audio circuit improved massively.  Thanks!

Sending 11 bits over serial at a baud of 9600, but for the sampling, I store it in an array with as little delay as possible, then once it's done, I send it through the serial port to be read by a python script. I'm doing this for an FFT using matplotlib. I listen to a 0-5V signal, then without using the delay() function, I store the analogRead() values into that array. In a split second the reading is done, then the serial data dump starts. When I calibrated the input frequency using tone() from another connected Arduino, I realized that I had to divide the index by 8915 in order to get accuracy to within .1 Hz. Because one would have to divide by the frequency of the sampling to get the proper index intervals, my guess is the Arduino sampling frequency (at least mine with my code) is 8915Hz.

Each loop you are printing 8 characters over a 9600bps serial link. Each character takes 10 bits (1 start, 8 bits for the character, 1 stop). That means you can only go through this loop ~120 times/sec.
The analogRead() function can sample at about 9600 times/sec in theory, realistically it is about 8600 times/sec.
You are being bounded by the serial communication.

So increasing to 115200, gives 1440 times/sec, is that the sample rate?

Give or take, yes. You need to bear in mind that Serial requires that the other end responds, so you are dependent on the PC responding. This is not deterministic so you will get jitter.

You are right on the Arduino end of things, it all appears fine, but on Python things are much slower, what kind of things would I need to do to increase the performance on the computer end of things?

You need to not look at this as a problem with the serial performance on the PC, but how do you get the sampling to be decoupled from the sending of data.

@Cybergibbons - no, as this is running on an Uno where the USB and serial are decoupled, there is no dependence on the PC beyond issuing the 'S' character and not issuing the 'F' one.  The sketch posted here and platform on which it runs will happily throw serial data at the USB-serial companion micro, blindly oblivious if that or anything on the other end of the USB is keeping up.

Referring to the part about the difference between sample rate and baud rate, they are different measurements.
Sample Rate is the frequency at which the device (arduino) can recreate a digital representation of incoming analog values.
Baud Rate is the rate at which information is transferred in a communication channel. It describes the rate of communication between the microcontroller and the outside world (the computer).
I would recommend this electronics_stack_exchange link.
https://electronics.stackexchange.com/questions/135056/sampling-rate-data-rate-and-bandwidth

Have you considered getting A Saleae or similar logic analyzer. The simple inexpensive ones work great and allow you to make these measurements quite easily. This works better then a scope in most of my applications. If there is signal overlap it will show. I simply devote one pin for testing and call it testpin. Just set it high when starting the routine and then low when finished.  It has 8 inputs so you can see the relationship between signals. You could monitor the A/D, starting the trigger and place the serial on another pin. You still have 6 left for other things. Spend a few hours with it and it will become one of your most important tools. I use Linux Mint so I just keep it on another screen so a simple click brings it in view and it will run whether the window is in view or not. Be careful if you have unused inputs they will act as antenna and pick up stray signals especially from switching power supplies. Just select the channels you want or ignore the ones that are not relevant. The built in analyzers make short work of serial signals.

8915Hz - it is very close to 125000/14 ~= 8928.6
My initial guess that exactly one gap is required between adjacent conversions
One ADC clock for sampling and 13 ADC clocks for conversion itself.
Small error could be effect of not perfect clock source of Arduino.
I am not sure yet.
This topic is actual for me now as sampled data must feed digital filter.

I'm not sure what you mean when you say "This topic is actual for me now as sampled data must feed digital filter.". Are you having a similar problem?

Each conversion starts on a rising edge of the ADC clock, and at least one ADC clock cycle is lost executing code. So yes, 8928.6 Hz is the fastest you can get by calling analogRead() in a tight loop, v.s. a very consistent 9615.4 Hz in free-running mode.

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

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


text:
Arduino error message that I don't understand
I downloaded Arduino code from this: https://github.com/BabyWrassler/MissionControl/ Github, and got the  error message below.
It is designed to work with a Raspberry Pi, and I installed the two Adafruit libraries.  I also have not hooked it up to either the Pi, or the two Adafruit devices, but that is partly because I cannot get it to run without the error message.
Update:
Here is what was highlighted:
Adafruit_LEDBackpack matrixA = Adafruit_LEDBackpack();
The orange bar says:
    Variable or field ‘matrixOff‘ declared void
I cannot tell what of the following was from before, but here is the entire console log:
    mcDesk.ino:2:53: error: Adafruit_LEDBackpack.h: No such file or directory
    mcDesk.ino:3:45: error: Adafruit_GFX.h: No such file or directory
    mcDesk:11: error: variable or field 'matrixOff' declared void
    mcDesk:11: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:11: error: expected primary-expression before 'buffer'
    mcDesk:12: error: variable or field 'ledOn' declared void
    mcDesk:12: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:12: error: expected primary-expression before 'buffer'
    mcDesk:12: error: expected primary-expression before 'cat'
    mcDesk:12: error: expected primary-expression before 'an'
    mcDesk:13: error: variable or field 'ledOff' declared void
    mcDesk:13: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:13: error: expected primary-expression before 'buffer'
    mcDesk:13: error: expected primary-expression before 'cat'
    mcDesk:13: error: expected primary-expression before 'an'
    mcDesk:14: error: variable or field 'dispMat' declared void
    mcDesk:14: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:14: error: expected primary-expression before 'buffer'
    mcDesk:17: error: variable or field 'threeDigitDisp' declared void
    mcDesk:17: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:17: error: expected primary-expression before 'buffer'
    mcDesk:17: error: expected primary-expression before 'cats'
    mcDesk:17: error: expected primary-expression before 'ans'
    mcDesk:17: error: expected primary-expression before 'number'
    mcDesk:18: error: variable or field 'digitDisp' declared void
    mcDesk:18: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:18: error: expected primary-expression before 'buffer'
    mcDesk:18: error: expected primary-expression before 'pos'
    mcDesk:18: error: expected primary-expression before 'cat'
    mcDesk:18: error: expected primary-expression before 'an'
    mcDesk:18: error: expected primary-expression before 'num'
    mcDesk:23: error: variable or field 'switchBars' declared void
    mcDesk:23: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:23: error: expected primary-expression before 'buffer'
    mcDesk:23: error: expected primary-expression before 'grphCats'
    mcDesk:23: error: expected primary-expression before 'grphAns'
    mcDesk:23: error: expected primary-expression before 'cmnd'
    mcDesk:23: error: expected primary-expression before 'offset'
    mcDesk:24: error: variable or field 'barDisp' declared void
    mcDesk:24: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:24: error: expected primary-expression before 'buffer'
    mcDesk:24: error: expected primary-expression before 'grphCats'
    mcDesk:24: error: expected primary-expression before 'grphAns'
    mcDesk:24: error: expected primary-expression before 'pos'
    mcDesk:24: error: expected primary-expression before 'offset'
    mcDesk:25: error: variable or field 'cBarDisp' declared void
    mcDesk:25: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:25: error: expected primary-expression before 'buffer'
    mcDesk:25: error: expected primary-expression before 'grphCats'
    mcDesk:25: error: expected primary-expression before 'grphAns'
    mcDesk:25: error: expected primary-expression before 'pos'
    mcDesk:25: error: expected primary-expression before 'offset'
    mcDesk:11: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:12: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:13: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:14: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:15: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk.ino: In function 'void decodeCommand()':
    mcDesk:193: error: 'matrixE' was not declared in this scope
    mcDesk:193: error: 'ledOn' was not declared in this scope
    mcDesk:199: error: 'matrixE' was not declared in this scope
    mcDesk:199: error: 'ledOff' was not declared in this scope
    mcDesk:204: error: 'matrixC' was not declared in this scope
    mcDesk:204: error: 'cBarDisp' was not declared in this scope
    mcDesk.ino: In function 'void allMatrixOff()':
    mcDesk:213: error: 'matrixA' was not declared in this scope
    mcDesk:213: error: 'matrixOff' was not declared in this scope
    mcDesk:214: error: 'matrixB' was not declared in this scope
    mcDesk:215: error: 'matrixC' was not declared in this scope
    mcDesk:216: error: 'matrixD' was not declared in this scope
    mcDesk:217: error: 'matrixE' was not declared in this scope
    mcDesk.ino: At global scope:
    mcDesk:220: error: variable or field 'matrixOff' declared void
    mcDesk:220: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:220: error: expected primary-expression before 'buffer'

"Adafruit_LEDBackpack not declared" tells me maybe the library wasn't installed? Can you run one of the examples in that library? (File > Examples)

@sachleen which one?  Does it matter?

Printscreen is far clearer than taking a picture of the screen. Also put all of your code up on pastebin.

@cybergibbons sorry, I was using my iPad to make the post.  My Arduino computer doesn't have wifi on it.

Copy and paste the messages from the text below the code window, as well as the code section that has the error in it (the highlighted section). Try not to post images of code or error messages, when it is in plain text.

Don't use images to explain your problem. Nobody is ever going to find this question through a search engine because the text cannot be indexed and it uses much more resources than necessary. What is wrong with a regular copy and paste of the text?

It's hard because I don't have my Arduino computer connected to the internet.

Ok I figured out how to copy and paste it.   Adding all the spaces before each line took FOREVER but it is all on there now.

Those error messages are exactly the ones I get when the libraries aren't there and they go when the library is there.

The first 2 lines clearly show that you have not properly installed the 2 required adafruit libraries.

It seems to me that those Adafruit libraries were not correctly installed on your PC or your sketch.
In addition to downloading and installing the library onto the Arduino library directory (on Windows, that's normally C:\Users\UserName\Documents\Arduino\libraries), when you want to use that library with Arduino IDE, you must add the library for your sketch with the menu command "Sketch -> Import Library..."
Important note: it seems just adding #include "library.h" does not work with Arduino IDE, you absolutely need to use the menu.

I don't think I've ever used the menu to include a library - it definitely works just typing it in here.

@Cybergibbons I faced that problem a couple of times in the past (I almost never use Arduino IDE anymore though, except for quick qnd dirty proofs of concept), that's why I mentioned it here.

Interesting. The more I use the Arduino IDE, the more I dislike it.

I tried that, but still got the exact same error message. @cybergibbons + jfproilpret

I agree with Cybergibbons, you don't have to use the menu...


text:
How can I use Python from a sketch?
I'd like to be able to use Python from a sketch. According to the Arduino playground, one can use PySerial from a computer to talk with an Arduino via Python.
It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.
If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a .py script from a computer or from anything on the Arduino.

It's not an Arduino board, but you might be interested in Micro Python. It got kickstarted a few months back.

It looks like from that page you can also use various API's to execute
  Python directly on the Arduino.

I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.
You'd need a python interpreter to be able to run python on the Arduino. There is the Python On A Chip project and it seems like they have support for the Mega.

2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.

Some more info from the PyMite page:

any device in the AtMega family which meets these requirements: 20KiB
  Flash and 4K RAM, will run today

I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.

According to the python-on-a-chip website, you need at least 8 kB of ram to run a normal program

Hmm, so basically your options are to either execute Python from a computer, somehow use the Python On A Chip project with an Arduino, or just execute native C\C++ code? Interesting...


text:
What is the difference between the revisions of the Arduino Uno board?
There are three different revisions of the Arduino Uno. What changed in each revision?

UPDATE: I was given an UNO by my son which has A6 and A7 wired out to J2 pins 9 and 1. The normal size of J2 is 8 pins while this version has J2 and J3 combined as a single component. My best guess is that he bought this off an official Arduino site since that would be his philosophy plus the board says it is made in Italy. I took a photo but my wifi is not letting my cell phone connect to upload the photo right now. >:(

Here is a summary from the official site:

Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to
ground, making it easier to put into DFU mode.
Revision 3 of the board has the following new features:

1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that
allow the shields to adapt to the voltage provided from the board. In
future, shields will be compatible with both the board that uses the
AVR, which operates with 5V and with the Arduino Due that operates
with 3.3V. The second one is a not connected pin, that is reserved for
future purposes.
Stronger RESET circuit.
Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found here.
R2:

The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees.

Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA."

Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP.

An LED connected to pin 13 was added. It turns on when pin 13 is HIGH, off when LOW.

The main microchip was changed from an ATmega168 to an ATmega328.

A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.

R3:

The rotation of the ATMEGA8U2 was changed back by 45 degrees.
The ATMEGA8U2 was changed to an ATMEGA16U2.
A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.

The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.

User Side Changes

Both revision 2 and 3 boards add four solder pads (JP2) connecting to pins PB4 to PB7 of the USB ATMEGA.
Revision 2 and 3 boards are both supplied with header pins in the USB ATMEGA ICSP header rather than just solder pads in the Arduino Uno.
The revision 3 board changes the 8 pin connector that contains Arduino pins 8 to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. These are the two analog input pins that can be used for I2C.
Revision 3 boards change the 6 pin connector that has the reset pin connected to it to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is reserved for future use.

Electronics Based Changes

The Arduino Uno and Arduino Uno revision 2 both have an ATMEGA8U2 USB microcontroller on board – this is upgraded to an ATMEGA16U2 on the revision 3 board.
Revision 3 adds a diode across the USB ATMEGA reset pin pull-up resistor.
Both revision 2 and 3 boards add a 1k pull-down resistor to the DTR (HWB) line coming from the USB ATMEGA microcontroller – from the PD7 pin.
The Arduino Uno and Arduino Uno revision 2 both have a LED and resistor connected in series on Arduino pin 13. The revision 3 board buffers this LED/resistor through a unity gain op-amp. This is the spare op-amp that was unused on previous boards.

Sources:

http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/


text:
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup?
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup? Like so:
// Simplest tone
void setup() {
}

void loop() {
    tone (8,500); //on pin 8 output 500 Hz
}

Because the tone(hertz) code initializes the pinmode, along with the timer/counter control registers to produce the appropriate frequency.
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
{
  uint8_t prescalarbits = 0b001;
  long toggle_count = 0;
  uint32_t ocr = 0;
  int8_t _timer;

  _timer = toneBegin(_pin);

  if (_timer >= 0)
  {
    // Set the pinMode as OUTPUT
    pinMode(_pin, OUTPUT);
   ...

See Tone.cpp - line 255 for the source.


text:
Arduino Yun external antenna
Can someone help me understand how the external antenna IPX connector actually stays connected to the Yun? Do I have to "force" it in so it snaps in? I've been somewhat gentle with it in fear I'll break something. However when I get close to getting it in, it just pops back out.
I've never worked with an IPX connector before, and I'm trying to not break anything.
EDIT: I may have figured this out. Looks like the socket on the Yun is an IPEX socket, which is female. The cable I have is an IPX/uFL/u.FL connector, which also appears to be female.
It looks like I need to use an MCX cable adapter as found here: http://www.adafruit.com/products/1532 If someone could confirm this for me, that'd be great.
Here's a picture of the cable I purchased and my Yun.

If you can confirm that you've figured it out, could you add your solution as an answer? That will make it a bit easier for future visitors to find. Thanks!

@Brodie I haven't purchased it yet, however this project has gained steam this week, so it might be ordered soon. Looking back at it again, I think it's the right connector, but can't confirm first-hand (yet)

I think what @Gianni72 said is correct.  This Digikey presentation has a nice animation showing how an RF Switch Connector works.  This type of operation would make sense on the Yùn, since it would automatically (mechanically) switch the signal route from the internal antenna to the external one.

There's a discussion on the Arduino Forum about this:
Mystery component on Yun board?
From what I read it's only for testing purposes.

the connector is a MM8430-2610 (see this). You can plug in a
  MXGS83RK3000/MM126036: once plugged in, the switch connector will turn
  the internal antenna off and use the probe as an external antenna

I don't think I would call it testing purposes if the Arduino uses the "probe" as an external antenna. That seems like normal expected behavior for a device to turn off the internal antenna in favor of an external antenna. The PDF you linked may be onto something though with the validation of the MCX connector, and not the IPX connector I bought (pictured above).

Testing with my Yún, it took quite a bit of force to install the connector. I had to use pliers to get extra leverage, but it eventually snapped in place.

Did your cable look like mine in the photo? I think I may have bought a female cable (and the board connector is female) so I would have needed a male cable (I think).

@pat - Yep. you have the right cable. They don't look like they should fit, but they do

I went through this last night.  I got the adapter cable [ .../852] and antenna from Adafruit.
It appeared to be hard to snap into place, but it did go.
It did not improve performance though when testing signal strength with the Example>Bridge>WiFiStatus
Which leads me to believe that the connector didn't mate -or- I damaged it -or- it isn't the proper connector.
I am thinking the latter is the case.
Still looking for the answer.
Jim
I bought:
1 ea.     RP-SMA to uFL/u.FL/IPX/IPEX RF Adapter Cable     $3.95
http://www.adafruit.com/products/852
1 ea.     2.4GHz Dipole Swivel Antenna with RP-SMA - 5dBi     $8.95
http://www.adafruit.com/products/945

Thanks. That's the cable I have [.../852], and it doesn't work either. I think that's a female connector because of the way it looks. I think I need to purchase this male connector. http://www.adafruit.com/products/1532 - I haven't tried it yet though

I have several old mini-pci mini-pcie wifi cards laying around and the poster is correct: for some reason, they put the female end on the board whereas any wifi antenna you pull from a laptop, the cable will be female; all of my cards are the male version of the port on the YUN.
I can actually snap my old wifi cards onto the YUN's antenna port and they snap together perfectly just like the cable does in the laptops they belong.
For hobbyists, an old laptop wifi antennas are something we all have.
Why they did this I don't know.

@Jim was very close, the /851 part is the female to work with that connector. I have an adafruit Flora GPS with the same thing, a male connector on the board. I asked Adafruit for the adapter lead for it and they said the SMA to uFL #851 was what I needed. I just tried it on my shield and it fits.


text:
What are some steps to attach an Arduino to an electric heater?
I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?
As you can see, it does have a start time, but it does not have a stop time.
The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green.
Where would a noob begin?
-EDIT-
The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

One important point to clarify: if you plug it out then plug it in again to main power (with the power cord), in which state is it, on (heating) or off (waiting for someone to push the on button)?

A lot of newer devices with soft switches like this, unfortunately, don't work when turned on. A step backwards.

@jfpoilpret The unit is always off when plugged back in. I've update the question.

Off when power returns is a failure mode with safety in mind. It would be wise to make sure your timer device replicates this behavior.

Easiest: External relay or solid state relay. Relay defaults on. A' (Arduino cct can detect current draw, turn relay off/on, be programmed to either stop time or run time). ||  Set external A' timer to desired time. A' sets relay ON. | Set heater to desired start time. When heater start A' sees current and starts timing, or in time of day mode just turns off power at correct time. || This keeps all circuitry external.

Would or should begin? Don't fiddle with the internals of the heater.
Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.
Use:

an RTC (real time clock) breakout to keep accurate time
optionally a 7 segment display to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
couple push buttons to configure the device
a relay rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be very careful when experimenting with mains power, it can be leathal.

The unit is always off when plugged back in. This is likely why a timer on the outlet won't work. I've updated the question.

Opto coupled relay would be safer. Or use something like this from spark fun https://www.sparkfun.com/products/10747

I don't know if that heater will work for sure with this approach because the buttons are weird. However, I am 99% sure this will work.

(From http://keshavsaharia.com/2012/12/01/coffeeduino/)
Basically here's what you do:

Disassemble the control panel to find the PCB where the buttons are mounted. Find which button you want to simulate a press of.
Find the solder joint where the button meets the PCB.
Solder a wire to the two terminals that are connected. Some buttons have three or four terminals: look at the traces on the PCB to see which buttons are connected.
Wire the relay with the two wires connected so the relay acts as a switch.
Make the proper connections to the Arduino board to control the relay.

In code, you can just turn the relay on for a quarter of a second or so. Then, the IC on the heater will react like you pushed the button.
Make sure to seal all of this up and make sure you don't accidentally short out any of the wires. I would say to also isolate the Arduino and relay to make sure that you don't electrocute yourself at all if something goes wrong.

+1 This is (probably) a good solution if you are competent at delving inside mains powered gear. It may void your home insurance :-(.

To be safe use a device like the power tail from spark fun(basically a sealed relay unit, ready for you to connect to the arduino)
Much easier and safer if you don't have any experience working with 120V/240V
uses a 3-12 input to switch 120v up to 15A
https://www.sparkfun.com/products/10747

Thanks. I did consider this as well and would be a good solution in some cases. With this particular heater, it always starts as OFF when its plugged in, regardless if it was ON before power was cut. Therefore, the Power Tail would not work here. It is a good product and I am considering it for other projects. Thanks for the recommendation!

Use the Arduino to set the start and stop time. Always leave the heater switched on and use something like the 'Mains Switch widget' from SF innovations to control the mains. This unit has a mains relay, is fused to protect against fire and is enclosed in a plastic case.
http://www.sf-innovations.co.uk/mains-switch-widget.html

Thought about this, but this particular heater does not remember it was left ON. Therefore, each time it gets unplugged I even have to reset the clock (since it has time based turning off/on).

The following will work and meets the requirement that the heater does not auto turn on when powered up. You need to turn the heater on manually, so no different from existing, and this then allow you to either

Power it down at a preselected time of day, provided the Arduino is able to keep track of time, or
The Arduino will turn it off a set period after it has started to heat.

The latter is easier to do and meets the need well enough.
The only technical requirements are

Able to sense current drawn by heater.
Able to turn a heater control relay on/off
Able to set or select a time delay on Arduino.

Of these, the current detection is hardest and even then, not very hard. Possible means include:

Current transformer connected to heater lead.
Opto isolator with LED in series with lead with suitable parallel resistor across opto LED to drop enough voltage to trigger opto on voltage peaks when heater is on,  and backwards diode across opto LED for reverse mains cycles. This provides a series of pulses to Arduino when heater is on.

Equipment:
Arduino controlled external relay or solid state relay.
Some means of detecting that heater is drawing current - timer mode only.
Arduino.

Arduino cct can:

Detect current draw.
Turn relay off/on
Be programmed to either stop time or run time.
Drives external relay or solid state relay.
Optional: Relay defaults on.

Then:
Set external Arduino timer to desired time.
Arduino sets relay ON.
Set heater to desired start time.
When heater start Arduino sees current and starts timing, or in time of day mode just turns off power at correct time.
This keeps all circuitry external.


text:
A digital I/O pin as ground
I want an I/O pin to return current in a circuit, similarly to the function of ground.
Which of these will achieve what I require?
pinMode(pinnumber, OUTPUT)
digitalWrite(pinnumber, LOW)

or
pinMode(pinnumber, input)

your second option pinMode(pinnumber,input) is placing the pin in the "third state" of the pin, which is also called "high impedency". It's basically like if the pin was not connected to the circuit, like a ohmmeter does.

"digitWrite"? Don't you mean "digitalWrite"?

Your first snippet is the correct solution.
pinMode(pinnumber,OUTPUT)
digitalWrite(pinnumber,LOW)

Be careful though, you can only sink up to 6mA or 9mA per pin (as per the documentation ["Input and Output" section], I never tried more). If you need more current, use a transistor (this looks like a good example, you just need to invert the output pin to HIGH).
When the pin is configured as input it is supposed to be high impedance, not what you want.

Thanks, the current also comes from the IO pins of Arduino. Therefore, i don't think 40mA limit will be a issue.

@rajat Doing some sort of LED matrix ? Be careful, assuming you plug (for example) a high current LED between two pins (at least without a proper current limiting resistor), you could still damage the chip. Not even mentioning the case where you create a short circuit.

It is a pressure sensor matrix, it has 10 16:1 multiplexers. The current only comes from the Arduino USB cable and no external power supply.Therefore, i don't think high current will be a issue. Can you shed some light on what possibly can cause a short circuit?

@rajat something like that would create a short if pin "1" and "2" are connected : pinMode(pinnumber1,OUTPUT); pinMode(pinnumber2,OUTPUT); digitalWrite(pinnumber1,LOW); digitalWrite(pinnumber2,HIGH); PS : do not try this at home, do not harm innocent arduini, do not sue me, etc...

i was doing exactly this right now. Runs to check if innocent Arduino is fine. Thank god, it's fine :). Why would this damage the Arduino ? So, we can't supply any current when the pin is configured as OUTPUT?

PS (oops too late for edit) : read "connected directly", just to prevent any misunderstanding

@rajat If you do as I (do not) suggest, basically it's like plugging a wire between the + and -/0/GND poles of your battery/power supply. Except here the wire is your chip. If there is (sufficient) resistance between the pins you should be ok. But I'm starting to suspect some confusion here, maybe you could post another question with (the relevant part of) your schematic.

let us continue this discussion in chat

I was a bit surprised by the 6/9mA number. Turns out you’re correct for the Arduino Due, but for the AVR based Arduinos (Uno, etc), which I suspect are still in the vast majority, that number is more like 40mA.

@microtherion Indeed, I was similarly mistaken originally (see the editing history), the Due uses a rather different chip than the other Arduini.

Setting a digitalPIN to LOW give 0V. Not GND!!


text:
Passing a substring to a function or sub
I'm trying to send each character of a string object to a subroutine. I'm using the following code to do this, but it doesn't work:
string sInput = "some text"
for (int i=1; i < sInput.length(); i++) {
  showLetter(sInput.substring(i, i));
}

Subroutine:
void showLetter(String sInput)

My belief is that this should be iterating through the string and selecting one character (not to be confused with a char) at a time and sending it to the subroutine.
I haven't used C++ for 30 years and I am having difficulty finding why this won't work. I understand that I could use a char array, but I wanted to use this method.
If C++/Arduino coding doesn't work this way, to get credit you MUST explain why not.
Any help would be appreciated.
entire code follows...
/*
visual morse code

a dot is 1 unit
a dash is 3 units
  space between parts of the same letter is one unit
the space between letters is 3 units
the space between words is 7 units
*/

void parseString(String sInput);
void showletter(char sInput);
void dot(void); //dot
void dash(void);  //dash
void letterSeparator(void); //between letters
void wordSeparator(void); //space
int baseUnitLength = 100;

// the setup function runs once when you press reset or power the board
void setup(){
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop(){
  //call a routine with a string.
  //the routine parses the string and blinks the dot and dash for morse code for each character

  parseString("sos ");

  //showLetter("s");
  //showLetter("o");
  //showLetter("s");
  //showLetter(" ");
}

void parseString(String sInput)
{
  for (int i=1; i<sInput.length(); i++){
    showLetter(sInput.substring(i,i));
  }
}
void showLetter(String sInput){
  if (sInput == "a")
    {
      dot();
      dash();
      letterSeparator();
    }
  else if (sInput == "b")
    {
      dash();
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "s")
    {
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "o")
    {
      dash();
      dash();
      dash();
      letterSeparator();
    }
  else if (sInput == " ")
    {
      wordSeparator();
    }
}
void dot(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void dash(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength * 3);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void letterSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 3);
  }
void wordSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 6);
  }

If you write "to get credit you MUST explain...", then it is likely you won't get any response. People here are not answering for credits, they answer because they want to help.

"It doesn't work" isn't exactly helpful either...

If you haven't been working with C++ for 30 years, then you are totally outdated with the language as it stands today. I'd suggest you update your knowledge first. Also, regarding your question, if you had taken a look at String API in Arduino reference, then you would have found out what are the problems with your code.

@dda - i'm sorry if my description of the result is unacceptable.  I quite frankly do not what else to say.  The issue is clearly in the for loop in the code.  When executed it does nothing. No blinking, Nothing. I assumed people who have worked with and know arduino/C++ would either know why this doesn't work or would attempt to recreate a situation where it does.  Sorry, but that's all I have.

So here is the answer you did not find in the Arduino reference https://www.arduino.cc/en/Reference/StringSubstring for 2nd argument: to (optional): the index to end the substring before Note the "before" mention, which mean substring(i,i) will always be empty as it should be substring(i,i+1). And this is actually NOT a C++ question, but only an Arduino API question.

@jfpoilpret I thank you very much for your help. The arduino example i read, references 5 characters, but the substring method/function returns 4.  i don't understand why I have to +1 the second parameter and it isn't clearly stated that this is what you have to do nor why you have to do it.  the documentation clearly states, "with two parameters looks for a given substring from the first parameter to the second." That's not very clear, to me, in regards to positional reference and not how other languages do it.

It is very common. This is called a "semi-open" range, which is how the STL (Standard Template Library) also does it. See, for example, a Stack Overflow post. Without a semi-open range it is impossible to pass an empty range. The documentation for substring is very clear on this point: the optional ending index is exclusive (the corresponding character is not included in the substring).

Mr. jfpoilpret provided me with the answer and should be credited, as such.
It appears the subString function needs to have 1 added to the second parameter in order to properly reference the number of characters you need in the String.
In my case, iterating through a String and referencing only one character at a time means I need to do the following sInput.substring(i,i+1)
Also, the String object uses a zero based index.
EX:
   String sString = "This is a peach.";
   sString.substring(0,4)     //should return "This"
   sString.substring(8,9)     //should return "a"
   sString.substring(15,16)   //should return "."
In addition, you could also use the String function charAt (EX: sString.charAt(i)).
The charAt returns a char and if you are passing it to a function/sub you need to make sure the function/sub is expecting a char data type.
Also, it is easier to use a switch case when using the charAt function, as you don't have to do a conversion from String to char, as switch case does not work with Strings.

I understand you are trying to learn stuff, but what you are doing is highly inefficient. On a microcontroller memory is short, and the String library in particular tends to fragment memory. Your technique of breaking up a String into individual single-character String objects is the very thing that is likely to fragment memory. You are much better off converting it to an array (using c_str) and then indexing into that in the usual C way.

You got your answer, and you understood how this works. However, your
sentence “It appears the subString function needs to have 1 added to
the second parameter [...]” makes me believe you find this behavior
somewhat contrived, whereas it should be intuitive to any C or C++
programmer.
As I think this may help, I will share here the mental picture I use for
thinking about array indices. I call it the “L-shaped cursor”, and it
goes like this:
An array index can represent two different things:

a particular cell within the array
an “edge” of a cell, i.e. either the limit between two cells or an
edge of the whole array.

This is depicted in following picture of an array of length N, where
the numbers above it are the edge indices and the numbers below are the
cell indices. i and j are just two particular indices:
0   1   2           i           j               N
┌───┬───┬───┬───────┰───┬───────┰───┬───────┬───┐
│   │   │   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  │   │
└───┴───┴───┴───────┺━━━┵───────┺━━━┵───────┴───┘
  0   1   2           i           j          N−1

Since each index can represent two things, I like to think about them as
being L-shaped cursors, like the ones I've drawn in bold for the indices
i and j.
Now, if you think about the purpose of the substring() method, it's
job is to cut a slice along the string, and you need to tell it where to
place the “knife”. Since the knife will cut along edges, it's perfectly
natural to use edge indices for that. Then
someString.substring(i, j)

will give you the slice of the string that lies between the edges i
and j. Looking at the picture above you can see this includes the cell
numbered i but not the one numbered j.
I hope this picture helps you find the behavior of substring() more
natural now. It does help me avoid fencepost
errors.

Very nice and I thank you for the information.  you hit the nail on the head in your first paragraph.  I'm used to higher level OO languages and scripting code where this is never an issue. So to me, it appears somewhat odd. But, it makes sense once it was explained.  I took C++ forever ago because it was required but I haven't touched it since.

I would suggestion the following:
String sInput = "some text";

void showLetter(char c);

for (int i = 1; i < sInput.length(); i++) {
  showLetter(sInput[i]);
}

Rewritten using C/C++ strings (null-terminated character vector):
const char* sInput = "some text";

void showLetter(char c);

for (int i = 1; i < strlen(sInput); i++) {
  showLetter(sInput[i]);
}

And slightly more efficient:
const char* sInput = "some text";

void showLetter(char c);

const char* sp = sInput;
char c;
while ((c = *sp++) != 0) {
  showLetter(c);
}

The next step is to move the string literal to program memory to reduce the amount of RAM needed.
Cheers!

Mikael - thank you for the attempt, but I understand chars and char arrays and how to pass by value and reference.  However, what I'm looking for is an answer to why, what I am trying to do, doesn't work.  To me the substring function appears to return a string object that I should be able to pass to a function/sub expecting a string as an argument.  But, it doesn't seem to be working.

Could you elaborate on "But, it doesn't seem to be working". Is that a compile or run-time error? Are the parameters to substring() correct?

no errors. the application compiles and loads into the arduino Uno, but produces no output.  I guess I could have been clearer on that point.

authors: Алексей Прокофьев


text:
SoftwareSerial data not available
Second time I'm asking the same question with no solution, let me elaborate in other way for clarity.
I wrote an Arduino program which uses two serial ports, one is hardware serial port and other is SoftwareSerial port.
No problem with hardware serial port, the problem is with software serial port.
The software serial port's Tx pin works but Rx pin does not work, i.e. portone.available() is always zero, nothing in the input buffer of the software serial port.
I'm using Arduino IDE 1.6.12 with an Uno board. Previously I used version 1.6.9 but neither works. Here is the piece of code:
#include <SoftwareSerial.h>

String code = "", customer = "";
bool complete = false;
byte c = 0, j = 0;
char customercode[27];
SoftwareSerial portone(10, 11);
void setup() {
  Serial.begin(9600);
  portone.begin(115200);
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  if (Serial) {
    Serial.print("Connecting");
  }
}

void loop() {
  String copy = "";
  char inchar = '0';

  if (Serial.available() > 0) {
    while (Serial.available()) {
      char bytes = (char)Serial.read();
      if (bytes == '1' || bytes == '2' || bytes == '3' || bytes == '4' || bytes == '5' || bytes == '6' || bytes == '7' || bytes == '8' || bytes == '9' || bytes == '0' || bytes == '.' || bytes == '-' && bytes != '#') {
        customercode[c] = bytes;
        c++;
      } else if (bytes == '#') {
        complete = true;
      }
      if (c > 12 && bytes != '#') {
        code += bytes;
      }
    }

    if (c == 13) {
      customer += '+';
      for (byte i = 0; i < 12; i++) {
        customer += customercode[i];
      }
    }
  }
  portone.listen();
  if (portone.available() > 0) {
    portone.println("AT+CMGF=1");
    portone.println("AT+CNMI=2,2,0,0,0");
    portone.flush();

    while (portone.available()) {
      inchar = (char)portone.read();
      copy += inchar;
    }
    delay(1);
    Serial.print(copy);

  } else if (complete == true && customercode != "" && code != "") {
    sending();
  }
  Serial.print(portone.available());
  delay(1000);
}

SoftwareSerial is pretty low performance, and 115200 bps is probably asking too much. Can you lower the baud rate? Can you search the Internet for alternative implementations of a software serial port?

before I was using the 9600 baudrate but nothing happened that is why I decided to change, also I searched a lot in internet but I end up no solution. that is why I decided to come back again.

Don't call portone.listen().  That method is only necessary when you have created multiple SoftwareSerial ports.  It specifies which port you are listening to, because only one of them can receive at a time (you can transmit on any of them at any time).  It also empties the receive buffer so that data from one SoftwareSerial port is not mistakenly returned by another.  In your code, this empties the input buffer before checking portone.available().  Surprise, it's always empty!  ;)
Also, don't set the pin mode of the pins used for the SoftwareSerial object.  The pin modes were set during the constructor of portone, which happens before setup.  You're messing with pins that have been "promised" to that library for its own use and control.
As Edgar suggested, you should consider a more-efficient software serial library.  AltSoftSerial is best, but is only available on certain pins.  My NeoSWSerial library is next best, and works on any two pins, but only at 9600, 19200 and 38400.  Both of those libraries can transmit and receive at the same time, unlike SoftwareSerial.  Here is an answer with all the gory details.
And you really should ditch the String class usage.  You obviously know how to use char arrays (aka "C strings").  We can't see the sending() function, but you can probably just print a few pieces instead of building a complete String and printing it:
    portone.print( '+' ); // leading plus sign
    portone.write( (uint8_t *) customerCode, 13 ); // array of bytes, length

It would be better to terminate the character arrays with a zero byte (NUL-termination) in loop so they can be used as a standard C string instead of a byte array:
    customerCode[14] = '\0'; // NUL-terminate the C string

Then you can use the standard C string print in sending:
    portone.print( '+' ); // leading plus sign
    portone.print( customerCode );

Printing the pieces is always more efficient than building a big buffer with all the pieces.  This avoids copying the pieces and needing twice as much RAM.     :P

portone.print(code) is printing to the GSM module, then how can I control message so that it prints by iterations of peace wise message  while the full message should reach the receiver, and to control the iterations on receiving the message from the GSM module peace wise between the input buffer of an arduino and GSM, as it is sent full.

@kassim, if I understand your question, I think you are asking about calling print several times instead of just once.  The GSM does not see how many print calls were made, just that a certain number of characters were sent.  Because it takes about 1ms per char, the Arduino is able to start sending the second piece (i.e., customerCode ) almost immediately (~ 0.001ms) after the '+' character.  The GSM will not notice that tiny pause.  It will see an almost continuous stream of chars.  It is probably accumulating chars from the Arduino in the same way as loop accumulates customerCode.

I think the problem was library because I had added AltSoftwareSerial library now is fine.


text:
Connecting breakout board to Arduino with UART
I'm using a DigiX (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:
I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?
Additional info:
Pinout of the DigiX.
Schematic of the DigiX.
(The below links are in Chinese):
Here is a SIM908 Hardware guide.
The full schematic of the breakout board.

Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.
For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).
These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.
You could either:

Breakout the 3.3V signals onto connectors by modifying the SIM908
breakout board.
Build a level converter to take the 3.3V signals from
the DigiX to RS232 and then connect them as before.

You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.

Thanks for the answer. I dont want to modify the SIM908 board so I'm going to go with building or buying a level converter. I'm assuming I can go with 3x something like these http://www.ebay.com/itm/5-x-Mini-RS232-to-TTL-Converter-Adapter-Module-Board-MAX3232CSE-3-5V-120kbps-/330611479927 Or even building my own http://sodoityourself.com/max232-serial-level-converter/ just without the actual serial port? Will I need to have one of these for each RX and RX line (so 6 total)?

Both of those solutions would work. They are bi-directional and have two TX/RX pairs each, so you would only need 2 boards (1.5, sort of).


text:
Why can't most servos rotate more than around 180°
I was looking how a servomotor works. I realized that a standard servo can only turn up to 180°, but I didn't understand why. Is it because of the potentiometer?

You could actually modifiy (most) servo's to do a continious rotation. BUT it would be somewhat against the reasoning behind servo's. Usually, you won't be able to set the position anymore, but only be able to set the speed.

Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).
Next, because the control scheme of PWM position pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.
Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.
Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.


text:
How to get a list of IPs in a LAN using NodeMcu?
I'm going to create an IoT system. I use a Raspberry Pi as a MQTT broker and as a webserver. Every day, the Pi gets a new IP address, so I need to find its new IP address via ESP8266 to use this information in my code. I know that I can use a fixed IP, but I don't want to, so it is better if I can find a solution.

What is the question you are asking?

Welcome to the Arduino stackexchange. Please be sure to take the tour, to know, how things are working here: https://arduino.stackexchange.com/tour

You could use mDNS.

There was some problem in the libraries that i tried, i'm trying to solve it via Pinging now.

As @Gerben say use multicast DNS aka AVAHI, it is even supported on ESP's  ref.: https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html

First of all, if your Raspberry Pi acts as webserver and mqtt broker, in my opinion you should assign a fixed ip-address, either via configuration in the access point/router or via static ip.
However, if you insist on your approach you could do some hands-on method of pinging all addresses in your LAN-subnet and checking for the MAC-address of the respondents.
If the MAC-address matches to that of your Pi, you have found it.
I have not tested it myself, but this library seems to have what you need for this purpose.
After finding a responsive ip-address via ping, it tries to resolve the corresponding MAC-address using the etharp_find_addr function.
This struct field is the reference to a 6 byte character array that you can use for comparing with the Raspberry Pi's MAC address:
response.DestMacAddress->addr

Update:
If you only want to find the IP address of the Raspberry Pi, using mDNS as suggested by @Majenko is the superior choice.
If you are looking for all devices in your LAN, as your title suggests, pinging makes more sense.

I had a Lib problem, now i fixed it and i really close to get the result. In the loop, i send all of the ip addresses that i want and the mac adresses are shown in
pinger.OnEnd([](const PingerResponse& response)
function. I wrote a function for convert response.DestMacAddress->addr to String.
mac = mac2String(response.DestMacAddress->addr); I would like to have it on my setup function for create a list. But i can't. Could you please help me?

I am sorry, but I cannot follow your explanation. I guess it would be best, if you ask a separate question on Stack Overflow for this programming issue. Then you can layout all your code, your results/error messages and what you expect from the program. Then feel free to link to this question.

You should use mDNS.  Install (if it isn't already) avahi-daemon on your Raspberry.
Then check out the ESP8266mDNS library and the examples it has. Especially the mDNS-SD_Extended example, which performs a query for a service on the network.

I need also some other devices' ips. That's why mDNS does't work.

Make those use mDNS as well, then. Either that or redefine your expectations and requirements and embrace the static IP address.

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


text:
What happens to the Arduino if you don't use a resistor with an LED?
Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it HIGH and LOW repeatedly to flash the LED.
What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?

From page 411 of the ATmega328P data sheet, we have a graph of the output current vs voltage.

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.
A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.
I = (5-2)V / 25Ω = 120mA
This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.
That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.

Leaving series resistors out will definitely greatly (exponentially) shorten lifetime of both the controller and the LED. Absolute maximum ratings for most AVRs are (a.o.):

max. 40mA per GPIO pin
max. 200mA per package.

A new Arduino sets you back $20 or more, a fist full 220 ohm resistors sets you back 1$. When treated within spec, an Arduino (and LEDs for that matter) can survive a lifetime.

I have done this once (being a beginner concerning electronics). The LED died, luckily the Arduino survived (without any pin problems).
Wouldn't recommend this as it is not good for the Arduino.


text:
Bootup on lower power not functioning
I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works beautifully when 5V power is applied first, then the battery is inserted, then 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.
However, the problem comes when 3V is applied first. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, nothing. The power draw goes back up but it is unresponsive (over FTDI serial).
Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.
Update: I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

What is the BOD set to, and what is the current draw on startup?

It's set to 2.7V. Current draw while at 3V is about 4mA for the first few seconds, then drops and the LED goes crazy.

Have you tried without the bootloader, i.e. via ISP?

No, I haven't tried that yet. What's weird is it's fine when just running the blink sketch

ISTR that the bootloader causes D13 to have a weird pulse pattern which flickers the LED that's normally there, but since I don't actually have an Arduino (yeah I said it), I'm not certain of the timing/pattern.

I'm used to D13 flickering, but only when uploading the firmware.

Can you add a diagram to show "exactly" how your wiring is connected, including any and every sensor or load on the battery. What kind of coin cell are you using, is it a Lithium Ion (rechargeable) or alkaline?

If Blink is working, then it's more likely your code and not the bootloader. You probably will need to post your code and a schematic to get an answer. Also, have you tried disabling the BOD?

How are you measuring current?  Is it possible the burden voltage of your meter could be dropping the supply too low for reliable startup?

So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.

Exactly what is happening and why cannot be determined based on the amount of info provided. However, I see at least one potential problem which would at least partially explain the symptoms described.
You said that you are using diodes to select the voltage supply, and one supply is a 3V battery. If you are using standard diodes that drop ~0.6V then the supply voltage to the MCU is only ~2.4V. If you are using Schottky diodes with a voltage drop between 0.15-0.45, the supply voltage is potentially as low as 2.5V. You have the BOD voltage set to 2.7 volts, so in theory the MCU will never boot with the battery.
As for why you can start it at 5v, drop to 3v, and bring it back up again- I'm not sure. You could be disabling the BOD in code...maybe… Not sure why it works, but it's likely not guaranteed to work.
I setup a diode switch circuit with 5v and 3.3v to see what it looks like on my oscilloscope when the voltages switch. When at 3.3v switching up to 5v, the voltage oscillates quite a bit initially. This may potentially cause some problems when the MCU tries to come out of sleep. Putting a cap between VCC and GND smoothed the signal very nicely. When switching from 5v to 3.3v, there really wasn't any oscillating, just a clean drop.
From this information, it seems that you should lower the BOD threshold or turn off the BOD, and put a decoupling cap between VCC and GND. You probably also should make sure you have a pull-down resistor on INT0, and read the MCU datasheet sections explaining the various sleep modes all the considerations for sleeping and waking – it’s pretty involved. Cheers

I think the problem is with your bootloader, but not in the way you think.
When an Arduino starts up, a bootloader profiting several tasks, such as looking for a serial host or loading program data from flash is going to take a lot more energy than a sleeping Arduino.
I think the reason why your Arduino will not start is because the bootloader requires an accurate clock source, but applying 3v to it will mess up that clock and it will perhaps crash or wait for 3.3v to be applied for a stable source.
Looking at the datasheet:

We see that current draw while waking up (running the bootloader) is probably going to be around 2mA, while sleeping current is about 0.8 microamps. This could certainly lead to a blackout on startup without the proper current.
Perhaps you should only turn it on with 5v power, or maybe you need a higher current, higher voltage battery.

Wouldn't this mean that Blink wouldn't work either? Also, I'm running more than a few Arduino's from coin cells with no issues. They can provide a lot of current for a short time.


text:
Using TIMER0_COMPB_vect
I'm trying to understand how to fully use the COMPB vector ISR of Timer0 on the ATMega328 (standard Arduino core). I realize it will make delay() and millis() not work but that's ok by me. I've setup some test code that should output a 244Hz signal on D4 and 488Hz on D5 (note, this is running at 8MHz). But D5 (COMPB) is always what D4 (COMPA) is. Any thoughts? Code below:
#include <avr/interrupt.h>

volatile bool stateA = false;
ISR(TIMER0_COMPA_vect)
{
    if (stateA)
        PORTD |= _BV(PIND4);
    else
        PORTD &= ~(_BV(PIND4));

    stateA = !stateA;
}

volatile bool stateB = false;
ISR(TIMER0_COMPB_vect)
{
    if (stateB)
        PORTD |= _BV(PIND5);
    else
        PORTD &= ~(_BV(PIND5));

    stateB = !stateB;
}

void setup()
{
    DDRD |= _BV(PIND4) | _BV(PIND5);

    //set timer0 interrupt at 2kHz
    TCCR0A = 0;// set entire TCCR2A register to 0
    TCCR0B = 0;// same for TCCR2B
    TCNT0 = 0;//initialize counter value to 0
    // set compare match register for 2khz increments
    OCR0A = 255;//244Hz
    OCR0B = 127;//488Hz
    // turn on CTC mode
    TCCR0A |= (1 << WGM01);
    // Set CS01 and CS00 bits for 64 prescaler
    TCCR0B |= (1 << CS01) | (1 << CS00);
    // enable timer compare interrupt
    TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

    interrupts();

}

Update: After thinking about it, I'm realizing that it's not that I need two separate frequencies (though I just kinda wanted to know how, so this is good stuff) but I just need two separate interrupts, only using Timer0 (1 & 2 are already in use elsewhere). They can be the same frequency, most likely. I probably could put all the functionality I need in the same TIMER0_COMPA_vect, however I was trying to use that in a library I was writing and was trying to keep the functionality separate... this may not be possible.

You could optimize your code a little bit by replacing if (stateA) ... with PORTD ^= _BV(PIND4); (exclusive or of this bit) and removing those volatile state variables.

I don't see the point why you would need 2 interrupts at the same frequency, you can do your stuff in the same ISR.

Because some of the stuff is in a library and I want to keep it separate from other logic

Actually, after reading the ATmega328P datasheet again, I am not sure that you can use both OCR0A and OCR0B in normal timer mode.
In particular, since you use CTC mode, I think that TCNT0 will be cleared every time its value reaches OCR0A i.e. 127.
Since you need 244Hz and 488Hz (exactly twice 244Hz), I think you can operate with only one of OCR0A or OCRB0 and do the work in one ISR only:
#include <avr/interrupt.h>

volatile bool setBothPins = false;
ISR(TIMER0_COMPA_vect)
{
    if (setBothPins)
        // D4 is changed only once (244Hz)for every 2 changes of D5 (488Hz)
        PORTD ^= _BV(PIND4);
    PORTD ^= _BV(PIND5);

    setBothPins = !setBothPins;
}

void setup()
{
    DDRD |= _BV(PIND4) | _BV(PIND5);

    //set timer0 interrupt at 2kHz
    TCCR0A = 0;// set entire TCCR2A register to 0
    TCCR0B = 0;// same for TCCR2B
    TCNT0 = 0;//initialize counter value to 0
    // set compare match register for 2khz increments
    OCR0A = 127;//488Hz
    // turn on CTC mode
    TCCR0A |= (1 << WGM01);
    // Set CS01 and CS00 bits for 64 prescaler
    TCCR0B |= (1 << CS01) | (1 << CS00);
    // enable timer compare interrupt
    TIMSK0 = (1 << OCIE0A);

    interrupts();
}

Just checked it on my UNO, seems to work fine (with double frequencies, as the UNO runs on 16MHz).

See update above

Your code doesn't do what you think it does. The timer always runs at 244Hz, and OCR0B only matches twice per period, causing it to have the same frequency but a different phase. What you need to do is set OC0B on compare match and clear it in the overflow ISR. OCR0A you can simply set to toggle on match.
TCCR0A = _BV(COM0A0) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01);
TIMSK0 |= _BV(OCIE0A);

 ...

ISR(TIMER0_COMPA_vect)
{
  PORTB &= ~_BV(PD5);
}

Also, OC0A is D6, not D4.

Your code doesn't seem to match what you are saying to do... could you maybe clarify a little?

CTC resets the timer when it matches OCR0A. We set COM0A[1:0] to 0b01 in order to tell OC0A to toggle. For OC0B we set it in the middle of the timer (COM0B[1:0]=0b11, OCR0B ~= OCR0A/2) period, and then clear it at the end (via the ISR). This gives it twice the frequency of OC0A.

Sorry, but some code would be really helpful, I'm still a bit lost.

The code I gave integrates directly into the code you already have, simply replace the assignment to TCCR0A as well as the whole ISR.

As well as the overflow interrupt enable that I just added (since you won't have the Arduino libraries to do it for you).

Aaaand because I wasn't thinking, it didn't occur to me that a match on OCR0A would happen at the same time as an overflow, so I've changed the ISR used. It should now compile against the Arduino libraries.

So... I was thinking about my code some more and I don't have to have them running at two different frequencies. I really just need to separate interrupts. Does that make any of this easier?

@AdamHaile: You don't even need two interrupts, you just need OC0B to toggle twice as often as OC0A. My code takes advantage of the timer hardware to do just that, rather than doing it all in interrupts.

It is possible to use the Timer0 compare interrupts without affecting the millis() and micros() functions. Simply set the compare interrupts to occur at 1/3rd and 2/3rds of the overflow period. That way they won't conflict with each other because there will be some time between each of the three interrupts (overflow, compare A and compare B). You can't change the frequency though because that would change the update of millis() and micros(). Instead, you could use software post-scalers within the ISRs, something like this:
volatile bool     isr_t0a_flag = false;
volatile uint32_t isr_t0a_delta_time = 0;
#define           TIMER_0_COMPARE_A_POST_SCALER 50

volatile bool     isr_t0b_flag = false;
volatile uint32_t isr_t0b_delta_time = 0;
#define           TIMER_0_COMPARE_B_POST_SCALER 100

void setup()
{
  Serial.begin(115200);
  Serial.print("\n\n");

  // Find out what Timer0 has been initialised to.
  Serial.println(TCCR0A);  // 3 = Fast PWM mode with a fixed timeout of 255.
  Serial.println(TCCR0B);  // 3 = 64 prescaler.
  Serial.println(OCR0A);   // 0
  Serial.println(OCR0B);   // 0
  Serial.println(TIMSK0);  // 1 = Timer overflow interrupt enabled for millis()/micros().
  Serial.print("\n\n");

  cli(); // Disable interrupts.

  //
  // Set Timer0 compare interrupts
  //
  // Clock frequency     = 16 MHz
  // Prescaler           = 64
  // Timeout             = 255
  //
  // Overflow interrupt frequency = 16 MHz / 64 / (255 + 1) = 977 Hz (1024 us)
  // Overflow interrupt frequency =  8 MHz / 64 / (255 + 1) = 488 Hz (2048 us)
  //
  OCR0A  = 85;              // Set 1/3rd phase shift for compare A.
  OCR0B  = 171;             // Set 2/3rds phase shift for compare B.
  TIMSK0 |= (1 << OCIE0A);  // Enable compare A interrupt.
  TIMSK0 |= (1 << OCIE0B);  // Enable compare B interrupt.

  sei(); // Enable interrupts.

  // Verification.
  Serial.println(TCCR0A);  // 3   = Fast PWM mode with a fixed timeout of 255.
  Serial.println(TCCR0B);  // 3   = 64 prescaler.
  Serial.println(OCR0A);   // 85  = 1/3rd phase shift for compare A.
  Serial.println(OCR0B);   // 171 = 2/3rds phase shift for compare B.
  Serial.println(TIMSK0);  // 7   = All 3 interrupts enabled.
  Serial.print("\n\n");
}

void loop()
{
  uint32_t t0a_delta_time = 0;
  uint32_t t0b_delta_time = 0;

  ////////////////////////////
  // BEGIN CRITICAL SECTION

  cli();  // Disable interupts.

  bool t0a_flag = isr_t0a_flag;
  if (t0a_flag)
  {
    t0a_delta_time = isr_t0a_delta_time;
    isr_t0a_flag = false;
  }

  bool t0b_flag = isr_t0b_flag;
  if (t0b_flag)
  {
    t0b_delta_time = isr_t0b_delta_time;
    isr_t0b_flag = false;
  }

  sei();  // Enable interrupts.

  // END CRITICAL SECTION
  ////////////////////////////

  if (t0a_flag)
  {
    Serial.print("T0a ");
    Serial.println(t0a_delta_time);
  }

  if (t0b_flag)
  {
    Serial.print("T0b ");
    Serial.println(t0b_delta_time);
  }
}

ISR(TIMER0_COMPA_vect)
{
  static byte count = 0;
  count++;
  if (count >= TIMER_0_COMPARE_A_POST_SCALER)
  {
    count = 0;
    static uint32_t previous_time = 0;
    uint32_t time = micros();
    uint32_t delta_time = time - previous_time;
    previous_time = time;
    isr_t0a_delta_time = delta_time;
    isr_t0a_flag = true;
  }
}

ISR(TIMER0_COMPB_vect)
{
  static byte count = 0;
  count++;
  if (count >= TIMER_0_COMPARE_B_POST_SCALER)
  {
    count = 0;
    static uint32_t previous_time = 0;
    uint32_t time = micros();
    uint32_t delta_time = time - previous_time;
    previous_time = time;
    isr_t0b_delta_time = delta_time;
    isr_t0b_flag = true;
  }
}

I think your code did not set TIMSK0 properly.
Instead of:
TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

You should use:
TIMSK0 = (1 << OCIE0B) | (1 << OCIE0A);

Why? Because TIMSK0 is already initialized by Arduino libraries before your setup() is called.
If you take a look at hardware/arduino/cores/arduino/wiring.c and search for the init() function, you will see that it contains the following lines:
    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
#else
    #error  Timer 0 overflow interrupt not set correctly
#endif

With these lines, the TOIE0 bit of TIMSK0 is set, but your setup() does not clear it.

This shouldn't actually interfere though. Timer 0 overflow is only for the Arduino timing functions.

That's what I thought, but I think it is still preferrable to ensure you set all Timer0 registers properly. Timer functions are a bit complex and you may be bitten by some strange behavior you did not expect, if you don't care for it.

See update above


text:
Code doesn't seem to work when trying to program 2 sensors
Can anyone help me with this issue
I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.
The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.
The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin
This is the code that I've written
/* FSR simple testing sketch.

 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;
int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
int fsrReading ;
int fsr2Reading;   // the analog reading from the FSR resistor divider

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
}

void loop(void) {
    fsrReading = analogRead(fsrPin);
    fsr2Reading = analogRead(fsr2Pin);

    Serial.print("Analog reading = ");
    Serial.print(fsrReading);
    Serial.print("\t");
    Serial.print(fsr2Reading);

    // We'll have a few threshholds, qualitatively determined
    if (fsrReading < 10) {
        Serial.println(" - Nothing");
    } else if (fsrReading < 200) {
        Serial.println(" - Light");
    } else if (fsrReading < 500) {
        Serial.println(" - Lightness");
    } else if (fsrReading < 800) {
        Serial.println(" - Medium");
    } else if (fsr2Reading < 1100) {
        Serial.println(" - No-Pressure");
    } else if (fsr2Reading < 1400) {
        Serial.println(" - Light-touch");
    } else if (fsr2Reading < 1700) {
        Serial.println(" - Light-squeeze");
    } else if (fsr2Reading < 2000) {
        Serial.println(" - Medium-squeeze");
    } else {
        Serial.println(" - Big-squeeze");
    }
    delay(1000);
}

So could anyone tell how to edit this code correctly in order to get two sensors to work?
The one connected to the A0 pin is working but not the other

The picture is not really easy to check connections, so I'll take it for granted they match the diagram (which is correct). First, using analogRead will give values between 0 and 1023, hence why do your tests check thresholds above that (i.e. 1100, 1400, 1700, 2000)? Then your code is testing the second FSR only if the first one is pressed enough (analog read must be >= 800). That-s because of the first else if checking fsr2Reading: else if (fsr2Reading < 1100). You should remove the else there.

Try changing the pins to use A0 and A1, as pins 0 and 1 relate to the digital pins.
int fsrPin = A0;
int fsr2Pin = A1;   // the FSR and 10K pulldown are connected to a1

As has been mentioned by Matt, make sure you also only test for values between 0 and 1023.
You are also missing the pinMode, which sets the pins as input/output in the setup function
void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);
    pinMode(fsr2Pin, INPUT);
}

Hi I have received this error when typing the code matt has suggested do u have any idea how to fix it have a look at the link here http://postimg.org/image/7uy3kqwch/

It looks like you are trying to declare a function within a function. If you cut the function as suggested by Matt, and paste it at the bottom, after the last }, then that should fix the error you're receiving.

As JFPoilpret says you if logic is wrong.
It might make it easier if you took that whole if block out and made it into a function that accepted the value from the sensor as a parameter.
void CheckReading(int reading)
{
    if (reading < 10) {
        Serial.println(" - Nothing");
    } else if (reading < 200) {
        Serial.println(" - Light");
    } else if (reading < 500) {
        Serial.println(" - Lightness");
    } else if (reading < 800) {
        Serial.println(" - Medium");
    } else {
        Serial.println(" - Big-squeeze");
    }
}

Notice that the values only go up to 800, going larger than 1023 won't work anyway.

The error message says that a function-definition is not allowed here before the token click this link http://postimg.org/image/7uy3kqwch/

@rich1234 That's brilliant, as Holmez said functions can't be declared inside other functions (Lambda functions can, but don't worry about them for now) so moving the code should make the error go away.  However you have called the parameter fsr2reading which is also the name of a global variable, this is a bad idea, it could be confusing.  Finally you could call the function from within you setup function by doing this fsrReading(analogRead(fsrPin)); fsrReading(analogRead(fsr2Pin)); and you don't need the global variables fsrReading and fsr2Reading.

@Rich1234
I have taken your code, JFPoilpret's, Holmez's and my answers and put them altogether.  Hopefully this explains what we mean and will give you something to work from.  It does compile, but I don't know if it works, because I don't have two sensors to try it with.  The code is by no means perfect, but its a start.  If there are any problems, give us a shout.
/* FSR simple testing sketch.
 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

const int fsrPin = A0;      // Change to A0 so it refers to the correct pin
const int fsr2Pin = A1;     // Change to A0 so it refers to the correct pin
// int fsrReading ;     // Change Not required
// int fsr2Reading;     // Change Not required

// Function     : Read the data from the pin and write a meaningful description to the serial output.
// Parameters   : The analog pin to read from.
// Returns      : The value read from the pin
int checkReading(int pin)
{
    const int reading = analogRead (pin);       // Get the reading from the pin. (const because it won't change within the scope (life) of this function)
    Serial.print(reading);
    Serial.print(" - ");
    if (reading < 10) {
        Serial.println("Nothing");
    } else if (reading < 200) {
        Serial.println("Light");
    } else if (reading < 500) {
        Serial.println("Lightness");
    } else if (reading < 800) {
        Serial.println("Medium");
    } else {
        Serial.println("Big-squeeze");
    }
    return reading;
}

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);     // Change to define the pin 'direction'
    pinMode(fsr2Pin, INPUT);
}

void loop(void) {

    Serial.print("Analog reading A0 = ");
    checkReading(fsrPin);
    Serial.print("Analog reading A1 = ");
    checkReading(fsr2Pin);

    delay(1000);
}

Yes it all works for me now thank you very much everyone I really appreciate your help


text:
How do I split a number into individual digits?
How would I split part1 into 2-3 digits and put them into num1, num2, and num3?
int FMSTATION = 10250;

int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;

  part1 = (FMSTATION / 100);
  part2 = (FMSTATION % 100);
  part2 = (part2/10);

  int num1 = ;
  int num2 = ;
  int num3 = ;
  int num4 = part2;

  matrix.writeDigitNum(0, num1, false);  //1st number on lcd
  matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
  matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false);  //4th number on lcd

  matrix.writeDisplay();
}

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is 102.5.

% 10 returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.
So if you have the number 10250 as an integer you can get at each number with:
10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

So your code could be written as:
num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.

Will try it out

I think this will help you:
int FMSTATION = 10250;
int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;
  part1 = (FMSTATION / 100); //102
  part2 = (FMSTATION % 100); //50
  part2 = (part2/10); //5

  int num1 = part1/100; //1
  int num2 = (part1 % 100)/10; //0
  int num3 = part1%10; //2
  int num4 = part2; //5

  matrix.writeDigitNum(0, num1, false); //1st number on lcd
  matrix.writeDigitNum(1, num2, false); //2nd number on lcd
  matrix.writeDigitNum(3, num3, true); //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false); //4th number on lcd

  matrix.writeDisplay();
}

For num1 display, I would also check if it is not 0 before displaying it and clear the digit if it is, so that 95.6 would not get displayed as 095.6.

Ok, i will try it out

Thanks this did work, also i will try and implement the digit clear