text:
Why is the constrain function used after the map function?
I am reading some sample code and they use this method of mapping data from IR sensors:
  sensor1 = analogRead(0);
  adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
  adj_1 = constrain(adj_1, 0, 255);

What is the point of using constrain here if adj_1 is already getting a value 0-255 from the map function?

Are s1_min and s1_max the guaranteed or the expected limits of the raw reading? map() does not constrain its output.

@EdgarBonet what do you mean it doesn't constrain its output? Won't it return a value 0-255?

Not necessarily, it’s just a linear mapping.

Sorry, what does that mean?

A linear function.

An affine map :-) (http://en.wikipedia.org/wiki/Affine_transformation). If you draw a straight line through the points (fromLow, toLow) and (fromHigh, toHigh) then the input ('x') value is mapped to the corresponding 'y' value on the line.

From the official Arduino site:

[The map function] does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

EDIT: Example.
You can try this by yourself with this code:
int val = 20;
val = map(val, 0, 10, 0, 100);

Although you set the upper bound of the value's range to 10, you passed an higher value than that and the function will linearly map it accordingly, resulting in an output of 200.

One caveat would be when mapping an input that ranges from 0 to 1023, since the Arduino is incapable of reading outside of this range there would be no need to constrain. You can check this by running through each iteration from 0 to 1023 and outputting the corresponding mapped value:
for (int i = 0; i < 1024; i++){
    Serial.print(i);
    Serial.print(",");
    Serial.println(map(i, 0, 1023, 0, 255));

}

Certainly, if your sensor reading offers a range smaller than 0 to 1023, then the constrain() function is definitely required, as per LoganBlade's example. Otherwise, it is not needed, but may still fall into the realm of best practice.
The only hiccup to this logic would be if you are mapping to decimal values (which doesn't make much sense since the function will return a long type anyway), in which case the Arduino's internal typecasting will round-down your lowest value mapping. Example:
map(0, 0, 1023, 8.9, 61.9));
>> 0 becomes 8

map(1023, 0, 1023, 8.9, 61.9));
>> 1023 becomes 61

Again, for the sake of best practice and the potential time wasted trying to find a mapping bug, using constrain() is better than skipping it.

Some sensors output high numbers when they are out of their normal range of operation or if something else is off. The STM VLS30X can suddenly output 8190 after having measured 487 (mm) for example. Therefore, constrain should be a must. See also a solution to the mapping error too many users make https://www.jetmore.org/john/blog/2011/09/arduinos-map-function-and-numeric-distribution/


text:
How to upload program to board using Arduino sketch ver 1.6?
I am having problems uploading my program. I have been using the verify button aka the "checkmark" to upload my programs. I assumed that this was the correct button but now I am having problems uploading. When I attempt to use the "upload" button I get the error "can not open device". What am I doing wrong? How can I fix this error code?

install the device drivers for your Arduino!
steps to follow are mention in arduino website!

It's possible the port or the board got changed, check the tools menu.

Check Tools->Board, Tools->Port, and Tools->Programmer

The "problem uploading to board" error message includes this link to arduino.cc troubleshooting guide: http://www.arduino.cc/en/Guide/Troubleshooting

The checkmark button is used to compile your program (which "verifies" your code), but does not upload it to the board. The "arrow" button is used to compile and upload your program.
If you cannot connect to the device, make sure the correct COM port is selected on the Tools->Ports menu, and make sure you have the correct board selected on Tools->Board (usually an Arduino UNO).
If you have not installed the drivers yet, you will not have a port present for your Arduino. If that is the case, here is a great tutorial that will help you get everything installed and set up correctly: https://learn.adafruit.com/lesson-0-getting-started

source: Stack Exchange

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

sort: votes


text:
Programming ATmega2560 processor with FTDI instead of ATmega32
Has anyone tried to program an ATmega2560 with an FTDI chip as is done in the Arduino Nano (this is for a custom design).
Will it work?

That will work. The only think to look out for is how to reset the board. Either manually reset it before uploading, or connect the DTR pin of the FTDI, via a capacitor, to the reset pin.

It actually worked!

Reworded question to remove confusing references to the Arduino Mega, which is not what this question is about (see OP's comment below).

In fact, the basic Arduino Mega (with the ATmega 1280) utilizes an FT232RL, so yes, it will work if you connect it correctly.
It is only the newer Mega2560 (along with the similar-generation Uno, etc) which utilizes an ATmega16u2 or similar as the USB bridge.
Generally speaking, the bootloader doesn't care - you should be able to use either target chip with either USB bridge (or others).

The Arduino Mega already has a built-in USB-UART bridge, so there's no need for a separate chip.
The ATmega1280 on the other hand is just a bare AVR MCU and does require either a separate USB-UART bridge for serial programming (provided it is programmed with an appropriate bootloader) or an ISP programmer for ISP programming.

Sorry, I expressed my self wrong. My goal is to program the Atmega2560 (with the bootloader already burned in) with the FTDI chip instead the AVR USB bridge from the Arduino Mega original design. Do you think that might work assuming the connections are correct? Or in other words, is the Arduino IDE expecting some sort of response from the programmer that the AVR bridge will provide and the FTDI will not?

The FTDI chip is a USB-UART bridge, so I would expect not. But to be perfectly honest, I'd use a ISP programmer and save myself the cost of the bridge and the time of burning the bootloader.

Your comment seems either confusing or wrong.  Why would you expect an FTDI bridge not to work, when it is what the official Arduino Mega actually utilizes?  The Arduino IDE doesn't speak USB for the ATmega boards anyway; it relies on the host operating system to present a Serial API, so it has no idea of the implementation detail to tie to a particular board.

@ChrisStratton: "... is the Arduino IDE expecting some sort of response from the programmer that the AVR bridge will provide and the FTDI will not?"

If you think there is a difference there you are quite mistaken.  The bridge is merely a proxy.  The response comes form the bootloader on the target MCU.  As I'd mentioned previously the IDE (avrdude actually) relies on the operating system Serial API.  It doesn't care what USB bus operations or VID/PID are involved.  It merely cares that whatever operating system Serial device you point it at in the menu has a bootloader that responds at the baud rate configured for the board entry.  Take a look in boards.txt at the FTDI- vs. ATmega16u2 interfaced boards.

I don't understand why you've gone off on this tangent. Of course the bridge doesn't care about the protocol; it's just a bridge.

No tangent.  Just the illogical nature of your "I would expect not" comment.  I read that as you expecting this not to work.  Did you mean that you expected there to be no difference, ie, are you responding to the second question and not the first?

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


text:
Program attiny13 with Arduino uno 1.6
I am looking for the boards.txt, platform.txt and core files needed for the programming of the ATtiny13 with the Arduino Uno. Those I find on the internet probably only works with Arduino 1.0 and not with 1.6.

Have you tried porting them yet?

You can use the library for IDE 1.6 https://github.com/damellis/attiny/

Except for the fact that it lacks support for the '13, of course.

Thanks for your answer.
I already did, but this files are only for the ATTiny 44-45-84 and 85 and the ATtiny 13 is not supported.


text:
Connecting light and temperature sensors and LEDs to an Arduino
Fairly new to arduino, what is the best and simplest way to connect an LM35 temperature sensor, a GL5528 photoresistor and some LEDs as well as the required resistors to an arduino for recording values? Any tutorials with wiring diagrams for something similar would be helpful.

I'm pretty sure using the text entry box on the top right will find you some.

Hi, like Ignacio hinted, your requests would be easily answered with a search. I provided an answer by doing the search for you.

I meant the site search box, but either or.

The LM35 is a very common temperature sensor. It has 3 pins - Vs, Vout, and Gnd. Connect Vs to the Arduino's Vs pin. Connect the Gnd pin to one of the Arduino's GND pins. The Vout pin should be connected to an Analog input pin. If you google your board, you should find the pinout on Arduino's website. The LM35 pin diagram and information on how to calculate the temperature from voltage is found in the LM35's Datasheet. Here is LadyAda's Temerature Sensor tutorial (note: the tutorial specifies the TMP36, however the two sensors are comparable). Here is an instructable for the LM35 (includes diagrams and source code).
The GL5528 is a photoresistor. That means its resistance changes proportional to how much light strikes its sensor surface. Because of this trait, we can build a Voltage Divider. This will allow us to read in values (again, analog values). AdaFruit's tutorial is very comprehensive and includes diagrams.
LEDs are generally considered output displays (we program to use LEDs as a visual display of state). A good starting place for Arduino LEDs is the Blink Example. we connect an LED and resistor in series with an Arduino output pin and GND or 5v. This allows us to 'write' to the Arduino pin HIGH or LOW, turning the LED on or off.
I found these results by googling 'Arduino LM35', 'Arduino GL5528', and 'Arduino LED' respectively.


text:
Difficult between atmega328 & atmega2560 when coding & compiling in a pure c
I have an arduino uno with atmega328p controller.
I found the code to deal with some specific uart protocol, named mdb: https://github.com/Bouni/MateDealer/tree/master/arduino
But it's compiled just for atmega2560 controller: https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42
If I replace it by atmega328p or atmega328, I get the error:
asiniy@misha:~/projects/MateDealer/arduino$ make all

-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o

Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                        ^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                 ^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                          ^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                                   ^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_RX_vect){
     ^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_RX_vect){
     ^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
     data = UDR1;
            ^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_UDRE_vect){
     ^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_UDRE_vect){
     ^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
                 UCSR1B |= (1<<TXB81);
                               ^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
         UDR1 = data;
         ^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
     UCSR1B &= ~(1<<UDRIE1);
                    ^
make: *** [usart.o] Error 1

I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?

I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560!
Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).
The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)

The '328 only has a single USART. You will need to remove all references to USARTs beyond the first as well as the numeric suffix from the USART register names in order to get it to compile.

So, do you mean that I can't read data from MDB protocol and send it to the serial port of my computer to read it in the display?

If you require more than one USART to do so then no, you can't. You could try a serial UART, but this is beyond the scope of this question.

Can I use one usart for connect mdb and the second one for connect to serial of my computer?

Again, you don't have 2 USARTs.

SoftwareSerial library give me ability to  connect by 2 uarts, but not in the same time. I need to stop 1st usart, then run 2nd. How do you think, can I implement something like this in pure c?

You do have one hardware USART, as an uplink to the PC.

So, can I use one hardware UART to connect to the computer, and another one to connect to mdb?

You still only have one hardware USART. You will need to use a software UART as well.

So, can I implement connection from uno both to computer and mdb? Just yes or no, please


text:
Home-Made EL Tape chaser
I am working on a project involving 14 sections of EL tape. This is a circular array that incorporates a chaser effect with two lights lit on either side. originally I had found a small diy LED sequencer board that controlled both speed and brightness from 2 POTs.
Now I am attempting to adapt this to activate 7 relays (in place of the LEDs) which will in turn divert the power of the EL inverter to the tape sections.
Each relay is the connection of 2 EL panels to the (+) of the sole EL inverter while its (-) is hardwired in parallel among all the panels.
These are all small panels cut from a 3m length and have worked using this inverter independently both full length and cut. through some trial/error as well as some brightness and speed tweaking I have made this system work for a panel or 2, sometimes more, but other times the inverter and relays are working by the sound of it but the lights are not lighting or when they do they are skipping. It's intermittent too sometimes swapping panels works but at times it looks like the socket may be bad and the light is good other times it's the opposite even with the same pieces.
I have considered the sparkfun sequencer and it would most certainly save the day except that along with space being an issue my device also incorporates a few other Arduino devices including 2 servos, a sound module and a push button to start the sequence. however the sequencer doesn't seem capable to run 7 el connections as well as 4-6 other operations. is there a simpler way?
Am I missing components between my relays and lights?
Could I use my Uno in place of the sequencer? or can I expand the number of pins on the sequencer?
I would like to avoid daisy-chaining arduinos/boards as much as possible and even break down the number of separate boards I already have. I am trying to run this off of a single 9v and maybe a pair of button batteries.
Unfortunately I can no longer find the exact sequencer I am using but there are many 8 channel led chasers (w/o Brightness control) similar to mine on ebay.
Any help, insight, coding, recommendations anyone can offer would be greatly appreciated.
Thanks in advance.

Can you please edit your question to include what you've tried? Have you chosen any parts? What exactly do you need help with?

I can't bring myself to read the question. Have you heard of paragraphs? Or starting sentences with a capital letter? People here are volunteers who are keen to help you, but you have to make some effort to make the question readable. Please read How do I ask a good question?

My first guess is that you're using a power supply that can't supply all the power that the ELs, LEDs, relays, etc. are pulling. So the voltage drops (brownout) so low it makes the Uno act weird. Can you temporarily set up a test with a mains-powered power supply rated to supply at least 10 times the watts you think you might need? Can you help us help you by linking to which specific sequencer, specific relay, and specific EL you are using?

You raise a good point David. Though now that I have learned a lot more I am starting to think that perhaps the timing of the AC and relay switching is continuously falling out of sync and finds a different pattern each time I hook it up. I haven't been using anything for voltage controlled switches like triacs.

Is there a reason you've chosen relays? Every time the sequence changes you'll hear audible clicks. If this is not a problem then there's no real reason to change, but MOSFETs or (possible gate-drive) optocouplers would be both smaller and quieter.

just what was available combined with the, then, limited extent of my knowledge. I have since learned a lot more through research. I am currently experimenting with MOSFETs and triacs based on a design I found. Thanks for your input though CharlieHanson I will keep gate drives and optocouplers in mind as well. It all needs to fit in a narrow space but I may soon change that design as well.

I'm voting to close this question as off-topic because its 2 years old and no answers.


text:
Can I have help interperting this code? char variable somehow storing big numbers
I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.
  boolean Adafruit_FONA::callPhone(char *number) {
  char sendbuff[35] = "ATD";
  strncpy(sendbuff+3, number, min(30, strlen(number)));
  uint8_t x = strlen(sendbuff);
  sendbuff[x] = ';';
  sendbuff[x+1] = 0;
  //Serial.println(sendbuff);

  return sendCheckReply(sendbuff, "OK");
  }

This is the function however how is char being used to display a phone number in the parameter?

This is bad code. It uses magic numbers (3, 30, and 35) instead of calculating values based on the actual sizes. The second call to strlen isn't needed; x is the sum of the length of the first string and the number of characters that were copied. Setting aside the incorrect use of strncpy that I mention in a comment below, if the input string is to long, the code truncates it and dials the truncated number! It shouldn't do that; it should return an error code. Don't try to learn programming from stuff like this. You'll pick up lots of bad habits.

It's passed as a char*. This can be derived from either a string literal (e.g. "212555121") or from a String via its c_str() method.

so if i wanted to use the function all i have to do is enter a string with the number inside?

If you want to use a fixed string then you can call it with the literal. If you have a char* with the string then you can pass it directly. If you have a String then you need to call the c_str() method. Arduino string reference

can u give an example of how i would create the char* with the string

What's wrong with how your posted code does it (other than that fiasco with strncpy(), of course)?

Keeping it simple:
char *number; a variable pointing to a character (or string of them).
char sendbuff[35]; 35 characters in a row, making a string.
The first 3 chars at locatiion sendbuff are initialised to "A", "T", & "D", then the string at "number" is copied to it (to a maximum of 30 characters, by taking the lesser of the length of "number" or 30. This is important to avoid over-running the space allocated.
This string of characters gets sent out; & a check is made for an "O" & a "K"
If you don't 'get' pointers, you need to look it up, as it's pretty central stuff.

I don't know why strncpy has become so popular as a "safe" replacement for strcpy. It isn't. If the number string is longer than 30 characters strncpy will copy the first 30 characters and stop without adding a NUL terminator. The subsequent call to strlen can then run off the end of the buffer, and if that happens, the two bytes subsequently stored will go outside the buffer.


text:
Emulating 1-wire device(s)
What I want to do is make a ATTiny IC become a slave on the 1-wire bus, with its own S/N and command list for its specific functions.
What I want to know is if I can use the one wire library from the arduino site to send data as a slave.
For example, you can have a slave in one room with multiple types of sensors which would report to the master on requested information, or the master can tell it to control something like blinds.
Question
Would I have to monitor the bus line and respond to a request from the master and also take into consideration the way a normal sensor would send data? What frequency should I run the slave at to get the best functionality?
I won't use parasitic power, as a note.

http://forum.arduino.cc/index.php?PHPSESSID=trj6v208snqfutqhrfltnu0364&topic=65706.0

@Gerben - I had found that before on a search. Skimmed through it. But I was concerned because there were some errors, though solved, I don't know the reliability. Also search foe designs using custom slaves didn't seem like a common thing, hence question above.

It seems to say the library supports it. Here is a library specifically for it I think. Speed seems to be around 15kbps. I think CPU speed doesn't really matter, but that depends on the library. If it's not battery powered, just run it at 8mhz or 16mhz, and it should be fine.

@Gerben I will test out the library to see how it runs. One thing I still don't get is why it is so uncommon for some things not to use the one wire slave?

@RSM You should check this library https://github.com/MarkusLange/OneWireSlave

@Ryu_hayabusa you should put that as an answer

As far as I know, the 1-wire library you linked in your question allows only to act as a master, not a slave.
I've just released a library to turn an Arduino board into a 1-wire slave, here: https://github.com/neuoy/OneWireArduinoSlave (edit: moved here https://gitea.youb.fr/youen/OneWireArduinoSlave). I use it in my custom home automation system, and it works flawlessly in my setup (the 1-wire master, a DS9490R, is connected to a laptop via USB, and also provides power to the Arduino, which is an Arduino Uno). The library handles low level details: match rom, byte send and receive (which is actually quite hard to get right, mostly impossible without a logic analyzer). The rest is up to you.
It's entirely implemented with interrupts, all communications are performed in background, you can execute other code as usual, in parallel, and are notified by callbacks when bytes are received etc. Sending bytes to the master is also asynchronous.
I also know at least one other library exists, https://github.com/MarkusLange/OneWireSlave, as commented above by Ryu_hayabusa. It didn't work for me (don't know if it's because of my hardware setup or for another reason), but it definitely work for others, so also worth a try. It seems this library is not implemented with interrupts, so your program is blocked while waiting for master activity (which is perfectly acceptable in a lot of scenarios).

The repository seems to have moved to https://gitea.youb.fr/youen/OneWireArduinoSlave

@JonasBerlin Indeed, I've moved the repository (just edited the answer to reflect that). I leave the old link as a backup just in case, and as a reference to find other people forks on GitHub.

Should the issues be copied perhaps?

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


text:
What happens if an interrupt is triggered while sending data via serial?
I would like to use an inertial sensor to measure acceleration and send the results to an Android app using a serial communication with a bluetooth Mate Gold module. The sensor provides a data ready interrupt which notifies Arduino-Mega that a new value is stored in a register of the module. The output data rate can be modified during the configuration of the sensor.
I want the information to be sent at a 10 Hz rate to the bluetooth module.
Is an interrupt at 400Hz capable of compromising the integrity of a 50 bytes long message sent at 10 Hz with a baudrate of 9600?
If yes, which approach would you recommend to correctly send the data?
Edit:
I'm using the following formula to compute the amount of time required to send N chars.
bytes x bits_per_character / bits_per_second
N x (8+2) / 9600 = N/960 secs

For N = 52:
52/960 = 0.054 secs = 54 ms

So theoretically, I can send a 54 char-long message at 18Hz with a baudrate of 9600.
Edit2
I can use the hardware serial or the Software Serial interface.

Have you done the math?

Hi Ignacio, is the math correct?

I think it would depend on how long the interrupt to get data takes to execute. If I were you I'd just write enough code to test it and see.

What do you mean by compromising the integrity of the message? Is there is a delay between the transmission of two bytes of the message? What do you do in your interrupt?

The arduino has hardware serial. So it sort of runs in the background, independent of the main processor.

@fuenfundachtzig the interrupt routines asks a I2C connected sensor.

@Gerben do we have the same property using SoftwareSerial?

I think Software serial might break if interrupts occur during transfer (especially if interrupts take a bit of time)

This could be a problem. Do you have any advice? I sould probably use pin 0 and 1 of the board

SoftwareSerial disables servicing interrupts during transmission of every byte, although interrupts are allowed between consecutive bytes. Looks like you should be safe, but you will have some latency in responding to the sensor interrupt.

Ok that's a good news! So if I send, let's say, 10 chars, the values of the sensor won't be updated for 1/96th of second. (Loosing 4 updates of the sensor considering 400hz interrupt's rate) And this will occur every time the serial communicates with the bluetooth module. I think I have the answer. I will try to implement it and measure latencies.

Actually, the fact that readings are slowed down is a really bad behavior. Especially when dealing with integrations. What about timer interrupts? Does the serial disable them?

Please edit the question to discuss what board you are using and what serial port you intend to use.  The answer depends greatly on whether you have a hardware serial port or SoftwareSerial as interface to the BT module.  Also would benefit to mention the BT module.  On some modules you would be able to up the baud rate to 57.6k or 115.2k, which will change the question?

@narutov6: No, if you send 10 chars, interrupts will be blocked for 1/960 s, while you send the 1st char. If some interrupts trigger during this time, they will be put on hold, and serviced right after the 1st char is gone. Then interrupts will be blocked again for 1/960 s while you send the 2nd char and so on.

Actually I was wrong: at 9600 bps, interrupts are blocked during 9/9600 s ≈ 938 µs (plus a few cycles). They are enabled right after the stop bit has been written, which means they can be serviced during the stop bit period.

If you are on the ardruino platform, and are using the hardware serial port, you basically don't have to do anything.
The Serial library interface already uses a outgoing data-buffer (it's varies between versions, 1.5.5 has it set to 64 bytes. The arduino people keep changing it's size for no reason), where the call to Serial.print() or Serial.write() only places the bytes in question into the outgoing buffer, and the buffer is then emptied asynchronously in the background by the TX-ready (UDRE) interrupt (which is then disabled when the buffer is emptied).
Basically, all you have to do is ensure that you're not placing data into the transmit buffer from both an interrupt and the main loop(), because it's then possible for the message from the interrupt to be inserted into the middle of the message from the main loop thread.
This can be easily enough done by either guarding the call to Serial.print() with cli() sei() interrupt guards in the main loop() section (or the useless arduino analog: noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason), or simply not printing from an interrupt (which is a good idea anyways, string formatting can be slow).

As of 1.5.5, the transmit buffer in HardwareSerial.h is 64 bytes so his 54 character messages will fit.

@jdr5ca - Good to know. The only arduino package I have installed is 1.0.5, where it's 512 bytes(!).

That is fixed back to 64 in my 1.0.5-r2 install.  Two buffers per serial port is 1k!  With 3 ports on the Mega, that would suck up 3k of RAM = doh!

@jdr5ca - Yeah, it's possible I was hacking one some bits, and that value is not original. I removed the text.

cli() and sei() disables/enables all interrupts, correct? I have got problems with servo controlling (jittering) because of that. A decoupling queue to avoid corrupted serial communication was the only solution in my case.

See http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html for the specifics of sei() and cli(). The arduino serial transmit already involves a decoupled queue, so I'm not sure what's going on in your application.

"noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason": avr-libc and arduino are two different project, and the arduino library uses the avr-libc. Th existence of cli() sei() in the arduino environment is not because of intention, but the crosstalk of "include" directives.

Arduino is a bunch of libraries on top of avr-libc. There are no good reasons for it to re-implement underlying functions exclusively for the sake of changing their name.

You want to send a 50 byte (or 52 byte?) sequence every 100 ms (10 Hz).
For hardware serial, that will go into a buffer which is emptied via serial interrupts; it should be emptied well before the next 100 ms tic (as you have calculated).
You will get about 40 sensor interrupts during that 100 ms.  With hardware serial, that need not be a problem - so long as you don't send bytes from within a sensor interrupt.  If your sensor interrupt just accumulates results and the main loop (non-interrupt) uses those results to periodically send the 50 byte message, you should be good.
Suppose you were averaging each of the sensor readings.  In the sensor interrupt you might add 1 to the count and add the reading to a sum value.  In the main loop, test if it has it has been 100 msec since the last send, and if so turn off interrupts, divide the sum by the count and store that average in a new variable, zero the sum and count, turn on interrupts.  Then use the computed average to format and send the 50 byte package.
That's just an example.  The main thing is to make the sensor interrupt quick and simple; and to format and send the packet in the main loop (inhibiting interrupts temporarily while fetching and clearing the variables which get updated during the sensor interrupt).
Be sure to use "volatile" for the variables used by both the sensor interrupt and the main loop.
The serial should take care of itself if you use hardware serial, and might even be OK for software serial.  In the latter case, a sensor interrupt in the middle of sending the bits of a single character/byte would mess up the bit timing, but software serial should inhibit interrupts during that time - so your sensor interrupt might be delayed up to a millisecond.

What you are looking for is a way to safely interleave transmitting characters while at same time responding to the interrupts.  You can wrap the sending of bytes with
noInterrupts();
swSerial.write("somethinglongyaddayadda"); // takes 50-60 ms
interrupts();

That will protect the write() operation from being interrupted and ruined by you sensor interrupt handler.  But as you note, that will block the ability to process the the sensor every 2.5 ms.  During the noInterrupts() period you would miss readings.
To achieve the interleave of both operations, you should transmit the message one character at a time.  Implement a transmit queue to hold the outbound string.  When it has characters, send them 1 at a time, wrapping each interrupt protection:
...inside loop...
if(txQueue is not empty) {
  // do not need noInterrupts() or cli() as these are inside write();
  swSerial.write(one character from Q); // takes ~1 ms
  txPointerHead += 1;
}
// at this point the interrupts are enabled
// and the sensor will be processed if available
// if the interrupt occurred in the middle of the above,
// the level is still set and the interrupt handler will be invoked

The 1 ms is ideal and not accounting for overhead, but it is unlikely the 1 character write time could stretch out to 2.5 ms.  As long as the write time stays under 2.5 ms, you will never drop a sensor reading.
Note that this interleave means that the characters will have larger inter-character delay.  The serial ports will not care about that.  But if the processing of the sensor data takes too much time, you will not be able to keep up with your 10 messages per second goal.
Some options I see to improve:

Use a higher baud rate.  The baudrate of the serial port is not related to the bluetooth data rate, so you might as well use the 115.2k.  That will reduce the blocking time.  The baud rate doesn't even need to be the same on both ends.  The BT module isn't a simple modem; it is packetizing characters wrapping them in encryption and transmitting.  The receiver unbundles the packets and pushes out its serial port at the receivers baud rate.
Use hardware serial.  Using a hardware serial port greatly reduces the time because all write() does is put one character into a register.  The time for that is microsecond domain.  After the byte is put in the transmit register, the UART handles the clocking of the bits so the microcontroller is free to do other tasks.

Assuming you're on the arduino platform, the Serial library already does all this for you. It uses an internal 128-byte outgoing ring buffer, and the buffer is emptied by the transmit-ready interrupt of the USART.

True point that SoftwareSerial turns off interrupts character by character, so the calls are redundant.  SoftwareSerial uses the Print::write(uint8_t*,size_t) which is a synchronous call that does not return until all the characters are written.  There is no transmit queue which would allow an asynchronous call (at least in my 1.5.5).  So if he does not want the main loop blocked for the 50 ms periods during the transmit of the entire string,  this was my approach to keep the loop() running.


text:
Serial Error Correction
I currently have a setup where I take serial output from Arduino 1 and push it through a transmitter to the receiver of Arduino 2 where it is fed back into the serial input and further processed. I want to ensure that there is as little error as possible and recover the data wherever possible.
I have come across the syndrome decoding technique which seems to be the ideal one for me, but I am confused as to how I would go about implementing it.
I know that the Arduino Serial transfers data byte by byte, each being 8 bits, but do not know how this data is sent over the serial connection (i.e. how the start & stop bits & parity is implemented).
I would assume that a solution to this could either involve modifying the data in the buffer or reading it from the buffer and then operating upon it. I could also use adjacent bytes of data for error correction, but this seems wasteful.
How should I proceed with this?

Which "syndrome decoding technique" are you considering?  It will probably affect the approach.

Welcome to the wide world of Communications.  You are asking about "Error Detection and Correction".  This is different from "framing", which allows you to determine when a message starts and ends.
With "error detection", you know there was an error, but you can't necessarily recover from it.  With "correction", you know there was an error and you can determine what was originally sent.
This always requires extra bytes.  There are many schemes, but the Fletcher checksum for Error Detection is easy to implement, fast, and only requires 2 extra bytes in the message (4 if hex digits).
The generic approach is to use a finite-state machine.  In complicated message protocols, there would be nested state machines: the inner-most would probably determine framing, the next one out might looks at addressing, etc.  Any or all of those layers could use Error Detection and/or Correction.
For your simple "protocol", a single state machine is probably sufficient.  The states might be IDLE, RX_PAYLOAD and RX_CS.  As characters are received, they are processed according to the current state and occasionally change the state variable.
while (Serial.available()) {
  uint8_t c = Serial.read();
  switch (state) {
    case IDLE:
      if (c == MSG_START)
        state = RX_PAYLOAD;
      break;
    case RX_PAYLOAD:
      if (c == MSG_END) {
        state = RX_CS;
        cs = 0;
        csCount = 0;
      } else if (length < MAX_LENGTH-1) {
        msg[ length++ ] = c;
      }
      break;
    case RX_CS:
      //  Add in the next hex CS digit
      cs = cs * 16 + fromHex(c);
      if (++csCount == 2) {
        // both digits received, see if the CS matches
        if (cs == csOfMsg( msg, length )) {
          // Handle the message
          msg[ length ] = '\0';
          Serial.println( msg );
        } else {
          Serial.println( F("Bad message!") );
        }
        state = IDLE;
      }
      break;
  } // end switch
} // end while

There are entire books written on protocols and their design.  This is just a made-up example to give you an idea of how it should be structured: a finite state machine, driven by received character "events".
Sometimes you can compute the checksum as the characters are received, like Fletcher.  Here, it waits until the entire message plus 2 CS bytes are received.

In my case i used a buffer and a delimiter. Specificaly: The reading is placed on the byte array untill the delimiter is reached.
For example
From the arduino IDE serial monitor im sending this: CAT;
Each letter will be placed inside the byte array and this will stop when the ; sign is entered. This migh be usefull because you can send the bytes whenever you can and they will remain in the array.
void loop(){
if(Serial.available() > 0) {

 char rec = Serial.read();

 if(rec == '.'){
    Serial.print("Here: ");
    for(int i = 0; i < sizeof(attitude); i++){
       Serial.print(attitude[i]); //print
       attitude[i] = (char)0;
    }
    attitudePointer = 0;
    Serial.println();

 }else{
   if(attitudePointer <= sizeof(attitude)){
      attitude[attitudePointer] = rec;
      attitudePointer++;
    }
  }

 }
}

That code doesn't match your description!  That code waits for a period (full stop), not a semicolon.  And it's a little misleading to use attitudePointer, when it is actually an index, not a pointer.


text:
I²C between ATTiny85 (8MHz) and Arduino Uno
I keep receiving the following error in myATTiny85-Slave code below:

sketch_mar12a.ino: In function 'void setup()':
sketch_mar12a:19: error: 'class USI_TWI_S' has no member named 'onRequest'

I have downloaded TinyWireS and TinyWireS.h clearly has a public function onRequest. I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.
I am using Arduino 1.0.6
What am I doing wrong?
ATTiny85-Slave Code:
#include "TinyWireS.h"                  // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

byte t=10;

void setup()
{
   TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
   TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
   TinyWireS.send(t);
}

Arduino Uno-Master Code:
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

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

 void loop()
 {
      byte num;

     // read 1 byte, from address 0x26
     Wire.requestFrom(I2C_SLAVE_ADDR, 1);

     while(Wire.available()) {
          num = Wire.read();
     }

     Serial.print("num = ");
     Serial.println(num,DEC);
 }

How did you install the library?

I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.

you may need to include: TinyWireS_stop_check();
in your loop

I was able to compile your code "ATTiny85-Slave Code" without problems.
You can try to extract the contents of the ZIP archive (i.e. the library) directly to the directory where your sketch is stored. #include "TinyWireS.h" should then pick up that version.
You should also switch on verbose output for the compilation to have a look at the directory in which the code is compiled. Here you would find (at least in my older Arduino IDE version) copies of the included files. (/tmp/build... on Linux systems.) You can then make sure the proper version of the files is used.
You can also search your drives for other copies of TinyWireS.h.

Which version of Arduino IDE are you using? What board did you select?

I am using Arduino IDE 1.0. It compiles with any board selection... Note that I did not install the Tiny hardware specs, but did a small hack in usiTwiSlace.c, declaring all missing symbols as ints.


text:
Connecting PC speaker to Arduino
I've looted this speaker from my old PC and trying to understand how to connect it to Arduino to produce simple sound notification (and not fry anything in the process).
As far as I understand this is a piezo speaker, there is no markings on it. Here is how it looks:

How do I connect\control it?
Should I connect it to PWM pin? If so, what are the safe values to output on PWM pin?
Should I use resistor when connecting speaker? What resistor should I use?

Take a look at the tone() function, it may suit your purpose.

As far as connections go, I would connect the red wire to a PWM pin and the black one to a GND pin, but I'm not sure if a resistor is needed, wait for someone more expert than me to answer. :)

No need for a resistor. Just connect black to ground, and red to a IO pin. Use the tone function to specify a frequency.

I'd recommend using a resistor. The piezo conducts quite well and might fry the pin. http://arduino.cc/en/Tutorial/Tone Also see http://www.uchobby.com/index.php/2007/11/11/arduino-sound-part-1/

@MrJones A resistor might be needed for (electromagnetic) speakers, not for piezos. A piezo is more like a capacitor, and doesn't conduct any current.

Why is no resistor needed? I don't exactly know OP's speaker, but my speaker says 8 Ohm. 8 Ohm at 5V is much more than an Arduino can handle, isn't it?

@ThomasWeller OPs "Speaker" is actually a piezo. A piezo you can drive with an Arduino pin. With a (8-ohm) speaker, you can't do that.


text:
Stop servo when enter 0
I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);
}

void loop()
{
  if (Serial.available () > 0)
  {
    state = Serial.read ();
    if (state == '1')
    {
      for (pos = 0; pos <= 180; pos += 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);
      }
      for (pos = 180; pos >= 0; pos -= 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);      // waits 15ms for the servo to reach the position
      }
      if (Serial.available () > 0)
      {
        state = Serial.read ();
        if (state == '0')
        {
          myservo.write ('90');
          delay (300);
        }
      }
    }
  }
}

Initialize state to 1, don't overwrite with value from Serial, but set to 0 when Serial reads 0.

From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'.  The loop section should look more like:
if(Serial.available()){
    state = Serial.read();
    if(state == '1'){
           Make motor move;
    }else if(state == '0'){
           Make motor stop;
    }//end of elseif
}//end of if


text:
What info should I look for when choosing a solid state relay for arduino?
I want to control a phone using an arduino board by connecting each pin of the arduino to a button on the phone using relays to simulate a button being pressed or release by switching a relay (on/off). I am using relays because from what I have seen (Use Arduino to Switch Power On and Off! ) relays are controlled swiches and I am using SSR because I want to use the less space possible.
I'm trying to buy a relay at mouser.com but I don't know what are the values I should look for, for those parameters (Control Voltage Range, Load Voltage Rating, Load Current Rating, Input Current).

You need to look at everything.

@IgnacioVazquez-Abrams yeah but I don't know what are the values I should seek

Do you know how a relay works?

All I know is that a relay has often 4 "inputs" 2 that I can use to connect a controller (the arduino) and 2 I can use to connect the controlled component (a button on the phone). I also know that mechanical relay (on the video) use an electromagnet on the control end to close the circuit.

Why use a relay for this? You can probably do this with some simple transistors. Or if you like the isolation, opto-couplers. What kind of phone are you talking about?

What do your phone buttons need?

I would tread carefully. A solid-state relay may or may not be suitable for the relatively low-level signals present across the phone buttons. Check the datasheet, buy just one, and try it out.
But do you need to control a physical phone? An Arduino can connect to a standard modem which has inbuilt commands to dial numbers and generally supervise a phone line.

An SSR is not a good choice for your application.  The common use of an SSR is for switching on and off an AC load.  If the data sheet mentions SCR or Triac, then it is meant for only switching AC and will not function for controlling DC.  So keep this in mind when looking for components: if it says "24-220 VAC" on the data sheet that does not mean it will work for DC.
A second common use of SSR and microcontrollers is the opto-coupled input type.  That input method provides a safe scheme for a low voltage low current control signal to switch a large load.
For a button on a phone, you are switching a near zero current DC load.  You should be able to control that with a transistor, but that would require some reverse engineering of how the phone keypads where being scanned.  You would need to trace out what the voltage was, how much voltage drop could be accommodated.
A certain easy method is to use a small reed relay.  Parts are available that have a coil that only draws ~10 mA so can be driven directly from an output pin.  The relays are packaged in a DIP so easy to prototype on a breadboard.  Many list the coil resistance and voltage for specs, for example a 5V and 500 ohm resistance coil would draw 10 mA.  You will find many for 1 - 2 $US.
When working with a relay, you need to take care of the back EMF (aka flyback voltage) that occurs when you turn off.  That is handled with a single diode which you will see in every schematic for driving a relay.  For a beginner, an alternate/sure success route is to use a driver chip such as a ULN2003 that will drive inductive loads such as small relays.

If you're only controlling a button, the load current and load voltage are pretty much irrelevant since I'd be surprised if you even used 5% of it's rating in either category. I can't tell you how much you'll need here since I don't know the voltage that the relay will be operated on and the resistance of the path for the load.
What you do need to look at is the voltage and current of the input/control/logic signal. It should allow a 5V control voltage and the current draw for that logic signal should be no more than 40mA, although it's ideal to stick to a lower number (say, 30mA).
However, manually picking out a relay manually isn't ideal for a beginner since it requires a bit of extra components to properly run. A relay module (Amazon) allows you just hook up your wires to the jumpers and terminals of the relay module without any extra soldering (as far as I know they aren't breadboard compatible, thus requiring a custom PCB or having it "flop") or parts.


text:
Use object of other class within class
I am writing a class for a project which will take care of handling any LCD updates for my project. The way I want to handle this is to initialize the LCD object in my main file, and then pass the LCD object on to my own class when initializing it.
The LCD object should be declared a private object in my class so several member functions can access it.
The problem is I can't find how to initialize the object correctly in the .h file.
Below is what I currently have, but when I try to build it, I get:
LCDController.h:_Clcd1' should be initialized
LCDController.h:_Clcd2' should be initialized

main .ino file:
void setup()
{
  //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
  LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
  LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

  LCDController.init(lcd, lcd2);
}

LCDController.h file:
// LCDController.h

#ifndef _LCDCONTROLLER_h
#define _LCDCONTROLLER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif
#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
    void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);
private:
   void _UpdateLCD(int iLine, int iPosition, String cText);
   LiquidCrystal& _Clcd1;
   LiquidCrystal& _Clcd2;
};

extern LCDControllerClass LCDController;

#endif

LCDController.cpp file:
#include "LCDController.h"
#include <LiquidCrystal.h>

void LCDControllerClass::init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1.begin(40, 2);
   _Clcd1.clear();

   _Clcd2 = Clcd2;
   _Clcd2.begin(40, 2);
   _Clcd2.clear();

}

What happens if you move the lcd and lcd2 definitions outside the setup function?

In C++, a class that holds reference members (in your sample, LiquidCrystal& _Clcd1; and LiquidCrystal& _Clcd2;) must ensure these references are initialized at construction time, not later.
This means your void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2); method is not the right way to initialize _Clcd1 and _Clcd2 because it will be called after construction time.
You have 2 ways to solve this issue,t hat I will detail further below.
HOWEVER, before we discuss the solutions, you must be aware that your sample code has a huge defect in setup() method code!
void setup()
{
    //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
    LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

    LCDController.init(lcd, lcd2);
}

Here, you create lcd and lcd2 in your setup method, but their life ends at the end of setup(), because they have been allocated on the stack. Using these outside setup() will most likely cause your program to crash as soon as your loop() tries to access lcd or lcd2, indirectly through LCDController method calls.
To remove this defect, you must declare these variables outside setup:
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(lcd, lcd2);
}

Now you can use them anywhere in your program, you are sure they are present and "alive".
Now we can go to the solutions of the original compilation problem.
1. Initialize references at construction by adding a constructor
class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2) {}
    ...
};

You can still keep an void init() method to complete the initialization if you don't want it to occur right at construction time, or you can fully integrate the current init() content into the constructor and re,voe init() altogether:
class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2)
    {
        _Clcd1.begin(40, 2);
        _Clcd1.clear();

        _Clcd2.begin(40, 2);
        _Clcd2.clear();
    }
    ...
};

In anycase, you will have to change the way you instantiate your LCDControllerClass LCDController which you did not show in your sample code, that would be something like this:
LiquidCrystal lcd(...);
LiquidCrystal lcd2(...);
LCDControllerClass LCDController(lcd, lcd2);

That obviously requires that you can instantitate lcd and lcd2 before creating LCDController. If that is not possible for you, then  you'll have to use the second way.
2. Replace references with pointers
As mentioned before, in a class reference members MUST be initialized at construction time (moreover, they cannot be changed afterwards, to point somewhere else). This is not the case for pointers however:
class LCDControllerClass
{
    public:
    void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);

    private:
    void _UpdateLCD(int iLine, int iPosition, String cText);
    LiquidCrystal* _Clcd1;
    LiquidCrystal* _Clcd2;
};

void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

Note that now, you need to use the arrow notation -> to access _Clcd1 and _Clcd2 members (dot notation cannot work for pointers).
The rest of the code should be slightly modified to reflect this change:
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(&lcd, &lcd2);
}

Note that we now have to pass the address of lcd and lcd2 to init(), by using & before their names.

Thanks for this great answer! Besides fixing my actual problem, you took the time to explain what was going wrong and I also understand the how and why. Thanks for making StackExchange great!

Could you also explain how I can later on in another member function of my LCDControllerClass create what I think should be another pointer to either _Clcd1 or _Clcd2? I have another member function should is in charge of putting text on the LCD, and depending on the line number that is passed to it (can be 1 to 4), it either has to update _Clcd1 or _Clcd2. I tried to accomplish this by defining LiquidCrystal* CActiveLCD = &_Clcd1 but this does compile but seems to crash my arduino...

@Alex I would suggest you post a new question (it is better than mixing several problems in one question) with the updated code, the explanation of what you want to achieve, and the problem you currently have. Cheers!

I was actually thinking if I should post a new question or not :) I just posted https://arduino.stackexchange.com/questions/9319/how-to-dynamically-switch-between-between-2-objects, would be great if you could chime in. Thanks again!


text:
arduino mega number of simultaneous pulse inputs
I'm looking at this specification page:
http://arduino.cc/en/Main/ArduinoBoardMega2560
It says there are 54 digital input pins. How many of those can be used at the same time to measure pulse input frequency? I've seen examples of a couple pins being used at the same time, but can it handle measuring frequency on say 12 pins at the same time?
Also I am looking at this bluetooth shield:
http://redbearlab.com/bleshield/
Would there be a limit on the number of simultaneous frequency measuring pulse pins when then this is added?
Currently I use an IOIO board and can monitor 9 pulseInput pins (at least it seems like it is simultaneous, but probably not, it has a PIC24FJ256GB206 microcontroller that has 9 input capture modules when used as single precision.) It works well with my around 15-30 Hz signals updated every 250 milliseconds. I'm wanting to move it to arduino for supported connectivity to many other devices. What are the capabilities of the arduino mega?

What are you using to measure?

@IgnacioVazquez-Abrams I think I will be using the pulseIn() method.

This depends on how long "the same time" lasts, and what frequencies you want to measure. There is no way for the processor to do anything simultaniously, but it can check all the pins in succession relativly fast. Thats no guarentee its fast enough though. BTW, pulseIn can only measure one pin at a time.

@BrettAM Currently I use an IOIO board and can monitor 9 pulseInput() pins (at least it seems like it is simultaneous, but probably not, it has a PIC24FJ256GB206 microcontroller that has 9 input capture modules when used as single precision.) It works well with my around 15-30 Hz signals updated every 250 milliseconds. I'm wanting to move it to arduino for supported connectivity to many other devices. What are the capabilities of the arduino mega?


text:
Error with Arduino/Processing Serial Communication
I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.
Arduino Code:
int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

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

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

Processing Code:
import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}

Nevermind, resolved!

It seems like you need to do some basic debugging:

Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.

Try using this code and run it on your Arduino
void setup() {
   Serial.begin(9600);
}

void loop() {

Serial.print('hello world');
}

After uploading the code open the serial monitor and see if it shows the string 'hello world' and make sure that the baud rate of the serial monitor is set on 9600. If nothing shows this could mean that there is something wrong with your Arduino board.

Serial.print('hello world'); is not correct. It should read: Serial.print("hello world"); and preferably: Serial.println("hello world"); Check out the difference between single and double quotes in C/C++.

oh sorry i wanted to use double quotes but i wrote it wrong :( @NickGammon


text:
Regarding the USB port, what is the difference between Uno/Mega and the older boards?
I would like to know what the exact difference is between the Uno and Mega boards and the older boards (Duemilanove, Diecimila, etc.).  Why do I need to install a FTDI driver for the older boards, and not for the Uno/Mega boards?  I was in a class the other day, using the Nano, and the lecturer recommended the FTDI drivers. The Nano is a newer type board, so why does that require a driver? I've just discovered that the Nano is old tech from 2008, after reading Are there any reasons to pick Nano over Micro?
What is it about the Uno and Mega boards that don't require the FTDI to be separately installed?
I see that the Getting Started w/ Arduino on Mac OS X page states that the older boards use the FTDI chip. Does that imply that the Uno/Mega boards do not? If they do not, then what do they use?
I have a vague notion that some USB sticks, keyboards, mouse and other various USB devices may contain a driver within the circuitry/firmware(?) of the device, which when connected to a PC for the first time, can be used to install the driver without the PC needing to access the web for the driver. Is this what the difference is between the UNO/Mega and the older devices? If so, is it possible to modify, or flash the firmware of the older boards so that they can connect without the need for an FTDI driver?

The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.
In the current Arduino boards, the USB to serial conversion is handled by dedicated Atmel Atmega8u2 processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.
So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.
Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".
Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.


text:
Can I control my Arduino using just a 2.4GHz Wireless Transceiver and a wireless Xbox 360 controller?
I want to control my Arduino using my wireless Xbox 360 controller. I've been looking up tutorials, and they all seem to recommend using a USB shield and the Xbox 360 wireless receiver.
I don't own either of those things, but I do own a 2.4 GHz wireless transceiver. Can I use it to listen to what buttons are being pressed on the controller? For example, if I press the A button on the controller, can I make an LED turn on?

Short answer is no, unless you have the machine and tools to do reverse engineering on the xbox controller proprietary 2.4Ghz protocol and you must have xbox 360 itself to see what goes on between Xbox 360 and the xBox controller. The time and money spent on these tools(hardware and software) aren't worth it.
The easiest way to do this is to buy the xbox controller receiver, Arduino USB shield and you can easily use your xbox 360 controller with your Arduino.

I contributed to this USB XBOX360 controller library to add multiple controller support, and to fix a couple of issues, including battery level indication. It worked fine for me with a cheap non-official version of the USB controller receiver, and a cheap version of the USB shield.

Would be good if you put this comment under the question. It will benefit the person that asked the question.

I don't know much about the engineering that goes into these kind of radios, but just being 2.4Ghz does not make them potentially compatible. xbox 360 controllers coexist with wifi and bluetooth without interfering, but they are all in the 2.4Ghz spectrum.
The xbox 360 controllers have some kind of proprietary frequency hopping system to avoid interference that you would first have find and reverse engineer before you could even get to the part about decoding the data, and your 2.4Ghz receiver probably can't match the 360 controllers even if you did know the pattern.
I'm relativly confident that it is practically impossible for that receiver to read 360 controller signals.

From the hardware side it should be possible but from the software it may not be easy.
Unless you find some documentation on the protocol that is used for communication between controller and receiver, you will need to decode the protocol (handshaking, commands, idle signals etc.) yourself.
Depending on the complexity of the protocol that could be rather frustrating.
I would recommend to do some research on the Internet first and see if there is material describing the protocol so you don't have to start from scratch.


text:
Arduino YUN server crashes after few hours!
I have made a simple server using the YUN SERVER and CLIENT Libraries./
The server runs on a loop and waits for a client to connect. After connection it sends the client a simple message and then disconnects the client.
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

#define PORT 6666
YunServer server(PORT);
int pin =13;

void setup() {
  Serial.begin(115200);
  Bridge.begin();
  server.noListenOnLocalhost();
  server.begin();
}
void loop() {
  YunClient client = server.accept();
  if(client.connected())
  {
    digitalWrite(pin,HIGH);
    //startup
    startup_msg(client);
  }
  else
    digitalWrite(pin,LOW);
    delay(500);
}
void startup_msg(YunClient client)
{
    client.print("SAndTerm");
    client.stop();
}

Well this code runs smoothly for few hours. But after that, it stops responding to any client request. I guess the server crashes.
I have to restart the YUN to get it working again.
Is there anyway I can run this without it getting to crash?
Well I want it to be running just like a normal server would.

Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date.
Here a link on how to do this
Another thing to try is to add delay(50); at the end of the loop() function. It prevents the processor from doing lots of work.

My YUN is upgraged to the latest firmware, and if you closely see the inside loop() there is already a delay of 500ms.
Anyway, I am just confused. It is suppose to behave like a server without any hassle. But its not.

I just noticed that. Maybe 500 millisecond is too much delay. 50 milliseconds is recommended on the Arduino website.
I would be happy to fix this easily by running it on my side here but I don't have YUN. I have Uno and Mega.
It looks like you are writing HIGH to pin 13 without making it OUTPUT. Assuming your goal is to turn on the led connected to pin 13, you should first make the pin OUTPUT once in the "setup()" function.
pinMode(pin,OUTPUT);
Also comment or remove Serial.begin(115200);  to see if that is the problem.
Finally, is this the whole code you are having problem with?

Thanks for your insights! Really helpful!
Well, i removed Serial.begin(115200) and set the pin 13 to output.
Now I just have to test this for few hours and see if it stays put without crashing.
And yes, this is the basic code I have now, but will be developing it for further work. Just needed to know if this was stable before proceeding!

Ok. Let me if it stops working again.

It has been over 24 hours. Did it work?

Sir, Its been 24 hours and its running without any problem.
I think you have fixed the problem.
Still I will be running it for few more days to check for any other issues.
Anyway it seems to be ok now! :)

Glad I was able to help you.


text:
My Arduino Robot doesn't move, and it's the only thing that doesn't work
It will be simple. I started to look at the sketch of the Arduino Robot and just tried one, Disco_Bot, and uploaded it one the top board. The Arduino started to play some music and the name was on de LCD screen but he wasn't moving. Then i tried then sketch Wheel_Calibration. The information was on the screen but the Robot was supposed to move so that i could calibrate the speed. I was lost so I went on the Arduino page for the Arduino Robot (http://arduino.cc/en/Guide/Robot) and found nothing that could explain my problem . So now I ask you, can you please help me because iI have no idea on what i should do.
Chris

Doesn't it require batteries for the motors? I tried looking at the schematic, but couldn't find the motor driver, so that was of no use.

Did you unplug the USB cables from the robot? The robot will never move if connected to some external device; this is a protection measure.

Did it work before (motors board) or it never worked since you have it? Is it possible you unintentionally uploaded something on the motor board and overwrote the sketch there (which you are not supposed to do except if you really know what you do)?

@Greben, well normally it comes whit a set of 4 pills but i noticed that the motor doesn't use the batteries and i have power it by a other source. Thank you for you're help !

@jfpoilpret, in the back i got i sed that it was all tested before shipping, but is thing i also did plug the usb cable on the motor board and may have overwrote the sketch that was preloaded. I'll try to find them to reste the board. Thank you for you're help !


text:
Ethernet Shield on Arduino Mini
I would like to connect my custom-made Arduino with an Ethernet shield but I'm not so sure I can.
The problem
My board is using the design from the Arduino Mini which lacks the ATmega16U2 which does the USB-to-serial conversion and adds the ICSP pins. I think you get the point... I have only the ATmega328P on the board. Nothing else.
Is it even possible to work my way around it without adding the ATmega16U2? I can't find the chip anywhere on Ebay.

Are you using an IEthernet shield (using a W5200, W5500 or such like), or do you mean a generic Ethernet shield? Your title and body are inconsistent. Not that important, but a little confusing :-)

Im using the shield with the W5500. Is there any difference with the other chips?

There may be some differences, but I was just trying to clarify whether the "IEthernet", in your title, was a typo or not. I understand now, that it wasn't :-)

You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the Schematic to see what pins are used for what (and which can be left unconnected)
The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v (the shield has it's own 3.3v regulator, so you only need to connect 5v)
That 16u2 doesn't do anything but usb-to-serial. It's not needed for the ethernet shield.
The ISP header is just 5v, GND, and the 3 SPI pins and reset. But those SPI pins are also broken out to the pins 11, 12 and 13.

So basicaly im just using the pins 11, 12 and 13 for the shield?

Indeed those, and 10 for the ChipSelect (SS). Pin 4, if you want to use the SD card functionality. See my edit concerning the 3.3v.


text:
How to dynamically switch between between 2 objects?
I have a 40x4 LCD which internally consists of 2 40x2 LCDs.
To control this LCD I have to create 2 LiquidCrystal objects and than later on in code decide which one to use depending on which of the 4 lines I want to change.
Due to the size of my project, I split all the LCD handling off to a separate class.
To make my code as readable and easy as possible, I want to create a member method of this class, to which I can just pass line number 1-4, and have this method take care of deciding which LiquidCrystal object to use.
LCDController.h:
#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
        void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);
 private:
   void _UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength);
   LiquidCrystal* _Clcd1;
   LiquidCrystal* _Clcd2;
};
extern LCDControllerClass LCDController;

My 2 LiquidCrystal objects are initialized in my main .ino file like so (before the setup() loop)
:
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

These two objects are then passed as pointers to my LCDControllerClass like so:
LCDController.init(&lcd, &lcd2);

The init() member method of my LCDControllerClass then puts these pointers in private variables like so:
void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

Then I have another private member method which should take care of updating the correct LCD object:
void LCDControllerClass::_UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength)
{
   LiquidCrystal* CActiveLCD;
   if (_iLine > 2)
   {
      //DisplayLine is higher than 2, this means we need to update the 2nd LCD
      LiquidCrystal** CActiveLCD = &_Clcd2;
      _iLine = _iLine - 2; //Convert line number to correct line number for 2nd display
   }
   else
   {
      //LiquidCrystal** CActiveLCD = &_Clcd1;
   }
   /* we have to convert this number
      to a real display line (0-1) by substracting 1 again
   */
   _iLine = _iLine - 1;

   CActiveLCD->setCursor(_iPosition, _iLine);
   CActiveLCD->print(_strText);
}

Now in this last member mehthor my code goes into the woods for some reason. The LCD is not updated at all and it seems the arduino is freezing as well since I put a small Serial.print() test in the main loop and it's not printing anything...
What is the correct way to pass the correct LiquidCrystal object to the CActiveLCD
object?

The problem is that you're declaring multiple pointer variables called CActiveLCD in the _UpdateLCD() function. You do it once at the start of the function like this:
LiquidCrystal* CActiveLCD;

You then declare a new and totally separate pointer inside the if block like this:
LiquidCrystal** CActiveLCD = &_Clcd2;

This is called masking. The original pointer you declared at the start of the function still exists, but you can't access it because it's temporarily replaced by the new one. When the if block finishes, that new pointer is destroyed (it goes out of scope) and the old one is available again.
All of that means you never actually store a value in the original pointer variable. The result is that it contains an arbitrary memory address, so attempting to use it at the end of the function results in undefined behaviour.
When you are assigning to the pointer inside your if block, you need to do it like this:
CActiveLCD = _Clcd2;

Notice that this doesn't declare a new CActiveLCD pointer. It simply copies _Clcd2 into the existing one. Additionally, it's important not to use the address-of operator here (&). Adding that in this context gives you a pointer-to-a-pointer. It is technically legitimate in C++, and sometimes does serve a useful purpose, but it's not what you want to do here.
As a side note, when declaring a pointer variable it's usually a good idea to initialise it to something. If you're not assigning an actual address to it right away then initialise it to 0, like this:
LiquidCrystal* CActiveLCD = 0;

This means you can check the pointer later on before using it. If it's 0 then you know it's not got a valid address yet so it's not safe to use. This isn't always strictly necessary, but it can help avoid some frustrating bugs.

Thanks a million, your answer solved my problem and explained the reason behind it!


text:
Which Arduino is compatible for atmega164pa
I am working on a project using 5 pins of ADC, 5 pins for PWM, and LCD. I need to use Atmega164pa. I would like to know how I can transfer it to Arduino. Is there any Arduino compatible with this chip?

You could port it yourself. It's not that hard.

@MattYoung what do you mean? do you suggest to avoid using Arduino?

Well actually yes, but you could port the Arduino libraries to a new device easily.

Why exactly do you need to use the 164PA?

@microtherion the reason is that ATMEGA16 does support at most 4 PWM channels while I need 5 PWM channels.

My question was meant to be more along the lines of why it would be an 164PA rather than a 644PA or 1284PA; for the latter, there used to be the Sanguino board, though it's not clear whether these still are produced.

There is an Arduino core for the '1284A, but it can be adapted to the '164A.

but the link is to the software not to the board. What is the name of board that I can buy for this software.

You don't need a board for it; the DIL package mounts on a breadboard.

sorry but what is DIL package?

http://en.wikipedia.org/wiki/Dual_in-line_package


text:
Possible to store variables directly in EEPROM?
Is it possible to store a variable directly in EEPROM and retrieve it without needing to use a library?
I'm building a project that can change the colour of an RGB LED and I want to store the colour in a non-volatile memory space, but I was wondering if I could avoid using one of the EEPROM libraries and have a global variable stored in nonvolatile memory, but still accessed directly, without needing to call a function.

It is possible - but comes down to rewriting it yourself, as there is quite a complex requirement to write EPROM & the libraries are not doing it a long way round just for fun ; take a look at the source code in the library to see how to do it.

Also be aware that EEPROM access time is slower than SRAM. It is preferrable to not use an EEPROM memory cell as a variable in your program, and rather save the value to EEPROM from time to time, and read it at reset time only.

"Without needing to call a function" is a curious requirement -- what is the benefit of that? Even if you write the EEPROM access yourself, you would wrap it in a function to avoid code duplication. (Unless you need it only in one place, but still wrapping in a function would be good programming style.)

Just use <avr/eeprom.h>, instead of the arduino library, which is atrocious.

"Without using a library" is probably a better description. I'd attempted to use the Arduino EEPROM library and it appeared to crash the chip, seemingly regressing to a prior Pin13-flashing program instead of the program I'd spent hours writing.

Writing and reading EEPROM is possible to do without a library. Take a look at the datasheet of the ATmega328P to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.
Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.
However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.

EEPROM can store one byte at a location. To store Integer variable, it requires two consecutive location. For Double, it requires four consecutive memory location. I have written function to store and read, int & double to and from built-in EEPROM. As per your question, you can modify it as per your need.

Actually this answer was copied from another thread.

/*
  StackExchange Question: "How to Store 2 analogRead values and read using EEPROM for Arduino uno?"
  Question Id: 15910 (https://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno)
  Author: Anurag S. Vasanwala (AnuragVasanwala@gmail.com)

  Tested on Arduino Version 1.6.7

  Description:  This sketch helps to store and read, Integer & Double to and from built-in EEPROM.
  Objectives:
    + Write Integer @ Specified Address (Fn: EEPROM_Write_Int)
      + Conversion from Integer to Byte Array
      + Store Bytes
    + Read Integer from Specified Address (Fn: EEPROM_Read_Int)
      + Read Bytes
      + Conversion from Byte Array to Integer
    + Write Double @ Specified Address (Fn: EEPROM_Write_Double)
      + Conversion from Double to Byte Array
      + Store Bytes
    + Read Double from Specified Address (Fn: EEPROM_Read_Double)
      + Read Bytes
      + Conversion from Byte Array to Double
 */
#include <EEPROM.h>

// MACRO : Combines FROM_BYTES into TO_OBJECT of datatype "DATATYPE"
#define CombineBytes(FROM_BYTES, DATATYPE, TO_OBJECT) \
  TO_OBJECT = *((DATATYPE *)FROM_BYTES);

// MACRO : Splits FROM_DATA of DATATYPE into equivalent byte array TO_BYTES
#define GetBytes(FROM_DATA, DATATYPE, TO_BYTES) \
  *((DATATYPE *)TO_BYTES) = FROM_DATA;

// Writes Integer's equivalent bytes to Address and Address + 1
void EEPROM_Write_Int(unsigned int Address, int Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, int, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads two bytes from Address and Address + 1 and returns equivalent int
int EEPROM_Read_Int(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  int Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to int
  CombineBytes(Temp_Buffer, int, Result);

  return Result;
}

// Writes Double's equivalent bytes to Address, Address + 1, Address + 2 and Address + 3
void EEPROM_Write_Double(unsigned int Address, double Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, double, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads four bytes from Address, Address + 1, Address + 2 and Address + 3 and returns equivalent double
double EEPROM_Read_Double(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  double Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to double
  CombineBytes(Temp_Buffer, double, Result);

  return Result;
}

void setup()
{
  // Initialize Serial @ 9600 baud
  Serial.begin(9600);

  // Print size of datatype just for reference
  /* Serial.print("Size of byte = ");
  Serial.println(sizeof(byte));
  Serial.print("Size of int = ");
  Serial.println(sizeof(int));
  Serial.print("Size of float = ");
  Serial.println(sizeof(float));
  Serial.print("Size of double = ");
  Serial.println(sizeof(double)); */

  int myInt1 = -290;
  int myInt2;
  double myDbl1 = 23.41;
  double myDbl2;

  // Write myInt1 @ 100 memory location; It requires 2 consequtive memory location to store integer
  EEPROM_Write_Int(100, myInt1);

  // Read integer located @ memory location 100 and assign it to myInt2
  myInt2 = EEPROM_Read_Int(100);
  Serial.println(myInt2);

  // Write myInt1 @ 200 memory location; it requires 4 consequtive memory location to store double
  EEPROM_Write_Double(200, myDbl1);

  // Read double located @ memory location 200 and assign it to myDbl2
  myDbl2 = EEPROM_Read_Double(200);
  Serial.println(myDbl2);
}

void loop()
{

}

This code is successfully tested on Arduino Version "1.6.7".

You can have a global variable in EEPROM if the EEPROM is memory
mapped. Memory-mapping
the EEPROM is possible on ATxmega
chips.
Notice that writes go to a temporary buffer, not the EEPROM itself,
until you explicitly issue a write command.
Most Arduinos, however, use ATmega chips, which do not have this
feature. I am not aware of any xmega-based Arduino or clone.