text:
Why is my arduino acting like a radio? And is there a way to abuse this?
I am playing around with an arduino and a cheap SDR dongle and I just noticed something strange!
When I play a tune on pin 13 with just a random piece of wire connected to the pin (Using the Melody example from the arduino page: http://www.arduino.cc/en/Tutorial/Melody)
I can pick it up as AM sound on my SDR on exactly 64Mhz even as far as 15meters away through walls with a little gain!!!
What magic is going on here and secondly and maybe most importantly would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?
(Just for educational purposes of course, I know that there is better options depending on what I need to send)

I would like any qualified guess as to what is going on, I am genuinely puzzled...

https://www.youtube.com/watch?v=HV6YQ4WKtYY

That gives a good explanation for the signal. Thanks, still don't understand how the internal RF-clock can affect pin output, interresting that it can be hacked into transmitting FM signals too!

My guess is you are seeing harmonics of your pin's output. Fast toggling digital signals, like your PWM, carry heavy harmonic content. I would expect many more peaks, but your setup may be by pure luck (stray inductances and capacitances) well tuned for that particular band.

@EdgarBonet the display isn't wide enough to see the other harmonics

I did something like that a while ago. Hardware:

Code:
const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.
If you hold the Arduino near an AM radio tuned to around 800 KHz you should hear a hissing toggling on and off (like Morse code) as the carrier is turned on and off for 0.5 / 0.3 second intervals.

would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

I think you might find making a receiver a bit harder than a transmitter.

I just tried to modify the Melody example, replacing the digitalWrite calls with pinMode and I can basicly now play tunes on the AM band, is that even legal :D ?

I doubt it. I also doubt it would have enough power to get much further than the walls of your room.

Bottom line: The OP has built an 800 kHz AM radio transmitter. All it transmits is an 800mHZ carrier signal.  If you modulated the amplitude of that carrier, you could transmit sounds. However, an Arduino doesn't have the processing power to do that. You'd be better off building an analog 800 kHz AM transmitter.

I dont think Nick Gammon's answer actually explains clearly enough what is going on - he just made an example of how to do it. Since no-one else on this site has had a go at explaning it-I will-though Im no expert in arduino radio communications.
"What magic is going on here"
Its not magic -you are observing the principle of "electromagnetic induction" and the principle of "resonance".
Its not unique to arduino- basically an Antenna transmits information by making on and off power changes in the electrical current in the wire-as you are doing playing the melody. By the famous Maxwell equations this energy in the wire creates a corresponding invisible waves in the air. A well known circuit in electrical engineering (tank circuit or oscillator circuit) says that there is also a corresponding receiver circuit (which can be a radio) that will change the waves back into sound (by using the principle of electrical resonance).

I think the “magic” the OP is talking about is not the propagation of electromagnetic waves, but rather the emission being at 64 MHz, way above anything the Arduino does.

@Edgar Bonet. I can only at best guess what the OP is thinking (from what they wrote in the question) and I think a new reader would appreciate to know what going on in terms of electromagnetic waves-and how how an antenna works-especially if they really didnt know any physics or how transmitters and receivers work


text:
uint8_t * to integer and string
Convert text array/buffer to integer and string.
hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.
Atm the text send is a number between "0" and "1023"
void something(uint8_t * text){
 analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/

i need to convert it to an  integer or better to a uint16_t.
As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.
i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++
if it's needed the length is also aviable inside the function.

Your problem is that you are storing your text in an unsigned pointer (uint8_t *)instead of a signed pointer (char *).
If you change all your text types to char * then you can directly use atoi().  If you have a lot to change, though, you can just cast the unsigned pointer into a signed one (and make it const at the same time):
analogWrite(13, atoi((const char *)text));

its from a websocket lib... i would need to rewriter the whole lib...anyway this worked perfectly

btw i will update this analogwrite at 60Hz . is "cast" slow/are there faster ways to convert the buffer to a string or int?

@cocco Cast makes no difference at runtime, only compile time.  There are faster ways to convert than atoi, but they aren't as safe - i.e., they don't do any bounds checking.

it works but i have a bigger problem now. it crashes really fast. i can't send data faster than 2 times per second. maybe you know more about this.http://arduino.stackexchange.com/questions/17811/esp8266-websockets

analogWrite is a function to set a PWM duty cycle value to a pin on the micro
Usually to control a motor speed or LED brightness or similar.
Unless you plan to use the char value to set the PWM value??
A bit more context would help with your problem.

i control a led with websockets. now it works. @Majenko answered it correctly

This isn't really an answer.

I've converted first four bytes to string, and then to int :
void something(uint8_t * payload){
String str="";
char c;
for(int i=0;i<4;i++)
    if (isDigit(c=(char)(*(payload+i))))
        str += c;

int Val =str.toInt();
Val=Val>1023?1023:Val;

analogWrite(14,Val);
}

This is a very inefficient approach.

source: Stack Exchange

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

sort: votes


text:
Use all pins As digital I/O
Increase the number of digital pins
There are many post that explain how to use more than just the standard pins on the various arduinos but none of them explain the limitations and the proplems properly.

Arduino Uno:
1.You can use the analog pins
Pin 14 = Analog in 0
Pin 15 = Analog in 1
Pin 16 = Analog in 2
Pin 17 = Analog in 3
Pin 18 = Analog in 4
Pin 19 = Analog in 5

digitalWrite(14,HIGH);
or
digitalWrite(A0,HIGH);

2.You can't use both SDA , SCL & A4 , A5 as they are basically the same (18,19).
3.You can also use the TX/RX.

"Don't do it, you break the serial communication..."
"Never use pins 0 and 1"
"you can't use the TX/Rx Pins"

You can... but you need to take precautions. Which ones?
It should have software serial over USB, right?
Or do i break the USB serial?
Are there internal Chip problems if i use TX/RX?
As i use those TX/RX pins in the code i probably should not use Serial.print()?
What happens if i forget to remove Serial.print() after uploading the code that use pins 0,1?
How to hardware reset the arduino/bootloader if something goes wrong?
As there are various other Arduino's that use different chips, is the above valid for all Atmel chips?
So, what shuold i know before using those TX/RX or also maybe the other analog pins?

There are cheap shiftregisters, pwm drivers, led drivers, spi, i2c and
  more ic's to expand your I/O

But if there are not to big problems it means that the arduino has 20 I/O pins...
You could theoretically control:
17x3 = 51 = 17 RGB leds (multiplexing, pwm sourcing&sinking);
14x6 = 84 leds (multiplexing, pwm on 6 rows/colums );
10x10 = 100 leds (multiplexing, high low);
20x(20-1) = 380 leds (charlieplexing, high low);
// yes it would flicker

Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one arduino.

The main issue is with pins 0 and 1.
Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc.  But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.
All the other pins, while being multi-function, have their function defined basically by what you attach to them.  Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

As soon as you enable Serial in your sketch (Serial.begin()) those two pins can no longer be reliably used for digital IO.

That means that you can either use the hardware serial port or you can use the pins for digital IO, but not both.

Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches.  You have serial data coming in from the PC while the same pins are being affected by other things connected to them.  The most common one is things like GPS modules which connect to those pins and constantly send serial data.  That serial data will conflict with the PC's serial data and neither will arrive right.

How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't.  It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering.  Just disconnect those two pins from whatever is connected and you will be able to upload sketches again.  Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield.  You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc.  Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins.  That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.

"Many shields now are starting to add a small switch" cool. Micro has "USB to Serial bridge chip" ?  Does that mean i can use pins 0,1 on uno but not on micro?

You can use them on any that do not have a USB to Serial bridge. The Uno has one, the Mega has one, the Mini doesn't have one, however you do need to connect one externally to the TX/RX pins to program it.  All of those are out.  The Micro, and the Leonardo do not have one, so you can use those.

Thats what @Nick Gammon is talking about ? Uno and the others you wrote down have pullup resistors that don't allow you to properly use pin 0 and 1 but the Micro has no pullup resistor and so pins 0 and 1 work properlky and also the usb to upload new sketches?

For once Nick is mistaken on that point. There aren't any pullup resistors. What is there is a pair small inline resistors to prevent problems if the main MCU and the USB chip both try driving the same line to opposite levels at the same time.  You can see them on the Uno schematic as RN4A and RN4B.

If the USB chip happens to try driving the RX pin (you have the USB port plugged in and you open the serial connection [or maybe it's just plugged in, not sure]) then it can affect the voltage on the RX pin independent of whatever you're doing in your sketch, so it may not be safe to use that pin for things like charlieplexing.

so i can charlieplex 380leds or switches with an Uno if i don't use serial,i2c,spi. if the usb is not used as serial. then if i want to add a new sketch i just need to unplug stuff from pin 0 & 1.At the other side with micro i don't even need to unplug pins 0,1 as they are not connected to the usb?

That is almost correct.  You may be able to use 0 and 1 for charlieplexing, but the USB chip may still interfere despite your best efforts.  Different USB chips work in different ways, and it depends on what firmware is loaded on the USB chip on those that use an MCU instead of a dedicated chip like FT232 etc.

Even if the usb is not connected but i use only vin or the dedicated power supply? Once programmed i use a external powersupply usb is not connected. to change sketches remove pin0,1stuff

That is not a question that can be answered with a simple "yes" or "no".  It completely depends on what the USB chip does and that depends on what the USB chip is, which depends on what the board is, where you bought it from, who designed and built it, etc.  It's best to assume the worst and not use those pins for that kind of operation.

It's unclear ... or they work or they don't ... if it's something like yes it works with charlieplexing as the interferences are to low to have a visual impact on the leds , while using switches its not suitable a could get to many bad readings. btw i'm talking about original Arduinos.. Uno rev 3 and microalso latest... the "real" arduinos. Maybe it implies that the chip firmware also changes and so it could write some random data on those pins? like i said usb is not connected after programming. has the chip some sort of loop on those pin to check if it's connected or whatever?

what happens if i put 2 leds inverted(with resistors) on pin 0 and 1, set pin 0 high pin 1 low delay 1 second and set pin 0 low and pin 1 high delay 1sec? same question i asked Nick.

Let us continue this discussion in chat.

Have you tried it?  You won't do any damage by having a go. Yes, firmware can (and probably will) change over time.

i try, post updates later.. i hope my arduinos don't explode.AAAAAnd that i'm able to program it later with other sketches...

Tested on Arduino Uno, 2 inverted leds on pin 0,1 blink correctly , no visible interferences even if powered with usb from pc. sketches load normallly also with the leds plugged in.actually the tx rx are probabliy wired exactly as the test as you can see in and out tx rx comunication... so if it works on uno... the arduino micro should have totally no problem.

I can't comment due to insufficient reputation but I want to point out that the OP pinout has at least one pin wrong!
PB6 should be PB5
I spent quite a lot of time trying to figure out why I couldn't see SCK on scope (SPI bus). I was working low level, not with the IDE.
As this is the first picture that comes up when googling I wanted to avoid the same trouble to others...

20x(20-1) = 380 leds (charlieplexing, high low);
  Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one Arduino.

First, the figure of 380 is correct for 20 pins (202 - 20) however pins 0 and 1 are connected to pull-up resistors on the Atmega16U2, so they are never really at 0V. If you load a blank sketch, you will measure 5 V on pins 0 and 1.
Second, you can't drive 380 "whatevers" you can drive 380 LEDs via Charlieplexing. The property of the LED, that current only flows one way through it, is important to the way it works.
Related question Is there a way to have more than 14 Output pins on arduino?

First: what happens if i put 2 leds inverted(with resistors) on pin 0 and 1, set pin 0 high pin 1 low delay 1 second and set pin 0 low and pin 1 high delay 1sec?

Second: By "whatevers" i mean switches... click switches, reed switches, sensors or every type of combination of inputs outputs that support high low.http://electronicdesign.com/site-files/electronicdesign.com/files/archive/electronicdesign.com/files/29/18652/fig_02.jpg done with diodes.

Well, not really. Charlieplexing is a form of multiplexing, so unless you want your switches clicking like mad, it won't really work for them. And it is an output situation, so you won't be doing inputs, like you seem to think. I suggest you read the other links. Shift registers, or port expanders, are more practical than Charlieplexing here.

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


text:
The code to turn off the RGB LED by pressing the 4,5,6 switches in sequence doesn't work
I'm making photoresister alarm. When distance under 5cm over notes[] 5 times, piezo speaker off. And I want to turn off the led rgb by pressing the 4, 5, 6 switches in sequence. The code to turn off the led rgb by pressing the 4, 5, 6 switches in sequence does not work. What's wrong? Here is a code below.
int pins[]={4,5,6};
int melody[]={262,294,330};
int notes[]={392,392,440,440,392,392,330};
int b=0,r=0,g=0;

void setup() {
  // put your setup code here, to run once:
 randomSeed(analogRead(A0));
 for(int i=0;i<3;i++){
   pinMode(pins[i],INPUT);
 }
}
int c=0;
int value1=digitalRead(4);
int value2=digitalRead(5);
int value3=digitalRead(6);

void loop() {
  // put your main code here, to run repeatedly:
  int vin=analogRead(A0);
  if (c>5){
    //  b=0,r=0,g=0;
    noTone(8);
    //analogWrite(11,b);
    //analogWrite(10,r);
    //analogWrite(9,g);
   // return;
  }
  if(digitalRead(0)==HIGH){
    if(digitalRead(1)==HIGH){
      if(digitalRead(2)==HIGH){
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }
    }
  }
  if(vin>800){
    for(int i=0; i<7 ;i++){
      tone(8,notes[i],100);
      delay(200);
      noTone(8);
      analogWrite(11,random(256));
      analogWrite(10,random(256));
      analogWrite(9,random(256));
      delay(200);
    }
  }
  long duration = pulseIn(3,HIGH);
  long distance=duration/58.2;
  if(duration == 0){
    return;
  }
  if (distance<5){
    c++;
  }

}

The code to turn off the RGB LED by pressing the 4, 5, 6 switches in sequence, RGB LED is off. And when distance under 5cm over notes[] 5 times, piezo speaker off.

How are the switches connected? Have you tested with a single switch to see what effect it has? There are presently a number of odd things in your code. At the moment it looks like you need to press switches connected to port 0, 1 and 2 (shouldn't that be 4, 5 and 6?) simultaneously to turn off the LED. You need a simple state machine to allow your code to detect them in sequence. You're declaring value1, value2 and value3 but never use them. You're initializing the pins[] array with the values 4, 5 and 6 but never use it except in the initialization code.

thank you for your advice. I goin' to check my code.

What's wrong? ... your program is unfinished

Umm... I'm goin' to check the code.

This might not be correct because I'm new in arduino projects but i think the problem comes from here
On your setup
for (int i=0;i<3;i++)
pinMode(i,OUTPUT);

SHOULD BE
for (int i=4;i<=6;i++)
pinMode(i,OUTPUT);

on your loop
if(digitalRead(0)==HIGH){
    if(digitalRead(1)==HIGH){
      if(digitalRead(2)==HIGH){
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }

I think you need to change the pin to
if digitalRead(4).....
if digitalRead(5)......
if digitalRead(6)....

Just change it that way maybe it may work.
Remember to remove the // on the b=0,r=0,g=0
And also remove the double slash // from the analogWrite
And I see you declaring value 1,2,3 and not using them.
hint...
int value1;
int value2;
int value3;
int delaytime=500; //half a second

value1=digitalRead(4); /* you are supposed to press the button on pin 4 by now */
if (value1==HIGH) {
  delay(delaytime);
  value2=digitalRead(5); /* you are supposed to press the button on pin 5 by now */

  if (value2==HIGH) {
    delay(delaytime);
    value3=digitalRead(6); /* button on pin 6 is supposed to be pressed by now */
    if (digitalRead(6)==HIGH) {
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }
  }
}

I added the delay because that might be the greatest problem you have. Arduino is fast at processing, so in order for it to work when you press the three button you will need to press the three all at once before it can give you the output. But if you want to press them one by one, you need to add the delay and make sure you press the three button before the delay time elapse.

I Appreciate to your advice.

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


text:
How to make 2 lidar lite v3 work with 1 Arduino?
I'm using the code below, but I had no success.
I'm using this connection wire:
The photo of the Arduino doesn't show the SCL and SDA pins, but please consider that it has 2 SCL pins and 2 SDA pins in the places where I marked them in the image.
Both sensors are working, however they are mirroring each other's measurements.
That link is from the datasheet:
https://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf

#include <Wire.h>
#include <LIDARLite.h>

#define LIDAR1_ADDRESS 0x62 // Endereço I2C do LIDAR Lite 1
#define LIDAR2_ADDRESS 0x63 // Endereço I2C do LIDAR Lite 2

LIDARLite lidar1; // Objeto para o LIDAR Lite 1
LIDARLite lidar2; // Objeto para o LIDAR Lite 2

void setup() {
  Wire.begin();        // Inicializa a biblioteca Wire (I2C)
  Serial.begin(115200);  // Inicializa a comunicação serial

  // Inicializa os objetos dos LIDARs
  lidar1.begin(LIDAR1_ADDRESS); // Inicialização do LIDAR Lite 1
  lidar2.begin(LIDAR2_ADDRESS); // Inicialização do LIDAR Lite 2
}

void loop() {
  int distance1 = lidar1.distance();
  int distance2 = lidar2.distance();

  // Exibe as medições dos LIDARs no Monitor Serial
  Serial.print("LIDAR 1: ");
  Serial.print(distance1);
  Serial.print(" cm | LIDAR 2: ");
  Serial.print(distance2);
  Serial.println(" cm");

  delay(500); // Intervalo entre as leituras
}

what does mirroring each other's measurements mean?

you connected one to I2C bus and the other to the SPI bus ... why don't you connect both sensors to the same bus?

had no success doesn't tell us much. What is actually happening? What is appearing in the serial monitor?

I agree with @jsotola - if these are I2C devices, why connect one to the SPI port? I2C devices can be connected in parallel.

@jsotola, I'm so sorry, I wasnt really clear. Let me try again, both sensors seem to be measuring , but when I place an obstacle in front of either of then, both show the same reading on the serial monitor.

@NickGammon both sensors seem to be measuring , but when I place an obstacle in front of either of then, both show the same reading on the serial monitor, and i need that both display individual readings.

@jsotola sorry, that arduino in the image is not the same as mine. My arduino has two scl a sda pins. Where you are seeing the ISCP pins actually has a scl and sda pins

I put these twoaddress but im not sure if they are rigth. how can i get theses address?

I put the wire example to get the address, but the serial monitor only show me the "device found at address 0x62 "

Is the address of both Lidar Modules configurable and did you configure them on the boards (hardware)? If not it is possible that both listen and react to both of the addresses simultanously and then I2C transports the superposition of the bits from both devices to the arduino which then gets the same (possibly wrong) values independent of which device it tries to connect to.

@PeterPaulKiefer no, I didn't any configuration on the hardware, I just wire like the image and put the code.

What type of lidar device do you use (I mean the board not only the chip/sensor)? Do you have a link to its documentation? How did you know which addresses are appropriate? Have you a link to the docs of the used Arduino Library (LIDARlite). If you read the docs you might find the answers yourself. If not, show us the links; I mean add them to your question and you increase the chance, that someone invests more time and may help you.

@GUSTAVOTELES You haven't answered my question. You say "both sensors seem to be measuring", on your diagram you show one connected to the SPI port. This won't work. If the diagram is completely wrong, fix it or remove it. You are using I2C addresses 0x62 and 0x63. If you haven't configured the hardware they will both be responding to 0x62, which would account for the same readings. There appears to be an option to change the address, according to the datasheet. The I2C address can be changed from its default value. Have you done that?

My arduino has two scl a sda pins. - Don't post a photo which shows something completely different from reality. That just confuses everyone. Either photograph your own setup with your phone and upload it, or just sketch a circuit diagram.

@NickGammon You are sure I just changed the diagram for the real that I'm using, actually I didn't understand how to configure the hardware.

@PeterPaulKiefer I just added the link of documentation, On page 5 of the datasheet has the instruction to change, but didn't understand properly how do that.

Maybe my page didn't refresh, I see it now.

Run the I2C scanner described here - if that only shows one device, then naturally it will only give one reading. If not, please amend your question to show what the results are.

@NickGammon I used aTCA9548A multiplexer and I solved the addressing problem.

@NickGammon I appreciate  a lot your support, thank you.

Please make your own answer to this question and describe how you solved it, so as to help future people with the same problem. Thank you!

If these are the Garmin Lidar Lite V3, here is a link to their data sheet. On page 5 of the datasheet you'll find instructions for configuring their I2C addresses. If you haven't already done that, it's quite likely that both devices are replying at once to the same query.
If you have done that already, please update your question with that and any other relevant data - such as the manufacturer, if I got that wrong, add any configuration changes you've made.

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


text:
Keyboard key press listener
Is there a way to make a listener for a key press to begin a loop?
Example:  I press the Tab key on my keyboard and the programmed loop begins running.
Essentially creating a keyboard hotkey.

Please edit your question so that it meets the quality standards set out in the help center.

The answer is yes and no.
Only the Arduino and its IDE, no.
The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.


text:
Arduino disconnecting at upload
This problem doesn't seen to be very common around the Arduino community.
Basically, what's happening is that as soon as I click the upload button, the Arduino IDE tells me that my Arduino board is not connected. What's strange though is that the python application ino is able to upload my code just fine, so my only guess is that there is something wrong with the IDE itself.
Here's a copy of the error message I am getting at the time of uploading the sketch:

Binary sketch size: 444 bytes (of a 32,256 byte
maximum)processing.app.SerialException: Error opening serial port
'/dev/ttyACM1'.at processing.app.Serial.<init>(Serial.java:178)at
processing.app.Serial.<init>(Serial.java:77)at
processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)at
processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
processing.app.Sketch.upload(Sketch.java:1671)at
processing.app.Sketch.exportApplet(Sketch.java:1627)at
processing.app.Sketch.exportApplet(Sketch.java:1599)at
processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
java.lang.Thread.run(Thread.java:744)Caused by:
gnu.io.UnsupportedCommOperationException: Invalid Parameterat
gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:213)at
processing.app.Serial.<init>(Serial.java:163)... 9
moreprocessing.app.debug.RunnerException: Error opening serial port
'/dev/ttyACM1'.at
processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:101)at
processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
processing.app.Sketch.upload(Sketch.java:1671)at
processing.app.Sketch.exportApplet(Sketch.java:1627)at
processing.app.Sketch.exportApplet(Sketch.java:1599)at
processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
java.lang.Thread.run(Thread.java:744)

I am expecting to hear a few questions regarding this issue, so I'll go ahead and answer all the questions I can think of.

Is this the first time you trying to connect to the Arduino from this computer?

No. In fact, I was able to upload the same source code just fine less than two hours ago.

Did you try a different USB cord?

Yes, I did.

Can you upload the source code from a different computer?

Yes, I can.

Have you tried removing and reinstalling the IDE?

Yes, I have.

Have you tried a different USB port?

Yes, I have.
What seems to be the problem here?

What platform are you on?

@jippie Peppermint Linux

Does ls -l /dev/ttyACM* list the exact device that is mentioned in the error message, and is this the exact device set in the Arduino IDE under Tools => Serial Port?

/dev/ttyACM1 was the port to the board until it got disconnected. So in short, when I click upload, it starts uploading then stops half way through and prints out the error message mentioned in the question above. I know the IDE is what is disconnecting the board. What I want to know is why!

Are any devices / peripherals connected to the Arduino? If so, disconnect everything then try to program it.

Please consider switching to a more recent version of the IDE: version 1.5.6 has replaced buggy and old RXTX library with JSSC. Updating may not solve your problem, but at least it makes sure you're not facing old and already solved problems.

I'm having a similar situation on my older work computer.. I feel like it is the hardware on the computer (HP xw9400 Workstation) that is causing the the Arduino to keep connecting and diconnecting. Perhaps it is a low power signature coming in from the Arduino that the usb port "loses" the Arduino. I will try with another computer to see if this is the case.

First of all, you must test if the device that you are trying to access, actually exists. The device file may change when you replug the Arduino. The easiest way to accomplish that is to find the device name in the error message, in this case /dev/ttyACM1. Then check two things:

Does the device file exist in  the /dev tree? ls -l /dev/ttyACM*
Is the Arduino IDE configured to use the correct device? Check under Tools => Serial Port.

Maybe another application is using the device. When working on Linux, you can verify this with the following commands:
$ lsof /dev/ttyUSB0
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
avrdude 7356   jippie    3u   CHR  188,0      0t0 266450197 /dev/ttyUSB0

or
€ fuser /dev/ttyUSB0
/dev/ttyUSB0:         7356

Where of course you have to replace /dev/ttyUSB0 with the device file as mentioned in the error message. In case of this question /dev/ttyACM1, but do notice that the number can change when you unplug the board for a moment and then replug it.
In both results, the 7356 is the PID of the process that is locking the device. In my example I was reading flash from the command line, so the output for your specific situation will be different. To identify the process, you can use:
$ ps -fp 7356
UID      PID  PPID  C STIME TTY          TIME CMD
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

or a more portable command:
$ ps -ef | grep 7356
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

If another application is using the device, how come I can still upload to the board from ino?

@FadiHannaAL-Kass Good question. Did fuser or lsof list a PID? Maybe there is something else going on.

@FadiHannaAL-Kass For example, I have a daemon running on my PC that queries my Arduino only every so many seconds. If I am attempting to program that Arduino, and the query comes along, then the program cycle fails. Maybe some serial monitoring program is running?

I have already used ls -al to make sure the device exists. I also unplugged the board and ran the command again to make sure I am looking for the right device. The Arduino IDE is pointing to the right port as well. When I upload and get the error message, the Tools --> Serial Port menu gets disables, so that's another way to know the device has been disconnected while uploading. lsofand fuser, however, don't list a PID, so now I also know no other application is interrupting the upload process!

I might be able to get away with Installing a new Linux version, but I want to be prepared in case this happens ever again

@FadiHannaAL-Kass Reinstalling Linux is not going to solve your issue. In the Windows world people reboot their system, reinstall their machine. In the Unix/Linux world, we figure out why things happen and fix them.

It most likely will, as I have performe the exact same process on a different Linux distro on the same machine, and everything worked fine

@FadiHannaAL-Kass isn't it more effective to figure out why things go wrong and subsequently fix them, rather than reinstalling your PC every time something happens that you don't understand (yet)?

exactly. that's why I said I want to be prepared in case this ever happens again

A pretty detailed troubleshooting guide is available at arduino.cc. Besides the checks already mentioned in the question and the answers, it is recommended to check that serial.download_rate is set to 19200 in ~/.arduino/preferences.txt.
19200 is the default baud rate used by most bootloaders, so this doesn't apply if you don't use one, or use a modified version.

Try setting the baud rate to 9600 in the Serial Monitor. You need a working serial port to open the Serial Monitor. Or go to >File >Preferences> and edit the preferences.txt (must close Arduino IDE before editing) "serial.debug_rate=9600"
I have several Arduino boards and had the exact same issue with the boards that use the Atmel mega8U2 as the USB - serial bridge. The boards with the FTDI USB bridge (SparkFun Red board, Pro mini) did not show the same problem. Setting the baud rate solved my problem.
There is a firmware upgrade for 8U2 that might fix it but I didn't want to risk making bricks. ;-)

Does the baud rate in the serial monitor affect the uploading process? I'm not so sure it does but Arduino can be quirky sometimes ;)

I have same problem after set baud rate to 14400.
For fix this I manual set serial.debug_rate=115200 in config file ~/.arduino/preferences.txt

Actually, setting the baud to 14400 is exactly where my issues started too.


text:
Error compiling code (tv-b gone)
I have been getting started with the Arduino and found a great project online called TV-B-Gone. It includes some code which I cannot compile. Yes I have included main.h and worldcodes.cpp.
/*
TV-B-Gone for Arduino version 0.001
 Ported to Arduino by Ken Shirriff, Dec 3, 2009
 http://arcfn.com

 The original code is:
 TV-B-Gone Firmware version 1.2
 for use with ATtiny85v and v1.2 hardware
 (c) Mitch Altman + Limor Fried 2009
 Last edits, August 16 2009

 With some code from:
 Kevin Timmerman & Damien Good 7-Dec-07

 Distributed under Creative Commons 2.5 -- Attib & Share Alike

 This is the 'universal' code designed for v1.2 - it will select EU or NA
 depending on a pulldown resistor on pin B1 !
 */

#include "main.h"

void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code );
void flashslowLEDx( uint8_t num_blinks );
void quickflashLEDx( uint8_t x );
void tvbgone_sleep( void );
void delay_ten_us(uint16_t us);
void quickflashLED( void );
uint8_t read_bits(uint8_t count);

#define putstring_nl(s) Serial.println(s)
#define putstring(s) Serial.print(s)
#define putnum_ud(n) Serial.print(n, DEC)
#define putnum_uh(n) Serial.print(n, HEX)

/*
This project transmits a bunch of TV POWER codes, one right after the other,
 with a pause in between each.  (To have a visible indication that it is
 transmitting, it also pulses a visible LED once each time a POWER code is
 transmitted.)  That is all TV-B-Gone does.  The tricky part of TV-B-Gone
 was collecting all of the POWER codes, and getting rid of the duplicates and
 near-duplicates (because if there is a duplicate, then one POWER code will
 turn a TV off, and the duplicate will turn it on again (which we certainly
 do not want).  I have compiled the most popular codes with the
 duplicates eliminated, both for North America (which is the same as Asia, as
 far as POWER codes are concerned -- even though much of Asia USES PAL video)
 and for Europe (which works for Australia, New Zealand, the Middle East, and
 other parts of the world that use PAL video).

 Before creating a TV-B-Gone Kit, I originally started this project by hacking
 the MiniPOV kit.  This presents a limitation, based on the size of
 the Atmel ATtiny2313 internal flash memory, which is 2KB.  With 2KB we can only
 fit about 7 POWER codes into the firmware's database of POWER codes.  However,
 the more codes the better! Which is why we chose the ATtiny85 for the
 TV-B-Gone Kit.

 This version of the firmware has the most popular 100+ POWER codes for
 North America and 100+ POWER codes for Europe. You can select which region
 to use by soldering a 10K pulldown resistor.
 */

/*
This project is a good example of how to use the AVR chip timers.
 */

/*
The hardware for this project uses an Arduino:
 Connect an IR LED to pin 3.
 Connect a visible LED to pin 13 (or use builtin LED in some Arduinos).
 Connect a pushbutton between pin 1 and ground.
 Pin 0 is floating for North America, or wired to ground for Europe.
 */

extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

/* This function is the 'workhorse' of transmitting IR codes.
 Given the on and off times, it turns on the PWM output on and off
 to generate one 'pair' from a long code. Each code has ~50 pairs! */
void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code )
{
  TCNT2 = 0;
  if(PWM_code) {
    pinMode(IRLED, OUTPUT);
    // Fast PWM, setting top limit, divide by 8
    // Output to pin 3
    TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(WGM22) | _BV(CS21);
  }
  else {
    // However some codes dont use PWM in which case we just turn the IR
    // LED on for the period of time.
    digitalWrite(IRLED, HIGH);
  }

  // Now we wait, allowing the PWM hardware to pulse out the carrier
  // frequency for the specified 'on' time
  delay_ten_us(ontime);

  // Now we have to turn it off so disable the PWM output
  TCCR2A = 0;
  TCCR2B = 0;
  // And make sure that the IR LED is off too (since the PWM may have
  // been stopped while the LED is on!)
  digitalWrite(IRLED, LOW);

  // Now we wait for the specified 'off' time
  delay_ten_us(offtime);
}

/* This is kind of a strange but very useful helper function
 Because we are using compression, we index to the timer table
 not with a full 8-bit byte (which is wasteful) but 2 or 3 bits.
 Once code_ptr is set up to point to the right part of memory,
 this function will let us read 'count' bits at a time which
 it does by reading a byte into 'bits_r' and then buffering it. */

uint8_t bitsleft_r = 0;
uint8_t bits_r=0;
PGM_P code_ptr;

// we cant read more than 8 bits at a time so dont try!
uint8_t read_bits(uint8_t count)
{
  uint8_t i;
  uint8_t tmp=0;

  // we need to read back count bytes
  for (i=0; i<count; i++) {
    // check if the 8-bit buffer we have has run out
    if (bitsleft_r == 0) {
      // in which case we read a new byte in
      bits_r = pgm_read_byte(code_ptr++);
      // and reset the buffer size (8 bites in a byte)
      bitsleft_r = 8;
    }
    // remove one bit
    bitsleft_r--;
    // and shift it off of the end of 'bits_r'
    tmp |= (((bits_r >> (bitsleft_r)) & 1) << (count-1-i));
  }
  // return the selected bits in the LSB part of tmp
  return tmp;
}

/*
The C compiler creates code that will transfer all constants into RAM when
 the microcontroller resets.  Since this firmware has a table (powerCodes)
 that is too large to transfer into RAM, the C compiler needs to be told to
 keep it in program memory space.  This is accomplished by the macro PROGMEM
 (this is used in the definition for powerCodes).  Since the C compiler assumes
 that constants are in RAM, rather than in program memory, when accessing
 powerCodes, we need to use the pgm_read_word() and pgm_read_byte macros, and
 we need to use powerCodes as an address.  This is done with PGM_P, defined
 below.
 For example, when we start a new powerCode, we first point to it with the
 following statement:
 PGM_P thecode_p = pgm_read_word(powerCodes+i);
 The next read from the powerCode is a byte that indicates the carrier
 frequency, read as follows:
 const uint8_t freq = pgm_read_byte(code_ptr++);
 After that is a byte that tells us how many 'onTime/offTime' pairs we have:
 const uint8_t numpairs = pgm_read_byte(code_ptr++);
 The next byte tells us the compression method. Since we are going to use a
 timing table to keep track of how to pulse the LED, and the tables are
 pretty short (usually only 4-8 entries), we can index into the table with only
 2 to 4 bits. Once we know the bit-packing-size we can decode the pairs
 const uint8_t bitcompression = pgm_read_byte(code_ptr++);
 Subsequent reads from the powerCode are n bits (same as the packing size)
 that index into another table in ROM that actually stores the on/off times
 const PGM_P time_ptr = (PGM_P)pgm_read_word(code_ptr);
 */

uint16_t ontime, offtime;
uint8_t i,j, Loop;
uint8_t region = US;     // by default our code is U

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

  TCCR2A = 0;
  TCCR2B = 0;

  digitalWrite(LED, LOW);
  digitalWrite(IRLED, LOW);
  pinMode(LED, OUTPUT);
  pinMode(IRLED, OUTPUT);
  pinMode(REGIONSWITCH, INPUT);
  pinMode(TRIGGER, INPUT);
  digitalWrite(REGIONSWITCH, HIGH); //Pull-up
  digitalWrite(TRIGGER, HIGH);

  delay_ten_us(5000);            // Let everything settle for a bit

  // determine region
  if (digitalRead(REGIONSWITCH)) {
    region = US; // US
    DEBUGP(putstring_nl("US"));
  }
  else {
    region = EU;
    DEBUGP(putstring_nl("EU"));
  }

  // Tell the user what region we're in  - 3 is US 4 is EU
  quickflashLEDx(3+region);

  // Indicate how big our database is
  DEBUGP(putstring("\n\rNA Codesize: ");
  putnum_ud(num_NAcodes);
  );
  DEBUGP(putstring("\n\rEU Codesize: ");
  putnum_ud(num_EUcodes);
  );
}

void sendAllCodes() {
  // We may have different number of codes in either database
  if (region == US) {
    j = num_NAcodes;
  }
  else {
    j = num_EUcodes;
  }

  // for every POWER code in our collection
  for (i=0 ; i < j; i++) {
    PGM_P data_ptr;

    // print out the code # we are about to transmit
    DEBUGP(putstring("\n\r\n\rCode #: ");
    putnum_ud(i));

    // point to next POWER code, from the right database
    if (region == US) {
      data_ptr = (PGM_P)pgm_read_word(NApowerCodes+i);
    }
    else {
      data_ptr = (PGM_P)pgm_read_word(EUpowerCodes+i);
    }

    // print out the address in ROM memory we're reading
    DEBUGP(putstring("\n\rAddr: ");
    putnum_uh((uint16_t)data_ptr));

    // Read the carrier frequency from the first byte of code structure
    const uint8_t freq = pgm_read_byte(data_ptr++);
    // set OCR for Timer1 to output this POWER code's carrier frequency
    OCR2A = freq;
    OCR2B = freq / 3; // 33% duty cycle

    // Print out the frequency of the carrier and the PWM settings
    DEBUGP(putstring("\n\rOCR1: ");
    putnum_ud(freq);
    );
    DEBUGP(uint16_t x = (freq+1) * 2;
    putstring("\n\rFreq: ");
    putnum_ud(F_CPU/x);
    );

    // Get the number of pairs, the second byte from the code struct
    const uint8_t numpairs = pgm_read_byte(data_ptr++);
    DEBUGP(putstring("\n\rOn/off pairs: ");
    putnum_ud(numpairs));

    // Get the number of bits we use to index into the timer table
    // This is the third byte of the structure
    const uint8_t bitcompression = pgm_read_byte(data_ptr++);
    DEBUGP(putstring("\n\rCompression: ");
    putnum_ud(bitcompression);
    putstring("\n\r"));

    // Get pointer (address in memory) to pulse-times table
    // The address is 16-bits (2 byte, 1 word)
    PGM_P time_ptr = (PGM_P)pgm_read_word(data_ptr);
    data_ptr+=2;
    code_ptr = (PGM_P)pgm_read_word(data_ptr);

    // Transmit all codeElements for this POWER code
    // (a codeElement is an onTime and an offTime)
    // transmitting onTime means pulsing the IR emitters at the carrier
    // frequency for the length of time specified in onTime
    // transmitting offTime means no output from the IR emitters for the
    // length of time specified in offTime

#if 0

    // print out all of the pulse pairs
    for (uint8_t k=0; k<numpairs; k++) {
      uint8_t ti;
      ti = (read_bits(bitcompression)) * 4;
      // read the onTime and offTime from the program memory
      ontime = pgm_read_word(time_ptr+ti);
      offtime = pgm_read_word(time_ptr+ti+2);
      DEBUGP(putstring("\n\rti = ");
      putnum_ud(ti>>2);
      putstring("\tPair = ");
      putnum_ud(ontime));
      DEBUGP(putstring("\t");
      putnum_ud(offtime));
    }
    continue;
#endif

    // For EACH pair in this code....
    cli();
    for (uint8_t k=0; k<numpairs; k++) {
      uint16_t ti;

      // Read the next 'n' bits as indicated by the compression variable
      // The multiply by 4 because there are 2 timing numbers per pair
      // and each timing number is one word long, so 4 bytes total!
      ti = (read_bits(bitcompression)) * 4;

      // read the onTime and offTime from the program memory
      ontime = pgm_read_word(time_ptr+ti);  // read word 1 - ontime
      offtime = pgm_read_word(time_ptr+ti+2);  // read word 2 - offtime
      // transmit this codeElement (ontime and offtime)
      xmitCodeElement(ontime, offtime, (freq!=0));
    }
    sei();

    //Flush remaining bits, so that next code starts
    //with a fresh set of 8 bits.
    bitsleft_r=0;

    // delay 250 milliseconds before transmitting next POWER code
    //delay_ten_us(25000);
    delay_ten_us(10000);

    // visible indication that a code has been output.
    quickflashLED();
  }
  while (Loop == 1);

  // flash the visible LED on PB0  4 times to indicate that we're done
  delay_ten_us(65500); // wait maxtime
  delay_ten_us(65500); // wait maxtime
  quickflashLEDx(4);

}

void loop() {
  if (digitalRead(TRIGGER) == 0) {
    sendAllCodes();
  }
}

/****************************** LED AND DELAY FUNCTIONS ********/

// This function delays the specified number of 10 microseconds
// it is 'hardcoded' and is calibrated by adjusting DELAY_CNT
// in main.h Unless you are changing the crystal from 8mhz, dont
// mess with this.
void delay_ten_us(uint16_t us) {
  uint8_t timer;
  while (us != 0) {
    // for 8MHz we want to delay 80 cycles per 10 microseconds
    // this code is tweaked to give about that amount.
    for (timer=0; timer <= DELAY_CNT; timer++) {
      NOP;
      NOP;
    }
    NOP;
    us--;
  }
}

// This function quickly pulses the visible LED (connected to PB0, pin 5)
// This will indicate to the user that a code is being transmitted
void quickflashLED( void ) {
  digitalWrite(LED, HIGH);
  delay_ten_us(30);       // 30 millisec delay
  digitalWrite(LED, LOW);
}

// This function just flashes the visible LED a couple times, used to
// tell the user what region is selected
void quickflashLEDx( uint8_t x ) {
  quickflashLED();
  while(--x) {
    delay_ten_us(DELAY);  // 150 millisec delay between flahes
    quickflashLED();
  }
}

When I try compile and upload to my Arduino Mega 2560, I get this error
In file included from main.h:9:0,
                 from TVB.pde:21:
TVB:78: error: variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
TVB:79: error: variable 'EUpowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

Is there any way I can fix this?

"Is there any way I can fix this?" Yes.  You can change NApowerCodes and EUpowerCodes to be const like the error tells you.

As @Majenko suggested, add const. Recent versions of the compiler enforce this. When that code was written they did not.

Try:
extern  PGM_P * const NApowerCodes[] PROGMEM;
extern  PGM_P * const EUpowerCodes[] PROGMEM;

The definition of PGM_P is:
#define PGM_P const char *

which gives "const const" and gives "error: duplicate 'const'". But it is the variable that should be const.
Cheers!


text:
Manually Declare Global Variable
Is it possible to manually declare a global variable that is inside of a function. The only current way I know how to do so is to declare that variable within the setup() function or simply outside of any function, but I was hoping there was a way to manually declare a variable as global so that I may call one variable from within one function in another function.

You need to research 'Scope'.
Your variable has to be at the same level as all functions that will use it.  So at a simple level the answer has to be no.
int variableOne = 0;
void setup ()
{
  variableOne = 1;
}
void loop ()
{
  variableOne = 2;
}

The above code will work, but if you move int variableOne = 0; inside either function then it won't work, because the variable will not be in scope in the other function.
You can use parameters to functions.
void AFunction (const int& variable);

Will let you pass a single integer value to the function from the parent.  You can't change that value, because of the const qualifier.  If you remove the const then the & means pass the parameter by reference, which means you are passing in a reference (pointer) to the variable in the parent function and you can change it.  A better way to change the parent's value is to return a value from the call.
int AFunction (const int& variable);

So you could use this like this:
int AFunction (const int& variable)
{
  return (++variable);
}
void loop (void)
{
  int value = 0;
  value = AFunction(value);
  // value now == 1.
}

You could use a Singleton class, but this is hardcore and I'm not sure you would see any real benefit on an Arduino.  A class is a grouping of related function and variables that you see in libraries and a Singleton class means there will only ever be one during the lifetime of the program.  In this way you can declare an instance of the class (i.e. CSingleInstanceClass onlyOne;) and then retrieve/set data from the setup and loop function, i.e.
void setup ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  onlyOne.SetVariableOne (1);
}
void loop ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  Serial.println(onlyOne.GetVariableOne());// Prints 1
}

Hope that helps.

Thank you so much! I have decided to declare the types above the setup function, even though I understand this takes up a bit of dynamic memory, but not  much to worry about. I really appreciate the thoughful response, and will definitely come back to this post in the future!

@JonathanA: Types do not consume memory.

Global variables use 731 bytes (35%) of dynamic memory, leaving 1,317 bytes for local variables. Maximum is 2,048 bytes. This is what I was referring to.

Types are the type of the variable, so int or char.  It is referring to what you think, its just the word you used was a bit wrong.  If memory is that much of an issue (I don't think it is yet) then you could look at using external RAM, an additional IC, but that will be slow compared to main RAM.

even though I understand this takes up a bit of dynamic memory

There is no way around that. They have to go somewhere and that place is RAM (exception: constants could be stored in flash).
Another variation (which goes beyond your question) is that a parent function could declare and build a collection of data in a local array or struct and pass a pointer to it to any sub-functions. It still takes RAM, but it will be on the parent function's stack, so only for the duration of parent function's execution(s); it will be released when the parent function exits.

Appreciate it JRobert!

Please note that 'Scope' of a variable is limited inside the block ( a block starts at { and ends at } ), and that variable cant be accessed outside the block.
consider life time of a variable as well. using the keyword static may can help you some times. refer this link.


text:
Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?
In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.
I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.
My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
An optional library would need installing in only one place;
Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.

I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.
Lets start with the Libraries
What you do is:
In arduino eclipse ide remove all libraries from the library manager.
In windows->preferences->arduino->"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.
Then the boards
The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content.
If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
Step 1: Keep as little boards as possible installed. You have to keep at least 1 or the plugin will reinstall the AVR boards of Arduino when started.
Step 2: In windows->preferences->arduino->"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
Step 3: Recreate the project in eclipse as described in your other question.
Step 4: If the build fails modify the [eclipse installation]/arduinoPlugin/post and pre processing files to try to get it to work.
Step 5: in project properties->Arduino select apply and OK (this will take your changes in step 4 into account)
Step 6: Goto Step 4
Good luck
Jantje

This works - except for one library set (Blynk) - but I was surprised that #include <someLibrary.h> was not sufficient; that the library had to be imported as well. In the Blynk librarycase, their example program compiles in the Arduino IDE but Eclipse complains that it can't find a Blynk.begin() with a signature matching the call from the example program.

About the boards: Does that mean I can't compile the same code for either an Uno or a Mega2560 at will? Or I can, but not if I upgrade the Arduino IDE (currently v1.6.7 with eclipse plugin 'mac64.2016-03-23_03-43-04')?

The way Arduino IDE finds libraries is different from the Arduino eclipse ide. This may explain why Blynk was not found and needed to be imported. The Arduino IDE searches the content of the library folders for (header)files matching your include. The Arduino eclipse plugin finds libraries based on foldername=include -".h"

I do not understand your board question.

.h files: Are you saying quoted .h file names will be found automatically but bracketed ones won't?  -- Boards: You wrote "For libraries I am 100% sure it will work but the problem is the platforms." and described some limitations due to the board manager. I didn't understand what the consequences are or when they might happen.

Making Blynk libraries, v0.3.6 and (presumably) later, Eclipse compatible.
With much help from Jantje (thank you!), I found 4 easy steps that make the Blynk v0.3.6 libraries Eclipse-compatible:

Create .../libraries/Blynk/Blynk.h (may be empty) and #include it before including any Blynk libraries.
Likewise, create and #include .../libraries/BlynkESP8266_Lib/BlynkESP8266_Lib.h
Delete the entire folder .../libraries/Blynk/linux (unless you're running Linux! In which case, some more discovery needs doing.)
In Blynk projects previously imported to Eclipse Arduino, delete the (possibly hidden) file .ino.cpp and do a clean build.

This recipe works for me under MacOS 10.11.5, the Eclipse Arduino IDE nightly build, and ArduinoIDE version 1.6.9. It should be reproducible by anyone wishing to compile Blynk programs in Eclipse. Under OSes other than Mac, especially linux, step 3 may need to be modified. I deleted the linux folder to prevent Eclipse from compiling main.cpp and BlynkDebug.cpp from there which was resulting in multiple definition errors at link time.
The above is an excerpt from a how-to I posted to the Blynk community but I think this has all of the relevant information.


text:
Controlling an RC car using Arduino
I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.
I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?
I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.
If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.
The code I'm using to test everything looks like this:
void setup() {
  //Initialize the pins and serial
  pinMode(reversePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
}

void reset() {
  digitalWrite(forwardPin, HIGH);
  digitalWrite(reversePin, HIGH);
  digitalWrite(leftPin, HIGH);
  digitalWrite(rightPin, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  reset();

  digitalWrite(forwardPin, LOW);
  delay(4000);
  reset();
  digitalWrite(reversePin, LOW);
  delay(4000);
  reset();
  digitalWrite(leftPin, LOW);
  delay(4000);
  reset();
  digitalWrite(rightPin, LOW);
  delay(4000);
}

Images: https://i.sstatic.net/mCpcI.jpg

Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)
If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.
If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.
The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.
Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.
You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.
You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628

Can't measure the current, it just shows 0. Open circuit voltage between controller's ground and control wire is 3.1V. Controller is powered by 2 1.5V batteries btw.

At 3.1V, a 150 ohm resistor would limit the current to 20mA.   If you can put a 150 ohm resistor between the control wire and control ground, does the motor operate normally? Also can you measure the voltage across the resistor?  If it works with the 150ohm resistor, you could put the resistor in series between the control wire and the arduino input and use it as a current limiting protection resistor.

Didn't have a 150 ohm resistor, used a 330 ohm one instead. Voltage across the resistor is 0.54V. Every possible combination of directions now works. Does it matter if it's 330 or 150 ohm? Thanks for the help, this was more complex than I thought.

A 0.54V drop across a 330 ohm resistor is 0.0016A of current, which is well within the Arduino's I/O capability.  That same current through the 3.1V - 0.54V=2.56V voltage drop inside the controller implies it has about 1600 ohms of internal resistance, so you could rely on the controllers's internal protection you just measured and go without any resistor at all.  I assume you connected the common ground as well -- If so, that is the main improvement.   The resistor fiddling was testing that the controller would not overload your arduino.

Tried connecting the controller ground to the Arduino ground and that didn't change anything. It only works when I'm using the resistors.

Hmm.  If the controller ground is not connected, and the only connection between the two are the four controller signal lines, I'm confused.  Please post  a schematic and maybe a picture of your controller and  connections in your Question.  If only the 4 controller signal wires are connected between the two, the best I can guess is that it is storing a charge somehow relative to the other pins/device, which seems sort of magical and unreliable.

Added image of controller and arduino in the question. Can't provide a schematic for the controller unfortunately.

Ah.  The Arduino's output of 5V is probably feeding too much voltage into the controller, confusing it when you have the ground connected.  You will  probably need something like the level-shifting in http://arduino.stackexchange.com/a/419/6628

We have to add 1k resistors and 2k resistors as 330 ohms instead and follow the link below..!


text:
pass class internal function as callback
I am trying to pass a class internal function as a callback function within the class. The error behavior is similar to this problem. Whatsoever, I was unable to construct working code based on that question's answer.
I try to pass over a callback function from within the class,in order to create a finite state machine, inspired by the examples I found on adafruit regarding multithreading. The idea is, that each state can call his successor. The class itself then represents the state machine and I just will call its update function.
While the following code does not resemble this utility, it resembles the problem in a minimal example (based on this larger codepiece):
class MyClass
{
  const byte theAnswer = 42;
  void (*myCallback)();

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }

  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

  void call()
  {
    myCallback();
  }

   MyClass()
  {
    setCallback(&MyClass::print_info);
  }
};

MyClass AClassOfItsOwn();

void setup()
{
  Serial.begin(9600);
  while (! Serial); // Wait until Serial is ready
}

void loop()
{
  AClassOfItsOwn.call();
  return;
}

I get the following error code returned:

...testscript.ino: In constructor 'MyClass::MyClass()':
testscript:25: error: no matching function for call to
  'MyClass::setCallback(void (MyClass::*)())'
     setCallback(&MyClass::print_info);

                                     ^

...\testscript.ino:25:41:
  note: candidate is:
...\testscript.ino:6:12:
  note: void MyClass::setCallback(void (*)())
   void setCallback(void (*callback)())

        ^

...\testscript.ino:6:12:
  note:   no known conversion for argument 1 from 'void (MyClass::)()'
  to 'void ()()'
...\testscript.ino:
  In function 'void loop()':
testscript:40: error: request for member 'call' in 'AClassOfItsOwn',
  which is of non-class type 'MyClass()'
   AClassOfItsOwn.call();

                  ^

exit status 1 no matching function for call to
  'MyClass::setCallback(void (MyClass::*)())'

fun times with polymorphism
This is code we discussed during looking for a solution. I leave it here for future reference.
I tried creating an instance of this wrapper within the actual class to hold the callback, but that did not work either.
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  {
    myCallback();
  }

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }
};

class MyClass : public CallbackWrapper
{
  const byte theAnswer = 42;
  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

   MyClass()
  {
    CallbackWrapper::setCallback(&MyClass::print_info);
  }
};

trying to store the callback function in a wrapping class (also not working, '((MyClass*)this)->MyClass::CBW' does not have class type)
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  { myCallback(); }

  void setCallback(void (*callback)())
  { myCallback = callback; }
};

class MyClass
{
  const byte theAnswer = 42;
  CallbackWrapper CBW();
  public:
  void print_info() { Serial.println(theAnswer); }
  void call() { CBW.call(); }
  MyClass()
  { CBW.setCallback(&MyClass::print_info); }
};

An update on why I want to change the callback function during runtime. Here I try to randomly change the callback function:
class MyClass
{
  CallbackWrapper CBW();
  public:
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CBW.call();
    if (rand() > 0.5)
    {
      CBW.setCallback(&MyClass::do_this)
    }
    else
    {
      CBW.setCallback(&MyClass::do_that)
    }
  }
   MyClass()
  {  }
};

For discussion with Michail
class CallbackWrapper
{
  public:
  void (*myCallback)();
  void call()
  { myCallback(); }

  virtual void setCallback(void (*callback)())
  {  }
};

class MyClass : public CallbackWrapper
{
  public:
  void setCallback(void (*callback)())
    { myCallback = callback; }
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CallbackWrapper::call();
    if (rand() > 0.5)
    { setCallback(&MyClass::do_this); }
    else
    { setCallback(&MyClass::do_that); }
  }
   MyClass()
  {  }
};

A member function does not have the prototype that you think. It has a hidden parameter for "this". A static member function could work as callback function but then it could not access member data. You should consider using virtual instead. The callback setting is then done by sub-class and implementation of the virtual member function. The C++ run-time will do the dispatch depending on the instance.

OK, I tried a bit with virtual functions, but I cannot make it run (see latest addition of code failure). Could you provide an example?

Have a look at this https://github.com/mikaelpatel/Cosa/blob/master/examples/Blink/CosaBlinkFSM/CosaBlinkFSM.ino and the FSM library https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/FSM.hh. The state is a callback style function.

Without addressing the polymorphism part of the question, I have a post about calling an ISR from a class.

Unless you specifically limit yourself to one single class for a callback (i.e., include the class name in the function pointer specification) then you can ONLY use static member functions as callbacks.
static member functions appear as a normal function, not a member function, so don't have the implied MyClass *this as a first parameter.
If you want to allow member functions that aren't static you will have to make use of polymorphism and have a single base class that all classes which provide a callback function will inherit from.  Then you limit the callback function pointer to be members of that base class.
It is possible to do it if you are happy to limit to just one class, though the syntax is rather cryptic:
class MyClass
{
  const byte theAnswer = 42;
  void (MyClass::*myCallback)();

public:

  void call() {
    (this->*myCallback)();
  }

  void setCallback(void (MyClass::*callback)()) {
    myCallback = callback;
  }

  void print_info() {
    Serial.println(theAnswer);
  }

  MyClass() {
    setCallback(&MyClass::print_info);
  }
};

Using polymorphism you can only pass a callback function that is a member of the parent class, so it looks like that method may be out.

So, I tried creating a base class CallbackWrapper which has the callback functionality ((*myCallback)(), setCallback() and call()). I inherited MyClass from that base class. I tried to hook up my Callback using CallbackWrapper::setCallback(&MyClass::print_info()). Return is no matching function for call to 'MyClass::setCallback(void (MyClass::*)())'

I can't visualize what you are describing. Polymorphism is a tricky subject and easy to get wrong.

I abuse the edit question to post my futile try. (:

That's not abuse - that's what it's there for.  You're not using polymorphism in the right way - you need to think along the lines of an "interface" as Java has it.  I'll see about an example.

Actually, I am not sure even I can do it using polymorphism - it's incredibly tricky.  Can you have just one standard function name that will always be the callback function in a class?

I appended another code piece to explain why I want to change the callback during runtime. In my specific case, I think I could try with some tedious code refactoring I could e.g. define a class State, which will have an initialization (constructor) and an update() and an exit callback. All could be based on the same abstract base class, which I think is what you envisioned in the first place?

Callbacks with classes are an absolute nightmare to manage. If I must have one (say for an interrupt handler) it is always either static or an external wrapper function - never an instance member function. I am wondering if what you are trying to achieve is actually the best way to do what you want to do...

I think you are right; I will rethink how to do what I want to do. I could imagine I could find a better way to deal with this problem.

@Faultier I have finally found the right syntax for passing an internal member function within the same class, but you are limited to just the one class with that method.

seems almost right, but execution yields me ´request for member 'call' in 'AClassOfItsOwn', which is of non-class type 'MyClass()'´


text:
Motor controller for 24v motor, Arduino Uno
I need a motor controller for a 24v motor and I want to control it using än Arduino Uno. Suggestions?
The motor needs to run both directions and is going to draw about 5A

I see, the Arduino Motor Shield only supports upto 12V. But there are motor controllers for 24V and beyond that and can find those on ebay, aliexpress and whatever local suppliers you can find.

try this Arduino Compatible Mega Motor Shield. Specs:

Low-cost robust H-bridge ''shield'' for Arduino
Provides the ability to control up to 30A of current at up to 28V
Supply voltage: 5V to 28V (24V max battery rating)
Continuous output current: 13A
Have, a look:

I'm doing my own driver dude using Tip122 but you can use TIP120 too TIPand other components

Using bipolar power transistors for this is far from the best idea in this day and age.  This is a classic MOSFET application.  Also, since you posted the question has been updated to clarify the need for bidirectional drive, which means two high side switches and two low.

better invest few dollars and use a motor controller that will keep you from shooting threw the MOSFET transistors, enable soft start of motor and let you select between fast decay and slow decay when PWM is in OFF state. ( see details for DRV8814 by TI)


text:
Problem running WiFiWebClient example
I'm running the WiFiWebClient example which comes preloaded with Arduino IDE 1.6.7. I'm using Arduino Uno board with WiFi Shield Model R3.
/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using a WiFi shield.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>

char ssid[] = "Vanilla Sky"; //  your network SSID (name)
char pass[] = "mypass";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

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

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

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80) == 0) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: keep-alive");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

It gets my WiFi shield connected to Vanilla Sky but doesn't fetch the HTTP request (see image below). What is getting wrong here?

Let's break it down :)

Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.
https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading
Also add this to your project to help us determine your firmware:
  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer,  the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.
Just b/c it connects to your router, doesn't mean that it can still communicate correctly.
One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting
Hope this helps!

My firmware version is 1.0.0 and it's not a concern unless you're using it for a sophisticated application. 1.0.0 should be able to do at least simple GET requests. I'm using Arduino Uno with the WiFi shield Model R3. My IDE version is 1.6.7


text:
Problem updating Arduino WiFi Shield's Firmware
I'm using Arduino Uno R3 and the official Arduino WiFi Shield R3. I'm trying to update the Shield's firmware to 1.1.0 through this guide.
Everything goes fine until Step 9. When I execute the code in Step 10, I get an error (see attachment) as:
AtLibUsbDfu: 3EB 2FF8 no device present
FAIL Could not open USB device.
ISP done.

EDIT: I re-installed the firmware on my shield and now the problem's gone.

I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.

Many of the online instructions do not work. This one does - http://arduinotronics.blogspot.com/2015/06/upgrading-arduino-wifi-shield-firmware.html