body:
Remove watchdogs flag at init is one solution. I am using optiboot 8.0 and it works perfect.

    // Function Pototype
    void wdt_init(void) __attribute__ ((naked, used, section(".init3")));

    // Function Implementation
    void wdt_init(void)
    {
        MCUSR = 0;
        wdt_disable();
        return;
    }


sender: user

message:
How to integrate smoothing into project (HVAC thermostat / controller)

I am working on building a "simple" HVAC thermostat. This is my current sketch.

        // include the libraries for gizmos
    #include <LiquidCrystal.h>
    #include <dht11.h>

    dht11 DHT11; // Figure out what this line does
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

    // These constants won't change:
    const int ACledPin = 8;      // Air Conditioner LED (RED)
    const int HTledPin = 9;      // Heat LED (YELLOW)
    const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

    const int RELAY_01 = 6;    // RELAY 1 PIN 9
    const int RELAY_02 = 10;   // RELAY 2 PIN 10

    void setup() {
      DHT11.attach(7);       // Attach DHT11 sensor to pin 7
      lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
      Serial.begin(9600);    // Serial setup

      pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
      pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
      pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
      pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

      // Leaves the relays in default "off" (no noise/click)
      digitalWrite(RELAY_01, HIGH);
      digitalWrite(RELAY_02, HIGH);

    }

    void loop() {

      float analogValue = (DHT11.fahrenheit()); // trying to set up the temp reading as an int variable
    ////////////// if then ////////////////
    // if the analog value is high enough, turn on the LED:
      if (analogValue > threshold) {
        digitalWrite(ACledPin, HIGH);
        digitalWrite(HTledPin, LOW);
        digitalWrite(RELAY_01, HIGH);
        digitalWrite(RELAY_02, LOW);
      }
      else {
        digitalWrite(ACledPin, LOW);
        digitalWrite(HTledPin, HIGH);
        digitalWrite(RELAY_01, LOW);
        digitalWrite(RELAY_02, HIGH);
      }

    Serial.println(analogValue);  // print the analog value:

    // Set up the LCD Stuff
      lcd.setCursor(0, 0);      // Set cursor to top left
      lcd.setCursor(0, 1);
      lcd.print(analogValue, 1);
      lcd.print("F");

      delay(1000);

    }

I want to add "smoothing" to the temperature reading. I Found this tutorial http://arduino.cc/en/Tutorial/Smoothing and have it working the way I want it.

    // Define the number of samples to keep track of.  The higher the number,
    // the more the readings will be smoothed, but the slower the output will
    // respond to the input.  Using a constant rather than a normal variable lets
    // use this value to determine the size of the readings array.
    #include <dht11.h>
    dht11 DHT11; // Figure out what this line does

    const int numReadings = 5;

    float readings[numReadings];      // the readings from the analog input
    int index = 0;                    // the index of the current reading
    float total = 0;                  // the running total
    float average = 0;                // the average

    void setup()
    {
      DHT11.attach(7);       // Attach DHT11 sensor to pin 7
      Serial.begin(9600);    // initialize serial communication with computer:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:
    }

    void loop() {
      // subtract the last reading:
      total= total - readings[index];
      // read from the sensor:
      readings[index] = (DHT11.fahrenheit()); //analogRead(inputPin);
      // add the reading to the total:
      total= total + readings[index];
      // advance to the next position in the array:
      index = index + 1;

      // if we're at the end of the array...
      if (index >= numReadings)
        // ...wrap around to the beginning:
        index = 0;

      // calculate the average:
      average = total / numReadings;
      // send it to the computer as ASCII digits
      Serial.println("");
      Serial.print("Realtime: ");
      Serial.println(DHT11.fahrenheit(),2);
      Serial.print("Average:  ");
      Serial.println(average);
      delay(2000);        // delay in between reads for stability
    }

I'm new to Arduino and don't know the best way to do this. I'm not certain how to do multiple loops/delays in a single project, or if I even need to.

EDIT:

I've ended up with this based on the comments from @Craig. The only thing that needs some adjustment are the first 4 readings are low, so it would be nice to somehow ignore, probably not a big deal in the long run.

Example readings on startup;

    Realtime: 77.00
    Average:  15.40

    Realtime: 77.00
    Average:  30.80

    Realtime: 77.00
    Average:  46.20

    Realtime: 77.00
    Average:  61.60

    Realtime: 77.00
    Average:  77.00

Final code

    // include the libraries for gizmos
    #include <LiquidCrystal.h>
    #include <dht11.h>

    dht11 DHT11; // Figure out what this line does
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

    // These constants won't change:
    const int ACledPin = 8;      // Air Conditioner LED (RED)
    const int HTledPin = 9;      // Heat LED (YELLOW)
    const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

    const int RELAY_01 = 6;    // RELAY 1 PIN 9
    const int RELAY_02 = 10;   // RELAY 2 PIN 10

    // START ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////
    const int numReadings = 5;
    float readings[numReadings];      // the readings from the analog input
    int index = 0;                    // the index of the current reading
    float total = 0;                  // the running total

    float get_smoothed_temp() {
        total = total - readings[index]; // remove oldest reading
        readings[index] = DHT11.fahrenheit();
        total += readings[index];
        index = (index + 1) % numReadings;

        return (total / numReadings);
    }
    // END ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////

    void setup() {
      DHT11.attach(7);       // Attach DHT11 sensor to pin 7
      lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
      Serial.begin(9600);    // Serial setup
      for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:

      pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
      pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
      pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
      pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

      // Leaves the relays in default "off" (no noise/click)
      digitalWrite(RELAY_01, HIGH);
      digitalWrite(RELAY_02, HIGH);

    }

    void loop() {

      float analogValue = (get_smoothed_temp()); // trying to set up the temp reading as an int variable
    ////////////// if then ////////////////
    // if the analog value is high enough, turn on the LED:
      if (analogValue > threshold) {
        digitalWrite(ACledPin, HIGH);
        digitalWrite(HTledPin, LOW);
        digitalWrite(RELAY_01, HIGH);
        digitalWrite(RELAY_02, LOW);
      }
      else {
        digitalWrite(ACledPin, LOW);
        digitalWrite(HTledPin, HIGH);
        digitalWrite(RELAY_01, LOW);
        digitalWrite(RELAY_02, HIGH);
      }

    Serial.println(analogValue);  // print the analog value:

    // Set up the LCD Stuff
      lcd.setCursor(0, 0);      // Set cursor to top left
      lcd.print("Real F:");
      lcd.setCursor(0, 1);
      lcd.print("AVG  F:");
      lcd.print(analogValue, 1);

      delay(1000);

    }

sender: assistant

body:
> I'm not certain how to do multiple loops/delays in a single project

You *can't* do this.* [Software threading](https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads) is the only way to do something like what you want, but it's too complex for what you need. What you want is to use the `millis()` function to return the time and

    // constants won't change. Used here to
    // set pin numbers:
    const int ledPin =  13;      // the number of the LED pin

    // Variables will change:
    int ledState = LOW;             // ledState used to set the LED
    long previousMillis = 0;        // will store last time LED was updated

    // the follow variables is a long because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long interval = 1000;           // interval at which to blink (milliseconds)

    void setup() {
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
      // here is where you'd put code that needs to be running all the time.

      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis > interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }

You can then pull button changes while you wait for a new reading. Another way would be to use an *interrupt* to interrupt the flow of the program when a button changes. I won't get into that.

For your use, you can use this template I made:

    long previousMillis = 0;        // will store last time temp was updated
    long interval = 1000;           // interval at which to check the temp (milliseconds)

    void setup() {
      //Foobar
    }

    void loop()
    {
      //Bar of foo
      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
        //Check Temp
      }
    }

*Not to be confused with the `loop` statement.


body:
What you want to do is replace your call to `DHT11.fahrenheit()` with a call to a new function (e.g. get_smoothed_temp()) that keeps track of the last several readings and returns the smoothed value.

    const int numReadings = 5;
    float readings[numReadings];      // the readings from the analog input
    int index = 0;                    // the index of the current reading
    float total = 0;                  // the running total

    float get_smoothed_temp() {
        total = total - readings[index]; // remove oldest reading
        readings[index] = DHT11.fahrenheit();
        total += readings[index];
        index = (index + 1) % numReadings;

        return (total / numReadings);
    }

You will still need to set the readings array to all zeros in the setup function.


body:
I've just done a fan controller (using digital sensors - DS18b20, in my case) and chose an exponential average for smoothing the readings because it doesn't require storing or managing old data and I could get the smoothing I needed. During setup I took a reading from each sensor and preset the averages to those values. That gives the system a "running start"; it doesn't need to wait for enough samples for the averages to settle.

The exponential average I chose was `(3 * oldAverage + tempr)/4` because it gave the performance I needed and is easy and fast to calculate without floating point. Multiplying by 3 is done by shifting and adding; dividing by 4 is done by shifting.

Here's the routine I used. It could easily be put in-line; the compiler probably will:

    int16_t xpavg(int16_t tempr, int16_t oldAverage)
    {
       // (3*oldavg + 1*tempr)/4
       return( (((oldAverage<<1) + oldAverage + tempr) + 2) >> 2 );
    }


body:
Your running average code is fine.

A quick way to start up fast is to take your first reading in setup, and fill the array with that value instead of zero.  That way you always get a reasonable temperature from the smoothing, it just gradually drifts from the first reading to the average of multiple readings  (rather than from 0 - a bogus value - to the that average).

This can work for the exponential smoothing too (old average = first reading).

An alternative is to only average as many samples as you have put into the array (1 then 2, then 3 etc until it's filled).  That takes extra code to handle just the first few results, tho, and the simpler approach suggested above (initially fill the array with a legitimate reading) is usually fine.


message:
How does RXD/TXD request signal look betwen 16u2 and 328p on oscilloscope?

I have a broken Arduino Uno. The man tells that he connected power supply and USB at the same time.

I got the new 16u2 (empty) chip. then asked my friend to re-solder it. He was using an air soldering station, but that did not work out. Then I try do that by myself. After 6 or 8 time I was successful. I think.

With stk500v2 programmer thru ICSP I burned in the hardware called:

    Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

which I found in Arduino "hardware" folder.

I then burned bootloader to 328p controller:

    optiboot_atmega328.hex

That hardware also from Arduino folder.

The problem is that I can upload sketch

    error: avrdude: stk500_getsync(): not in sync: resp=0x00

meaning that device not recognizing.

My PC founds Arduino in device manager. 328p with ICSP programmable and working. (checked with blinking.hex 13 pin)

When pressing reset button the 13 led turns of then blinks fast several times that means the boot loader installed property.

Right after pressing upload the Rx blinks 3 times after that I am getting error.

Strange isn't it?

So what I what to know:

* I suppose the first must start blinking Tx led?

* Can anyone show me how must look like rxd txd interrupts?

* So about my assumption that I overheated 16u2 and it does strange things. What are you thinking about that?

body:
See screenshot below. The Rx on the Uno (incoming data) should flash first.

[![Uno boot sequence][1]][1]

The programmer sends `STK_GET_SYNC` and the board replies `STK_INSYNC`:

    Sent: STK_GET_SYNC / CRC_EOP  (30/20)
    Got: STK_INSYNC / STK_OK (14/10)

Afterwards you see the bigger blocks on the lower line as the programmer sends the hex code to the board. Then about half-way through the bigger blocks are on the top as the board sends back the verification data (by reading the flash back).

The little blips would be the other side acknowledging a packet of data.

---

For more details see <https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader>

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


message:
Operating / pin voltages ATTiny chips

I would like to set up a project with an ATtiny chip, such as the ATtiny84 or ATtiny85, in which I interface the microcontroller directly with an XBee for both wireless serial communication, as well as monitoring a digital signal from the Xbee (digital input to the ATtiny). As the Xbee chips can handle only 3.3V and will be damaged at higher voltages (such as 5V), I was wondering whether I can simply power the entire project at 3.3V so that all digital inputs and outputs will be at that voltage?

body:
Yes.  As given in the [datasheets][1], normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.

  [1]: http://www.atmel.com/devices/ATTINY85.aspx


message:
Can't send DHT11 temperature data to Xively from Yun

I thought this would be easy but how wrong I am... All I want to do is plot temperature data but I can't seem to get it to work. It reads it out on the serial monitor and says it has sent the data (in the serial monitor) but nothing on the Xively plots! Why?? Below is the code.

I have the API key and feedID from the Xively site. The useragent I'm assuming is the name of the project. My channels are called `sensorValue1` and `sensorValue2`. Please help - this is taking me far too long.

    #include <Bridge.h>
    #include <Console.h>
    #include <Process.h>

    #include "DHT.h"
    #define DHTPIN 0
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

     #define APIKEY "BLablablablabla" // your pachube API key
     #define FEEDID blablabla // your feed ID
     #define USERAGENT "SebYun2" // user agent is the project name

    // set up net client info:
    const unsigned long postingInterval = 60000; //delay between updates to xively.com
    unsigned long lastRequest = 0; // when you last made a request
    String dataString = "";

    void setup() {
      // start serial port:
      Bridge.begin();
      Serial.begin(9600);
      dht.begin();
      while(!Serial); // wait for Network Serial to open
      Serial.println("Xively client");
      // Do a first update immediately
      updateData();
      sendData();
      lastRequest = millis();
    }

    void loop() {
      // get a timestamp so you can calculate reading and sending intervals:
      long now = millis();
      // if the sending interval has passed since your
      // last connection, then connect again and send data:
      if (now - lastRequest >= postingInterval) {
        updateData();
        sendData();
        lastRequest = now;
      }
    }

    void updateData() {
      // convert the readings to a String to send it:
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      dataString = "Temperature,";
      dataString += dht.readTemperature(false);
      delay(250);
      // add pressure:
      dataString += "\nHumidity,";
      dataString += dht.readHumidity();
      int sensorValue1 =  analogRead(A0);
      delay(100);
      int sensorValue2 =  analogRead(A0);
      dataString += "\nVoltage1,";
      dataString += sensorValue1*0.0049;
      Serial.print(sensorValue1);
      dataString += "\nVoltage2,";
      Serial.print(sensorValue2);
      dataString += sensorValue2*0.0049;
      delay(1000);
    }

    // this method makes a HTTP connection to the server:
    void sendData() {
      // form the string for the API header parameter:
      String apiString = "X-ApiKey: ";
      apiString += APIKEY;
      // form the string for the URL parameter:
      String url = "https://api.xively.com/v2/feeds/";
      url += FEEDID;
      url += ".csv";
      // Send the HTTP PUT request
      // It is better to declare the Process here, so when the
      // sendData function finishes the resources are immediately
      // released. Declaring it global works too, BTW.
      Process xively;
      Serial.print("\n\nSending data... ");
      xively.begin("curl");
      xively.addParameter("-k");
      xively.addParameter("--request");
      xively.addParameter("PUT");
      xively.addParameter("--data");
      xively.addParameter(dataString);
      xively.addParameter("--header");
      xively.addParameter(apiString);
      xively.addParameter(url);
      xively.run();
      Serial.println("done!");
      // If there's incoming data from the net connection,
      // send it out the Serial:
      while (xively.available()>0) {
        char c = xively.read();
        Serial.write(c);
      }
    }

body:
As long as I checked, this way of uploading data to Xively only works for up to tree pairs of name,data.

If you try with more pairs at the same time the response is "Done", but nothing happens. I finally divide the upload in groups of 3 parameters, and everything is Ok.

I saw your question yesterday when I was looking for a way to upload data to Xively from Yun. It was really helpful for me. Thank you.


message:
Arduino PWM fading led

I am trying to blink an LED with PWM on Arduino.

I don't know what is wrong but my LED is not fading as expected. What is wrong?

I think that I have bad registers settings, but I am not sure.

LED is connected to Arduino pin 9.

Here is my code:

    #include <avr/io.h>
    #include <util/delay.h>
    const int delay=1000;
    void initialize_PWM()
    {
        TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
        TCCR0B=1;
        DDRB|=(1<<PB1);
    }

    void set_pwm(uint8_t data)
    {
        OCR0A=data;
    }

    int main (void)
    {
        initialize_PWM();
        uint8_t brightness=200;
        while(1)
        {
            for(brightness=0;brightness<255;brightness++)
            {
                set_pwm(brightness);
                _delay_ms(1);
            }

            for(brightness=255;brightness>0;brightness--)
            {
                set_pwm(brightness);
                _delay_ms(1);
            }
        }
        return 0;
    }

body: It's much too soon to optimize. Get your LED working using the standard (known working) libraries. Only then - and perhaps never, unless you find a need to - should your optimize (use direct register I/O). If it works with the libraries but not with your direct I/O, you'll know the bug lies in the direct I/O code and nowhere else, ruling out failed hardware, improper or unreliable connections, and programming errors elsewhere in your project. Right now, you don't know even that much.


body:
From your code you are using **Timer0** in **FastPWM mode with top = 0xFF**.

In this mode, as used in your code, `OCR0A` defines the pulse width rate (more precisely, `OCR0A / 256`).

**Timer0** uses port `OC0A` and `OC0B` to ouput PWM signals, in your code, you are using only `OC0A` (which is perfectly fine).

Now if you take a look at [ATmega 328 data sheet][1], chapter 14.3.3 you will see that pin `OC0A` maps to **port D, pin PD6** (on Arduino UNO, this is port **D6**, according to http://arduino.cc/en/Hacking/PinMapping168).

So this means that **you have used the wrong port** in your setup (Arduino pin D9 maps to `OC1A`, which is pin **PB1** of **port B** on ATmega328, `OC1A` is used by **Timer1**, not Timer0).

Hence you should do the following to fix the problem:

1. Plug the LED to Arduino pin D6 instead of D9
2. Fix `initialize_PWM()` by replacing `DDRB|=(1<<PB1);` with `DDRD|=(1<<PD6);`

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!

  [1]: http://www.atmel.com/Images/doc8161.pdf


body:
The easiest way is to use the timer1 library written for arduino. You can download it [here][1].

To install, simply unzip and put the files in Arduino/hardware/libraries/Timer1/

----------

Prescaler set for 16Mhz

    Prescale Time per counter tick Max Period
    1 0.0625 uS 8.192 mS
    8 0.5 uS 65.536 mS
    64 4 uS 524.288 mS
    256 16 uS 2097.152 mS
    1024 64uS 8388.608mS

In general:

Max Period = (Prescale)*(1/Frequency)*(2^17)
Time per Tick = (Prescale)*(1/Frequency)

----------

Instructions available using this library are:

initialize(period)
You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set at 1 second. Note that this breaks analogWrite() for digital pins 9 and 10 on Arduino.

setPeriod(period)
Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 8388480 microseconds or about 8.3 seconds. Note that setting the period will change the attached interrupt and both pwm outputs' frequencies and duty cycles simultaneously.

pwm(pin, duty, period)
Generates a PWM waveform on the specified pin. Output pins for Timer1 are PORTB pins 1 and 2, so you have to choose between these two, anything else is ignored. On Arduino, these are digital pins 9 and 10, so those aliases also work. Output pins for Timer3 are from PORTE and correspond to 2,3 & 5 on the Arduino Mega. The duty cycle is specified as a 10 bit value, so anything between 0 and 1023. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.

attachInterrupt(function, period)
Calls a function at the specified interval in microseconds. Be careful about trying to execute too complicated of an interrupt at too high of a frequency, or the CPU may never enter the main loop and your program will 'lock up'. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.

setPwmDuty(pin, duty)
A fast shortcut for setting the pwm duty for a given pin if you have already set it up by calling pwm() earlier. This avoids the overhead of enabling pwm mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call pwm().

detachInterrupt()
Disables the attached interrupt.

disablePwm(pin)
Turns PWM off for the specified pin so you can use that pin for something else.

read()
Reads the time since last rollover in microseconds.

----------

Example - Sets up PWM output on pin 9 with a 50% duty cycle, and attaches an interrupt that toggles digital pin 10 every half second.

    /*
     *  Timer1 library example
     *  June 2008 | jesse dot tane at gmail dot com
     */

    #include "TimerOne.h"

    void setup()
    {
      pinMode(10, OUTPUT);
      Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
      Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
      Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
    }

    void callback()
    {
      digitalWrite(10, digitalRead(10) ^ 1);
    }

    void loop()
    {
      // your program here...
    }

Source: http://playground.arduino.cc/Code/Timer1

[1]: http://code.google.com/p/arduino-timerone/downloads/list


message:
Is it possible to press a button from Arduino and my computer will get a key event?

My idea seems easy:

I connect a button with arduino, then write some code and upload it to arduino. Then I open the notepad(or any other editor) on my computer. When I press the button, there will be a character "A" displayed in the notepad.

I have tried with my Arduino uno, and use `Serial.write/print` function to send an `A` to serial port `9600`, but it seems the character `A` only shows in the serial monitor GUI.

My question is:

1. Is "Arduino uno" is OK to implement this?
2. If not, what other board should I use?
3. Is `Serial.write/print` the correct function?
4. Or shall I use the `Keyboard.???` function?
5. Do I have to write an application which runs on the computer and listens the serial port, and emit a real key event? (that's sad)

body: Your example describes collecting text - does that meet your goal or do you need to generate any kind of key-event? If you don't need to generate system events, any terminal emulator (not just the Arduino IDE) should be able listen to that same port and to log whatever it receives to a file.


body:
The Uno is not the best board for this. You may be able to get somewhere with the [Virtual USB][1] project but there are a couple of boards that are better suited for this.

Those are the Arduino Leonardo, Micro, and Due. In those, you can use the [Keyboard Library][2] just like you are using the Serial library now. [This page][3] has an example very similar to your project:

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(2, INPUT_PULLUP);
      Keyboard.begin();
    }

    void loop() {
      //if the button is pressed
      if(digitalRead(2)==LOW){
        //Send the message
        Keyboard.print("Hello!");
      }
    }

  [1]: http://practicalarduino.com/projects/virtual-usb-keyboard
  [2]: http://arduino.cc/en/Reference/MouseKeyboard
  [3]: http://arduino.cc/en/Reference/KeyboardPrint


body:
There is a micro designed more specifically for keyboard emulation, I haven't done any experimenting with it (yet), but it's very popular in the flight simulator world where these micro's are rigged up with buttons and switches and rotary encoders to simulate a cockpit. These inputs are converted to keyboard inputs (as far as I can see).

There are some general projects here: https://www.pjrc.com/teensy/projects.html

Some more keyboard specific stuff: https://www.pjrc.com/teensy/usb_keyboard.html

More info on the teensy in the arduino environment: https://www.pjrc.com/teensy/teensyduino.html

More specifically about what you're looking for, this could be quite useful: https://www.pjrc.com/teensy/td_keyboard.html

I'm not steering you away from Arduino, it's just something else to look into


body:
Check this video,
[Arduino UNO as a USB keyboard (HID device) \[Anything Arduino\] (ep 6)][1],
as I think this is what you are looking for.

From the youtube video you can get links to the library site and schematics.

You do need to build a small interface to connect your Arduino to a PC.
I got it for Uno and Micro, but other Arduinos with latest firmware would be OK.

  [1]: https://www.youtube.com/watch?v=RoG_-9lAnSI


message:
nRF24L01 pipe question

I am looking through the example code found [here][1]. I know there are 6 pipes that the nRF24L01 module can use but I've been searching the internet for the address designations and have been able to find nothing. More specifically on line 37, is there a reference for where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?

Thanks.

  [1]: https://github.com/maniacbug/RF24/blob/master/examples/GettingStarted/GettingStarted.pde

body:
The values `0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL` are arbitrary values and define the adresses of the senders and receivers to talk to.

If you use the Mirf library

    Mirf.setRADDR((byte *)"serv1");
they can be also strings like `serv1`.

`RF24` uses

    write_register(RX_ADDR_P0, &value, 5);
    write_register(TX_ADDR, &value, 5);


body:
As most of the people have posted, the values for the pipe are arbitrary, but must follow the rules per the API:

> Pipes 1-5 should share the first 32 bits. Only the least significant
> byte should be unique, e.g.

Before I answer your question, I think an explanation on Hex and Decimal values are needed.

The 40 bit hexadecimal is a number representation of base 16. A decimal is of base 10. So you can convert a Hex Value to Decimal. As this is out of scope for the question, you can google on how to convert from one to another. There are some online converters:

[Hex to Decimal Converter][1]

You will see when you convert the Hex value to decimal, that its just a number representation. When you convert, you drop the `0x` and `LL`. As stated the `0x` indicates the value is a hex value and [`LL` means type Long Long][2].

So to answer your question, use the a converter to find a hex number like:

    F0F0F0F0A1
    F0F0F0F0A2
    F0F0F0F0B4
    F0F0F0F0E9

Just change the last 2 digits (least significant bit):

    Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.
       openReadingPipe(1,0xF0F0F0F0AA);
       openReadingPipe(2,0xF0F0F0F066);

Add the `0x` and `LL`

    0xF0F0F0F0A1LL
    0xF0F0F0F0A2LL
    0xF0F0F0F0B4LL
    0xF0F0F0F0E9LL

All should work.

I am no expert on hex, as I am learning, so if I am incorrect, then please someone correct me.

Finally, the nRF24L01 datasheet makes the following point that the choice of address is not completely arbitrary:

> Note: Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate.

  [1]: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
  [2]: https://stackoverflow.com/a/7036077


body:
There's something that everyone forgets to tell you:

Pipes at **receiver** should be shortened after the first one

    const uint64_t pipe01 = 0xE8E8F0F0A1LL;
    const uint64_t pipe02 = 0xA2LL;
    const uint64_t pipe03 = 0xA3LL;
    const uint64_t pipe04 = 0xA4LL;
    const uint64_t pipe05 = 0xA5LL;
    const uint64_t pipe06 = 0xA6LL;

 radio.openReadingPipe(1, pipe01);
 radio.openReadingPipe(2, pipe02);
 radio.openReadingPipe(3, pipe03);
 radio.openReadingPipe(4, pipe04);
 radio.openReadingPipe(5, pipe05);

Pipes at **transmitter** should be

    const uint64_t pipe01 = 0xE8E8F0F0A1LL;
    const uint64_t pipe02 = 0xE8E8F0F0A2LL;
    const uint64_t pipe03 = 0xE8E8F0F0A3LL;
    const uint64_t pipe04 = 0xE8E8F0F0A4LL;
    const uint64_t pipe05 = 0xE8E8F0F0A5LL;
    const uint64_t pipe06 = 0xE8E8F0F0A6LL;

    uint64_t setPipeToSend = pipe01; // or pipe02 or pipe03 or pipe04 or pipe05
    radio.openWritingPipe(setPipeToSend );

If you want to know which pipe's message has come, use

      uint8_t someVariable;
        if (radio.available(&someVariable))
        {
           Serial.print("pipe number ");
           Serial.printLn(someVariable);
        }

Also **pipe number 6** is used for receiving **acknowledge** messages.

In addition, the initialization code must have `radio.enableDynamicPayloads();`
This one works well for me:

        radio.begin();
     //radio.setChannel(0x57); //if set should be the same at the both sides
     radio.setPALevel(RF24_PA_LOW);  // "LOW" is more stable mode
     radio.enableAckPayload(); //for autoanswers
     radio.openWritingPipe(pipe01); //for sending
        //link pipe numbers to the pipe addresses
     //radio.openReadingPipe(1, pipe01); // I use pipe01 for sending
     radio.openReadingPipe(2, pipe02);
     radio.openReadingPipe(3, pipe03);
     radio.openReadingPipe(4, pipe04);
     radio.openReadingPipe(5, pipe05);
     radio.enableDynamicPayloads(); //must have for multi pipe receiving
     radio.startListening();  //start listening

Good luck...


message:
If statement behaves erratically

I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.

    Serial.print(cnt);
    cnt=0;
    Serial.print("  ");
    Serial.print(cnt);
    motor1_up(255);
    motor2_up(255);
    while(1)
    {
        if(cnt>380)
        {
            Serial.print(" break ");
            Serial.print(cnt);
            break;
        }
    }
    motor1_down(255);
    motor2_down(255);
    Serial.print("  ");
    delay(40);
    Serial.println(cnt);
    motor1_down(0);
    motor2_down(0);
    delay(2000);

Here is the serial output

     1  0 break 381  389
     396  0 break 256  264
     271  0 break 381  389
     396  0 break 381  389
     396  0 break 256  264
     270  0 break 381  389
     397  0 break 381  390
     396  0 break 381  389
     397  0 break 381  389
     396  0 break 256  264
     271  0 break 381  389

body:
It looks like it could be a caching issue. If you're accessing a variable from the main loop *and* from an interrupt handler, then you need to ensure it's declared as `volatile`. For example:

    volatile int cnt = 0;

That tells the compiler that the contents of the variable could change unexpectedly, i.e. when an Interrupt Service Routine is triggered. The result is that it always fetches the actual value from RAM, instead of relying on a cached copy which could be out-of-date.


body:
Not only must `cnt` variable be declared `volatile`, but accessing it from the main loop must also be protected because:

- it can be modified by an ISR
- it is longer than 1 byte

In AVR architecture (8-bits), **read/write operations on bytes are guaranteed to be atomic**, i.e. no function can access a byte while it is read/written by an ISR.

However, **operations on types larger than bytes are not atomic!**

This means that reading e.g. an `int` variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.

I would advise you to write a pair of functions to read and write `cnt` in a protected way, i.e. with interrupts disabled:

    volatile int cnt;

    void set_cnt(int val) {
        uint8_t status = SREG;
        cli();
        cnt = val;
        SREG = status;
    }

    int get_cnt() {
        uint8_t status = SREG;
        cli();
        int val = cnt;
        SREG = status;
        return val;
    }

What those functions do are:

1. get the current status of exceptions (from `SREG` register)
2. disable exceptions with `cli()`
3. access `cnt` without any risk of it being accessed concurrently
4. restore initial status of exceptions (to `SREG` register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access `cnt` variable.


message:
How to connect mini jack output to arduino mini pro and send sound to it?

I would like to connect arduino mini pro to mini jack output and send sound through it.

What would I need here, how can I connect the mini jack to arduino and how to send data of sounds (any library?) to that connected output?

**EDIT**

The sound source will be a music file ( streamed via bluetooth). I would like to be able to connect this output to a speaker and play (stream) music via bluetooth.

**EDIT**

Either mono or stereo will be good for me. My plan is to: stream the music via bluetooth to bluetooth module (for now I think about HC-06), send that data stream through arduino mini pro to the output mini jack.

Do I need in that case some kind of mp3/other format decoder module like [VS1003B on ebay][1] ?

  [1]: http://www.ebay.com/itm/VS1003B-MP3-Decoder-Module-Development-Board-STM32-Contains-Microphone-/121315052297?pt=LH_DefaultDomain_0&hash=item1c3ef0cb09

body:
The Arduino Uno / Mini Pro is not really the right tool for the job. It has no native audio output such as a 3.5mm jack.

Having said that I am sure it can be done - but it won't be the best quality sound. I have no doubt that it can be achieved with one of the following methods:

 - using the [`tone()`][1] function.
 - by using a [R-2R resistor ladder network][2] and some sort of amplification circuit.

The [Arduino Due][3] and the [Arduino M0][4] / [M0 Pro][5] both have inbuilt DAC's, meaning that they can output analog signals which can be used to drive a speaker circuit.

Another option is to use a Raspberry Pi which has a native 3.5mm audio jack.

  [1]: https://www.arduino.cc/en/Reference/Tone
  [2]: https://en.wikipedia.org/wiki/Resistor_ladder
  [3]: https://store.arduino.cc/usa/arduino-due
  [4]: https://store.arduino.cc/usa/arduino-m0
  [5]: https://store.arduino.cc/usa/arduino-m0-pro


message:
Reading speed of different arduinos

I'm thinking about using an Arduino for one of my Projekts. This would require that the Arduino can read/write a digital input/output in the order of 100kHZ to 1MHz. Is this possible or do I have to resort to my own boards using ATmegas?

body:
Any Arduino will do just fine. Technically, you could output 8 digital signals simultaneously at the Arduino's clock speed (16 MHz on most models), as it only takes one clock cycle to flip an output bit.

In more realistic scenarios 100kHz is no problem at all, and depending on your code 1MHz is possible as well.


body:
Focussing on your final question:

>Is this possible or do I have to resort to my own boards using ATmegas?

Remember, an Arduino is already just an ATMega already on a board. Designing your own board around an ATMega that is already part of the Arduino family is not going to significantly alter your project. That is unless you are going to have supplementing hardware, or go via higher clock speeds or ARM processing.


message:
How to program arduino for ethernet with only usb cable

I have arduino UNO r3 ATMEGA 328P board and [this][1] kind of a cable. But I want to make and test a program that need to get the data through ethernet port. Can I do only with them. I want to know whether they are enough to that (there are any converter or virtual devices) or should I buy anything.

  [1]: http://www.seeedstudio.com/depot/TypeB-USB-cable-for-Arduino-Diecimila-and-Freeduino-p-130.html

body: You can do the programming of the Arduino through the USB cable, but in order to test and operate the program, you'll need an Ethernet shield and a cable to connect that to the LAN.


message:
SerialEvent handling when using multiple serial ports

I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).

I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?

body:
The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.

EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.


body:
That should be fairly simple to implement.

Each serial port has TX and RX interrupts. You just need to tie into the various interrupts.

[Here is an example](http://mbed.org/cookbook/Serial-Interrupts) for a mbed, but it should be similar (both use ARM NVIC interrupt controllers).

To be clear, this wouldn't involve touching the `serialEvent()` function stuff at all, but rather implementing what it does using your own code.

---

If you set up your own interrupt handlers, you also get the benefit of being able to control interrupt priority yourself. The ATSAM3X has 16 interrupt priority levels, and a interrupt of a higher priority can pre-empt a lower-level interrupt.

I Strongly suggest you read the [ATSAM3X datasheet](http://www.atmel.com/Images/doc11057.pdf). It describes the interrupt controller, as well as the rest of the processor peripherals.


message:
Sending wireless data over with xbee s1

I am following this [tutorial][1] to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.

I've programmed the Xbee S1s by screening into the /dev/tty/* and configuring them with: `+++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000)` and `ATWR`. I've double checked the values to ensure they are correct.

So i've created a super simple Sender and Receiver package:

Sender.ino

    int counter = 0;

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

    void loop() {
      Serial.println(counter++);
      delay(1000);
    }

Receiver.ino:

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

    void loop() {
      Serial.println("Looping");
      while (Serial.available() == 0);    // wait
      int counter = Serial.parseInt();
      Serial.println(counter);
      Serial.flush();
      delay(500);
    }

  [1]: https://www.youtube.com/watch?v=vKVNmA8C6m8

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.

When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.

Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?

body:
**blah** reported:

> So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?


message:
Can the SPI pins of an Arduino be separated from SPI?

Are the SPI pins on the ICSP header of an Arduino Uno "separable" from the correspondent I/O pins - when one chooses to the use the ICSP header can the corresponding I/O pins be used for something else?

body: No.  Those pins are not separate on the microcontroller itself.  If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs.  Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.


body:
Actually, it can. You just can not use them at the same time. One needs to be careful to wire it in ways not to comprise the shared functions. Where MISO can be used as GPIO-INPUT and MOSI/SCK can be used as GPIO-OUTPUT, avoiding any pull up/downs, etc... As such electrical items may interfere with the ICSP.

For example I use the ICSP programming, along with the MISO, MOSI and SCLK pins as hard SPI and use them as Bit Bang one-wire, all on the same board and same wires. I simply ensure the SPI is properly configured each at each use.

One additionally needs to ensure that any peripherals on the shared SPI/ICSP lines are guaranteed to be in reset. Such as a pull down on such devices reset pins. Or a Pull Up on their ChipSelects. Noting that ATmega's GPIO pins are Hi-Z out of reset and during the ICSP.


message:
SRF04 Ultrasonic sensor - inaccurate readings

I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/

I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.

I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).

Has anyone experienced something similar?

body:
This is pretty standard. Altitude and air temperature will change the speed of sound enough to cause these errors, and minor variations in sensors could compound the problem. I would try calculating your own scale to convert ping time to distance using actual measurements from where you live; The library probably uses the speed of sound at sea level.

Similarly, any shape that poorly reflects or absorbs ultrasound will cause erroneous readings. There is really not much to do about this, sorry. If you have multiple sensors aimed a few degrees apart you are more likely to get one that will read the right distance.


body:
While BrettM discussed some excellent points that can occur with ultrasonic/sonar/'Ping' sensors I've noticed a few others when I have used these sensors.

The first and most common issue with sensors of this type is accurately identifying what is triggering the distance value. Consider at an abstract level how these work. You've got the bit that transmits a 'ping'. It transmits the 'ping' and stops. At this point the bit that listens for the 'pong' activates and starts listening. These sensors work by sending out that 'ping' and starting a timer, the first 'pong' the sensor hears triggers a stop response to the timer and distance is, roughly, figured out from here.  Notice that there is no way for the sensor to distinguish where the 'pong' is coming from. If you yodel on a mountain you don't know which surface echoed back and this is the same issue you are potentially facing with your sensor.

Typically when I work with people who are getting inaccurate readings from their sensors of the sort you are describing some variation of this issue is occurring. Often readings that are 'short' are so because there is an obstacle in the cone of the 'ping' that causes the sound to reflect back more quickly than expected for the surface you are measuring. Recall that sound is not a accurate,directed laser. Rather it spreads out in waves from the source. In my experience any objects within a roughly 160 degree arc(in my experience) in front of your sensor can cause these readings to be unusual. That can include the floor, your shoes, measuring devices. In theory the sensor is created to avoid these readings, in practice not so much.

To test if this is the case with your sensor setup I would recommend a few experiments. First setup the arduino and sensor in a fixed position and in such a way that the sensor is at the edge of a support surface with nothing but the surface you desire to measure in front of it. So, for example, set up the sensor on the very edge of a table facing a wall. Measure the distance from the wall to the support surface edge(table's edge). Some variation is normal, as described by BrettM, but 20% on 100 cm is a bit much in my experience. Once you get a solid, repeatable reading start changing the environment. Put something in the front arc of the sensor and see how that effects it. Move the sensor/support surface towards and away from the object. Typically when I see values like -5 that means something was too close to the sensor or, potentially, another sensor is interfering.

It is worth checking to confirm that there are no other range sensing devices in the area you are working within. Other devices sending out similar 'ping's can cause unusual readings(since they don't distinguish who's ping/pong is whose).


body:
Just don't use that library, it seems poorly designed.

Here is how the distance for roundtrip is calculated (code excerpts):

    long sum = 0;
    for (int i=0;i<_average;i++)
    {
        digitalWrite(_trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(_trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(_trigPin, LOW);
        _duration = pulseIn(_echoPin, HIGH);
        sum=sum+_duration;
    }
    return(int(sum/_average));

If we remove the averaging stuff (as `_average` is `1` by default), this boils down to:

    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    return int(pulseIn(_echoPin, HIGH));

`pulseIn` normally returns an `unsigned long` which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.

If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then `pulseIn()` should return:

    3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.

Now, if we take a look at the [SRF04 datasheet][1] timing diagram, it is mentioned that if no object is detected, an echo of **36ms** will be sent by the sensor; in this situation, `pulseIn()` will return **36000us**.

The problem here is that `36000` does not fit into an `int` (max value = `32767`), the conversion to an `int` will change it into a **negative value**! That explains your strange negative outputs.

Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:

    int DistanceSRF04::getDistanceCentimeter()
    {
            return (getDistanceTime()/29/2);
    }

The problem here is the `int` calculation, it should rather be performed as `float`. For a speed of sound of 340 m/s, one should divide the time of the echo in us by `29.4` (ie `1000000 / 340 / 100`), not 29, that can make a difference in the final calculated distance!

If you want to go on using this library, then just forget about the `getDistanceCentimeter()`method and replace it with the following code:

    distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as `float` and converted to `int` distance only at the end.

Your code should also explicitly detect negative values as meaning "no object detected".

  [1]: http://www.robot-electronics.co.uk/htm/srf04tech.htm


body:
Have you got a satisfying answer to this question?

I'm having a same issue with my HC-SR04 sensor.
It's supposed to be mm-accurate, instead I'm getting ~30%+ off values.
E.g.) @ 30cm, the readout is ~40cm.
      @ 15cm, the readout is ~20cm.

This isn't exactly a "solution" but here's what I did.
For calculating distance, I divided by additional 1.25.
>> distance = (duration/2.0)/29.4/1.25

Now my readings look a lot more accurate(+/-0.5cm) within ranges of 0~30cm. And although it wasn't perfect, at 2m it read 202cm.

Not sure if this is sensor issue or Arduino issue... Maybe it's lacking power such that a portion of echo pulse is not being registered at Ardu as High. I'm running my board on USB 5V, which is in turn taken off raspberry Pi2.
Still, 25% is a huge discrepancy...

WOWOWOW OK I FOUND SOMETHING!

After writing that last paragraph, I connected Arduino to my PC (instead of RPi), uploaded the s/w without 1.25 factor, and the readings are correct! (more or less. NOT like +30% before)

So yeah, it's because of lack of power.

Hope this is the case with you as well, in which case we can finally put this issue down for good.


body:
This saved my project:

https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478?f

Please spread the word, I almost gave up. This gem seems widely unknown, I spent two full days in vain trying to improve my ultrasonic sensor's accuracy.


message:
Why voltage at AREF is given by Vin * R2 / Rtotal

In [chapter 4](https://docs.google.com/viewer?url=http://www.nostarch.com/download/samples/Arduinows_ch4.pdf) of Arduino Workshop on page 85 (or page 31 in the pdf) it says that the voltage at AREF in the schematic is given by:

Vin * R2 / (R2 + R1)

However, the voltage is flowing from 5V to Ground so isn't AREF actually in parallel with R1, and so shouldn't AREF be given by:

Vin * R1 / (R1 + R2) ?

body:
You are correct.

$$V_{ref} = \dfrac{R_1}{R_1 + R_2} \cdot V_{CC}$$

or Vref = Vin * R1 / (R1 + R2) until we finally get [MathJax](https://arduino.meta.stackexchange.com/questions/13/is-there-an-easy-way-to-enter-formulas-in-questions) enabled on this site.


message:
Can't send serial data throught serial pins but it works with the usb port

I am just starting out a project and I am having a little bit of trouble. I want to send data collected from an IR distance sensor, and send it with an XBee Pro S2B to my computer so I can do other stuff with it. The code I am using right now is pretty simple:

    void setup()
    {
      Serial.begin(9600);
    }
    void loop(){
     int distance = analogRead(0);
      Serial.println(distance);
      delay(1000);
    }
The problem I am having is that when I turn on the arduino with batteries and disconnect the usb cable, the tx light stops turning on and no serial data is sended, AND if I connect it to the computer via USB again it won't work anyway, only works right when I upload the code. The XBees are configured correctly, I have done the chat example on the Building Wireless Sensor Networks by Robert Faludy.

Is it some code error? I must be really obvious.
By the way, when I upload the code and the serial data is sended throught usb, the data displayed on Arduino IDE's console is correct, so the sensor is wired correctly.

I am using an Arduino UNO and I have the XBee's and arduino's drivers installed correctly, and for the XBee I am using the XBee Explorer from Sparkfun

body:
I suggest you try to flash the pin 13 LED in your loop().  It seems like the Arduino is not booting correctly on the batteries?

The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that.  I prefer the Leonardo for these applications - where the USB serial and serial pins are totally independent.


body:
You have an XBee shield on top of the Arduino UNO?

Do you have an XBee attached to the computer?

Can you describe your setup a little more.

The TX Led on the Arduino is only on the USB side, and doesn't signify TX on the XBee. The XBee itself should/could have a TX/RX leds itself. Check the [Arduino schematic][1] to confirm this.

How are you reading the Serial on the computer? Thru the Arduino serial monitor? That won't work for the XBee. You'll need another Serial monitor for the XBee attached to the computer. ie, Arduino with XBee shield. Then an XBee connected via some breakout board to the computer. The Arduino Serial monitor won't see the XBee (use hyperterm on windows or some serial port monitor on other systems).

Also, check your switch on the XBee (if you have one), most redirect the USB/Serial connection between computer/Arduino and Arduino/XBee. It's one or the other not both.

  [1]: http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf


body:
Try interchanging the Tx-Rx pins of your XBee-Arduino connection.

Since you are getting correct values on the Arduino IDE, this means that both sensor and serial is working, but it sends values only when connected via USB which means that problem lies in your link between Arduino-Serial Device (in this case XBee)


body:
Ok, I have verified this behavior with a bare Uno on an external power supply driven from Vin.

The serial is outputting, but because of the way the TX and RX LEDs are wired in the Uno, they do not activate unless the USB processor is active.

This is super dumb and super confusing, but you can clearly see it's wired up this way:

[![Arduino Uno schematic detail][1]][1]

I have confirmed that serial data is coming out of the Arduino with a logic analyzer, but the LEDs **do not** light up.

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


body: Finally found out how to get the Arduino Uno serial port to work without a USB cable! I used a scope to see what was going on and found that using an external power supply on the Arduino power port only showed +3.3 volts on the +5 line. I pulled the plug on the external power supply and put a regulated +5 VDC on the +5 VDC pin.  Now, both software serial and the UART ports work fine - hope this helps!


message:
Direct 5V current based on analog signal

I would like to manage many LEDs from my Arduino - 12 or so - but I do not have the available digital pins to do this. Only one LED needs to be on at one time. Instead, I was hoping to control these with an analog pin. I was wondering if there is some sort of switch out there which can take an analog signal and, based on the value, direct a 5V current to a certain LED.

I realize that I could use a second Arduino for this, but I am trying to avoid that.

Thanks in advance for any help!

body:
You can accomplish this digitally with a device called a *decoder*. For example, the [74154](http://www.nxp.com/documents/data_sheet/74HC_HCT154.pdf) takes 4 inputs and maps those to one of 16 outputs (depending on the binary coding of the inputs). From the data sheet:

> The 74HC154; 74HCT154 decoders accept four active HIGH binary address inputs and
provide 16 mutually-exclusive active LOW outputs.


body:
If you have 4 pins available, you could use [charlieplexing](http://en.wikipedia.org/wiki/Charlieplexing#Charlieplexing) to selectively light up 12 led.
![charlieplexing][1]

Alternatively you could use some IC. You could use the one Greg suggested.

Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's `shiftOut` command.

You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).

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


body: You can use some of the analog pins to clock a shift register by defining them as a digital output.  Also two of the analog pins are also defined as I2C depending on your code. You could use 2 PCF8574s or an PCF8575 expansion board and control it that way. They can be used as inputs and outputs any order you want. There are a lot of other chips you can use to do this.  The reason I am suggesting this approach is later you will probably want to expand into other peripherals such as LCDs etc.


message:
splitable jumper wires question

I just received my starter kit from oddwires.com today and it came with a split-able ribbon cable for prototyping. I was curious if it is possible to split each wire off and use only what I need to for the tutorials or is that a bad idea? I am very excited to start playing around and learning this as it has been a interest of mine for many years.

body: Each wire in the Dupont ribbon cable is is independent, and does not hold onto its neighbors with any real force. You can split them or join multiple wires together using larger connectors as desired.


message:
Arduino Micro just blinks, won't connect to PC

*Edit - Sorry it's a **Micro** not a Nano*

I have a Micro board hooked up to an EasyDriver breakout using its 5V output to power the Micro.

Today I plugged it in and instead of booting up like normal the power LEDs on the wall plug, the easy driver, and the Arduino started flashing. The Micro became very hot, but not hot enough to burn.

After that if I plug the Micro into the USB port it just rapidly blinks the pin 13 LED. The PC does not detect the device but it does receive power.

Holding or pushing the reset button doesn't seem to help at all. I've used different USB cables, and different ports on the PC as well to no effect.

Is this something it can recover from? Why did all the LEDs blink like that?

body:
I have something similar happen a couple of times with some atmega328s (on arduino unos). I believe it was the bootloader that some how became corrupted and so no longer responded to the computer. The only way to fix this is to reflash the bootloader using an ISP programmer. Luckily the arduino can act as an ISP programmer so all you need is another working arduino.

See https://www.arduino.cc/en/Tutorial/ArduinoISP for how to do this on an uno. The same can be done with the micro/nano as they all use the same atmega328p chip its just a matter of wiring it up correctly.

If you cannot reflash the bootloader with this method then one of the chips is probably damaged and would need to be replaced. At this point it might be easier to replace the whole board.


body: I've had the same problem. I fixed it through a series of resets (removing the serial cable and plugging it in again), and punching 'make upload' a few times. Eventually it accepted my upload. The problem was an invalid code upload, which caused the Arduino to reset QUICKLY after booting. As an alternative, had this not worked, I would have blanked the chip with a USBtinyISP - it will hook up easily to your Arduino.


body:
I have had a similar problem, on a Pro Micro, and the PC, in the end, could not see it, and it would not show up in Device Manager. It was, to all intents and purposes, bricked.

----

It could be just a question of timing the double resetting of the Micro correctly, in order to enter bootloader mode, see [Pro Micro & Fio V3 Hookup Guide - Troubleshooting and FAQ - Reset to Bootloader][1]:

[![Pro Micro and Fio v3 reset functionality. Press reset twice, quickly to enter bootloader mode][2]][2]

While the Micro is in Bootloader mode, you should see it appear in Device Manager like so:

[![Pro Micro in bootloader mode - in Device Manager][3]][3]

While it is temporarily in this bootloader mode, you should be able to upload a new sketch.

----

However, this did not work for me and I ended up having to [burn the bootloader again][4], via ISP, using either a USBasp or an Arduino Uno configured as an ISP.

After a number of attempts the apparently bricked Pro Micro showed up again in Device Manager, and became fully functional:

[![Pro Micro with driver warning - in Device Manager][5]][5]

After that, all that was required was to install the correct Windows drivers, to get rid of the yellow warning icon.  From [Pro Micro & Fio V3 Hookup Guide – Installing: Windows][6], obtain the zip file *Arduino_Boards-Master.zip*. Then selecting the Pro Micro in Windows Device Manager, right click and “Update Driver Software”, following these instructions, from the link:

> Unzip that zip file, and don’t forget where you’ve left its contents.
> In that zip file, you should find an INF file, which contains all the
> information Windows needs to install the Pro Micro’s driver. This
> sparkfun.inf will be found in Arduino_Boards-master → sparkfun → avr →
> signed_driver.

Once the driver was installed, then the Pro Micro should appear correctly in Device Manager

[![Pro Micro - in Device Manager][7]][7]

If you haven't already done so, add the following URL to the Board Manager line in the Preferences dialog in the Arduino IDE:

    https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

Then opening the “Board Manager…” in the Tools/Boards menu, search for the “SparkFun AVR Boards” package and install it.

----

I have written two lengthy blogs about the whole experience:

 - [The case of the broken Pro Micro][8]
 - [The case of the broken Pro Micro (reprise)][9]

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/troubleshooting-and-faq
  [2]: https://i.stack.imgur.com/VBdHc.png
  [3]: https://i.stack.imgur.com/8bZ90.png
  [4]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader
  [5]: https://i.stack.imgur.com/2wlLv.png
  [6]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows
  [7]: https://i.stack.imgur.com/kH4QO.png
  [8]: https://gr33nonline.wordpress.com/2015/08/05/the-case-of-the-broken-micro/
  [9]: https://gr33nonline.wordpress.com/2016/10/19/the-case-of-the-broken-pro-micro-reprise/


body:
I had similar problem to Yours. Actually I tried to run my program in Clion IDE and then something broke in Arduino. I connected my Arduino Leonardo to my second PC clicked 2 times reset button and while the Bootloader COM appeared i fastly ran blink program.
(What is important that it wasnt one trial to run this blink program so i recommend to do it 5-10times if it doesnt work).


message:
Arduino Ethernet Shield connection to PC

is it possible to connect Arduino Ethernet Shield direct to PC and send a String variable? How can I read it later on the PC?

Will this code work?

    #include <Ethernet.h>
    #include <SPI.h>

    byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // Shield MAC

    byte pc[] = "192.168.0.13"; // pc IP
    EthernetClient client;

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

      Serial.println("connecting...");

      delay(5000);
      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("Sample String");
        client.println();
      } else {
        Serial.println("connection failed");
      }

    }

    void loop()
    {

    }

body:
No, you seem to be off on a tangent. There at least two problems:

 1. The Ethernet library is designed to run on an Arduino board. If you set the IP address to the same as the PC IP address, the network will get confused and nothing will work reliably.
 2. Are you asking how one can publish data from an Arduino board and read the results on a PC? This is easier. Just set up the web server example on the Arduino, and access it from a browser on your PC.


message:
Keyboardmessage on Arduino UNO

Can an Arduino UNO and Arduino Leonardo do the same things?

Some of the examples in the Arduino software say to use Leonardo e.g. [KeyboardMessage][1].

  [1]: http://arduino.cc/en/Tutorial/KeyboardMessage

body:
No, the Uno and the Leonardo cannot do the same thing.  The Leonardo is a single MCU directly connected to the USB port. It is down to the software on that MCU as to how it communicates (what it enumerates as) on the USB bus.

The Uno, conversely, is a dual MCU system. It has the "main" MCU (the ATMega328P) which is what you program, and that communicates to the USB port via another MCU.  The two MCUs are connected using TTL RS-232 (UART), so the only communication you have with your computer is through the Serial object.

There are benefits and problems with both approaches.  The benefits of the Leonardo are that you can emulate keyboards, mice, etc.  The down side is that the whole USB communication is more fragile and is at the mercy of the user.  The Uno's benefits are that the USB serial is always connected and available regardless of the state of the main MCU, which is much more friendly from the PC's point of view.  The down side is that it severely limits your communication options.


body:
Yes you can, but not with that library. This method is a little advanced and requires you to upgrade a different type of firmware to your second MCU on your Uno.

*(The full tutorial is available [here](http://mitchtech.net/arduino-usb-hid-keyboard/))*

Example code from the tutorial link shown above (for process outlined below):

    uint8_t buf[8] = {
      0 };  /* Keyboard report buffer */

    void setup()
    {
      Serial.begin(9600);
      randomSeed(analogRead(0));
      delay(200);
    }

    void loop()
    {
      int randomChar = random(4, 130);
      long randomDelay = random(1000, 10000);

      delay(randomDelay);

      buf[2] = randomChar;   // Random character
      Serial.write(buf, 8); // Send keypress
      releaseKey();
    }

    void releaseKey()
    {
      buf[0] = 0;
      buf[2] = 0;
      Serial.write(buf, 8); // Release key
    }

Here's what you need to do:

 1. Get a DFU programmer

 > Windows: Download Atmel's flip programmer from here http://www.atmel.com/tools/flip.aspx

 > Mac: Install MacPorts following these instructions: http://www.macports.org/install.php#pkg Once MacPorts is installed, in a Terminal window, type `sudo port install dfu-programmer`

 > Linux: from a command line type `sudo apt-get install dfu-programmer` or `sudo aptitude install dfu-programmer` depending on your distribution

 *(Source: http://arduino.cc/en/Hacking/DFUProgramming8U2)*

 2. Download the Keyboard [LUFA firmware](http://www.fourwalledcubicle.com/LUFA.php)

 3. You'll have to solder a resistor on a non-SMD Uno (that's outlined in the Arduino link in the second step)

 4. Connect the Uno to your comptuer and reset the 8u2 (short the farthest left pair of metal contacts in the upper left hand corner of the Uno)

 5. Upload the firmware using the GUI in flip, OR for Mac/Linux go to the directory where the firmware is using the terminal then:

Type this line (Still, Mac or Linux only):

    sudo dfu-programmer at90usb82 erase
    sudo dfu-programmer at90usb82 flash [Replace-this-with-file-name].hex
    sudo dfu-programmer at90usb82 reset

Unplug/plug in your board and enjoy! Note: you'll have to flash the standard firmware to upload a new sketch and the flash the keyboard firmware again to get this to work.


message:
No usb serial on Mac

I've been using my Arduino UNO without a hith for a few days now, but suddenly I can't program it anymore.

When I try to programm my Arduino on Mac, I get the following Error:

    avrdude: stk500_recv(): programmer is not responding

The USB option under serial port has disappeard (It was there before). Has anyone an idea on how to fix this?

The last thing I did is use the serial port for some communication. A reboot hasn't improved anything.

I tried programming Linux, but it resulted in the exact same result.

body:
If I try to upload with no device connected, I get a dialog with the message "port is blocked" and a message in Eclipse's console window that the port is not found.

So I'm guessing you've got a sync problem. UNO should reset automatically when avrdude connects. Try manually resetting it just before you click to start the download. If that works, then the automatic reset has failed.


body: It seemed to be a hardware problem on the board. Thanks for the effort.


message:
7 Segment Display SET UP

I am new to Arduino.
I have been trying to connect a 7 segment display (3 digits) to my Arduino and I was successful, but I am not doing any connection to ground. I do not find the data sheet so I am not sure if this connection is well done.
My doubt is: Is the connection to ground necessary? Or how do Arduino pins work? I am using 12 pins of the Uno to do the set up.

Thanks

My set up is the following:
![enter image description here][1]

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

body:
I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.

Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.

The wiring inside the display will likely look similar to this:
http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif


message:
Code flow for precission applications

This is a question about programming. Mainly about the loop() function

As an example
Consider code where you get data from an accelerometer, and if the Gs are high enough you do something.

Consider the following pseudocode:

    void setup()
    {
    pinMode(1, INPUT);
    bool flag = false;
    }

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

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

Now loop runs repeatedly
That means all the commands are executed in a continuous/serial style

Since that happens, what will happen if the accelerometer reading where (x>2), which is what we look for, happen in the REAL world, at a time where in the CPU, the cpu is at that time processing or checking following commands in the program flow, like

    if (button)  // if user hits the emergency button
          flag = true;

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

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

Should i worry about that?

body:
Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.

You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to `analogRead()` (and the more likely it is to miss something). Optimising your code can help.

You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.

If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.

If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See [`attachInterrupt()`][1] for more information.

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


body:
one should take into account the frequency response of the signal versus the sample rate. Per Arduino's web site [AnalogRead](http://arduino.cc/en/Reference/analogRead) "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second." or 5K/S for 2 AnalogRead's.

Where I read the output response of the [accelerometer used on the Esplora](https://www.sparkfun.com/datasheets/Components/General/MMA7361L.pdf) is 300-400Hz. Note often there are additional filters between the accelerometer and the A2D input.

So in short there should be enough time to sample both X & Y along with a Z, leaving a margin of 10x. To do other things.

Just be careful not to do too much, with routines that block.

As a matter of practice, it is best not to rely on a loop for what ever timing it loops at. But rather setup a timer, either by interrupt or by watching the millis(), to trigger the analog reads at a known interval.

    #include "TimerOne.h"
    volatile int x,y,z;
    void setup()
    {
      Timer1.initialize(3000);         // initialize timer1 to overflow at 333hz
      Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
    }
    void callback()
    {
      x = analogRead(A0);
      y = analogRead(A1);
      z = analogRead(A2);
    }
    void loop()
    {
      noInterrupts(); // to ensure they are all in sync.
      // do something with x,y&z
      interrupts();
      // do something else, that is not blocking.
    }


message:
Read Arduino code generated by Simulink

I am trying to do a [Hardware-in-the-loop][1] (HIL) system with Arduino and Simulink but the driver of my motor (Pololu VNH5019) works at 20kHz and simulink PWM block only supports 490Hz.

I would like to read and modify the code before it is sent to the Arduino to modify this and add other libraries.

It would be that possible?

If it is not possible, there is any other visual environment (with blocs, like simulink or Xcos) to generate Arduino Code?

   [1]: https://en.wikipedia.org/wiki/Hardware-in-the-loop_simulation

body:
Simulink just supplies code for all the things you could be up to, triggered by a serial command of yours. This is very slow and I think it's obvious, that you would want a fast and slim realization of everything possible, if you attempt to do HIL.

If there is a special part you think is only easy for you with blocks, just ask right away, but it is really easy to do everything you can wish for in a few simple lines.
Also this is better for you, because you really know, what's going on.

I could provide some detail code, since I'm doing HIL myself atm, but you would need to specify a bit, what you are up to.

To really answer your question: I don't know of any other visual programming tool for arduino and as stated above, my best knowledge is, that simulink uses pretty messy things. And loads them onto the board right away, right?


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


message:
Arduino Uno wiring and code with Parallax PMB-688

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

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

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

  [1]: https://arduino.stackexchange.com/users/490/phillynj


message:
Confusion around LEDs on a breadboard

I am just starting out with an Arduino Diecimila and am playing around with LEDs, and am confused by why some circuits result in an LED not lighting up.

Successful Scenarios:

1. Yellow LED from pin13 to 16B on the breadboard, Green LED from 16A to GND. This works both LEDS light up.

2. Yellow LED from pin13 to 16A on the breadboard. Wire from 16E to 14E. Green LED from 14A to GND. This works and both LEDs light up.

Failed Scenarios:

1. Yellow LED from pin13 to 16A. Green LED from 16E to 14E. Yellow LED from 14A to GND. No LEDs light up. I would assume that all the LEDS are in series, and all 3 should light up, I assumed this would be exactly the same as my second successful scenario where the LED is acting the same as the wire.

2. Yellow LED from pin13 to 16A. Wire from 16E to 14E. Yellow LED from 15A to GND. Green LED from 16B to 14B. Here I have both Yellow LEDS lit, but the Green LED is not lit. I was expecting that the Green LED would have been in parallel and should have lit up.

In both failed scenarios I have swapped around the LEDs and proved that all the LEDs function.

There must be some basic concept that I am not understanding with the circuits, any ideas?

body:
Scenario 1 fails because yellow and green LEDs have forward voltages of about 2V each, so when putting 3 in series, you need a forward voltage to light them that exceeds the 5V available.

Scenario 2 fails because the wire you have in parallel with the LED provides a path with a very low voltage drop (close to 0V), so the path through the LED with a ~2V voltage drop is not taken (and if you remove the wire, the same reasoning as in scenario 1 applies, so nothing would work).

BTW, you should never run LEDs without a series resistor, as your experiments will surely demonstrate to you soon ;-)


message:
Serial.write() prints a variable twice

I have this 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()
    {

            bool isGpsLocationValid = false;
            do
            {
                while (ss.available()>0)
                {
                    char c = byte(ss.read());
                    if (gps.encode(c))
                    {
                        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);
    }

Now when all is done, the clng value is printed twice in the serial monitor.
The value i get is in this format:

    27.275869  15.151013
      15.151013

As you can see, clng is printed twice. Any ideas why is that?

body:
The width parameter to `dtostrf()` is the width of the resulting string NOT including the null terminator. So you are overflowing the array.

Change:

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

to

    char clat[12];
    char clng[12];

and it should work.


message:
Trouble with variable types and integrating DHT11 temperature sensor

I am trying to modify this sketch;
https://github.com/itsallvoodoo/home_automation/blob/master/Arduino_HVAC_Controller/HVAC_Controller/HVAC_Controller.ino

But I have a different temperature sensor, a DHT11, and I am using the libraries from Adafruit.

The DHT11 can't be constantly polled, 1 second intervals is the maximum rate.

I am currently working (fighting) with the portion towards the bottom in the section:

    boolean getTemp() {

As my sketch stands, I have "currentTemp" statically assigned to 79 degrees. When I upload, the arduino acts as I would expect it to given that data.

If I change it to 0 (zero) and try to set the temp by reading the sensor in the section starting at line 237  like this;

    boolean getTemp() {

      currentTemp = 0;
      long temp = 0;

      if ((millis() - TempLastCheck) > 2000) {
        TempLastCheck = millis();
        //  currentTemp = dht.readTemperature(true);
          temp = dht.readTemperature(true);
         Serial.println(dht.readTemperature(true));
      }

The LCD is blank after it restarts, and the arduino triggers the "heat" relay because the temperature is 0 (zero)

I'm sure I'm missing something simple, because the DHT11 outputs floats, or something... I'm too new to this language to know what I'm missing. Any help will be greatly appreciated.

    // name:     HVAC_Controller.ino
    // author:   Chad Hobbs

    // -------------LIBRARIES---------------- THESE ARE REQUIRED TO BE IN YOUR SKETCHBOOK\LIBRARY FOLDER FOR COMPILING ----
    #include <Wire.h>                   // Protocol to communicate with I2C devices
    #include <Adafruit_MCP23017.h>      // LCD protocol
    #include <Adafruit_RGBLCDShield.h>  // LCD + Button shield protocol
    #include "DHT.h"                // DHT11 Temp/Humidity Sensor
    // --------------PARAMETERS---------------------
    int heat = 55;                    // This is the default heater trigger temp setting
    int cool = 70;                    // This is the default cooling trigger temp setting
    int buffer = 1;                   // This is the range away from the setpoint the heat or AC will overcool/heat to prevent shorter cycles
    int heatPin = 7;                  // Digital pin used for turning on the heater relay
    int coolPin = 8;                  // Digital pin used for turning on the AC relay
    int cycleTime = 60;               // The length of time to delay running the AC or heat to prevent short cycling
    boolean heatRunning = false;      // Stores whether the heater is currently running or not
    boolean coolRunning = false;      // Stores whether the AC is currently running or not
    long currentTemp = 0;             // Current room temperature

    int serialSpeed = 9600;           // Default serial comm speed
    long oldTemp = 0;                 // Used to only update the currentTemp if the temp has changed
    unsigned long timeOut;            // Backlight timeout variable
    boolean editable = false;         // Determines whether or not button presses will do anything, used to avoid accidental changes
    char* menu[] = {"Cooling", "Heating"};  // Menu display for either setting the high point or the low point of the temp range
    int menuPosition = 1;             // Current position in the setting menu
    unsigned long heatLastRan;        // Stores the time the heater last ran
    unsigned long coolLastRan;        // Stores the time the AC last ran
    unsigned long TempLastCheck;      // Stores the last sensor reading ran

    // -------------Library Interaction--------------
    // Create our LCD Shield instance
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
    #define ON 0x7            // For single color LCD, set on to white
    #define OFF 0x0           // For single color LCD, set off to black

    #define DHTTYPE DHT11   // DHT 11
    #define DHTPIN 4     // what pin we're connected to
    DHT dht(DHTPIN, DHTTYPE);

    // ----------------------------------------------------------------------------------------
    // Function Name: setup()
    // Parameters:    None
    // Returns:       None
    // Description:   This function executes housekeeping duties and staging for the loop() function; executed once
    // ----------------------------------------------------------------------------------------
    void setup() {

      //  pinMode(busPin,INPUT);  // Designate temperature bus pin data direction
      pinMode(heatPin, OUTPUT);               // Heat circuit relay
      pinMode(coolPin, OUTPUT);               // Cooling circuit relay
      Serial.begin(serialSpeed);

      lcd.begin(16, 2);       // set up the LCD's number of columns and rows
      lcd.setBacklight(ON);   // Start off with backlight on until time-out
      timeOut = millis();     // Set the initial backlight time
      TempLastCheck = millis();  // Set the initial sensor timing

      dht.begin();
    }

    // ----------------------------------------------------------------------------------------
    // Function Name: loop()
    // Parameters:    None
    // Returns:       None
    // Description:   This is the main executing block of the program, calling all ancillary functions to operate the Arduino
    // ----------------------------------------------------------------------------------------
    void loop() {
      if ((millis() - timeOut) > 30000) {                   // Turn on backlight for 30 seconds, else turn it off
        lcd.setBacklight(OFF);
        editable == false;
      } else {
        lcd.setBacklight(ON);
      }

      lcd.setCursor(0, 1);                  // Starting position of character printing

      uint8_t buttons = lcd.readButtons();  // Constantly check to see if something has been put on the bus

      // --------------Handle updating Temp Change Display---------------------
      if (getTemp()) {                      // Constantly check to see if the temperature has changed, and update appropriately
        lcd.clear();
        lcd.print("Temp:");
        lcd.print(currentTemp);
      }

      // --------------Handle Button Presses---------------------
      if (buttons) {
        timeOut = millis();
        lcd.setBacklight(ON);

        if (buttons & BUTTON_SELECT) {      // Allow parameters to be changed only if the Select button has been pressed first
          editable = true;
        }
        if (editable) {                     // go to buttonHandler to handle menu switching and parameter manipulations
          buttonHandler(buttons);
        }
      }

      // --------------Handle Heat and Cooling Cycles---------------------
      powerControl();

    }

    // ----------------------------------------------------------------------------------------
    // Function Name: powerControlHandler()
    // Parameters:    None
    // Returns:       None
    // Description:   This function will handle turning AC or Heat off and on based on current temp, timers, and setpoints
    // ----------------------------------------------------------------------------------------
    void powerControl() {

      // TODO: Add in fan relay control

      // This executes if the heater is running and it gets warm enough to turn off.
      if (heatRunning && (currentTemp > (heat + buffer))) {
        heatRunning = false;
        heatLastRan = millis();
        digitalWrite(heatPin, HIGH);
        return;
      }

      // This executes if the AC is running and it gets cool enough to turn off
      if (coolRunning && (currentTemp < (cool - buffer))) {
        coolRunning = false;
        coolLastRan = millis();
        digitalWrite(coolPin, HIGH);
        return;
      }

      // This executes if it gets cold enough and the heater has not run for a minimum time (short cycle protection)
      if ((currentTemp < heat) && ((millis() - heatLastRan) > cycleTime)) {
        digitalWrite(heatPin, HIGH);
        heatRunning = true;
        return;
      }

      // This executes if it gets hot enough and the AC has not run for 10 minutes (short cycle protection)
      if ((currentTemp > cool) && ((millis() - coolLastRan) > 60)) {
        digitalWrite(coolPin, HIGH);
        coolRunning = true;
        return;
      }

      return;
    }

    // ----------------------------------------------------------------------------------------
    // Function Name: buttonHandler()
    // Parameters:    None
    // Returns:       Boolean, True if the temperature has changed, else False
    // Description:   This function polls the temp sensors, retrieves the values, and then returns
    // ----------------------------------------------------------------------------------------
    boolean buttonHandler(uint8_t buttons) {

      // --------------PARAMETERS---------------------
      int heatModifier = 0;
      int coolModifier = 0;

      // --------------SETUP---------------------
      lcd.clear();

      // If the UP Button is pushed, increasing the setpoint
      if (buttons & BUTTON_UP) {
        if (menuPosition == 0) {
          coolModifier = 1;
        }
        if (menuPosition == 1) {
          heatModifier = 1;
        }
      }

      // If the Down Button is pushed, decreasing the setpoint
      if (buttons & BUTTON_DOWN) {
        if (menuPosition == 0) {
          coolModifier = -1;
        }
        if (menuPosition == 1) {
          heatModifier = -1;
        }
      }

      // If the Left Button is pushed, change the menu context
      if (buttons & BUTTON_LEFT) {
        if (menuPosition == 1) {
          menuPosition = 0;
        } else {
          menuPosition = 1;
        }
      }

      // If the Right Button is pushed, change the menu context
      if (buttons & BUTTON_RIGHT) {
        if (menuPosition == 1) {
          menuPosition = 0;
        } else {
          menuPosition = 1;
        }
      }

      // If anything has been modified, update accordingly
      heat = heat + heatModifier;
      cool = cool + coolModifier;

      // Print proper menu title and setpoint
      lcd.setCursor(0, 0);
      lcd.print(menu[menuPosition]);
      lcd.setCursor(0, 1);
      lcd.print("Setpoint: ");

      if (menuPosition == 0) {
        lcd.print(cool);
      }
      if (menuPosition == 1) {
        lcd.print(heat);
      }

    }

    // ----------------------------------------------------------------------------------------
    // Function Name: getTemp()
    // Parameters:    None
    // Returns:       Boolean, True if the temperature has changed, else False
    // Description:   This function polls the temp sensors, retrieves the values, and then returns
    // ----------------------------------------------------------------------------------------
    boolean getTemp() {

      currentTemp = 79;
      long temp = 0;

      if ((millis() - TempLastCheck) > 2000) {
        TempLastCheck = millis();
        //  currentTemp = dht.readTemperature(true);
         //temp = dht.readTemperature(true);
         Serial.println(dht.readTemperature(true));
      }

      /////////////////////////////////////////////////////////////////////////////////////////////////////
      //  sensors.requestTemperatures(); // Send the command to the device to get temperatures

      // Go through devices and read the temperatures
      //  for(int x = 0; x < numOfDevices; x++){
      //   temp = sensors.getTempF(addrs[x]);
      //  if(temp != currentTemp){
      //   currentTemp = temp;
      //    }
      //  }
      /////////////////////////////////////////////////////////////////////////////////////////////////////
      // Check to see if temperature has changed
      if (currentTemp != oldTemp) {
        oldTemp = currentTemp;
        return true;
      }
      else {
        return false;
      }
    }

body:
First of, you read the temperature and put it into local variable `temp`. You need to copy the value from `temp` into `currentTemp`.

Secondly, you are reading the temperature twice in a row. Once to assign it to `temp` and again for the `Serial.println`.

      if ((millis() - TempLastCheck) > 2000) {
        TempLastCheck = millis();
        currentTemp = dht.readTemperature(true);
        Serial.println(currentTemp);
      }

When setting the `currentTemp` to 0 inside `getTemp`, getTemp never return `true`, because you initialized the value of `currentTemp` with 0 (`long currentTemp = 0;`). So it never changed, and the lcd is never updated. Just change it to something like:

    long currentTemp = -100;


message:
Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328)

I am currently working on a project that requires communication between an android phone(galaxy s4) and an ATmega328 microprocessor. To connect these devices wirelessly I'm using an HC05 bluetooth module and to understand the connection I'm using pre-built arduino codes(turn LEDs on and off) and an android app called blueterm.

This connection is established and able to transmit data when connected to the Arduino uno, but as soon as this chip is removed and connected to a standalone breadboard the connection fails. The standalone breadboard works fine and has been tested with many other projects and I have attached the breadboard connection below. The HC05 when connected to the breadboard changes the blinking pattern to notify the user it is connected but the serial connection is never made. Any help would be greatly appreciated, if any other information is needed feel free to ask.

![enter image description here][1]

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

body: If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -> Tx and Tx -> Rx.


body:
I had same issue and solved by below mentioned layout.[![HC05 with Atmega328][1]][1]

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