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

[![Op-amp buffer][1]][1]

## 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:

[![PWM and op-amp output][2]][2]

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:

[![Ripple on PWM output][3]][3]

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:

[![Ripple averaged][4]][4]

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`

[![Ripple on op-amp output][5]][5]

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](http://ladyada.net/library/rccalc.html).

Also [Mathematical treatment of charging and discharging a capacitor](http://www.schoolphysics.co.uk/age16-19/Electricity and magnetism/Electrostatics/text/Capacitor_charge_and_discharge_mathematics/index.html).

    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:

[![RC discharge graph][6]][6]

See [Wikipedia - RC circuit](https://en.wikipedia.org/wiki/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.

  [1]: https://i.stack.imgur.com/6gU8Y.png
  [2]: https://i.stack.imgur.com/dFRE2.png
  [3]: https://i.stack.imgur.com/L4fbV.png
  [4]: https://i.stack.imgur.com/kI88i.png
  [5]: https://i.stack.imgur.com/Xe3tR.png
  [6]: https://i.stack.imgur.com/Bg2mK.png


sender: user

message:
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](http://we.tl/Kk89gm2PRL) (in Italian):

![enter image description here][1]

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

Any hints?

  [1]: https://i.stack.imgur.com/gieFs.png

sender: assistant

body: 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


message:
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?

body:
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!
    }


message:
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?

body:
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](http://playground.arduino.cc/Learning/AtmegaStandalone). 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.](http://playground.arduino.cc/Learning/4051).


body:
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][1].  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.

  [1]: https://www.sparkfun.com/products/733


body:
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. <br>Once you connect it, here is a code snippet of how to use it:

<!-- language: c -->

    #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][1] (note: they are using wire interface, so the code will differ. Choose the one you prefer).
  [1]: http://ardugonic.blogspot.com/2010/06/icm7218a-combined-with-pcf8574-to.html


body:
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.


message:
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.

body:
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.


body:
I recommend you to look into cross-platform tool named [PlatformIO][1]. It has support for *Windows OS* and doesn't require *Arduino IDE* or any tools.

From [Get Started][2] 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>

  [1]: http://platformio.ikravets.com
  [2]: http://platformio.ikravets.com/#!/get-started


message:
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.

body:
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][1] tutorial

  [1]: http://arduino.cc/en/Hacking/Upgrading16U2Due


body: 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.


message:
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?

body:
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.


message:
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.

body:
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](https://play.google.com/store/apps/details?id=com.primavera.arduino.listener). 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](http://www.martinmelchior.be/2013/07/use-tp-link-tl-wr703n-to-send-arduino.html?m=1) 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 :-))


message:
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?

body:
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);
    }
    }


message:
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?

body: 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.


body:
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.


body:
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).


body:
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


body:
> 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.


message:
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.

 1. I've tried increasing the buffer size from 10(initially) to 64(in the code above)
 2. 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.

body:
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).


message:
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);
        }

    }

body:
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](http://arduino.cc/en/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);


message:
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?

body:
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][1]

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.

  [1]: http://arduino.cc/en/Reference/pulseIn


body:
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.


body:
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:

[![enter image description here][1]][1]

- 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.

  [1]: https://i.stack.imgur.com/x2Mel.jpg


body: 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.


message:
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.

 1. 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)?

 2. Similarly, I'd like to write some software that allows me to remap
        the keyboard. Would the Teensy firmware allow this?

 1. Does the Arduino have enough memory to support #2?
 2. Is it possible to reflash BOTH the 8u2 and the 16u2 on my UNO (for details see #2 in update one below)
 3. 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(https://arduino.stackexchange.com/questions/991/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):

 1. 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)
 2. 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

body:
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.


body:
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


body:
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


message:
tinygps abnormal behaviour with EM408 gps

I have an Arduino Duemilanove and em408.

My code is this:
<!-- language-all: lang-cpp -->

    #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...

1. 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? </br>

2. 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.

body:
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:
```lang-c
#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);
}
```


body:
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

```lang-c
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 ; )


message:
Arduino IDE has no shortcut in openSUSE

I just installed the Arduino IDE in openSUSE 13.1. I am able to open the application using the run dialogue, so I know it has installed. However, there is no way to open the IDE from any application launcher. I have tried both the Kickoff and Lancelot applciation managers. I have also tried to uninstall and re-install the IDE, both through the 1-click on the Arduino website as well as through the command line.

Does anyone know why I am unable to launch the application from the launcher? Thanks in advanced for any help!

body: I had the same problem and this seems to work. If you right click on the Kickoff Application launcher and open 'edit applications' with KDE Menu Editor, you can 'add new item' where you want and give it a name (ArduinoIDE) and then just put arduino (small case) in the 'command' box, and shut down KDE Menu Editor, it should appear in the menu where ever you placed it. At least it did for me.


message:
Arduino LCD shows only black boxes

I've hooked up my Arduino on [this][1] LCD, and after running the following code, all I see is a row with black boxes and another one empty.

    //LiquidCrystal d(RS, E, D4, D5, D6, D7);
    LiquidCrystal lcd(0, 1, 2, 3, 4, 5);

    void setup() {
         lcd.begin(16, 2);
         lcd.print("hello, world!");
    }

    void loop() {
         lcd.print("hello, world!");
    }

Wiring:
![table showing wiring between arduino and lcd][2]

(The UTP cable is used just for the data lines :-)

Actual wiring photos: (sorry for the total klutz in the wiring, I had limited solid-core wires so I had to use these scrap ones)

![wiring][3]
![wiring][4]
![wiring][5]

  [1]: http://arduino.cc/documents/datasheets/LCD-WH1602B-TMI.pdf
  [2]: https://i.stack.imgur.com/nZumv.jpg
  [3]: https://dl.dropboxusercontent.com/s/t7u0e8jt2640zep/Photo 08-06-14 08 31 13 PM.jpg
  [4]: https://dl.dropboxusercontent.com/s/o9hg6i5drzva1x8/Photo 08-06-14 08 31 20 PM.jpg
  [5]: https://dl.dropboxusercontent.com/s/3ugmxr0ddjcpz4x/Photo 08-06-14 08 31 31 PM.jpg

body: The problem was that the R/W pin on the LCD was left floating, after I connected it to GND, I started working :)


message:
Problems controlling servos using proximity sensor

I've just started using Arduino and I need to make a code to simulate the behavior of a lizard, meaning that if you come close to it, it moves away from you.

I'm using a "Arduino duemilanove" that my university lend me, I was told that it was an alternative version of Arduino Uno.

Both of the servos says "Tower Pro, mg996r, digihi-speed"

Looking different codes I made one which I think is correct. Also, I checked for each servo motor (I'm using two) and the proximity sensor running codes for everyone of them alone, if they worked well and they did but with this code, they supposed to move when you are closer than a meter but they don't stop spinning.

If anyone could help me with this, it would be great.

Here is the code:

    #define Servo1 9
    #define Servo2 11
    #define trigPin 10
    #define echoPin A0

    #include <Servo.h>

    Servo servo1;
    Servo servo2;

    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin (9600);
      pinMode(echoPin, INPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(Servo1, OUTPUT);
      pinMode(Servo2, OUTPUT);
      servo1.attach(9);
      servo2.attach(11);

    }

    void loop(){
      long duracion, distancia; // variables

      /* Hacer el disparo */
      digitalWrite(10, LOW);
      delayMicroseconds(2);
      digitalWrite(10, HIGH);  // Flanco ascendente
      delayMicroseconds(10);        // Duracion del pulso
      digitalWrite(10, LOW);  // Flanco descendente

      /* Recepcion del eco de respuesta */
      duracion = pulseIn(A0, HIGH);

      /* Calculo de la distancia efectiva */
      distancia = (duracion/2) / 29.1;

      if (distancia<100){
        for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
        {                                  // in steps of 1 degree
          servo1.write(pos);    // tell servo to go to position in variable 'pos'
          servo2.write(pos);
          delay(15);                       // waits 15ms for the servo to reach the                 position
        }
        for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
        {
          servo1.write(pos);              // tell servo to go to position in variable                 'pos'
          servo2.write(pos);
          delay(15);                       // waits 15ms for the servo to reach the position
        }

      }
      else{
      }
    }

body:
As an extra tip, from my experience do not power the servos from the same power supply as the sensors. I built a similar project to you and it didn't work as expected. I then powered the servos directly from the battery (6v) and the sensors and arduino from a regulated 5v supply taken from the battery.
The servos can cause power spikes that mess with the sensor readings.


body:
I am new to servos as well, but I do have two coding thoughts. The servos I have used in the past have started in the halfway position. That would mean the "pos" variable would start off trying to go from the starting 90 position to the 0 value in 15ms. Not enough time before the next for loop. I could see that causing some weird spinning while the servos try to get to the intended position. So..

    int pos = 90; // Start servo position.

And secondly, the "distancia" could just always be less than 100. I would try finding a max distance value to compare to vs a hard coded value.

    void loop() {...
 long duracion, distancia; // variables
 boolean isMoveTrigger = false; // Movement trigger.

 /* Calculo de la distancia efectiva */
 distancia = (duracion/2) / 29.1;

 // Store a maximum value.
 if (distancia > maxDistance) {
  maxDistance = distancia;
 }

 // Wait to get a starting maximum distance value.
 if (countDown > 0) {
  countDown--;
 } else {
  if (distancia > 0) {
    int distancePercentage = (maxDistance * 100) / distancia; // A 0-100 percentage of the maximum value.
    // Then trigger the movement when less than this percentage.
    isMoveTrigger = distancePercentage < 50;
  }
 }
    if (isMoveTrigger) {
        for(pos = 0; pos < 180; pos += 1) ...


message:
Prototyping method

I'm currently using a normal breadbord 'n' solid-core-wires for prototyping, but it gets messy when I need to connect a large number of pins on the arduino, as when using an LCD display + another sensor. What are my other options for prototyping?

body:
One of the Arduino's greatest strengths are shields, and shields upon shields. (Another is it's ease of programming via USB amongst a whole host of others).

They are perfect for prototyping. There's nothing wrong with breadboarding it as well, but it's pretty much one or the other (excluding making your own circuit board).

I am working on a garage controller and it has three shields on top of the arduino itself.

1. XBee/wireless coms

2. a relay shield, and

3. a prototying shield where I have created custom circuitry (buttons, connectors, optocouplers etc).

Especially with the top shield, I have made several changes to get it to perform as I'd like. If I'd committed to making a custom board, then I would have had to change it (and re-change it). What I've done would be virtually impossible on a breadboard.

The idea is, you use the shields to get your idea up and running, as a proof of concept. Then, you could/can leave it as is, or you could take the next step, break it down to the required components and make a custom PCB for your project. If it wasn't for shields and stacking shields, you would either breadboard it (which as you've indicated can get ugly, cumbersome and problematic), or make a PCB which (depending on the project) might not be a small task. So shield it up, test it out, then build your own based on what you've put together.

That's not to say, you have to make your own PCB in the end, many projects can remain a shield on an arduino. So if you can find a shield to do specifically what you're after, then why wouldn't you use it?


message:
RF missing characters

I've got two arduino nano devices connected via RF 433 MHz. The modules are MX-05V and MX-FS-03V. I'm using VirtualWire for sending and receiving. The speed is set to 1000 bps.

One has got a pir sensor and sends "1:ON" when it detects movement and "1:OFF" when movement stops.

The other is just receiving these messages, but after a while (20 messages) the text is chopped off. I only receive "1". If I restart everything the same thing happens.

They are currently on my table (cca 20cm distance) and powered by my PC via USB.

What can I do? Is it because the modules are from ebay and probably not the best quality?

Receive part:

    // recieve

    int ledPin = 13;
    int rcvPin = 13;

    #include <VirtualWire.h>
    byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
    byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

    void setup() {
      Serial.begin(9600);
      Serial.println("Device is ready");

      // Initialize the IO and ISR
      vw_set_rx_pin(rcvPin); // set pin for rx
      vw_setup(1000); // Bits per sec
      vw_rx_start(); // Start the receiver

      digitalWrite(ledPin,HIGH);
    }

    void loop() {
      // non-blocking receive
      if (vw_get_message(message, &messageLength)) {
        Serial.print("Received: ");
        for (int i = 0; i < messageLength; i++)  {
          Serial.write(message[i]);
        }
        Serial.println();
        digitalWrite(ledPin, LOW);
        delay(500);
        digitalWrite(ledPin,HIGH);

      }
    }

Transmit part:

    /*
    SimpleSend
    This sketch transmits a short text message using the VirtualWire library
    connect the Transmitter data pin to Arduino pin 12
    pin 11 to high for power
    gnd connected to gnd
    */

    // RF
    int ledPin = 13;
    int trxPin = 12;
    int pwrPin = 11;

    // PIR
    int inpPin = 2;               // choose the input pin (for PIR sensor)
    int pirState = LOW;             // we start, assuming no motion detected
    int val = 0;                    // variable for reading the pin status

    #include <VirtualWire.h>

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Starting...");

      // PIR
      pinMode(inpPin, INPUT);     // declare sensor as input
      // RF
      pinMode(pwrPin, OUTPUT);   // Set digital pin 11 as OUTPUT pins
      digitalWrite(pwrPin,HIGH);

      // Initialize the IO and ISR
      vw_set_tx_pin(trxPin);
      vw_setup(1000); // Bits per sec

      Serial.println("Device is ready to send.");
    }

    void loop() {

      val = digitalRead(inpPin);  // read input value
      if (val == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        if (pirState == LOW) {
          // we have just turned on
          Serial.println("Motion on seonsor 1!");
          send("1:ON");
          // We only want to print on the output change, not state
          pirState = HIGH;
        }
      } else {
        digitalWrite(ledPin, LOW); // turn LED OFF
        if (pirState == HIGH){
          // we have just turned of
          Serial.println("Motion ended on seonsor 1");
          send("1:OFF");
          // We only want to print on the output change, not state
          pirState = LOW;
        }
      }

    }

    void send (char *message)
    {
      vw_send((uint8_t *)message, strlen(message));
      vw_wait_tx(); // Wait until the whole message is gone
    }

body:
In your first sketch, you have

    int ledPin = 13;
    int rcvPin = 13;

Did you mean both those to be assigned to the hardware LED on the Nano? (Pin 13 is the on-board LED). If so, why? With all the pins available to you.

The other thing I don't understand is your use of:

    byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
    byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

It will always just be one byte, won't it?

Why not use available()?

http://arduino.cc/en/Serial/available

I see this was posted six months ago - no doubt you have already solved it.


message:
Assigning formatted value to variable

Look at this snippet of code (from TinyGPS++ library):

    Serial.print(gps.location.lat(), 6);

It prints the latitude location with 6 decimal points.
I want, instead of printing that value, to have it assigned to a variable.

But i want it assigned just like above, with six decimal points. Is there a way to do this?

body:
Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

>The dtostrf() function returns the pointer to the converted string s.

>`char* dtostrf ( double          __val,
              signed char     __width,
              unsigned char   __prec,
              char *          __s
)`
The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.

>Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides `millis()` by 1000 and saves this in a float, we then use this float as a source for `dtostrf()` to do it's work and store the result in a char array.

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

    void loop(){
      char c[12];
      float f = millis()/1000.0;
      dtostrf(f,11,3,c);
      Serial.println(c);
      delay(111);
    }

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits *as well as the null terminator!*


message:
2 Arduino controller boards - 1 shared input

I'm beginning with electronics and don't have all the good reflexes yet. So here is my question:

Can I do what I did here?

![can i do this](http://www.movod-design.com/forum_img/canIDoThis.jpg)

Do I have to add diodes between the Nano +5V and the junction point?

My goal is to have one button's state read by 2 Arduino Nano.

body:
You don't need to add anymore components to your schematic. But you can leave some components.

Before you're adding a button to your schematic please consider first how you want to detect your signal. A logic 1 as if a button is pressed? Or logic 0 as if a button is pressed. You can do this using pull-up and pull-down resistors. These resistors should be wired like this.

![pull resistor][1]

(The 100Ohm resistor in an internal resistor from the MCU)

Using the pull-down resistor means that when the button is pressed you'd get a logic 1.
Using pull-up resistors means that when the button is pressed you'd get a logic 0.

When I see your schematic it seems like you're trying to make a pushbutton with pull-down resistor. Then you should wire your arduino like this.

![pull-down button][2]

Another option is to use the Arduino internal pull-up resistors. That way you don't have to add the 10k resistor in your schematic. And your schematic will look like this.

![internal pull-up][3]

To use the internal pull-up resistors from the Arduino you'll need to put this in your setup(): pinMode(pin, INPUT_PULLUP); where pin should be your pin number. Please keep in mind that when you use the internal pull-up resistor a logic 0 means the button is pressed.

  [1]: https://i.stack.imgur.com/PrGmn.png
  [2]: https://i.stack.imgur.com/HtNNl.png
  [3]: https://i.stack.imgur.com/uTxT0.png


body:
I have done something like this to be able to have a redundant system.
Is this what you were doing: Two computers receiving the trigger, if one computer failed you have the other running?

If that is your case, then there is a problem on this setup:

 - If one computer shuts down the Arduino on that computer will be powered by the second one and there will be not enough power for both.

I fixed it with a couple of diodes.

I still had some problems with false triggering from time to time, with tests on a Mac running OSX. The same tests with a Linux machine give no problem for now.

I wanted to make this really stable (next I'll try to use opto-isolators)
I'm not a Programer nor a Engineer. Please tell me if I'm saying something stupid or if there is any other easy fix.

I was using two Arduino Pro micro Chinese copies and passing the data to midi to the computers - I did not test with real Arduinos to see if it was a board problem.


message:
Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS?

I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.

    #include <GSM.h>
    GSM gsmAccess;
    GSM_SMS sms;
    char senderNumber[20];
    int led=13;
    void setup()
    {
      Serial.begin(9600);
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);
      while (!Serial) {
        ;
      }
      Serial.println("SMS Messages Receiver");
      boolean notConnected = true;
      while(notConnected)
        {
          if(gsmAccess.begin("6442")==GSM_READY)
            notConnected = false;
          else
            {
              Serial.println("Not connected");
              delay(1000);
            }
        }
      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop()
    {
      char c;
      int val=0;
      val=digitalRead(led);
      if (val==HIGH){
        digitalWrite(led,HIGH);
      }
      if (sms.available()){
        Serial.println("Message received from:");
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);

        if(sms.peek()=='#')
          {
            Serial.println("Discarded SMS");
            sms.flush();
          }
        while(c=sms.read())
          if(c='off'){
            digitalWrite(led,LOW);
          }else{
            digitalWrite(led,HIGH);
            Serial.print(c);
          }
        Serial.println("\nEND OF MESSAGE");
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }
      delay(1000);
    }

body:
First of all, you have a typo: You need the double-equals operator in

    if (c == 'off') {

But more importantly, you can't use a `char` variable to hold or compare more than one character at a time. I don't know the details of the Arduino GSM library, but if `sms.read()` returns a string, then you'll need a string variable or an array of `char` to hold the result.


body:
```sms.read()``` function returns only a single byte of the SMS string. You can store the whole data in a character array and process it later like following:

    char c, message[140];
    int i=0;
    while (c = sms.read()) {
        message[i++] = c;
    }
    if (strstr (message, "off")) {    //If SMS contains off anywhere
        digitalWrite(led,LOW);
    } else {
        digitalWrite(led,HIGH);
        Serial.print(message);
    }

And I believe the following portion in your code is not required as it is doing nothing:

    val=digitalRead(led);
    if (val==HIGH){
        digitalWrite(led,HIGH);
    }


message:
Are there any GPS data pusher for Arduino?

I plan to build a GPS logger for my car using a GPS device, an Arduino board and a SD Card. The plan is that the GPS device forwards the position to the Arduino which is responsible for storing the data on the SD card. However, I would like to regularly (say every hour) send my current position to a server at home.

For that you can use GPS pusher or puller, but I couldn't find any such devices on the Internet. Do these devices exist? What are my (other) options?

body:
Check [this shield][1] out, it sounds almost exactly like what you need, plus it has OBD2 (CAN) access to log RPM, indicated speed, steering wheel angle, and whatever else your car exposes. You can get a GPS module from Sparkfun as well. Matter of fact, I'm using it in a [very similar project][2], but development is paused until I upgrade to a Mega, since I've run out of RAM.

![enter image description here][3]

The shield comes with example code that's hacked together from other sources but it serves the demo purpose well.

As for pushing to a server--that'd be tougher. I would go the route of a Bluetooth shield and make a corresponding app for the phone that pushes the data.

  [1]: https://www.sparkfun.com/products/10039
  [2]: https://bitbucket.org/nearwood/carduino
  [3]: https://i.stack.imgur.com/J6pPW.jpg


message:
Are there any pressure sensor for 22 kg (~50lbs) and more?

I'm looking for pressure sensors up to 22 kg and more. So far the highest capacity I could found was 25 lbs. Do higher ones not exist?

body:
Your problem may be that you are using sub-optimal search terms.
The kilogram is not a unit of pressure, but instead of mass.
Scales technically do not sense mass, but instead sense force.
This is assumed to be the force exerted by a resting body under earth gravity.
Pressure is force over an area, such as pounds-per-square-inch (PSI) or the Pascal which is a newton per square meter.

Anyway, the sensor you want is called a force cell.
The nice ones are rated in newtons or kilonewtons, with a kg being equivalent to
9.8 newtons.

Here is a load cell that take up to 50 kg.
http://www.phidgets.com/products.php?product_id=3135

Sources:
http://en.wikipedia.org/wiki/Force


message:
Reading a car mass air flow, volumetric air flow meter

I'm looking to build an air flow meter that will output in standard liters per minute. The cheapest sensors seems to be a car's Mass Air Flow sensor. I'm wondering if there is a way use  one of these MAF to measure air flow in liters per minute.

Essentially I need to measure a medical ventilator's air flow in order to calibrate it. The gas flow analyzers that are normally used are way too expensive and offer too many extra features that I don't need.

Thank You

body:
There's no reason that an MAF couldn't be used with an Arduino.  It's likely that the sensor will run on 12v and output an analog voltage from 0 - 12, so you might need to use a voltage divider with the Arduino.

See this [Sparkfun article](https://learn.sparkfun.com/tutorials/voltage-dividers) on implementing a voltage divider to scale down the 0-12 volt signal to 0-5v for the Arduino.


body:
Does the sensor have to elecrtonic? How about a ball and tube flow-meter, say a lucite tube with a gradually expanding bore (harder) or constant bore just larger than a ping-pong ball, with a number of relief holes up the side (easier)? The higher the ball rises, the more air escapes through the relief holes. leaving less to support the ball while escaping around it.

You'd calibrate it with a positive displacement (piston) pump driven at values of (displacement/time) in the range if interest, and marking pen to record the ball position for each.


body:
If you don't need to much precision, then use pulse counting from turbine wheel measuring device, that will give you the speed og air in the duct, multiply with duct area and you get the flow Volume.
Alternatively use a delta pressure sensor for the air speed measurement something like http://www.rcdrone.cl/producto/sensor-velocidad-aire-para-aviones/

Just some idea from
Lars Funder
Have a great day


message:
Arduino Wifi Shield with monitor mode ( promiscuous mode )

Is there a WiFi Shield or driver that supports monitor mode and receiving raw packets ?

body:
Does it have to be a shield?

I would consider buying a cheap Wi-Fi router instead with good open-source support and a way to interface it to the Arduino. Their price is near to the price of Wi-Fi shields.

 - They consume little power, can be powered by 5V and have built in Wi-Fi.
 - Some have a built-in USB port, most have a serial port, which can be used to talk to the Arduino.
 - You would have to put custom firmware on it, plus the program which receives the raw packets for you.

Specifically, I would get a TP-Link TL-WR703ND for this task.

 - It can be fed 5 Volts, or 3.3 Volts with a little hacking
 - It has USB
 - It also has serial, and you can even hack an I2C port onto it
 - It can run OpenWRT

[More info][1] on this particular router

  [1]: http://wiki.openwrt.org/toh/tp-link/tl-wr703n


message:
Operating HB100 backpack with Arduino Due

I need to connect a speed sensor module with an Arduino Due and calculate the speed of an approaching object.

the sensor is:
http://www.limpkin.fr/index.php?post/2013/08/09/Making-the-electronics-for-a-$7-USD-doppler-motion-sensor

The sensor already output a signal that its' frequency represents the speed of the object.

I would really appreciate any help understating how can it be connected and operated by the Arduino without burning it, and how can I sample its output?

If more details are needed I'll be happy to supply.

Thanks.![The module's connectors][1]

  [1]: https://i.stack.imgur.com/bCYgd.jpg

body:
The articles and tutorials I've read on the subject say that the HB100 module produces a very weak signal which needs to be amplified before your Arduino can read it. They recommend building an op amp. This post on the Arduino forums, for example: http://forum.arduino.cc/index.php?topic=61989.0

BUT looking at your picture and linked article, I find that your device already includes the signal amplification and filtering you need in the backpack board. I found the [store page](https://www.tindie.com/products/limpkin/hb100-doppler-module-with-backpack-1/) for this module, which has a more noob-friendly explanation. From what I gather:

* VCC: provide the module with a 5v supply.
* VOUT: analog reading of the *amount* of return signal being received. My guess is you could use this with `analogRead()` to get a rough estimate of the size or distance of the object being read. If you want only the speed reading, you don't need this pin.
* FOUT: digital output of the speed that the sensor is reading. Thanks to @sachleen's [link](https://tushev.org/articles/arduino/9/measuring-frequency-with-arduino), you can use either `pulseIn()` or FreqCounter library to measure the frequency and then convert it to a MPH or KPH speed.
* GND - ground, aka common, aka `-`.

So connect VCC to 5v, GND to ground, and FOUT to an input pin on your Arduino. If you use `pulseIn()`, frequency **f** = 1 / **t**, t being the return value from `pulseIn()`. If you use the FreqCounter library, it no doubt has documentation on its usage.


message:
what is the coversion details of temperature usnig lm35?

I found similar type of code in many sites for coverting analog signal lm35 to centigrade.
But i can't understand that fully. So I need some help what this equation means

    tempC = (5.0 * tempC * 100.0)/1024.0;

Thank you,

body:
I took a quick look at the data sheet for [LM35][1] and it says that each centigrade means a 10 millivolt change.

If you have an ADC with 10-bit resolution, it means you have 1024 steps from 0 V to 5 V.

The temperature is then:

tempC = 5 * (ADCdata / 1024) * 100

This is equal to your equation. So it seems to be correct.

**EDIT:**

A more thorough explanation of the formula:

Lets call the value you read from your LM35 "ADCdata". The range of this value is determined by the resolution of the Analog-to-Digital Converter (ADC). The ADC converts a voltage to a digital value in the Arduino. This value is again what I refer to here as "ADCdata".

If the ADC resolution is 10-bits, it means the 5 volt input can be divided into 1024 equal levels. One level is about 5 millivolts (five thousands of a volt).

To find what value "ADCdata" is in volts we need to divide it with the resolution (1024) and multiply with 5 volts.

Lets say we have a 2.5 volt input signal. The ADCdata will then be 512. If we now divide 512 by 1024 we get 0.5. Lets multiply that with 5 volts and we get 2.5 volts!

We know from the data sheet that 10 millivolts equals 1 centigrade. Since we have our value in volts (2.5 V, which is the same as 2500 millivolts) we need to multiply it with 100 to get centigrades.

  [1]: http://www.ti.com/lit/ds/symlink/lm35.pdf


message:
Seeking to measure back EMF of an electric motor via Arduino

Is it possible to measure the back EMF of a motor, using just the Arduino and no sensors?

Or what type of sensor do I need? One that measures current?

body:
You will need at least an external current sensor, the arduino has no way of measuring current built in. You will also need to measure the winding resistance of the motor beforehand. look to this answer for a good explanation:
https://electronics.stackexchange.com/questions/54997/how-can-i-measure-back-emf-to-infer-the-speed-of-a-dc-motor

DC current sensors compatible with arduino should not be hard to find; just search one of the standard hobby electronics components sites.


body:
Take a look at this website:
http://www.vwlowen.co.uk/arduino/current/current.html

It shows how to make a create a simple current sensor with just a few resistors.


body:
There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see [Back EMF][1].

This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the  motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.

Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.

  [1]: https://robidouille.wordpress.com/2009/09/20/back-emf/


message:
Wired serial connection between two Arduinos - do they need a common Ground (GND)?

I would like to connect two Arduinos by a serial connection. Is it sufficient to connect TX1<-->RX2 and RX1<-->TX2 or do I also need to connect the GND of the two Arduinos?

body:
Short answer: Yes.

Rx/Tx is referenced with a logic ground. Without ground being common, there is no way to determine what is high or low.

(Sorry I don't have a more technical explanation)

Edit: I thought I would add, if you are using the same power source, then they probably have a common ground. In this case, a common power source doesn't mean the wall side of a wall adapter, but the SAME wall adapter.


message:
Reading the rpm of multiple fans

I am trying to build a fan controller for my pc, the problem is that the example code(http://playground.arduino.cc/Main/ReadingRPM) im using utilizes interrupts. On my uno I can then only read the rpm of one fan. I want to also control the rpm (via pwm) and monitor temperatures (via thermistors) Anyone know how I coud do it differently? I. E. Without interrupts. I would also like it to be as close to real time as possible

body:
If temperature regulation is what you seek, why bother with the Tachometer signal at all?

Thermistors don't require interrupts. Why do you need fully closed loop fan control? A simple proportional control of each fan and each hot item would likely suffice in keeping your system cool. Noise concerns, perhaps?

[A brief article on proportional temperature control](http://faculty.washington.edu/brengelm/neut_zone/pg4.html)

[A data sheet on a TI chip that may have some inspiration for you](http://www.ti.com/lit/ds/sbas386c/sbas386c.pdf)


body:
If you only want 2 fans, the uno has 2 external interrupts, so you can use the same strategy as your example, just make another interrupt function for fan 2 and attach it on interrupt 1 instead of 0. the fan should be plugged in to pin 3 in this case. On a leonardo, you could have 5 fans on interrupts, and a mega has 6 external interrupts. See http://arduino.cc/en/Reference/attachInterrupt

If you need more than what your hardware can support, I would look into using a timed interrupt to check all the fans. If you find the minimum amount of time in-between reads to read your fans at max RPM and then use a timer interrupt to check some pins at that interval, you can probably read as many as you need, provided the interrupt routine stays fast enough. the function

    attachInterrupt(function, period);

from the libraries on this page : http://playground.arduino.cc/Code/Timer1
should help you out with this.


message:
Watchdog timer stuck in restart loop? (green led flashing)

I am trying to set up a way to reboot arduino on command. The code below should do that but it seems like my arduino just get's stuck in some sort of a loop where I cant upload or get any serial output. The green led (pin 13) flashes very fast. The only way to stop this is to cut power to the device, even reset button does not work. This happens only when "R" is received via serial or if wdt_reset() function is commented out.

    #include <avr/io.h>
    #include <avr/wdt.h>

    int ledPin = 3;

    void setup()
    {
      MCUSR=0;
      wdt_disable();
      Serial.begin(57600);
      Serial.println("BOOT!");
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      delay(500);
    }

    void loop(){
      if (Serial.available() > 0){
        char cmd = Serial.read();
        if (cmd == 'R'){
          Serial.println("R received!");
          wdt_enable(WDTO_1S);
          delay(2000);
          Serial.println("1 SEC.");
        }
      }
      wdt_reset();
      digitalWrite(ledPin, HIGH);
    }

What am I doing wrong?

body:
One of the most obvious issues here is that you are enabling the watchdog timer with a delay of 1S and then you are asking the micro controller to sleep for 2S, printing something and then going back into the loop. This, in theory, should be fine(your wdt should trigger a reboot during the 2 second wait) but I've seen it cause issues.

Additionally some bootloaders(notably the Optiboot bootloader on Uno and newer boards) can have issues with watchdog timers causing the wdt to remain enabled after reset even though the setup loop disables it. To start with - try increasing the wdt time to something greater than 2S(you should be able to do WDTO_8S) and see if the issue persists.

**EDIT** - The OP is using an Arduino Pro Mini clone. The included bootloader on the Arduino Pro Mini does not support system restarts by the WDT. Essentially, on a device with a bootloader that does not support WDT restarts, the board will restart but the timer / reset will not causing the board to continuously reset on reboot. There are alternative bootloaders for Arduino boards that may resolve this issue. Another solution is to use a different method to reboot the board.


body:
Enabling watchdog timer system restart and waiting in a loop until reset is a legitimate way of SW resetting the µC as is using watchdog for catching µC's misbehavior which can be caused by various reasons.

However, some precautions have to be made when using watchdog system reset because on all AVRs that also have watchdog interrupt the watchdog **with prescaler set to 0000 = 16 ms** remains active after watchdog system reset condition. It is therefore responsibility of a programmer to clear **MCUSR** and to disable watchdog timer **as soon as possible** after occurrence of such a condition. Since LPM routines for initializing .data and .bss sections can last longer than watchdog timeout interval, the code for disabling the watchdog must be placed in **.init3 section** and the contents of **MCUSR** can optionally be saved for later reset source examination. Here is the code that does the described:

<!-- language-all: lang-cpp -->

    uint8_t mcusr_copy __attribute__ ((section (".noinit")));
    void disable_wdt(void) \
      __attribute__((naked)) \
      __attribute__((section(".init3")));
    void disable_wdt(void) {
      mcusr_copy = MCUSR;
      MCUSR = 0x00;
      wdt_disable();
    }

However, the problem may arise when using a bootloader which does not account for the possibility of watchdog system reset condition. If that is the case, watchdog timeout will happen inside bootloader (which is executed the first) before the above code will have the chance to disable the watchdog timer and µC will be stuck in an endless reset loop. Since reseting the µC will **not** clear **WDRF** flag in **MCUSR** register (it can be cleared only in software or by Power-on reset) the only way will then be to cycle the power and upload a new code when watchdog timer is still not activated by previous code. **WDRF** in **MCUSR** register must be cleared before `wdt_disable()` because **WDE** can not be cleared if **WDRF** is still set - therefore the order of the instrucions in the above code is very important. The function placed in **.init3** section must not be called from later code.