text:
How to measure voltage with Arduino analog input
I'm totally new to Arduino and to electrodynamics in general.
I'm wondering what happens if I connect my digital pin to an analog input on Arduino, and make digitalWrite and analogRead on the according pins. Here are the options I can think about:

Just connect them directly - it is not a short circuit, is it?
Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?
Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

As you see, I'm really confused now. I would highly appreciate if someone could explain in detail what is happening in all the cases, with corresponding values for the current, voltage and resistance.

The more interesting cases are connecting the input such that there's a resistor between the input and the digital output and another resistor between the input and ground, forming a voltage divider.  Or connecting the input to a PWM output via a several kilohm resistor and connecting the input to ground via a several uF capacitor, forming a filter to smooth the PWM duty cycle into an analog voltage.

You can connect digital pin to analog input directly. That's not very interesting though, since you'll only see two values from the analog input (at least theoretically).
The digital pin gives out 0 or 5 Volts. The analog pin expects 0 to 5 Volts input. The only thing that matters to the analog input is the voltage with respect to ground. That can be between 0 to 5 volts (returned as 0...1023 by analogRead function).

Just connect them directly - it is not a short circuit, is it?

No, it's not a short circuit. In general, connecting anything to an input is not a short circuit. Connecting output to another output is potentially a short circuit.

Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?

This makes no difference compared to connecting them directly, unless the resistor value is very high (should be hundreds of kOhms or even MOhms to see a difference, I suppose), because almost no current flows to the input.

Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

This makes no other difference than that the resistor loads, i.e. draws current from, the digital output. If the resistor value is too small, then the digital output is unable to supply enough current so the 5 V voltage could become less than 5 V, or you could even burn the chip.

Thank you for the detailed answer!
I didn't get "you'll see the two values" - not only one, voltage? And I didn't get the last paragraph. Can it be explained with only I = U/R?

You see one value at a time, of course, but the value will be either 0 (digi-out LOW, 0 Volts) or 1023 (digi-out HIGH, 5 Volts). You cannot create, for example, 2.5 Volts with the digi-out, which is either on or off. The last paragraph, yes, I = U/R, and your digi-out has either 0 or 5 Volts, so I = 0 for LOW and I = 5 / R for HIGH digi-out state. If R is small, then I becomes high. The top limit is 20 mA for some Arduinos at least. If you use 250 Ohm R, then you'll get 20 mA from 5 Volts.

If you have a 250 ohm resistor from the digital pin to Gnd, and connect the digital pin to an analog input pin, then 20mA will flow thru the resistor to Gnd (5V/250 ohm = 20mA), while almost nothing flows into the analog input, as the max input current is 1uA per the datasheet, implying the input acts like a large resistor to Gnd: High input of 5V/.000001A = 5Meg-ohm.
I say acts because the input pin is the gate of a MOSFET, and a diode protection clamp to +5 and another to Gnd to limit the input voltage to -0.5 and Vcc+0.5V (so 5.5V with Vcc = 5V).
The diode clamps are only good for ~1mA (not shown in the data sheet, but discussed in an application note on detecting AC zero crossing), exceed that and you risk blowing the diode and/or the input pin and/or the chip (which will then feel warm or hot to the touch when it is powered up).
That's why you don't apply signals to unpowered chips - to prevent damaging the diode clamp circuits.


text:
Problems with Dallas temperature sensor code
I have connected up my temperature sensor and I am trying to run the one wire address finder to find the address of the sensor.
The problem is that when I run the code it gives me the error: 'OneWire' does not have a type.
I have imported by the temperature and the onewire libraries but it still does not work.
#include <OneWire.h>

OneWire ds(6);  // This is where the error is

I assume this a compile-time, not run-time, message? Please copy/paste it. What OneWire library are you using? Were there any other error messages, especially any about OneWire.h not being found?

I presume the exact error you get is

error: 'OneWire' does not name a type

This error is typical when the OneWire library (or any other library for that matter) is not located under the  libraries folder, which should be at the root of the Arduino installation folder.
Also, make sure that the OneWire.h and OneWire.cpp files are 1 folder down the hierarchy, as follows:
[Arduino Installation Folder]\libraries\OneWire\OneWire.h
If they are nested deeper inside the folder hierarchy, the Arduino IDE will not find these files in its initial scan, and you will get the same error.
Make sure to close all Arduino IDE windows and re-open it after fixing the folder path.

source: Stack Exchange

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

sort: votes


text:
AnalogRead always 1023 on Arduino Due?
Just using the Basic Example AnalogReadSerial.
// the setup routine runs once when you press reset:
  void setup()
{
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

I have a basic voltage divider set up between two 10K resistors from 5V to GND. I have verified with a DMM that the DC voltage at pin A0 is 2.5V. Grounding the A0 pin has no effect.
It also seems that enabling either ADC channel 7 (Arduino pin AD0) or enabling every channel, putting the ADC in free-running mode, and deliberately setting it to not sleep has no effect:
ADC->ADC_CHDR = 0;
ADC->ADC_CHER |= 0xFF;
ADC->ADC_MR |= 0b10000000;
ADC->ADC_MR &= 0b11011111;

Also, by running the sketch DigitalInputPullup, I can get the LED on pin 13 to toggle and serial communication to work as I tie the pin to ground, demonstrating that the board is being programmed properly.
I guess I'm just stumped. Should be the simplest thing in the world and it's just not working.
EDIT:
This is my attempt at manually controlling the ADC:
volatile unsigned long value;

void setup()
{
  //ADC setup
  ADC->ADC_WPMR &= 0xFFFE; //disable write protect
  ADC->ADC_CHER = 0b100; //Enable AD2     |
  ADC->ADC_MR &= 0b11111111000000001111111100000000;
  ADC->ADC_MR |= 0b00000000000100100000000000000000; //software trigger, hi res, no sleep, not free running
  ADC->ADC_IER = 0b100; //enable interrupt
  ADC->ADC_IMR = 0b100; //enable interrupt in mask

  ADC->ADC_CR |= 0b10; //start first conversion
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  ADC->ADC_CR |= 0b10; //start conversion
  while (!(ADC->ADC_ISR & 0b100)); //wait for conversion to end

  for (int i = 0; i <= 15; i++)
 {
    value = ADC->ADC_CDR[i]; //read conversion data for all channels
    Serial.println(value);
 }

 Serial.println();
 Serial.println();
 Serial.println();

 delay(3000);
}

Just doesn't seem to be doing anything. ADC_CHSR (the ADC channel status register) shows channel 2 and only channel 2 enabled and conversions are starting and completing, yet now the conversion data is always 2048. Here's the serial output of all 15 channels, now in 12 bit mode:
0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

Have you tried the same on another analog input pin?

Yup, I've tried all of them.

I've abandoned all hope and decided that the ADC is just bad.

You need to add this to your setup():
pinMode(A0, INPUT);

...to set the pin for reading.
Since you're reading an input that's already pulled up (in the middle of a voltage divider), that should be all. However, you can turn on the internal pull-up with:
digitalWrite(A0, HIGH);

...while the pin is in input mode.
More details here:
http://arduino.cc/en/Reference/PinMode
http://arduino.cc/en/Tutorial/AnalogInputPins

Could've sworn I needed something like this, but it wasn't in the example or the code on the website. However, it's still outputting only 1023.

Try connecting that pin to ground. If you still get 1023, you might have a damaged chip.

The value remains the same no matter what it is connected to.

It seems like a broken chip.

You could have a short somewhere.

No, you do not need to do analogRead() since the ATmega chips default to low impedance mode (input). Would've been needed if they set it to output, but that wasn't done.

@AnnonomusPenguin: Sorry for the bump, but don't you mean pinMode() and not analogRead() ?

pinMode(), yes :-)

Answer to a 6 years old thread. Hope this will help others :)
Looks like you have been using an external power source and only connected the positive core to the pin. If you had an external power source, did you connect the external power source GND to Arduino GND?

If you have AREF pin pulled out onto the shield board not connected to anything, and you don't declare analogReference in your code (thus keeping it as the default internal 5V), it could still cause you to have the 1023 symptom you are describing. My suggestion: cut the AREF connecting pin, or put a constant 5v onto the AREF line.

Try to force sensorValue at the beginning of the void loop to zero, put short delay before reading the analogue pin. I tried this and works for me. Unless your prgram will misbehave at zero sensor value at every loop start. The will  No need of initializing A0 as input because they are input by default.

Try adding this line in your void setup(), also disconnect AREF pin from any kind of bias,
analogReference(INTERNAL1V1);

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

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


text:
Arduino Yun and REST call security
I'm not expert about web development but very excited of doing some rest call using the yun as server (with a minimal python or node.js server inside the openwrt machine in the yun) and expose sensors and actuators to the cloud.
I'm also worried about security. I don't want the super-shellproof system but just don't want that accidental visitors reads my home temperature or make my garden light switch on when I'm out.
For instance I have a central unit yun with some logic inside it and few arduino yun that makes reads from sensors and runs actuators around my home. The communication between the central yun and the slaves is happening via REST calls. I'm using curl for testing it, for instance. Here two questions:

Arduino Yun provide a simple user/password account when arduinoname.local/arduino is called. How is it implemented?
Let's say I'm using node.js to make a super simple web-server, what is the best way to protect the communication central-yun and slave-yun? and to protect central-gun and internet communication?

Best way in term of computation (the yun machine is not very powerful and I'm going to use battery in some cases) and in term of "easy to implement".

Just sayin'... I think hackers have much bigger targets than reading the temperature of your garden :) By the way, you never mention if you use session hijacking prevention, HTTPS, or a simple password for the web interface you make. Those three you'll need to implement in the HTML, which is off topic here. Also, unless you have port forwarding, no one is going should able to access your Yun unless they have a physical connection or connected to the same WiFi.

Password protection of the REST API is done with Basic Authentication. This, coupled with HTTPS, makes API calls more secure. Since the SSL certificate is self-generated, you'll need to run curl with -k parameter.
As Annonomus Penguin suggested, before going into securing the Yuns, you should secure the network they are using (e.g.: home WiFi should use a strong password).


text:
Where can I find out how to make a hex file for arduino firmware?
I have followed this tutorial on flashing my Arduino R3 to turn it into a "USB keyboard", but the article doesn't explain how the hex works, it's just for granted. Where can I learn about how to make my own hex file so that I can learn how to make my Arduino mimic any USB device?

Welcome to Arduino SE! You're really vague here. USB devices are a really complex topic, and most likely, you won't be able to make your own files for USB without a bit of skill. You can find HEX files for the USB chip to mimic other devices pre-compiled.

@AnnonomusPenguin Hi! I don't think any hex to imitate a DataLocker or IronKey device exist yet, so I'd like to try and do it. xD Any advice on where to start?

I don't really have any idea :D I'd say maybe look at some open source hex files that incorporate USB mass storage (I've seen a couple of open source projects with at least thirty types of USB devices for Arduino) and modify it so it doesn't show files until there is a text file with the password on the root of the device. The IRC would be a good route to get help with this. So you don't make people mad, try to learn how to do it, not just copy & paste. Also, if you do, make sure to share your code with others.

The very tutorial you are following contains links to a gzipped tar archive of the source code and makefile used to produce Darran's keyboard hex file which you loaded: http://hunt.net.nz/users/darran/weblog/b3029/attachments/bd341/arduino-keyboard-0.3.tar.gz

It is possible, but it's kind of hard(especially if you want to mod both the 8u2 AND the 16u2. I'd recommend the Teensy(https://www.pjrc.com/teensy/index.html) I recently posted a question about a question similar to yours and after hearing about all the pitfall I decided to go with the Teensy. I has much richer USB/HID support by default (You can start on your project right away rather than trying to mod the UNO). Teensys are also relatively cheap ranging from $18 to $24.
By comparison, UNOs are $27.18 and are out of stock. To be fair both are probably cheaper used. This is probably moot since it seems you already have one. For more info, see my question (Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes)

You don't need to do something magical. Here's how you can use the Arduino IDE's affiliates.
Once you compile or upload a sketch, the .hex file is automatically created and stored in your computer's drive that has the OS installed (I've found this on Windows). You can access it by navigating to the directory containing temporary files.
Typically, the path will be something like this:
C: > Users > Admin > AppData > Local > Temp
Now you'll see (a lot of) directories with names that go like "build"... followed by a big number. One of these directories contains compiler-generated files of the code you're looking for. From this location, you can search (using Windows Explorer, for example) and identify the .hex file you're looking for by the date and time of last modification.
Once you've got your .hex file, you can upload it to your Arduino using Atmel FLIP after setting your Arduino's microcontroller to the Device Firmware Upgrade (DFU) mode. Atmel FLIP, an acronym for FLexible In-system Programmer, can be used very easily, thanks to its minimal UI.
Here's how to use FLIP:

Go to File > Load HEX File... and select the file.
Choose your microcontroller by selecting the first icon on the bar.
Choose your programming interface from the small list.

I've used this with ATXmega that supports USB but it's not the same for all.

Based on your answer, you are generating the hex files only through the use of Arduino IDE, right? Can you use Arduino IDE to, for example, write USB Human Interface Device (HID) code?

That's right, nothing other than the IDE is required. Assuming your HID is compatible with the Arduino IDE, you can. If it requires an add-on (like a Crumbuino or a Teensy, for example), it will still do the same thing. That's because it uploads the .hex file the same way. The only thing that add-on does is define custom features. You just have to find the .hex file among the temporary files. If the HID isn't compatible, you can try writing the code on Atmel Studio (only for AVR and ARM) with an appropriate compiler that can build the .hex file.

The HEX file is simply a translated version of the AVR executable, which is in turn a translated version of AVR source code.
There are many tools available for turning (compiling) AVR source code into an AVR executable, including but not limited to the Arduino IDE, Ino, AVR-GCC, and Atmel Studio. Note that all four tools will compile the code the same way, since AVR-GCC is used under the hood by the other three.
avr-g++ -mmcu=atmega328 source.cc -o executable

Once you've compiled the code, you can use avr-objcopy to extract the appropriate sections from the executable into HEX files for programming into the flash and EEPROM.
avr-objcopy -j .text -j .data -O ihex executable executable.hex

You can then use AVRDUDE to upload the various HEX files to the target device.
avrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p m328 -U flash:w:executable.hex:i

Note that the USB libraries in Arduino/Ino and AVR LibC are limited; you will need to use Atmel Studio if you want full USB capabilities.

There are plenty of sites out there that document how to make/build such.
Example: http://hunt.net.nz/users/darran/
or https://github.com/harlequin-tech/arduino-usb
GOOGLE: build usb keyboard 16u2

Please note that when attempting this on the Uno R3, the DFU is updating the code on the 16U2 and not the 328p.
I would suggest for novices to use the Leonardo. Where there are stock examples in the IDE for using the application directly as USB HID. Avoiding any alterations to either the boot loader or the USB to Serial co-processor chip (the 16u2). Making it much simpler.


text:
How to emulate an analog potentiometer with PWM
I have a piece of electronic that controls a motor. It takes power from AC power.
Now there is a 10KOhm Potentiometer. The data sheet of this controller says that the control signal is 10Vcc.
Here's the connections diagram (in Italian):

I'd like to emulate the Potentiometer with Arduino. I'm not sure if PWM will do the job.
Any hints?

I'm not sure your question is clear enough. Can you tell us more about what you want to accomplish? What will be receiving input from this emulated pot?

all right.. is it better?

It's better, thanks! But it's still not enough I suppose. Do you have more info on the board you want to modify? Maybe a picture of the board. Or even better, can you share the datasheet you have?

Usually a pot is part of a voltage divider. I'm assuming that 10Vcc is the voltage at one of the far terminals of the pot. The other end is usually grounded and the middle pin goes from 0 to 10Vcc. But there's no way of knowing if that's what's going on. If it is, you would need a DAC (digital to analog converter) to simulate it...

Hi ricardo, the data sheet is in italian sorry. It is here: http://we.tl/Kk89gm2PRL

No problem, I'm sure someone will read it... I'll read it a home as the firewall at work won't let me.

There exist "Digital Potentiometers" that can be controlled by microcontrollers.  Perhaps one of those will work.

Adding to Ricardo's answer:
PWM can do the job, sort of. You need a low pass filter (LPF) to convert the PWM to an analog voltage and an amplifier to take it from 0-5 to 0-10V. Or you can get a dedicated digital-to-analog (DAC) chip but that will obviously be more expensive than a resistor and capacitor for the LPF.
Here's some tutorials on converting your PWM to an analog voltage:
Analog-Output: How-To
Arduino’s AnalogWrite – Converting PWM to a Voltage
Then you need to basically double the voltage. You do that with an operational amplifier. The resistors you pick for the op amp set its "gain", in this case you want it to be 2 so you can go from ~5v (max output) to 10v.
Here's an example of that: My First OP-AMP Circuit

You can avoid the op-amp by using a PNP transistor to switch the 10v, and pulling down to ground with a resistor, and then filtering that, but the op amp way might make more sense.

You can take an analog (PWM) output from the Arduino and turn it into 0 to 10 V DC using something like this:

Amplification
The op-amp shown is hooked up as a non-inverting amplifier, where the gain is given by:
VOut / VIn = 1 + (R2 / R1)
Since R2 and R1 in this case are both 1 k then the output will be the input multiplied by:
1 + (1000/1000) = 2

Thus, if we have 5 V coming from D3 we will have 10 V at the output of the op-amp. We need to supply a bit more than 10 V to the op-amp supply pin (pin 8) because this is not a rail-to-rail op-amp, that is, it cannot output all the way up to its supply voltage.

Low-pass filter
The resistor R3 and the 10 µF capacitor form a low-pass filter that filters the PWM signal from the Arduino into a more-or-less smooth DC voltage.
This shows the difference between the Arduino PWM output, and the output of the op-amp:

You can see from the scope traces that the yellow line (the PWM output) has a 50% duty cycle, and the blue line (the op-amp output) is 5 V and has a slight ripple.
With a 100% duty cycle, the output is 10 V.

Ripple
Switching the scope to AC coupling we can see how much ripple we have in the op-amp output:

The scale for the blue channel has changed in this image, and the cursor shows that we have around 140 mV of ripple.
We can reduce the ripple by using a larger resistor for R3. For example, making it 10 k reduces the ripple to 86 mV.
The larger resistance make the output less responsive to changes at the input (it takes time to charge or discharge the capacitor) but in testing it still seems pretty responsive.

Code
Test code:
void setup ()
  {
  }

void loop ()
  {
  analogWrite (3, analogRead (A0) / 4);
  }

I had a potentiometer connected to A0 and adjusted it to alter the duty cycle of the PWM output on pin D3.

Theory
You might ask "Why 138 mV of ripple? Why not 50 mV? Why not 200 mV?".
Let's look at the theory. First, the image posted above looks a bit noisy, so let's take an average of the input to the op-amp:

Now we can see that the ripple is about 57 mV (the output of the op-amp would be double that). Indeed, the averaged output is 57 * 2 = 114 mV

The general formula for calculating the time taken by a RC network to reach a certain voltage is:
t = -log((V-Vc)/V)R*C

Where "exp" is the natural exponent.
See Ladyada - RC Delay Calculator.
Also Mathematical treatment of charging and discharging a capacitor.
V  = supply voltage   (initial voltage)
Vc = output voltage   (target voltage)
R  = resistance in ohms
C  = capacitance in farads
t  = time in seconds

These figures will be on the RC discharge graph at roughly the point indicated:

See Wikipedia - RC circuit
Introducing our values for the resistor and capacitor (using Lua) we get:
VS = 5.0       -- supply voltage
VMED = VS / 2  -- 50% duty cycle
VL = VMED - 27.2e-3   -- low voltage as measured
VH = VMED + 29.6e-3   -- high voltage as measured
RES = 4700            -- resistance in ohms
CAP = 10e-6           -- capacitance in farads

T1 = -math.log ( (VS - VH) /VS) * RES * CAP
T2 = -math.log ( (VS - VL) /VS) * RES * CAP

print ("T1 =", T1)
print ("T2 =", T2)
print ("diff = ", T1 - T2, "seconds")

Results:
T1 = 0.0331
T2 = 0.0321
diff =  0.0010 seconds

The time difference is 1 ms which agrees with the observations.

Great solution, but a small error in the circuit diagram ... R2 should be between pin 1 and 2, not 4. Pin 4 is ground.

Quite right! How come no-one noticed that for a year? I've converted your "answer" to a comment. With a bit more reputation, you will be able to post comments. Thanks for pointing it out. And, welcome to Arduino Stack Exchange. :)

You can use any typical motor control chip like a ULN2003 with PWM and maybe a smoothing capacitor, Google "ULN2003 Arduino" for many examples.
Based on the pinouts from Ricardo's answer, you'd get the 10V from pin 1 and ground from pin 3, and feed the PWM'd output from the ULN2003 back into pin 2.

that ia darlington transistor right? I'm still a student in electronics.. does it means that a darlington transistor can amplify current right? but what for pwm VS analog signal?

@nkint Yes, you're using a Darlington like a fast relay switch, using the Arduino's 5V output to control the device's 10V. The switching speed makes it suitable for use with PWM from the Arduino. You could add a capacitor to help smooth the output to make it more like analog.

I won't be able to answer your question completely, but hopefully I'll be able to make things a bit clearer for someone more knowledgeable to complete the answer.
From what I could understand from the datasheet, inputs 1, 2 and 3 are used to connect a pot that will control the motor speed. It's the POTENZIOMETRO DI COMANDO (control pot) in the figure linked in the question.
The datasheet also specifies (in the figure below) that you can connect terminal 3 to ground and feed terminal 2 with a voltage from 0 to 10Vcc, that will control the motor. That's how you control the motor using a MCU, I suppose.

Here's where my knowledge is getting short. I'm guessing that a PWM signal won't do the trick. You'll need to feed an actual voltage in terminal 2 to control the motor properly. To do that you have a few alternatives:

Use an ADC IC
Use an R2R resistor ladder network using digital outputs and some means to amplify its voltage to 10Vcc.

I hope this helps a bit.

my solution is simple get a servo (pwm input) and connect the shaft of the servo to the pot with a coupler then just use a simple servo control program


text:
Reading text/strings via processing
I'm trying to control an led attached to my arduino via key presses on my laptop.When i hold down a key, the led should light up, and when i release the key, the led should turn off.
While my code works ATM, i am wondering why my code will not work if i replace the numbers in my code with text/strings.
Processing code(Working)
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write(2);println("released");
}

Arduino Code(Working)
int red = 7;

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

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == 1){
    digitalWrite(red,HIGH);
  }else if(input == 2){
    digitalWrite(red,LOW);
  }
}

Processing Code (Not working)
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write("red");
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write("released");
  println("released");
}

Arduino Code(Not working)
int red = 7;

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

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == "red"){
    digitalWrite(red,HIGH);
  }else if(input == "released"){
    digitalWrite(red,LOW);
  }
}

From the above example, i get the error ISO C++ forbids comparisons between pointers and integers.After googling the error, it was suggested that i replace the double quotes with single quotes, after which the arduino code is able to compile, but the processing code gives an error "badly formed character constant(expecting quote,got e)".
I then tried changing using double quotes for processing and single quotes for the arduino quote, but predictably, it did not work.
Why does my code work when i pass numbers to the arduino via serial communication, and my code fails when i use text strings?

The problem is that you're mixing different variable types. It's kinda an oil/water scenario.
Basically, the serial.read(); command returns an integer, -1 if there's nothing in the buffer. If there is something, it will return the character code (i.e. 93 = a). Because of that, it's an integer. When you put something in single quotes, it compiles as the equivalent ISO character code.
So, when you do input == 2, it is integer [compared to] integer. When you do input == "string", you're doing integer [compared to] string, thus you get errors. BTW: a string is a type of pointer.
So, what you have to do is this:
string input = "";
if(serial.avaliable()) {
    delay(100); //Wait for all data to be received
    while(serial.avaliable()) {
        string = string + char(serial.read());
    }
}
if(input == "yay_it_works!) {
    //Done!
}


text:
How to connect more than 10 sensors to Arduino uno r3
How I can connect more than 10 sensors to Arduino Uno R3? I calculated it and I can connect just 4 fire flame sensors (sensors which can find a fire (a candle, for example)) and maybe 1 ultrasonic sensor. I need more for my project. I need an IR Sensor, a fire flame sensor on every side, and 1 ultrasonic sensor in front. Additionally, I need to connect 2 DC motors, 1 fan, and 1 servo-motor for ultrasonic sensor. How can I solve this? I must buy Arduino Mega?

Make a bus with protocol and some bus-devices :)

And if you don't want to make a bus:
Count the pins/protocols you need to use. Make a nice diagram out of it. And judge you requirements

Please want to know how to read the recording on a computer.Am a beginner

do you know how to solve the aforementioned problem with multiplexer TCA9548A?

You can easily increase number of I/O pins using an expander, e.g. PCF8574.
The expander can be connect using your SCL/SDA pins located next to GND/AREF pins. (Here you can find detailed photo: http://forum.arduino.cc/index.php?topic=84190.0) You can connect up to 8 such expanders to extend the number of your digital pins to 64. Once you connect it, here is a code snippet of how to use it:
#include <PCF8574.h> //library available at: https://github.com/skywodd/pcf8574_arduino_library

void setup() {
  PCF8574 sensors;
  sensors.begin(0x20); //0x20 means that you connected A0, A1, A2 pins of PCF8574 to the ground
  sensors.pinMode(0, INPUT_PULLUP);
  sensors.pinMode(1, INPUT_PULLUP);
/*...*/
}
void loop() {

  byte sensorValue = sensors.digitalRead(0); //reads digital value of 1st sensor connected to pin 0 of PCF8574 expander
  /*...*/
}

You can read more with this tutorial (note: they are using wire interface, so the code will differ. Choose the one you prefer).

I wouldn't recommend multiplexing, but I do agree that one way is to add a second MCU.
Another better option is to use an N-bit shift register.  These are little IC's that are exactly what the name entails: shift registers, and are much easier to setup and interface to than wasting a whole other microcontroller to add I/O's or multiplexing (which limits your application).  You effectively shift in the I/O settings that you want and then can latch those registers when you have the proper I/O sequence loaded into the register.  In other words if I wanted to have 8 new I/O pins, I could connect an 8-bit shift register to my MCU and if I wanted 4 of the first pins HIGH and the last 4 low, I would shift in 00001111b, then latch the data so that it appears on the output just as if it were any regular I/O pin on the MCU.
They only require a few pins to operate them (, so this is an easy way to add more sensors to your system.  As always, check the datasheet to make sure the IC meets your specs (in terms of current draw, voltage, etc).
A disadvantage to this is that for an N-bit shift register, you will burn N clock cycles to load in the data.  For most applications this should be fine, but it is worth noting.  It also makes for slightly more complex code (although I am sure there are libraries for them out there).
Note: I saw that you mentioned controlling things such as DC motors, etc.  Make sure you are not trying to directly drive them with the I/O pins, and are using a switch or transistor to control these types of peripherals.

The Mega is the easiest way to get many pins is, as you said, the Mega. It has many other advantages, such as more amperage, more memory, and more UART ports. I highly recommend doing this route for a beginner, even if you get a clone instead of an official board. If none of this would be an advantage to you, there are a few different things.

Second MCU. You can get another chip identical to the Uno's to connect. This is called an ATmega standalone. They're fairly cheap. I2C is the easiest way to connect them, using only two pins from each chip. The setup will depend on the project.
Multiplexing. There is a way that you can connect more stuff than there is pins on the Arduino. This is called multiplexing. It does affect performance a little, but for some applications it is worth it. Note: this won't work well with libraries or SPI/I2C. The 4051 chip seems like a decent chip. The Arduino playground has good introduction article on this chip..

There are a number of ways to get more inputs and outputs, with different implications.  And it depends on the types of sensors, and on the libraries or code snippets you want to use.
The first thing you need to do is list the sensors you want, along with the type of interface each uses; I use a spreadsheet.
For example, a flame sensor could just use a single digital output (going to a digital input on the Arduino), with the threshold set with a pot on the module.  Or it could output an analog signal which goes to an analog input on the Arduino, allowing the code to detect intensity or set varying thresholds without needing to move the pot.  Each approach has different implications.
There are still other sensor and actuator interfaces besides these two (simple digital and analog).  Some give a variable value (like analog) but based on timing a pulse on a digital signal; this is how most inexpensive ultrasonic rangefinders work.  And of course there are sensors which use standard (I2C or SPI) or proprietary (one-wire protocol, or the DHT-xx temp & humidity sensors).
Likewise some outputs will need PWM or other signally, beyond simple on/off.
Extra simple digital inputs, or outputs, can be had fairly easy with I2C extenders, or with shift registers.  For example, checking a digital output flame sensor, or turning on a light.
Extra analog inputs can be done with analog multiplexing (like an electronic switch), or via external ADC modules using I2C or SPI.
If timing is required, there are larger potential problems. Often you would use a library to handle such things.
Libraries. Most sensor and actuator libraries will be written to use direct input and output pins on the Arduino.  You may be able to pass a pin number when initializing, but if you are using a shift register or extender there's no way to tell the library how to use your custom extension.  In this case you will have to roll our own code without using the library, or make a modified version of the library which does I/O through your hardware extension hardware.
Special Pin Functions. A second problem is special pin functions; if the library or code snippet you want to use expects to use a special feature of a pin (like a pin interrupt, or a timer input capture), that may not be available from your extension hardware, or may be extra work to handle.  For example, some extenders may be able to signal an interrupt pin on the Arduino when one of their inputs changes - but you'll have to write your own interrupt handler to catch that, and replace the functionality of the direct pin interrupt.
Timing.  And a third problem is that sometimes tight timing is hard to manage through extension hardware.
Most of these can be resolved with appropriate effort, sometimes easy and sometimes not.  Look through your list of sensors and actuators; sort out which ones can most easily be attached to extension hardware (like a shift register), and which ones should be directly attached to the Arduino for simplicity or performance.  You could be lucky.
Recommendations
1) If you can handle any fancy sensors or actuators with direct pins, and cover any simple ones with shift registers or I2C extender chips, that's a viable option.  For example, if your code wants to check occasionally whether a flame has been sensed (digital version), or wants to turn on a motor, it's not that hard to go through a shift register instead of doing a direct pin access.
2) If you go beyond that, and run out of pins for things that are much easier to handle when directly connected, then I suggest going to a Mega or Mega2560.
It has more digital pins and more analog inputs and more PWM outputs.  Most (tho not all) libraries will adapt just by changing pin numbers.  It's much easier than rewriting libraries to use external digital and analog pins.


text:
Uploading Sketches from Windows Command Line
The resources I've found regarding the Command Line interface seem to be out of date so I was hoping to find someone with experience using it. I'm currently running Arduino 1.5.6-r2 BETA on Windows 8.1 looking to upload code to an Arduino Leonardo.
I'm trying to create a script(Powershell) file that I can just use to upload code without user intervention. The actual upload part using Arduino CLI is just straight not working for me. If my understanding is correct I should have it already due to my version of the Arduino IDE but none of the functionality works so I'm doubting myself.
Source: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
This is the command I'm attempting to run from Windows Command Prompt:
C:\Program Files (x86)\Arduino\arduino.exe --board arduino:avr:leonardo --port COM3 --upload C:\Users\Dev\Documents\Arduino\myProject\myProject.ino

Any insight into what I'm missing would be very much appreciated!
EDIT: Additionally, if anyone could provide information regarding the build/upload process which could lead me to a solution from within C# that would be even more amazing.

Personally, I'd compile to a hex file (or even read it back out of the board) and use avrdude, rather than rebuilding from source each time, unless doing a fresh build is part of your goal.  At any rate, do you get any error output from your attempt?

@ChrisStratton Basically I'll be downloading updated versions of the code via Powershell, so I'm trying to figure out how to then deploy that code without having to manually go through the process using the IDE. If compiling to hex and using avrdude is a simpler solution capable of working for this, that fits my needs as well.

Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.
Final setup for those looking for this in the future:
Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:
Working Directory: C:\Program Files (x86)\Arduino
arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino

EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.

I recommend you to look into cross-platform tool named PlatformIO. It has support for Windows OS and doesn't require Arduino IDE or any tools.
From Get Started let's install platform and setup environment for your Arduino Leonardo:
Install new development platform
> platformio platforms install atmelavr

Initialize new PlatformIO based project
> cd path\to\empty\directory
> platformio init
# Project has been initialized!
# Please put your source code to `src` directory, external libraries to `lib`
# and setup environments in `platformio.ini` file.
# Then process project with `platformio run` command.

Setup environments in the Project Configuration File platformio.ini
[env:my_leonardo_board]
platform = atmelavr
framework = arduino
board = leonardo

Process the project’s environments
> platformio run --target upload

P.S: What is interesting, this tool allows you to manage libraries via CLI and then you can build Arduino-based source code with single line
#include <%HEADER_FILE_OF_INSTALLED_LIB>

You should point out that you are the author of PlatformIO


text:
How can I reset the program on an Arduino Uno while the device isn't recognised by my computer at all?
So I've recently been playing around with my arduino uno, and today it completely refuses to communicate with my computer at all. I've tried using other cables, switched OS (Tried Windows 8.1 and Ubuntu 14.04), and tried on my laptop, none of them recognise the device at all.
From what I've read, this problem can be caused my a program on it with a Serial.println() frequently used, which I believe is the case here. The solution for this problem is according to other answers, to hold the reset button while I upload an empty sketch to the arduino. However, I can't do this, since the computer doesn't communicate with the arduino at all.
Any ideas what could've gone wrong, and how to fix it?
EDIT: Alright, the problem seems to have resolved itself... I have no idea what made it work, I was frustrated and went to bed last night, and today it works without an issue..
EDIT #2: Scratch that.. now I get this error when I try to upload a program to the arduino:
avrdude stk500_getsync() not in sync resp=0x00

The device does show up in Device Manager, so I tried installing the arduino drivers for it, but it gives me the error code 10. Windows automatically installs some serial driver for it, but any attempts of serial communication with the arduino fails.

What do you mean by "they don't recognize the device at all"?

The uno doesn't show up in the Device manager in windows, and in Linux I can't find any ttyUSB or ttyACM  devices-

The state of the program on the '328 chip should not really effect the ability of the USB chip to present a functional peripheral interface to the computer.  But if you hold down the reset button, then unless you somehow programed the reset disable fuse on the '328, it will be entirely out of the way and not bothering the USB chip in the slightest.  Failure (even to be detected as a malfunctioning peripheral) with multiple hosts/operating systems at that point suggests hardware damage (or possible a USB chip which has come unprogrammed).  On linux you should check dmesg when plugging, too.

I agree with @Chris. Is there any signs of damage on your board? Does it light up? Did it work before this? Do you know what sketch is on it currently?

There are no signs of physical damage on the board, and it lights up just fine. I'm not sure to what extent it worked before I tried uploading a program to it, it's been a while since I used it. I believe the sketch on the board was for reading the analog input of something, using Serial.println(). I don't have the sketch saved, as I just used it for debugging a while ago.

As for the dmesg, I couldn't find anything usefull using 'dmesg | grep 'serial|tty''

Don't grep like that - look for things like complaints about a mysterious or malfunctioning USB device or hub port.

Which uno revision ? Not a clone ?
You didn't update the ftdi drivers on windows did you ? What driver version ?(if you updated the drivers trying going back to an earlier version pre-the version that damages clone fetid chips) If its a dip version can you swap the atmel chip ? (Can get clone uno boards from US$4)

I had the same problem with my Arduino Leonardo. But when I kept the reset button pressed and plugged it into my laptop, it got recognised again. But since you're using an arduino uno it might also be the atmega16u2 which isn't working properly. If holding the reset button while plugging in the arduino to the laptop doesn't work, try to reset your atmega16u2 chip on the arduino. This is the chip which makes the communication from USB possible.
To reset the atmega16u2 follow this tutorial

I also got same problem and actually the problem was is of arduino. Arduino ATmega328 IC and ATmega16u chip was damaged . After that I replace ATmega328 Damaged Ic With new one reprogram it and program in ATmega16u chip and upload firmwares to ATmega16u chip.


text:
How do I convert code between Arduino platforms?
What documentation is available regarding the differences between the different Arduino platforms?
For example, I have some code written for an Arduino Teensy that I would like to run on an Arduino Mega.
Is there documentation on the capabilities and equivalencies between each of the platforms?  e.g. memory, number of PWM outputs, etc?

The most detailed one seems to be Baldengineer's, but Arduino, SparkFun, and Adafruit have their own as well, although more limited.
As always, the best source for information about them is the datasheets for both the MCU(s) used as well as for the boards themselves.
And note that different macros are predefined for each MCU and feature (e.g. __AVR_ATmega328__ and __AVR_HAVE_MUL__); it is possible to test for their existence in order to customize behavior.


text:
Input audio from jack to Arduino, and output by
I've never used Arduino but I know a few of its utilities.
I want to input audio from a Jack cable (analog) and be able to send it via Bluetooth, or Wi-Fi, or USB to an Android Phone and being able to print the values (from 0 to 1).
I'm looking for tutorials but I just find the way to make the input but not the output.
Which one would you recommend me of Bluetooth, Wi-Fi and USB?
Thanks.

I followed your requirement right to the point when you said you wanted to print values then I got baffled. Are you saying you want your android to act as an oscilloscope screen? You also don't mind (it seems) if it's a radio link or a wired link (USB) so maybe it also doesn't matter if the audio is already on the phone or it is fed to the phone via the microphone or a line-input connection?

And yes I would prefer radio link instead wired :)

There is an upper-limit to the sampling rate of the Arduino; this is something you need to be aware of. Arduino provides a convenient interface to the user but at a cost of flexibility. You may need to  look into programming the microcontroller directly. Also, see http://en.wikipedia.org/wiki/Nyquist_frequency.

Yes but maybe I'm using MIDI, then I wouldn't have problems on sampling

Maybe I would like to know the compontents to be used and I will learn on my own :)

The simplest solution: it really depends. There are a couple of things to consider:

Bluetooth would probably be the least professional to impliment. The easiest way to do this is with an app. You can impliment it into your application with this:

Let your own Android application receive data from Arduino by listening to the "primavera.arduino.intent.action.DATA_RECEIVED" intent. This intent will contain the "primavera.arduino.intent.extra.DATA" byte array with the received data. Call getByteArrayExtra("primavera.arduino.intent.extra.DATA") to retrieve the data. Send data to Arduino from your application by broadcasting an intent with action "primavera.arduino.intent.action.SEND_DATA". Add the data to be sent as byte array extra "primavera.arduino.intent.extra.DATA".

Still, that's pretty unprofessional IMHO. There are probably other ways to do this, but Arduino Uno Communicator is the easiest by far that I've seen. The main advantage of Bluetooth is it works without a router and it's very cheap (as far as wireless). I can't remember if it's the HC4 or HC5 chip that is commonly available, but [one of those] can be picked up for around $6. Just connect via serial and issue AT commands.
WiFi would be the most professional. First of all, people hear Wifi and they think Ohh! Shiny! I'm going to buy it! That's just what I've observed in the past, but it may not always be true. WiFi can be done with the TL-WR703N router. This blog post outlines how you can even connect it directly to the Arduino. You can also use an ethernet shield (or equivalence, I've seen breakout ethernet boards built for ~$5). Either way, it's a great way to add 5V WiFi to your Arduino. The only disadvantage is cost and it only works if you're near a WiFi router. If those aren't disadvantages, go ahead with WiFi; it's a great product.
USB is only useful if you want:

Speed
Stability
Portability (i.e. no WiFi Router)

Speed can be eliminated as a need if you only send data every 300 ms or so, depending on what you're doing. For WiFi, it might be best to only go to a webpage when an even occurs (i.e. button pushed on Arduino). Bluetooth and WiFi are stable enough if you're over short distances (and you couldn't go a long way with wires, anyway), and there's not too much interference (don't try at a football game with 50K cell phones... granted, they will be on different bands if using cell service, but Bluetooth may be on).
As far as portability, for the price of an OTG cable for your phone, you'd be better off buying a Bluetooth module for a dollar extra.

Suggestion: go with WiFi unless you need the portability. Consider figuring out WPS so your users can connect to WiFi with a push of a button. I don't know if the TL-WR703N has support for WPS, via serial or not.
Forgot to mention: I don't know everything about your app, but WiFi might have too much latency/overhead for near-instant response. As far as wireless, Bluetooth would have much lower latency AFAIK. (As you can tell, there's no perfect solution here :-))

Exactly I was interested in latency rates ;).
Sorry for not reveal my project, it's kinda game with "music" (not guitar hero, please :D)
Thank you very much, ;)


text:
Did I burn my Arduino UNO?
I've recenly bought my first Arduino uno and I was messing with DC motors. I put on the prototype shield on arduino with a mini breadboard on it. I was using L293D bridge. I've connected everything and then put in my 6V battery pack and it BURNED. I don't know what happened. I didn't upload the code, I just connected batteries. I put negative to GND and positive to pin 8. Arduino is responding, but I'n not sure whether all pins are working, how do you check this?

There is not enough information here to tell if you damaged the board or ATmega, you can check by writing a simple sketch to toggle the state of each IO and test them with a multimeter/logic probe/LED and resistor.

@Dan Nixon. The arduino has internal PULLUP resistors and a led on the board which makes it possible to test the pins without external tools except a jumper wire.

To make sure all pins are responding you could put all your pins as input with internal pull-up except pin 13 which must be set as output. The on board led is connected to pin 13, so when you put pin13 high it will turn the led on. Connect every other pin 1 by 1 to the GND to see if the led is toggling once you've connected a pin to the GND.
Try to use this code.
void setup(){
for(int p = 0; p <= 12; p++){  // Define pin0 until pin12 to INPUT with internal pull-up resistor
pinMode(p, INPUT_PULLUP);
}
pinMode(A0, INPUT_PULLUP);  // Define pinA0 as INPUT with internal pull-up resistor
pinMode(A1, INPUT_PULLUP);  // Define pinA1 as INPUT with internal pull-up resistor
pinMode(A2, INPUT_PULLUP);  // Define pinA2 as INPUT with internal pull-up resistor
pinMode(A3, INPUT_PULLUP);  // Define pinA3 as INPUT with internal pull-up resistor
pinMode(A4, INPUT_PULLUP);  // Define pinA4 as INPUT with internal pull-up resistor
pinMode(A5, INPUT_PULLUP);  // Define pinA5 as INPUT with internal pull-up resistor
pinMode(13, OUTPUT);        // Define pin13 as OUTPUT (INTERNAL LED);
}

void loop(){
if(digitalRead(0, LOW)){   // If pin0 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(1, LOW)){   // If pin1 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(2, LOW)){   // If pin2 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(3, LOW)){   // If pin3 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(4, LOW)){   // if pin4 is connected to GND turn led on
digitalWrite(13, HIGH);
}
 if(digitalRead(5, LOW)){  // If pin5 is connected to GND turn led off
digitalWrite(13, LOW);
}
 if(digitalRead(6, LOW)){  // If pin6 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(7, LOW)){   // If pin7 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(8, LOW)){   // If pin8 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(9, LOW)){   // If pin9 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(10, LOW)){  // If pin10 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(11, LOW)){  // If pin11 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(12, LOW)){  // If pin12 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A0, LOW)){  // If pinA0 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A1, LOW)){  // If pinA1 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A2, LOW)){  // If pinA2 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A3, LOW)){  // If pinA3 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A4, LOW)){  // If pinA4 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A5, LOW)){  // If pinA5 is connected to GND turn led on
digitalWrite(13, HIGH);
}
}


text:
Prevent Arduino Mega from setting all Outputs to HIGH on Reset
The Arduino Mega 2560 Rev 3 has multiple relays connected to its digital output pins.
Whenever the Arduino is reset (using reset button, turning on Serial Monitor etc), the Arduino turns on all relays then turns them off. I cant find any function in my sketch that causes the outputs to go HIGH then LOW. Assuming this is a normal feature of the Arduino, how can we prevent this and ensure that the outputs do not flip to the HIGH state?

How are the relays connected to the pins? Is there a pull-up or pull-down resistor?

@Craig The relays are connected directly to Arduino's pins. There's no pull-up or pull-down resistors

But there are flyback diodes, right?

Maybe I have different hardware/bootloader, but I cannot reproduce this. Can you reproduce this with the standard blink sketch and nothing attached other than a single LED/relay?

@jippie When using the blink sketch, the relays do not turn on and off during the reset... Wonder what's happening

The ATmega2560 itself comes out of reset with all pins in high-Z (DDRx=0, PORTx=0). Your observations are likely due to the bootloader. Check the bootloader source to verify that it is responsible for this.

Thank you, sounds like this is a possible reason. How should I check the bootloader source in that Arduino?

Well, first you have to find it. Try the Arduino code repository, and failing that ask for it in the forums.

Is it possible to flash with another bootloader that is known to not have this issue? Additionally, the blink sketch does not cause the relays to turn on then off when Arduino is reset.

It is absolutely possible to flash it with another bootloader. That the blink sketch doesn't cause it raises suspicions though...

Could it be the relay board? I'm using the 5V version of this relay board: http://www.sainsmart.com/16-channel-12v-relay-module-for-pic-arm-avr-dsp-arduino-msp430-ttl-logic.html

The relay board you are using has active low inputs to control the relays.
In your sketch when you are initialising the pins as outputs they are by default set low (this is turning all your relays on).
set the pins as outputs and set them high, they will be low for a very short time (too short for the relay to turn on effectively).

too short for the... ?

Just to add my five cents. I also experienced a relay, driven by a bipolar npn lowside. turning on while timers, Serial etc init and then turn off again.
Using INTERNAL_PULLUP mode helped me as well.
have no idea why. It must have something to do with relays beeing current driven. Mine requires 20 mA at 5V

There is an alternative to change the bootloader. Introduce a RC circuit in the relay driver that delay the rely to switch ON.
Note: Please add info about the relay and/or driver circuit for a better answer.

Assuming this is a normal feature of the Arduino,

It doesn't sound normal to me. Check with others to see if they have the same issue before you try to resolve an otherwise non existent problem.

how can we prevent this and ensure that the outputs do not flip to the HIGH state?

Design the relays to be active now.


text:
Unable to light up all the LEDS connected to Arduino using processing
I have 3 LEDs connected to my arduino which are controlled via laptop key presses with processing.
While the LEDs are able to light up when the respective buttons are pressed, i am unable to light up all 3 LEDs simultaneously when i press all 3 keys at the same time. I am however able to light up 2 LEDs by pressing 2 buttons simultaneously.
All the LEDs light up when their respective buttons are pressed, so i know that it is not a defective LED and/or faulty connections/wiring at play but something else that is causing the issue.
My processing code:
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(64);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(2);
      println("yellow");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(3);
      println("green");
    }
  }

}

void keyReleased(){
 if(key == 'r' || key == 'R'){
      myPort.write(4);
      println("red released");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(5);
      println("yellow released");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(6);
      println("green released");
    }

  println("released");
}

My Arduino code:
int red = 7;
int yellow = 6;
int green = 5;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
   pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
    if(input == 1){
      digitalWrite(red,HIGH);
    }
    else if(input == 2){
      digitalWrite(yellow,HIGH);
    }
    else if(input == 3){
      digitalWrite(green,HIGH);
    }
    else if(input == 4){
      digitalWrite(red,LOW);
    }
    else if(input == 5){
      digitalWrite(yellow,LOW);
    }
    else if(input == 6){
      digitalWrite(green,LOW);
    }
}

Things i've tried.

I've tried increasing the buffer size from 10(initially) to 64(in the code above)
I've tried increasing the baud rate from 9600 to 12000, just in case it was the serial information not being read fast enough.

None of the things i've tried, listed above, was above to solve my problem, and i dont see what could be causing the problem.
Any advice would be much appreciated.

could you include a screen dump of your serial port? ie, whilst you have the serial monitor open, press the keys in the sequences you're interested in, eg (CAPs is on, lowercase is off): RrYyGgRYryRYGrygYGygGYRgyr as I said, as an example. Then check to see if the serial data is as you'd expect. ie, in the above example you should see: 1425361245123456.... and so on

I'll add, I thought initially it might be a limitation of the keyboard, ie three main characters (ie not modifier keys) probably can't all be registered at the same time, but I just tried it on my Macbook Pro keyboard and it did, if you have an onscreen keyboard viewer, see if all the keypresses register as expected.

I'm unable to open the Serial monitor on my Arduino as i get the error Serial port already in use, try quitting any programs that might be using it. I suspect it is because i'm running the processing sketch. However, i've been looking at the processing display, and the when i press 3 keys, the 3rd key does not print to the screen.(e.g when 'g' is the 3rd key pressed,"green" is not printed to the screen). I'm not sure why it works on your Macbook Pro, but i'm guessing the problem lies with my laptop's keyboard's limitation in that it does not register 3 key presses at once!

what hardware and OS are you using? 2) You could try changing your keys, use the modifier keys instead, you should be able to press any combination of shift, control, option/alt, and windows/command. It's usuallt even possible to determine left from right modifier keys.

I'm guessing it is a hardware issue as I discussed in the comments above.
I have just set up a breadboard and copied your code verbatim into the Arduino IDE and Processing (I edited the port index to use). It works as desired. Pressing R, G, or Y will turn on the respective LED and releasing it will turn it off.
I can press these three keys in any combination of none on, one only, any two, or all three, and the LED gives the expected result.
Keyboards were not initially designed to have multiple "main" keys pressed down at any one time, the exceptions to these being the modifier keys (Windows/Command, Option/Alt, Control and possibly some others (I'm thinking the older keyboards here that had "other" keys—Scroll Lock, Print Scr, etc—I'm really unsure).
It appears now, that some hardware and software may have overcome this. As I've said, your project works fine for me. Also, you could try three different keys, it could be a result of how the keys are scanned and you may stumble across three that don't interfere with each other.
As I've suggested in the comments to your question, modify the code to utilise the modifier keys instead, or use the keyboard keys as toggles (ie press once for on, press again to turn it off).


text:
How does this code work?
I've found this code below, but I can't figure out how it works. Can someone explain to me the flow of the program?
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 10, 7, 5, 4);
int mem=0;
void setup() {
    pinMode (12,OUTPUT);
    pinMode(13,OUTPUT);
    // initialize the LED pin as an output:

    // initialize serial communications:
    Serial.begin(9600);
    lcd.begin(16, 2);
}

void loop() {

    lcd.setCursor(12,1);
    int se25 = analogRead(A4);
    int se50 = analogRead(A3);
    int se75 = analogRead(A5);
    int se100 = analogRead(A2);
    if(se100>=1000){lcd.print("100%   ");mem=100; }
    else if(se75>=1000){lcd.print("75%   ");mem=75; }
    else if(se50>=1000){lcd.print("50%   ");mem=50; }
    else if(se25>=1000){lcd.print("25%  ");mem=25; }
    else{lcd.print("emty");mem=0;}
    if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
        digitalWrite(13,LOW);
        lcd.setCursor(12,1);
        lcd.print("emty");
    }

    if(digitalRead(6)==HIGH){digitalWrite(13,LOW);}

    if(digitalRead(6)==LOW&&mem>0)
    {// read the value of the potentiometer:
        int tempw = 0;
        //digitalWrite(12,LOW);
        int tempa = analogRead(A1);
        delay(20);
        int tempb = analogRead(A1);
        delay(20);
        int tempc = analogRead(A1);
        delay(20);
        int tempd = analogRead(A1);
        delay(20);
        int tempe = analogRead(A1);
        delay(20);
        int tempf = analogRead(A1);
        delay(20);

        int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

        int temp = avg;
        // map it to the range of the analog out:
        temp = map(temp, 0, 1023, 0, 4900);
        float tempx = temp * (0.1);
        // change the analog out value:
        int tempy=analogRead(A0);
        tempy = map(tempy, 0, 1023, 0, 150);
        // print the results to the serial monitor:
        lcd.setCursor(0,0);
        lcd.print("act T=" );
        lcd.print(tempx);
        lcd.print("'C  " );
        lcd.setCursor(0,1);
        lcd.print("set T=");

        lcd.print(tempy);
        // Serial.println("'C ");
        lcd.print("'C  ");

        if(tempy<=tempx){digitalWrite(13,LOW);}
        if(tempy>tempx){digitalWrite(13,HIGH);}

        delay(200);
    }

}

who voted this down? This is a legit question from a new user.

I'm assuming you already have some understanding of programming, so I won't literally explain everything line-by-line (that would probably be beyond the scope of this site, and would result in a very long answer). I'll try to explain the important points though. If you need to lookup more information about specific commands, I recommend checking out the Arduino reference.
At a very broad level, the program is taking some readings, and reporting data to a screen (LCD). I would guess that the data is the fluid level in a tank, as well as some kind of temperature reading. It's impossible to be sure about that though, as I don't know what's actually connected to the inputs.
This line creates an object for talking to the LCD screen. The numbers specify which pins it's connected to:
LiquidCrystal lcd(2, 3, 10, 7, 5, 4);

The setup() function gets run once when the device starts up, and is typically used for initialisation tasks. In this case, the lines within setup() initialise two pins as outputs (#12 and #13), initialise serial communication (which isn't actually being used), and initialise the LCD object/screen:
pinMode (12,OUTPUT);
pinMode(13,OUTPUT);
...
Serial.begin(9600);
lcd.begin(16, 2);

The rest of the program is in the loop() function, which runs repeatedly as long as the device is on.
The following lines take 4 analog-to-digital readings (from different inputs), and output the approximate result:
int se25 = analogRead(A4);
int se50 = analogRead(A3);
int se75 = analogRead(A5);
int se100 = analogRead(A2);
if(se100>=1000){lcd.print("100%   ");mem=100; }
else if(se75>=1000){lcd.print("75%   ");mem=75; }
else if(se50>=1000){lcd.print("50%   ");mem=50; }
else if(se25>=1000){lcd.print("25%  ");mem=25; }
else{lcd.print("emty");mem=0;}
if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
    digitalWrite(13,LOW);
    lcd.setCursor(12,1);
    lcd.print("emty");
}

My guess is that each of the analog readings comes from a different fluid sensor in a tank. If the top sensor shows a strong reading, the tank is considered full. Otherwise, it checks the next sensor down, and so on. If none of them shows a strong reading, the tank is considered empty. Interestingly, the condition for an empty tank is actually checked twice, which is presumably a mistake.
(Once again, bear in mind that I'm just guessing that the readings are from fluid sensors in a tank. I don't know for sure.)
The remainder of the code only runs if a particular input (#6) is low, and if the tank is not empty. Input #6 could be from some kind of override switch, but again that's just speculation.
The following block takes 6 analog readings, all from the same input. There's a short delay (20 millisecond) between each reading. The results are then averaged. This is a common approach when you want to try to eliminate noise spikes in an analog signal.
int tempa = analogRead(A1);
delay(20);
int tempb = analogRead(A1);
delay(20);
int tempc = analogRead(A1);
delay(20);
int tempd = analogRead(A1);
delay(20);
int tempe = analogRead(A1);
delay(20);
int tempf = analogRead(A1);
delay(20);

int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

The next block re-maps that reading onto a different range (presumably related to the expected temperature range). It then takes another analog reading from a different input, and remaps that to a different range:
int temp = avg;

temp = map(temp, 0, 1023, 0, 4900);
float tempx = temp * (0.1);

int tempy=analogRead(A0);
tempy = map(tempy, 0, 1023, 0, 150);

The following block outputs the two re-mapped readings. It looks like both of them are treated as temperatures. One is presumably from a temperature sensor, and the other is presumably from a potentiometer used to calibrated the system:
lcd.setCursor(0,0);
lcd.print("act T=" );
lcd.print(tempx);
lcd.print("'C  " );
lcd.setCursor(0,1);
lcd.print("set T=");

lcd.print(tempy);

lcd.print("'C  ");

These lines compare the two readings from above, and set output pin 13 high or low depending on which reading is higher. I'd guess it could be connected to a warning light or similar.
if(tempy<=tempx){digitalWrite(13,LOW);}
if(tempy>tempx){digitalWrite(13,HIGH);}

Lastly, this delay stops the loop from running too fast. Interestingly though, the code only reaches this point under certain circumstances. In other circumstances, there's no limit on loop execution speed:
delay(200);


text:
What is the work of pulseIn?
I have code for an ultrasonic sensor which I found from a site. Here is the code:
#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

However, I don't understand the work of pulseIn() function. I mean, I want to know when the time count starts and when it ends. For example, in this code, does the time start at digitalWrite(trigPin, HIGH); or does the time start at the pulseIn() function?
If it's the second one, when it stops, then how does the time give us the distance of an obstacle when I am already delaying 1000 microseconds after I send a ping in air?

The 100us delay for the trigger pin seems a bit long to me. It depends on the brand of your sensor, but a typical value (I use it with HC-SR04) is around 10us.

How can i do this code in assembly languaje???? Please help.

http://arduino.stackexchange.com/questions/19767/what-if-ultrasonic-sensor-doesnt-detect-object/19772#19772

How can i do this code in assembly languaje - what does that have to do with this question?

From the docs:

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. pulsein

So, in this case, pulseIn(echoPin, HIGH) starts counting the number of microseconds until echoPin goes HIGH and stores that in duration.
It starts and ends on that line, it's what is known as a blocking function. It will really sit there until echoPin goes high and tells you how long it took (unless you specify a timeout).
That also means that any delays you have before or after the pulseIn call don't affect it in any way.
The way you get distance from this time is by the following equation:
distance = (duration/2) / 29.1;

You divide by two because it goes out and back so the time would be double that of a one-way travel. The 29.1 is the speed of sound (which is 343.5 m/s => 1 / 0.03435 = 29.1). So note the result is in CM's, not inches. You could probably figure it out by looking at the data sheet of the sensor or just get a lot of samples relating duration to distance (you would measure the distance manually) and get an equation that is very similar.

I've been Skeeted! Actually, the 29.1 is the speed of sound. Also, just a quick addition: IIRC the reason that there's a pulse to read is the ultrasonic module produces a HIGH signal until the sound makes its way back to the module.

I didn't understand the fourth paragraph. Because if I send a sound pulse in air and wait 2 second it will travel a lot distance. So when I start counting I will be 2 seconds late. So why there isn't any problem if I give delays before pulseIn? @ sachleen. And thanks Annonomus Penguin and sachlee

@shajib0o "pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing."

when do the pin go LOW? @sachleen

@shajib0o As far as I can tell, it's that the ultrasonic sensor makes the pin go HIGH when the signal is sent and then LOW when the signal comes back.

Actually, this is wrong. pulseIn(echoPin, HIGH) measures the time until the ECHO pin goes LOW.

@AnonymousPenguin "Actually, the 29.1 is the speed of sound" Well, actually, the speed of sound is 343.5 m/s. Then 1 / 0.03435 = 29.1. Note that the result is measured in cm's, not inches. To calculate the distance you can also do distance = duration / 58.2.

Indeed it would be a problem if you started to measure the pulse length 1000 microseconds after it starts. However, this is not how the HC-SR04 sensor works:

the sensor is triggered by the falling edge of TRIG, at digitalWrite(trigPin, LOW);
the ECHO pulse starts about 0.3 ms after the trigger

That's why a delay of 1 ms doesn't affect the measurement result. pulseIn(echoPin, HIGH) will actually wait for the ECHO pin go HIGH, then start measuring the pulse length until it goes LOW again. As such, the duration of the TRIG pulse can be reduced to 10 microseconds (minimum TRIG duration for HC-SR04), to make the measurements faster.

It is important to know that you do not measure the time from trigger start - by setting the Trigger pin HIGH - up to the Echo signal.
The Sensor HC-SR04 starts the measurement by receiving a HIGH on the Trigger input and then sends, a short time later, the time coded as the length of the HIGH level on the Echo pin.
If you use pulseIn() 2 ms, i.e. 2000μs, after triggering, it should work fine.

I'm not sure how much this adds to, or differs from, the accepted answer.

Don't get confused, as the ultrasonic module has a particular way of working. First you set a pulse in the trigpin. When it ends, the module sends 8 bursts of 40 kHz pulses (and thats actually what is used to measure distance, not your pulse in the trigpin, which goes nowhere). At exactly the moment the first burst is sent, the echo pin sets itself in HIGH. When this is happening, the program is in the line of pulseIn, and since echopin is in HIGH it starts timing (because pulseIN(echopin,HIGH) waits for echopin to be HIGH for start timing). When the first pulse of the 40 kHz bounces in the object and gets back to the receiver, the echopin sets itself in LOW. Then the pulseIn function stops the time and returns it. Then the program continues running. This module is a little bit tricky in order to learn the way of working of pulseIn.


text:
Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes
I've been working on a DIY keyboard project I have all the hardware designed and now its time for the code. For the microcontroller, I'm sort of locked into an Arduino UNO r3 as I already have it lying around. I know it doesn't have HID capabilities baked in, but I can flash different firmware to it. At first I was going to go with a generic HID firmware. This approach was problematic because it would require me to first write/send my Arduino sketch, then touch I wire to various portions of my UNO (it isn't SMD). After this,
I would flash the HID firmware and hope that there were no bugs in my sketch as fixing bugs would have required flashing Arduino firmware and repeating the aforementioned steps. I then had the idea to use Teensy firmware (https://www.pjrc.com/teensy/). This approach seems better, but I have questions regarding its feasibility.

Can I upload Teensy programs/sketches to the Arduino after I've
updated its firmware (if I had a real Teensy I could do this via the teensyduino plugin)?
Similarly, I'd like to write some software that allows me to remap
    the keyboard. Would the Teensy firmware allow this?
Does the Arduino have enough memory to support #2?
Is it possible to reflash BOTH the 8u2 and the 16u2 on my UNO (for details see #2 in update one below)
If 4 is possible is it possible to write code that would read/write the flash on the 8u2 as a filesystem? (for details see #2 in update one below)

Would the teensy firmware be a good option given these constraints? I know I've focused mainly on the Teensy, but if you have a more straightforward approach I'd love to hear it. Also, I know Arduino has a keyboard library(http://arduino.cc/en/Reference/MouseKeyboard) but, it seems rather basic, seems to block other keyboard signals while in use, and isn't easily remappable(see #2). I haven't completely written this off, so if you think this would be the best option please let me know. Thanks for any and all help.
Update
Thanks to one of the questions linked by @Ignacio Vazquez-Abrams(Can the 2nd MCU on the UNO R3 be used for keyboard emulation?) on the original question(weirdly it didn't show up here)  I have learned the following things(not necessarily from the question itself but by links provided in it):

the Atmel 8u2 of the UNO has 8kb of flash while the 16u2 has 16kb (should've known) I still don't know if either of these sizes are enough to hold my Teensy code AND 1+ map files generated by the mapping software I would make. (see #2 above)
the 8u2 seems like the chip that tinkers are generally advised to reprogram as it wouldn't hold the Arduino sketch. If I'm uploading teensy firmware I shouldn't need Arduino sketch capability (Teensy has that built in) So What I might do is use the 16u2 as a place to hold the firmware my code and use the 8u2 as a filesystem to hold any maps I'd like to store. This leads to more questions see the newly added 4 and 5

@IgnacioVazquez-Abrams I don't think that the question you reference or the question that it was marked as a duplicate of answer my question. From my point of view, they are more general (asking how/if the UNO can be reprogrammed to emulate keyboards, while mine asks about the feasibility of one specific approach. Thanks for the extra reference though.

Reading that question and all the other related questions will allow you to make an informed decision regarding your plan.

No, you can't put the teensy bootloader on the UNO. The teensy has an ATMEGA32U4 and the UNO has an ATmega328.  The 32U4 has USB support in hardware the 328 does not.
The UNO does have a ATMEGA16U2 which does have USB in hardware like the 32U4 but it is programmed as a USB serial converter (to replace the FTDI chip used in earlier arduinos).
It might be possible to install a modified teensy bootloader on the 16U2 but that wouldn't help you because it is not connected to any of the I/O pins on the UNO.
In any case to install new firmware on the 16U2 you would need to buy something that can program the 16U2 via the ICSP and if you are going to buy something you might as well just buy a Leonardo or Teensy since they already support emulating a keyboard.
Now if you really wanted to spend the time it might be possible to write your own bootloader for both the 16U2 and the 328 on the UNO in such a way that they emulate a teensy or Leonardo but it won't be easy, and you would be limited by the smaller memory available in the 16U2.

So your basically recommending Teensy? I may be in luck, someone offered to give me one

I am recommending getting a board that already can do what you want.  Either the Teensy or Leonardo can do it. If you have existing shields the Leonardo may be a better choice since it has the standard Arduino layout.

No shields are needed. Going with the teensy since it is free.

See my answer from http://arduino.stackexchange.com/questions/1840/where-can-i-find-out-how-to-make-a-hex-file-for-arduino-firmware/1845#1845 . The end is same goal. Where I recommend a Leo.

You actually do not need a ICSP programmer for the UNO's 16u2, as it supports DFU. Unlike the 328's bootloader is replaced. But for the cost, I would suggest getting a Programmer.

Teensy uses a proprietary boot loader called half K (as in 500 bytes). Doubt one would get the source or image to burn into the 16u2.
Where you can get 8/16u2 USB to HID code examples here: https://github.com/harlequin-tech/arduino-usb

Thank you while that does look interesting, I've decided to go with the Teensy (actual physical device). This way I have the key64 firmware to piggyback off of and can be sure that I have enough space

Its is possible and very easy to do. See the HID Project and the Hoodloader:
https://github.com/NicoHood/HID
https://github.com/NicoHood/Hoodloader


text:
tinygps abnormal behaviour with EM408 gps
I have an Arduino Duemilanove and em408.
My code is this:

#include <TinyGPS.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPS gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

void setup()
{
  Serial.begin(9600);
  ss.begin(4800);
  }

void loop()
{
  while (ss.available())
  {
    char c = byte(ss.read());
    // Here i tried Serial.write(c); and i succesully saw the NMEA data in my serial monitor
    if (gps.encode(c))
    {
      long lat, lon;
     unsigned long fix_age;
    gps.get_position(&lat, &lon, &fix_age);
    if (fix_age == TinyGPS::GPS_INVALID_AGE )
      Serial.println("No fix ever detected!");
    else if (fix_age > 2000)
      Serial.println("Data is getting STALE!");
    else
      Serial.println("Latitude and longitude valid!");

      Serial.print("Lat: ");
      Serial.print(lat);
      Serial.print(" Lon: ");
      Serial.println(lon);

    }
    else Serial.println("No data!");
  }
}

My output is this:
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
Latitude and longitude valid!
Lat: 32758239
 Lon: 15637489
No data!
No data!
No data!
No data!
No data!
No data!
No data!

And then i continue getting No data! forever...
So...

Why does gps.encode() only manage to return true only 1 time? I have gotten the raw data from the gps (the commented code on my code snippet) and it's ok. Why it returns true only one time?
Why the longitude/latidude data is like this? As far as i know, this isnt valid, correct?

EDIT:
Also tried with TinyGPS++.. but no luck in encoding too...
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

void setup()
{
  Serial.begin(9600);
  ss.begin(4800);
  }

void loop()
{
  while (ss.available()>0)
  {
    char c = byte(ss.read());
    // Here i tried Serial.write(c); and i succesully saw the NMEA data in my serial monitor
    if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
    {
      Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();

    }
    else Serial.println("No data!");
  }
}

New code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

void setup()
{
  Serial.begin(9600);
  ss.begin(4800);
}

char clat[11];
char clng[11];

void loop()
{
    //if (buttons || tilt) {
    //if (buttons & BUTTON_SELECT) {

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        //send-print
                        //delay (just in case multiple bumps)
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
       //}
    //}
}

EDIT: The newest code i have posted works 100%!
So if you have similar problems with that aweful gps, use this!
Apparently, TinyGPS and TinyGPS++ don't work well with this gps.
To be precice, there is a problem with the gps.encode(c) function.
So using if (gps.encode(c)) most of the times returns false, except some rare occasions which returns true and then you can do some processing...
My last code takes care of that problem by checking continuously, using a do...while loop.
If if (gps.location.isValid()) returns true, which means i have valid data, then i do the processing i want and end the do...while loop.

Your code doesn't seem to output "No data!" at any point. Is it supposed to be "Not encoded data!"?

Ok yeah. I modified the code

Try to change the baud rate of Serial.begin() to 4800 and in the serial monitor change the same.

Are you doing this indoors? Are you sure you have a GPS lock? You get NMEA data even without a lock, but they're empty NMEA data-frames.

Man, i know. I use it ourdoors. Get valid NMEA data (saw the coordinates on the raw data). Tried every combination of baud rate. Tried different permutations like
char c = byte(ss.read());
char c = ss.read();
int  c = byte(ss.read());
int  c = ss.read(); //best
byte c = byte(ss.read());
byte c = ss.read();
Noone can give me an answer, its ridiculous. Tried on arduino official foum, ene emailed the creator of TinyGPS and TinyGPS++...

If you're getting proper, locked GPS data if you output the raw NMEA stream, apparently there is an issue in the TinyGPS library, possibly as a result of an interaction with your particular GPS. Welcome to the world of open source. The TinyGPS library is a project someone did in their spare time, and released for free. They do not have to bother to support it at all. Since the source is available why don't you try to fix it yourself?

Try having tinyGPS parse the serial messages from the PC and then sending a valid NMEA string in the serial monitor yourself. That way you can be sure if the issue is with the library, or the GPS.

If you've solved the problem, could you post the solution as an answer? That will make it easier for future visitors to find. Thanks!

The newest code i have posted works 100%! So if you have similar problems with that aweful gps, use this!
Apparently, TinyGPS and TinyGPS++ don't work well with this gps. To be precice, there is a problem with the gps.encode(c) function.
So using if (gps.encode(c)) most of the times returns false, except some rare occasions which returns true and then you can do some processing...
My last code takes care of that problem by checking continuously, using a do...while loop. If if (gps.location.isValid()) returns true, which means i have valid data, then i do the processing i want and end the do...while loop.
NOTE: This code is for TinyGPS++ library. Same theory will work for TinyGPS too of course...
Here it is:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

void setup()
{
  Serial.begin(9600);
  ss.begin(4800);
}

char clat[11];
char clng[11];

void loop()
{
    bool isGpsLocationValid = false;
    do
    {
        while (ss.available()>0)
        {
            char c = byte(ss.read());
            if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
            {
                if (gps.location.isValid())
                {
                    dtostrf(gps.location.lat(), 11, 6, clat);
                    dtostrf(gps.location.lng(), 11, 6, clng);
                    isGpsLocationValid = true;
                }
            }
        }
    } while (isGpsLocationValid == false);
    Serial.write(clat);
    Serial.println();
    Serial.write(clng);
}

Are you sure about while (isGpsLocationValid = false);? That should be while (isGpsLocationValid == false);, otherwise, you won't ever go out of this while loop!

oops, good observation

Thaks very much!!!
You have already given me the solution for my problem, I`ve been trying to get this data for 3 days!!
When I was using just the GPS module, it was fine, I could get the data, but when I tried to use GSM module + GPS, I could not get the data from GPS!! U gave me the solution
bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);

Congratulations!!
Brazilian Hugs for you ; )

No problem... Just vote up my post, if you found it useful (becauce its -3 at the moment)

Is the conversion to byte what solves the issue? Because otherwise it doesn't make sense that this would work and the old code not since you still have to get through the encoding in order to execute the body of the IF.

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


text:
Code flow for precission applications
This is a question about programming. Mainly about the loop() function
As an example
Consider code where you get data from an accelerometer, and if the Gs are high enough you do something.
Consider the following pseudocode:
void setup()
{
pinMode(1, INPUT);
bool flag = false;
}

void loop
{
int x= analogRead(1);
if (x>2)   //if the Gs we get from accelerometer
  flag = true;
if (button)  // if user hits the emergency button
  flag = true;

if (flag == true)
{
//GET SERIAL DATA (EG GPS COORDINATES)
//DO SOME HEAVY PROCESSING
}
}

Now loop runs repeatedly
That means all the commands are executed in a continuous/serial style
Since that happens, what will happen if the accelerometer reading where (x>2), which is what we look for, happen in the REAL world, at a time where in the CPU, the cpu is at that time processing or checking following commands in the program flow, like
if (button)  // if user hits the emergency button
      flag = true;

    if (flag == true)
    {
    //GET SERIAL DATA (EG GPS COORDINATES)
    //DO SOME HEAVY PROCESSING
    }
    }

Is there any chance that the cpu will miss real world events, because at that time the real world event occured, the cpu was processing other code. Or rather, not checking for that at that time. For our example, when the event occured, it wasnt checking the analogread() at that time, but was processing following code.
Should i worry about that?

Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.
You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to analogRead() (and the more likely it is to miss something). Optimising your code can help.
You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.
If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.
If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See attachInterrupt() for more information.

one should take into account the frequency response of the signal versus the sample rate. Per Arduino's web site AnalogRead "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second." or 5K/S for 2 AnalogRead's.
Where I read the output response of the accelerometer used on the Esplora is 300-400Hz. Note often there are additional filters between the accelerometer and the A2D input.
So in short there should be enough time to sample both X & Y along with a Z, leaving a margin of 10x. To do other things.
Just be careful not to do too much, with routines that block.
As a matter of practice, it is best not to rely on a loop for what ever timing it loops at. But rather setup a timer, either by interrupt or by watching the millis(), to trigger the analog reads at a known interval.
#include "TimerOne.h"
volatile int x,y,z;
void setup()
{
  Timer1.initialize(3000);         // initialize timer1 to overflow at 333hz
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}
void callback()
{
  x = analogRead(A0);
  y = analogRead(A1);
  z = analogRead(A2);
}
void loop()
{
  noInterrupts(); // to ensure they are all in sync.
  // do something with x,y&z
  interrupts();
  // do something else, that is not blocking.
}


text:
Read Arduino code generated by Simulink
I am trying to do a Hardware-in-the-loop (HIL) system with Arduino and Simulink but the driver of my motor (Pololu VNH5019) works at 20kHz and simulink PWM block only supports 490Hz.
I would like to read and modify the code before it is sent to the Arduino to modify this and add other libraries.
It would be that possible?
If it is not possible, there is any other visual environment (with blocs, like simulink or Xcos) to generate Arduino Code?

Simulink just supplies code for all the things you could be up to, triggered by a serial command of yours. This is very slow and I think it's obvious, that you would want a fast and slim realization of everything possible, if you attempt to do HIL.
If there is a special part you think is only easy for you with blocks, just ask right away, but it is really easy to do everything you can wish for in a few simple lines.
Also this is better for you, because you really know, what's going on.
I could provide some detail code, since I'm doing HIL myself atm, but you would need to specify a bit, what you are up to.
To really answer your question: I don't know of any other visual programming tool for arduino and as stated above, my best knowledge is, that simulink uses pretty messy things. And loads them onto the board right away, right?

Thanks a lot, the thing is that I am developig fast HIL protyping systems.

Thanks a lot, the thing is that I am developing  HIL rapid protyping systems. For do that I am using Scilab/Xcos that provide me a serial monitor of my system in real time, about 8ms, with that i can monitor and create models of my plants to introduce controllers. Simulink is only for ensure that you can do all the project in a easy way, without programming anything. Once that you have your models and your prototype ready you start to write the code and polish it. If you didn't undertood me let me know and I will show you the projects that I am currently doing.

Simulink most definitely supports higher PWM frequencies than 490Hz. I know because I have used it to generate PWMs in the 20kHz range on microcontroller boards. I suggest you post more details or screenshots of your work. Have someone help you determine where you are going wrong.


text:
Arduino Uno wiring and code with Parallax PMB-688
I'm new to Arduino GPS and am wondering if I could be pointed in the right direction regarding code and wiring when hooking up my Parallax PMB-688 to an Arduino Uno

Try this: http://playground.arduino.cc/Tutorials/GPS -

The following link was suggested in the comments by user PhillyNJ. Adding it here as a community wiki answer:

http://playground.arduino.cc/Tutorials/GPS

authors: Антон Лабозин