body:
I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here  is my circuit:
I have marked the way I connect the ISP port and the chip.

![enter image description here][1]

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:

    Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

    avrdude: warning: cannot set sck period. please check for usbasp firmware update.

    avrdude: error: programm enable: target doesn't answer. 1

    烧录引导程序出错。

    avrdude: initialization failed, rc=-1

             Double check connections and try again, or use -F to override

             this check.

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.

**EDIT**
---
I do the flowing things as advise:

 1. short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
 2. I just found the way I connect the isp port might be wrong. so I changed it as flowing
![enter image description here][2]

And my actually circuit is like this:
![enter image description here][3]

But got no luck, things still the same :-(

  [1]: https://i.stack.imgur.com/ZzI6v.png
  [2]: https://i.stack.imgur.com/9Z7bn.png
  [3]: https://i.stack.imgur.com/imPKv.jpg

title: Can't burn arduino bootloader to atmega8a with usbasp

Answers: 2

body:
You forgot the Pull Up resistor for Reset.

Using 12Mhz crystal is not a good idea because the Atmega8 config probably uses 8Mhz or 16Mhz, and the fuses which are burned during the bootloader process (yes, they burn fuses first, and THEN load the bootloader) will not expect there to be a 12Mhz crystal, so any further communication can fail because of this too.

body: Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the _divide clock by 8_ fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.


body:
I have Arduino Mega and Weather Shield. I want to calculate wind speed.

    float get_wind_speed()
    {

    float deltaTime = millis() - lastWindCheck; //750ms

    deltaTime /= 1000.0;

      float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

      windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
      lastWindCheck = millis();

      windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

     Serial.println();
     Serial.print("Windspeed :");
     Serial.println(windSpeed);

     return(windSpeed);
    }

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.

How can I make it better?

title: arduino weather shield and wind speed

Answers: 1

body:
When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both `windClicks` and `deltaTime` are 0 or 0.0.  The IEEE 754 floating-point-operations specification dictates a result of `NaN` (not-a-number) for various zero over zero calculations.  It dictates a result of `+Inf` or `-Inf` for calculations like 7/0.0 or -13/0.0.  [See, for example, the stackoverflow question, [Why does division by zero with floating point (or double precision) numbers not throw an exception](https://stackoverflow.com/q/12954193).]

If arithmetic generates a `NaN` or `+Inf` result, subsequent arithmetic using that result will also produce `NaN` or `+Inf` results.

To deal with the problem, you could use `deltaTime > 0` as a required pre-condition for calculation of `windSpeed`.  That is, have an if-statement protecting the calculation block.


body: I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

title: How do I even out Infared distance sensor readings?

Answers: 5

body:
Wikipedia has a page on moving averages: http://en.wikipedia.org/wiki/Moving_average

I'd suggest at first try an exponential moving average:

> average = a * sample + (1 - a) * average

Experiment with different values of a (with 0 < a <= 1).

The smaller a is, the smoother the curve, but also the longer (more iterations) it takes for an actual change in the input to be reflected in average.

body:
My solution keeps reading for cycles (10 times) and calculate average it.

Be careful voltage output of many surface NOT same.

body:
IR sensors are very erratic in my experience. The best way is to take an average of multiple sensor readings. The number of readings required can be found by experimentation.

**Example Sketch** ([Source][1])

The example below should be similar, and a good start for your model of IR sensor.

    /*
     Sharp GP2Y0A21YK0F infrared proximity sensor (#28995)
     Collects an average of five readings from the sensor and displays the
     resulting value about every half second.

     See the SharpGP2Y0A21_Simple demonstration for additional usage notes,
     including connection diagram.

     This example code is for the Arduino Uno and direct compatible boards, using the
     Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other
     Arduino boards, including the Arduino Due.

    */

    const int irSense = A0;          // Connect sensor to analog pin A0
    int distance = 0;

    void setup() {
      Serial.begin(9600);            // Use Serial Monitor window
    }

    void loop() {
      Serial.println(irRead(), DEC); // Call irRead function to read sensor
                                     // Print value in Serial Monitor
      delay(250);                    // Wait another 1/4 second for the next read
                                     // (Note: Because of delays built into the
                                     //   irRead function the display of values will
                                     //   be slower than in the SharpGP2Y0A21_Simple
                                     //   sketch
    }

    // Take multiple readings, and average them out to reduce false readings
    int irRead() {
      int averaging = 0;             //  Holds value to average readings

      // Get a sampling of 5 readings from sensor
      for (int i=0; i<5; i++) {
        distance = analogRead(irSense);
        averaging = averaging + distance;
        delay(55);      // Wait 55 ms between each read
                        // According to datasheet time between each read
                        //  is -38ms +/- 10ms. Waiting 55 ms assures each
                        //  read is from a different sample
      }
      distance = averaging / 5;      // Average out readings
      return(distance);              // Return value
    }

  [1]: https://www.parallax.com/downloads/sharp-gpy2y0a21yk0f-ir-distance-sensor-arduino-demo

body:
Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
[additive white Gaussian
noise](http://en.wikipedia.org/wiki/Additive_white_Gaussian_noise), then
it can be shown that averaging is in some way the “best” way to clean
your data.

However, if you have big sporadic errors, then **averaging is not a good
solution**. This is because you will have to average _a lot_ of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get _another_ huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.

The solutions to this problem lye in the realm of [robust
statistics](http://en.wikipedia.org/wiki/Robust_statistics). It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
[median](http://en.wikipedia.org/wiki/Median). The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
_huge_ errors, as long as the _majority_ of samples are reasonable.

Here is an implementation of a simple moving-median filter based on the
standard libc’s `qsort()`. It assumes samples have `int` type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.

<!-- language: lang-c -->

    /*
     * Comparison function for qsort(): return an integer "less than, equal
     * to, or greater than zero if the first argument is considered to be
     * respectively less than, equal to, or greater than the second."
     */
    int compare(const void *pa, const void *pb) {
        int a = *(int *)pa;
        int b = *(int *)pb;
        return a<b ? -1 : a>b ? +1 : 0;
    }

    #define FILTER_LENGTH 11  // length of the median filter, should be odd

    /*
     * Input: raw sample.
     * Ouput: filtered sample.
     */
    int median_filter(int data) {
        static int input_buffer[FILTER_LENGTH];
        static int input_index;
        int sorted_buffer[FILTER_LENGTH];

        // Store the current data point.
        input_buffer[input_index] = data;
        if (++input_index >= FILTER_LENGTH) input_index = 0;

        // Sort a copy of the input buffer.
        for (int i = 0; i < FILTER_LENGTH; i++)
            sorted_buffer[i] = input_buffer[i];
        qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

        // Return median.
        return sorted_buffer[FILTER_LENGTH/2];
    }

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.

body:
The Sharp GP... infra red proximity sensors can produce noisy output sometimes.  This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.

So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself.  This is mentioned on some of their datasheets, but gets forgotten...


body:
It keeps giving me this warning:

>You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?

title: Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?

Answers: 1

body:
V2.2 is pretty old by now.
As far as I recall it should work fine.

V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.

But again V2.2 is old. We hope to release V3.0 end of February 2016


body: Is it safe to feed 5v dc 1amp to an Arduino uno board?

title: Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?

Answers: 3

body: Yes as long as the polarity is correct, the board will only take the current it requires

body:
The 1 Ampère you're mentioning is likely the maximum rating of the power supply, i.e. it cannot sustain higher currents for a long time. However, if you connect your Arduino board (or any other device) to your power supply, the actually flowing current will depend on the voltage U and the resistance R of the device as I = U/R. You can think of this as the Arduino drawing as much power as it needs.

In other words: you must not exceed the maximum voltage, but you don't have to (and cannot in a simple way) adjust the current flowing into the Arduino.

body:
That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"

The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.

But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a **regulated**(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.


body:
Please explain in detail. How the Hexadecimal code has been assigned?

Edit: This is the code:

    #include <Wire.h>
    void setup()
    {
       Wire.begin();
       Serial.begin(9600);
       delay(1000);
       Serial.println("AT+CMGF=1"); //set to SMS mode
       delay(1000);
       Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
       delay(1000);
       Serial.println("hello world. this is arduino");
       delay(1000);
       Serial.write(0x1A); // sends ctrl+z end of message
       delay(1000);
       Serial.write(0x0D); // Carriage Return in Hex
       delay(1000);
       Serial.write(0x0A);
    }
    void loop() {}

title: Can anyone explain how hex codes 0x1A is used for sending ctrl+z & 0x0D for Carriage Return & 0x0A for LineFeed?

Answers: 3

body:
These hex values are the numbers in the ASCII table, https://en.wikipedia.org/wiki/ASCII.

Characters corresponding to values below 32 are control characters, reserved for special purposes. For the values you mention in the question:

- 0x0d = 1*16 + d*1 = 13 = CR (carriage return)
- 0x0a = 0*16 + a*1 = 10 = LF (line feed)
- 0x1a = 1*16 + a*1 = 26 = [SUB][1]

("control+Z" is not the ASCII control character, but how you would generate this control character (SUB) on a keyboard.)

A table with both hexadecimal and decimal numbers is also [given][2] in the Wikipedia article.

  [1]: https://en.wikipedia.org/wiki/Control-Z
  [2]: https://en.wikipedia.org/wiki/ASCII#ASCII_control_code_chart

body:
They are all to do with where in the alphabet they are.  There are 26 letters in the English alphabet, and Z is the 26th.  The 26 in hexadecimal is 0x1A.

A carriage return is a CTRL-M, and a line feed is a CTRL-J.  M is the 13th letter of the alphabet, and 13 in hexadecimal is 0x0D.  J is the 10th letter - 10 is 0x0A in hexadecimal.

Why are they CTRL-M and CTRL-J?  Well, that all stems from the old teletype interfaces used on the very early computers.  That's what they used, and that's what's stuck, and finally made it into the ASCII standard.

body:
(I've formatted your code and edited it into your question).

This code is apparently driving a device - GPRS shield? - to send an SMS. No doubt the code was written to meet the requirements of the device. Note that the CR and LF literals could have been written as '\r' and '\n', respectively. The author chose to write them in hex, probably because there is no "\" code defined for Ctrl-Z, and so wrote all three in a consistent style.


body:
So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :

    {
      Serial.println(value1);//value that i get from analog sensor
      //this is just to get the values in order for the led and sound
      if (value1<=8) value1=-100;
      analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
      tone(tonepin,value1+100,100);
      delay(10);

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.

SO I thought I'll try to fade in and fade out to different values from present values.  Used the fading examples. Here:

    Serial.println(value1);
      if (value1<=8) value1=-100;

      if (value1+100<=value2+100) {
        for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

        analogWrite(ledPin, fadeValue);

        delay(10);
        }
      }

      else
      {

        for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
        {
            analogWrite(ledPin, fadeValue);

        delay(10);
        }
      }
      //analogWrite(ledPin,value1+100);
      tone(tonepin,value1+100,100);
      delay(10);
      value2=value1;

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.

Any help with what I could do and what I am doing wrong would be nice.

title: How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?

Answers: 2

body:
Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.

    int lastValue = 0;

    {
      Serial.println(value1);//value that i get from analog sensor
      //this is just to get the values in order for the led and sound
      if (value1<=8) value1=-100;
      value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
      analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
      tone(tonepin,value1+100,100);
      lastValue = value1;
      delay(10);

body:
You need to re-think the entire way of dealing with the fading.

Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".

Something like, in pseudo-code:

    TargetBrightness = SensorValue
    if LEDBrightness < TargetBrightness
        increment LEDBrightness
        set LED to LEDBrightness
    if LEDBrightness > TargetBrightness
        decrement LEDBrightness
        set LED to LEDBrightness

If that all happens too fast then you need to only run the brightness tests at certain periods.  Something like:

    TargetBrightness = SensorValue
    Has 10ms passed since last check? Yes?
        Remember the time this check happened.
        if LEDBrightness < TargetBrightness
            increment LEDBrightness
            set LED to LEDBrightness
        if LEDBrightness > TargetBrightness
            decrement LEDBrightness
            set LED to LEDBrightness


body:
I have Arduino Mega and Weather shield and GPS Receiver - GP-635T (50 Channel).

here is my code for GPS

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

    TinyGPSPlus gps;

    static const int RXPin = 5, TXPin = 4;
    SoftwareSerial ss(RXPin, TXPin);

    const byte GPS_PWRCTL = 6;

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

      pinMode(GPS_PWRCTL, OUTPUT);
      digitalWrite(GPS_PWRCTL, HIGH);
    }

    void loop()
    {
      smartdelay(800);
    }

And print weather with this code

    void printWeather()
    {
      Serial.print("lat=");
      Serial.print(gps.location.lat(), 6);
      Serial.print("lat=");
      Serial.print(gps.location.lng(), 6);
      Serial.print("altitude=");
      Serial.print(gps.altitude.meters());
      Serial.print("sats=");
      Serial.print(gps.satellites.value());

      char sz[32];
      Serial.print("date=");
      sprintf(sz, "d/d/d", gps.date.month(), gps.date.day(),gps.date.year());
      Serial.print(sz);

      Serial.print("time=");
      sprintf(sz, "d:d:d", gps.time.hour(), gps.time.minute(), gps.time.second());
      Serial.print(sz);
    }

But I see only zero for location and date and time. What should I do?

title: arduino weather shield with gps

Answers: 2

body:
You need to feed the output from the GPS module to the `TinyGPSPlus` routines, otherwise they won't do anything (other than return `0`). Try adding:

    while (Serial.available() > 0) {
      gps.encode(Serial.read());
    }

to your `loop`. `TinyGPSPlus` comes with examples that you should have a look at. It also provides many debug statistics, e.g. the number of characters processed (`gps.charsProcessed()`) and the if these made sense (`gps.passedChecksum()`).

body:
Until you have the correct baud rate *and* good satellite reception, many fields will be zero or empty.  I wrote a diagnostic program for [NeoGPS](https://github.com/SlashDevin/NeoGPS) that will try different baud rates and confirm that the GPS device is functioning.  The example program is in this directory:

    examples/NMEAdiagnostic

Installation instructions are [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Installing.md).

If you're inside, you may not be able to receive anything.  Move next to a window or go outside.


body:
I'm planning to make a handbrake for my racing simulator (Assetto Corsa) and I wanted to know how can I transform arduino into a joystick so the game can read the **analog** input?

Thanks in advance, and sorry for my bad english.

title: Arduino analog joystick

Answers: 2

body:
Never tried it with the Arduino, but it's [quite easy to do with Teensy](https://www.pjrc.com/teensy/td_joystick.html) (which is mostly compatible with Arduino).

[Teensyduino](https://www.pjrc.com/teensy/teensyduino.html) actually includes several examples.

body:
I made this [video][1] and [github][2] just for this about a year ago.

[![Breadboard][3]][3]

And here is the code:

    /*
    2-axis joystick connected to an Arduino Micro
    to output 4 pins, up, down, left & right

    If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
    This skectch is using pull up resistors.

    */

    int UD = 0;
    int LR = 0;
    /* Arduino Micro output pins*/
    int DWN = 13;
    int UP = 12;
    int LEFT = 11;
    int RT = 10;
    /* Arduino Micro Input Pins */
    int IUP=A0;
    int ILR=A1;

    int MID = 10; // 10 mid point delta arduino, use 4 for attiny
    int LRMID = 0;
    int UPMID = 0;
    void setup(){

      pinMode(DWN, OUTPUT);
      pinMode(UP, OUTPUT);
      pinMode(LEFT, OUTPUT);
      pinMode(RT, OUTPUT);

      digitalWrite(DWN, HIGH);
      digitalWrite(UP, HIGH);
      digitalWrite(LEFT, HIGH);
      digitalWrite(RT, HIGH);

      //calabrate center
      LRMID = analogRead(ILR);
      UPMID = analogRead(IUP);
    }

    void loop(){

      UD = analogRead(IUP);
      LR = analogRead(ILR);
      // UP-DOWN
      if(UD < UPMID - MID){
       digitalWrite(DWN, LOW);
      }else{
       digitalWrite(DWN, HIGH);
      }

      if(UD > UPMID + MID){
       digitalWrite(UP, LOW);
      }else{
       digitalWrite(UP, HIGH);
      }
      // LEFT-RIGHT
      if(LR < LRMID - MID){
       digitalWrite(LEFT, LOW);
      }else{
       digitalWrite(LEFT, HIGH);
      }

      if(LR > LRMID + MID){
       digitalWrite(RT, LOW);
      }else{
       digitalWrite(RT, HIGH);
      }

      delay(400);

    }

  [1]: https://www.youtube.com/watch?v=bTqk_QoeRmw
  [2]: https://github.com/PhillyNJ/ArduinoParallaxJoystick
  [3]: https://i.stack.imgur.com/Ad4hZ.png


body:
I have a wearable wristband project where I'd like to detect a touch to the outside of the wristband, like a button. However, all my attempts to get this to work with capacitive sensing fail.

The problems accumulate from these aspects:

- Without grounding, the behaviour seems totally arbitrary at times
- I need high response times (12 fps so < 100ms), so some resistor values keep hitting the timeout limit
- Testing is really hard, as behaviour changes after unplugging the USB connection to the computer. I have a bluetooth connection in the Arduino and debug via bluetooth connection to get a "actual scenario" type of reading
- I've also tried things like setting very short timeouts as well as low sample sizes as well as experimented with different resistors

However, I am not trying to really get any sort of gradual "capacitive sensing" here at all, I merely would need to detect a threshold for "is touching". In fact, the area that the user is touching could even be made out of metal (which it was in my tests so far) and touched directly (so nothing in between finger and metal).

This seems like such an obvious thing to try to achieve, I believe there must be some way to get this done. Any ideas?

title: Capacitive sensor touch detection on wearable

Answers: 1

body:
Expanding on my previous comment:

You can think of capacitive sensing as a form of impedance measurement,
even though it's more a threshold detection than an actual measurement.
In order to perform an impedance measurement, you have to build a
circuit like this:

    ┌─────────┐           ┌───────────┐
    │         ├───────────┤           │
    │  meter  │           │ impedance │
    │         ├───────────┤           │
    └─────────┘           └───────────┘

The important thing in this figure is that you need **two** electrical
contacts in order to close the circuit. The lower contact is often
provided by a common ground, but since your wristband is not properly
grounded, you will have to provide it by some other means.

My suggestion is to have two electrodes on the wristband: a lower
electrode in permanent contact with the user, and an upper electrode
that will be the touch button. If both electrodes are exposed metal,
then you have a full DC path all around, and this is not “capacitive”
sensing any more. Depending on how your sensing is done, this may not be
a problem, and it may be detected just like an infinite capacity.

If you want to avoid a full DC path, you can have one of the electrodes
covered by a thin layer of dielectric. Or even both, but then you have
two capacitors in series and need twice the sensitivity.


body:
Is there any way to store the values of necessary variables somewhere (may be in a file that gets updated by the program at various events), which can be read back when program starts after rebooting the Arduino board?

I am trying to control my AC appliances using IR remote control. Where I want Arduino to remember what was on and what was off in my room after a power failure.

Using EEPROM looks like a fairly good solution, though it has a limitation of 100,000 writes which is making me try to find another way out.

Using an external EEPROM which doesn't have that limitation or is fairly big, is a really good idea I got from fuenfundachtzig, thanks for this great idea. But I don't know how to implement this in my project. Any resource to gather knowledge on using external EEPROM, will be much appreciated.

title: How to remember variable values after rebooting an Arduino Uno R3 board?

Answers: 7

body:
Store them in the on-chip EEPROM.

* http://www.arduino.cc/en/Reference/EEPROM
* http://www.arduino.cc/en/Tutorial/EEPROMWrite
* http://www.arduino.cc/en/Tutorial/EEPROMRead

body:
The internal RAM of the Arduino will be reset when you repower the chip, so if you want to keep your data, you need to store it in EEPROM.

If you are worried about the limited write/erase cycles, you should estimate how often the data would be updated (i.e. written to EEPROM) and how long you plan the lifetime of the device you build. If 100,000 cycles then still is an issue, you have several options:

- Keep the variables in RAM and only write them to EEPROM say every 5 minutes (100,000 cycles then makes about one year of continuous usage until the EEPROM might fail).
- Use an external EEPROM (in a socket) that could be easily replaced if needed.
- If replacing it is not an option, consider using an [FRAM][1] instead (advantage vs EEPROM: *much* more erase/write cycles but also very expensive, so not an option for large amounts of data but certainly for a few variables).

Note, however, that your description sounds like a typical use-case for user settings that you don't want to get lost on reboot. For those the internal EEPROM is the right place: only store them when they're changed and you're golden -- the user won't change them a 100,000 times easily...

  [1]: http://en.wikipedia.org/wiki/Ferroelectric_RAM

body:
EEPROM space, as already mentioned, will work if non-volatile is required. However, you have not qualified if it needs to be non-volatile or not. If not then you can use an \__attribute\__ to define the variable space not to be initialized. As the SRAM on the ATmega's are not cleared by reset or power cycle. The Compiler defaults to initializing them. Where this can be turned off per variable as in the below example:

    //non-initialized value
    union configUnion{
      uint8_t    byte[6]; // match the below struct...
      struct {
        uint16_t value1;
        uint16_t value2;
        uint16_t chksum;
      } val ;
    } config  __attribute__ ((section (".noinit")));

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

      // prints title with ending line break
      Serial.print("Out of Reset -");
      sum = getchksum();
      printValues();

      if (sum != config.val.chksum) {
        config.val.chksum = sum;
        Serial.print("chksum is incorrect setting config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
      }

      config.val.value1++;
      config.val.value2++;
      Serial.print("setup new values - ");
      printValues();
      config.val.chksum = getchksum();
      Serial.print("updating chksum config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
    }

    int counter = 0;

    void loop() {
      if (counter < 200) {
        Serial.print("after a while - ");
        printValues();
        Serial.println();
        while (true) {
          continue;
        }
      }
      counter++;
    }

    void printValues() {
      Serial.print(" value1 = 0x"); Serial.print(config.val.value1, HEX);
      Serial.print(", value2 = 0x"); Serial.print(config.val.value2, HEX);
      Serial.print(", sum = 0x"); Serial.print(getchksum(), HEX);
      Serial.print(", chksum = 0x"); Serial.println(config.val.chksum, HEX);
    }

    uint16_t getchksum() {
      int sum = 0;
      for (int position = 0; position < (sizeof(config) - sizeof(config.val.chksum)); position++) {
        sum = sum + config.byte[position];
      }
      return sum;
    }

Output of above code is below. Note that the first output was the result of powering the UNO up with the Reset button depressed and then released after the Monitor window was started. Otherwise the "incorrect setting" print would have been missed, before the monitor window can be started.

    Out of Reset - value1 = 0xBFED, value2 = 0xD2F9, sum = 0x377, chksum = 0xF457
    chksum is incorrect setting config.val.chksum = 0x377
    setup new values -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x377
    updating chksum config.val.chksum = 0x379
    after a while -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379

    Out of Reset - value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379
    setup new values -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x379
    updating chksum config.val.chksum = 0x37B
    after a while -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B

    Out of Reset - value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B
    setup new values -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37B
    updating chksum config.val.chksum = 0x37D
    after a while -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37D

With this your variables will persist resets. As long as the power is not lost. Noting the above where you will get random data, to start.

Using either EEPROM or .noinit I would recommend that you checksum your persistent variable space during setup and if incorrect you can initialize or issue a warning.

body:
If you really need to update your NVRAM frequently, look into [FRAM (Ferroelectric Random Access Memory)][1] which claims a write life of 10^13 cycles (that's ~ 318,000 years if you write once/sec!). They're 8KB, and faster than Flash or EEPROM at 20MHz (SPI).

Adafruit (in the US) sells them on a breakout board for about US$6 in onesies. Or you can buy the bare chips from the usual suppliers for around US$1.30, but not DIP, only SOP8 packages.

  [1]: http://www.fujitsu.com/downloads/MICRO/fsa/pdf/products/memory/fram/MB85RS64V-DS501-00015-4v0-E.pdf

body: If you're open to a off-chip solution, it isn't too difficult to buy/build an SD card reader.

body:
I am very late to this party ... I just bought an UNO WiFi and I am looking at creating a simple protocol to persist data with a data store on another device connected to the WiFi. Probably will use HTTP with simple end points, treat the remote storage as a contiguous memory block:

    GET IP:port/addr/len
    PUT IP:port/addr data

I could also create named blocks (think files):

    GET IP:port/name
    PUT IP:port/name data

The actual remote storage could be anything, memory mapped disk file, SQLite3 database, etc.

There are many drawbacks, such as reliance on the external service, connectivity issues, error handling, etc. I could run out of code space just supporting the protocol.

body:
This was puzzling me too. I just wanted to use the onboard button to trigger a "count up an integer" regardless any setup routines. For me, mpflaga's answer gave me the right direction. But the given example was far too complicated for my needs. So here's the bare minimum example for an integer value that survives a reset, counting up. (But NOT a power loss, as it's in RAM!) Enjoy!

```
uint8_t c __attribute__ ((section (".noinit")));

void setup() {
  Serial.begin(9600);
  Serial.print("Just startet. c = ");
  Serial.print(c);
  if(c>7){c=0;}else{c++;}
  Serial.println(" - Waiting for RESET.");
}

void loop() {
  // Do more stuff.
}
```


body:
Does anyone have any information other than "coming soon" about the Tre?

Could the Tre be stuck in development hell?

Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

I'm just giddily awaiting its arrival, so I'm just wondering!

title: Arduino Tre, will it ever come out?

Answers: 1

body:
The latest news from Arduino that I can find is in their blog archive that the [second round of beta testing is out][1].

The mentioned this:

> When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the [Arduino LLC vs Arduino SLR][2] legal issue is also delaying the production.

Other than that, speculation is all that we know.

P.S: it's still spring until Sunday, June 21! :-)

  [1]: http://blog.arduino.cc/2014/12/12/arduino-tre-developer-edition-2nd-round-of-beta-testing/
  [2]: http://hackaday.com/2015/02/25/arduino-v-arduino/


body:
I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale.

Scale:
![Digital bathroom scale with 4 sensors][1]

HX711 amplifier:
![Amplifier][2]

I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale.
![Sensor wires][3]

Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what.
![Config][4]

The sensor is looking like this:
![enter image description here][5]

**I tried:**

 1. Two different libraries for this project both named HX711 (for this module)
 2. Changing A+ for A- on module

>     // Hx711.DOUT - pin #A1
>     // Hx711.SCK - pin #A0
>
>     #include "hx711.h"
>
>     Hx711 scale(A1, A0);
>
>     void setup() {
>
>       Serial.begin(9600);
>
>     }
>
>     void loop() {
>
>       Serial.print(scale.getGram(), 1);
>       Serial.println(" g");
>
>       delay(200);
>     }

with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.

**My questions are:**
How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?

  [1]: https://i.stack.imgur.com/Bxnr9.jpg
  [2]: https://i.stack.imgur.com/NppEm.jpg
  [3]: https://i.stack.imgur.com/04AzD.jpg
  [4]: https://i.stack.imgur.com/en6bG.jpg
  [5]: https://i.stack.imgur.com/EGMol.jpg

title: How to get weight data from glass electronic bathroom scale sensors?

Answers: 4

body:
1. The HX711 provides power to a bridge and amplifies the bridge's differential voltage.  The scale's original circuit board (which drives an LCD readout) also  provides power to a bridge.  You are unlikely to get any useful readings while both circuits are applying power to the bridge.

(You could cut the existing wires and attach connectors to allow changing back and forth between the original board and your Arduino circuit.)

2. Some scales like the one shown use a 9 V battery to run the electronics.  That voltage, if used, is likely to be incompatible with connecting an Arduino (typically powered by 3.3 V or 5 V) or an HX711 (powered with VDD in the range 2.7 V to 5.5 V) at the same time as the original board.

body:
Text mainly from my comments with some additions - with image added.

The sensors are quite possibly configured as in Fig1 in the data sheet.
 If so there should be +5 and 0V across two points, and weight signal between two others.

Use a DMM to Check for Vdd (probably 5V if pV battery, ~= 3V with Lithium battery). Find two leads to bridge with ~= Vdd on. Other two probably at Vdd/2 above ground. It is likely there are 4 wire effectively so each of the red wires on one side may be conncted tpo one on the other side - an Ohm-meter will tell you. Connect meter on LOW V range between other two and see if reading varies with weight change. Report back.

As jwpat7 says - you may need to repower sensors off HX711 supply to get correct readings.

HX711 looks nice. Under $1/module in modest volume on Alibaba and under $US/0.50 / IC in hundreds.

What Fig1? I know where is GND and VDD on HX711 module, and where goes the signal wires(A-,A+,B-,B+). That is clear. I dont know which colors of wires from sensors is GND VDD and Signal. I will do this. I will put back the power on the scale (3v from battery) and I will try to measure wires to determine what is what (i will put some load on the scale). I have a multimer so i will try to determine which wires are signal, and which wires are GND and VDD. I will report back. Tnx Russell. –

See fig  of [**HX711 Data sheet**](http://www.aviaic.com/uploadfile/hx711_brief_en.pdf) for larger view of this image.

![enter image description here][1]

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

body:
The sensor you have in your scale are a simple voltage dividers. Each consist of one resistor and one extensiometer, both connected in series. One wire (E+) is VDD another (E-) is GND and the third is divider output(S). You can not directly use it with HX711 which needs a bridge sensors not just dividers. You can try to set a 1/2vdd on S- and connect the signal from the sensor to S+. In case you get a negative weight, simply swap these connections. Your assumption that your scale uses full bridge, because it has four sensors, is completly wrong. You can read the signals  from the scale sensors using analog inputs in you arduino (without HX711) but you should amplify it before to get reasonable resolution. Good luck!
Greg

body:
Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711

If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245  or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

 [![three-wire 50kg load cell][2]][2]
... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture.  I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension.  In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant.  One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.

If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.

Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells.  With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.

To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires.  (This is the function of the soldered-together blues and blacks are in your scale.)  Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-.  Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A-  (Ignore B+/B- as a second, unused channel.)

Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds.  The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance.  Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown.   (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/GYEy2.png)

<!-- End schematic -->

Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.

With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low.  This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.

  [1]: https://i.stack.imgur.com/vS0Ff.png
  [2]: https://i.stack.imgur.com/PrHOR.jpg


body:
i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed.
If the output should be

    0

 it displays

    -
I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:

     #define HIGHX 0x0
     #define LOWX 0x1

but this is reversed and not a *good* solution...

The wiring is correct like this (just GND not connected):
![enter image description here][1]

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

But if i connect the GND, the hole display isn't showing something anymore.

title: HIGH and LOW reversed

Answers: 3

body:
reversing a boolean can be done using the `!` operator.
So doing something like `print(!true);` will print `false` (or 0, I'm not sure.)

And you make a wrapper or class to abstract this specific/odd behaviour.

Like:

"setLedPin(pinnr,state){digitalWrite(pinnr,!state)} //The pins are inverted, LOW is ON, HIGH is off, this piece inverts it."

You may even make a class for these segment displays and pass to your constructor if it's an inverted or "normal" one.
Or even make two classes that implement the same interface, but for such a small difference, that shouldn't be necessary.

body:
With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common *cathode*!)

It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:

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

    #define DISPLAY_SEGMENT_ON HIGH
    #define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a **common cathode** display, and the transistors are **NPN** types. If your displays are **common anode** then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be **PNP** types. Then you will indeed have inverted logic, and you should define:

    #define DISPLAY_SEGMENT_ON LOW
    #define DISPLAY_DIGIT_ON LOW

body:
If your display is a common anode type, the following will happen.

Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.

If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.

So the display is probably of the wrong type for your design.


body:
I have been trying OR conditional operator in a if condition statement in my arduino program and the result is not what I expected.

My program:

    // three variables assigned to const int datatype as the
    // pin numbers they are assigned to are  going to remain
    // constant through out the program.
    const int led1=10;
    const int led2=11;
    const int led3=12;

    void setup(){
      // assigning the pins as input/output.
      pinMode(10,INPUT);
      pinMode(11,INPUT);
      pinMode(12,OUTPUT);
    }

    void loop(){
      control();
    }

    void control()
    {
      int task1 = digitalRead(led1);
      int task2 = digitalRead(led2);
      if (task1==HIGH || task2==HIGH)
      {
        digitalWrite(led3,HIGH);
      }
      else
      {
        digitalWrite(led3,LOW);
      }
    }

if the 'IF' conditional statement used without 'OR' operator is working fine that is not including both the tasks instead only one task either task1 or task2, else it is working without errors but the result is not as expected.
hardware part is all fine. i reckon that there is a problem with the OR || operator.

title: Arduino OR operator

Answers: 2

body:
Your code is correct for what you described you want it to do - raise `led3` when either or both of `led1` or `led2` is high, and make it low otherwise. Some things to check:

 - Do the push-buttons pull their respective pins HIGH? (Pulling LOW is more common).
 - Are the pins pulled to ground with a 5K or 10K resistor, and not left floating, when the respective button is not active?
 - Real buttons need to be de-bounced. They behave as if their contacts bounce several times before making contact (even though that isn't really what happens). If this is an experiment and you hold the button down, even briefly, you should get proper results without de-bouncing, but it's something to be aware of as you move on.

body:
If you aren't getting the expected result, as JRobert suggested you should look at your hardware. Ensure pull-ups/downs are being used correctly, your interpretation of your hardware's logic is correct (positive/negative logic), and maybe even use a simple sketch to check that everything is working correctly. Firstly I would simplify the control function. You could try replacing the OR with a bitwise OR, or changing your variables to booleans. Realistically, more code and a diagram illustrating your implementation would help us reproduce and troubleshoot this with you. I'm a little confused as to whether pins 10 & 11 are LEDs or Buttons. I would be happy to help you get a test program together if you can provide more detail. :)

    void control()
    {
        boolean task1 = digitalRead(led1);
        boolean task2 = digitalRead(led2);

        // Note that the if isn't needed
        digitalWrite(led3, (task1 || task2));

        // If your buttons use negative logic
        // digitalWrite(led3, (!task1 || !task2));
    }

For humour-sake when I hit a problem that doesn't make sense, I rework my logic to break down the problem and output in stages, or use the Serial library to output what is going on periodically.

 - [Arduino Serial Reference][1]

 - [Arduino Serial Tutorial][2]

Typically for inputs and outputs I define a structure which buffers everything per IO, and write my code with a loop-based mentality, much like how a game loop is implemented in video games. It is easy to print and trace when troubleshooting, and the positive/negative/default-state logic is abstracted. This will help you get started if you are curious.

 - [Game Loop Example][3]

  [1]: http://www.arduino.cc/en/reference/serial
  [2]: http://www.ladyada.net/learn/arduino/lesson4.html
  [3]: http://rbwhitaker.wikidot.com/the-game-loop


body:
I'd like to use an Arduino Nano BLE to activate or deactivate an electric circuit.

I intend to use a relay to do so, but activating a relay seems to require a current with more intensity than what we can get out of a digital output (about 20 mA).

Is there a way to get more intensity out of a BLE nano ?

Are there others components that could behave the same way as a relay but could react from a digital output ?

title: Using Arduino BLE Nano to switch an electric circuit on and off

Answers: 0


body:
I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.

I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.

I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).

What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

title: Troubleshooting DC motor

Answers: 1

body:
If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.

9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.


body:
I'd like to print a bitmap on my TFT.

I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0

It is like the Adafruit_GFX library (only a little bit changed). Everything works.

With the tool Img2Code I converted my image into a bitmap.

    void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                                   const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

![screenshot][1]

How to include this code and print the bitmap on the tft?

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

title: How to draw a bitmap on a tft display?

Answers: 1

body:
As the function prototype you have show suggests, the data needs to be in a uint8_t array format.

    void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:

    const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
        0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
        .... etc ....
        0xff, 0xff, 0xff, 0xff, 0xff
    };

You then call the function with the needed parameters:

    tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


body:
I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.

I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.

I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a `getAngle()` function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.

**My questions:**

 - How can I implement this `getAngle()` function using a rotary encoder?

 - What is an example of a rotary encoder that is suitable for this application?

 - Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen [a few library's on Arduino Playground][1] that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this `getAngle()` function.

Thank you!

  [1]: http://playground.arduino.cc/Main/RotaryEncoders

title: How to read data from a rotary encoder with ATmega328

Answers: 4

body:
Your encoder choice will probably be driven by the mechanical requirements and the precision you need:

 - Runs occasionally, and briefly to 450 RPM or runs continuously, and often at the higher speeds?
 - Do you need position to e.g., within 3 degrees (7 bits)? Or 1/3 degrees (10 bits)? Or are you willing to count pulses from an index mark (this gets more complicated if the direction of rotation can change).

An n-bit encoder can probably be read whenever you need a position sample, so interrupts would probably not be necessary. With an index wheel (a pulse every x degrees, plus a separate pulse at 0 degrees, e.g.)
you would probably benefit from tracking the position at interrupt level and letting the main loop simply access the last known position.

Your `getAngle()` implementation depends totally on the choices you make above. If you use a [Gray-coded][1] encoder wheel, you'd need to convert the code to a binary fraction and multiply by 360 to get degrees. If you use an index wheel, `getAngle()` just reads the current pulse-count maintained by your interrupt routine and converts it to degrees. But you need an interrupt routine to count angle-pulses and reset the count on the index pulse (not especially hard to do).

Fixed-point arithmetic is pretty fast. Floating point takes longer. Depending on what else, besides position-keeping, your code needs to do, and how math-heavy it is, whether you can afford floating point. The floating point library will take more code space, too, but my guess is you'll be constrained by time more than by code-space.

  [1]: http://en.wikipedia.org/wiki/Gray_code

body:
There is no such thing as an encoder that "works well with Arduino" - encoders are encoders, and there are several basic types. As @JRobert said, you need to make an appropriate choice, and an encoder that will *mechanically* couple well with your drill motor is probably your primary criteria, and of course an encoder that can spin unrestricted (some are only for an angular range like 180 or 270 degrees); my guess is you'll want to put the encoder on the ungeared motor, rather than the geared output of whatever it is you're driving, to get good feedback from a cheap (i.e. relatively small number of 'pulses per rev') encoder.  Search on DigiKey, Mouser, online hobby stores, etc.  Then just deal with whatever type of encoder it is, hack its electrical interface into the Arduino:
http://www.digikey.com.au/product-search/en?pv69=848&FV=fff4001e,fff80033&k=encoder&mnonly=0&newproducts=0&ColumnSort=0&page=1&stock=1&quantity=0&ptm=0&fid=0&pageSize=25

This (2-signal quadrature) encoder library for Arduino is superb, by Paul Stoffregen @ pjrc.com:
https://www.pjrc.com/teensy/td_libs_Encoder.html
For best results you'll want the 2 'quadrature encoder' outputs to go into 2 interrupt inputs on the Arduino, and there are only 2 available.  There is an option to run this library on only 1 IRQ-capable input (the other can go into any input), or even no IRQ-capable pins, but performance will suffer.

Sampling at only 5/second isn't much - don't be afraid to increase that substantially - 10 to 50 / second.

You also might want a PID control algorithm, depending on what your actual aims are.  the "PIDLibrary" by Breatt Beauregard on the Arduino Playground website is excellent.

Coding your 'getAngle()' function shouldn't be hard - for a rotary quadrature encoder, X pulses from the encoder corresponds to 1 revolution.  The 'encoder library' you end up using may provider more than 1 pulse output per actual pulse output from the encoder.  Do that math. Simple.

body:
You are mixing two related ideas together.  Keeping track of encoders is best done with at least one interrupt in my experience. Whether or not you should use 2 or can get away with none depends on the speed of the shaft.  In my experience, RPMs generally encountered at the hobby level can be handled by 1.  So your interrupt code is interrupted by phase A rising or falling (Pin Change Interrupt).  At that point it read phase B, depending on the combination of A and B you are either going forwards (interrupt count+) or backwards (interrupt count-).  You know by specifications how many pulses you will have in a 360 degree rotation, and by modulo math, (e.g. x % 360) you will know how many degrees you are currently at.

The concept of sampling rate has to do with how often you read the current interrupt values, but they themselves will always be accurate and realtime.

Keywords to google volatile.  Also use signed long integers, not unsigned (don't ask how I know :| )

Not sure why the other answer suggested a PID, I didn't see anything in your question that would need it. For holding an angle you are more likely to use acceleration and deceleration, not PID.

Search [google][1], you might find a way to build your own encoders.

![enter image description here][2]

  [1]: https://www.google.com/search?q=optical quadrature encoder diy&tbm=isch
  [2]: https://i.stack.imgur.com/e7PUl.jpg

body:
You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.

Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.

Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.

This code goes at the start of your sketch, right before setup() function:

    const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
    volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.

Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.

    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    attachInterrupt(0, encoder_interrupt, CHANGE);
    attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.

    void encoder_interrupt() {
      static unsigned int oldEncoderState = 0;
      oldEncoderState <<= 2;
      oldEncoderState |= ((PIND >> 2) & 0x03);
      encCount += encoderDirections[(oldEncoderState & 0x0F)];
    }

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.

The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.

The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.

On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.

And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.

If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:

    const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.

    float getAngle() {
      long curCount = encCount;  // Store the current count.
      while(curCount < 0) {
        curCount += LINE_COUNT;
      }
      while(curCount >= LINE_COUNT) {
        curCount -= LINE_COUNT;
      }
      return (curCount / LINE_COUNT * 360.0);
    }

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.


body:
Adafruit has this wonderful product: http://www.adafruit.com/products/85

![enter image description here][1]

What are these actually called? I've looked all over the place in Mouser and DigiKey and can't find them (now, granted, it's impossible to find anything in DigiKey since they discontinued their printed catalog, but I'm digressing...)

They are great for putting other things that are on breakout boards on a tightly-packed breadboard and still be able to attach probes.

Also, sometimes, the board you are trying to attach is this:![TaylorEdge Smartnixie board][2]

As you can see, there is a dip switch blocking the 8-pin header. This is fine for its final resting place (on a board with a socket), but putting it on a breadboard is a bit of a pain. I have quite a few of those, so even though the aforementioned adafruit part is pretty cheap and I could get a bunch, I'd rather know what the real part is called so I can get the sizes I need.

PS: In case you are wondering, and you like old-style nixie tubes, that's http://www.tayloredge.com/storefront/SmartNixie/DataSheets/Datasheet_SmartNixie.pdf.)

  [1]: https://i.stack.imgur.com/caRKC.jpg
  [2]: https://i.stack.imgur.com/stwEE.jpg

title: Mouser/DigiKey part number for female "stacking" headers?

Answers: 5

body:
They're actually called "Wire-Wrap Headers" and they pre-date the Arduino probably by at least 50 years or so.

They used to be used to create circuits between chips and components by wrapping wire around the pins and routing it to other connectors:

![enter image description here][1]

They have since been adopted as stackable headers on boards like the Arduino shields.

Being such old technology not many people make them any more, though thanks to their popularity on things like the Arduino they are starting to appear more and more from normal electronics supply companies.

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

body: That DIP switch is also connected to the 4 address pins so you could cut the switch off, plug it into a proto board and then set the address by selectively grounding those pins.

body:
A [Digikey.com search for `samtec SSQ`](http://www.digikey.com/product-search/en/connectors-interconnects/rectangular-connectors-headers-receptacles-female-sockets/1442548?k= SSQ samtec) includes numerous longtail stackable headers (as well as some shorttail, or non-stackable).  However, looking at Digikey's prices suggests to me that [adafruit.com's price](http://www.adafruit.com/products/85) is a bargain unless you are purchasing thousands of pieces.

Also see [an arduino.cc thread](http://forum.arduino.cc/index.php?topic=23857.0) on this topic.

body:
If you are already ordering from Digi-Key, they do carry the [same set of stackable headers][1] from Adafruit.  It's just a bit hidden in an accessories family.  Otherwise it looks like Samtec is the only company Digikey carries that makes this style of connector.  Some dual-row long tail headers can be found using the term [stackthrough][2], but this is mostly used in conjunction with PC104 connectors.

  [1]: http://www.digikey.com/product-detail/en/85/1528-1074-ND/5154649
  [2]: http://www.digikey.com/product-search/en?keywords=STACKTHROUGH &stock=1

body: You can find stackable headers on eBay (ie. 141063314400 , 191576393028 , 271841707614). [Futurlec](http://www.futurlec.com.au/ConnHead.jsp) also sell them pretty cheap - about half-way down the page.


body:
The unsolved: when I connect power and signal lines to my Arduino - while power is on - I potentially kill it. I have fried 2 so far.

Situation:

- I have build an DMX-controlled lighting fixture, which consists of the fixture and a Controller Box.
- The fixture houses 2 Arduino's (5V), 2 steppers, 2 drives (36V), 2 fans (24V) and some temperature sensors.
- The controller box houses 1 Arduino, amongst other electronics.

The controller box receives DMX and does calculations an send controls via I2C to the fixture.

There is a 8 pole connector between fixture and controller box.

    1 - GND
    2 - 5v
    3 - 24v
    4 - 36v
    5 - CLK (i2c)
    6 - SDA (i2c)
    7 - signal line (used as charge pump)
    8 - reset

All wires are shielded(but the shield is only connected AFTER the initial pins make contact)

When the power on the controller box is ON and i connect the light Fixture with the 8-pole connector my arduino goes to heaven.

My own idea's so far:

1. Voltage spike, because the connection wires is grounded after it connects the pins.
2. Some strange flyback? via the Arduinos in the light fixture? I connected everything straight to the 5v pins, not using the regulator.
3. no idea

Any help on a way to search for the most likely cause of the problem would be greatly appreciated.

title: How to protect my arduino, while hotplugging its power supply and other related electronics

Answers: 2

body:
There's usually a number of scenarios that can cause hardware to go *poof* when you plug it in to a live system.  Most of them you have managed to identify, so I won't go into detail here.

Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.

There are two main critical things to consider when designing your system:

* Suppression

Invest in TVS diodes to suppress ESD.  All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression.  Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

* Connector

The connector itself is pretty critical.  Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order.  Normally you want your ground and shield to connect first.  Then your power supplies, and finally your IO pins.  Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.

If you can't use a proper hot-plug connector then there are ways you can simulate it internally.  You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through.  Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.

One other small trick is to ensure that all your IO lines have a series resistor in them.  This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware.  470Ω - 1KΩ are good values.

body: If you ever drive an I/O more than a diode drop above or below its power supply rails, the internal ESD protection structure will begin to conduct.  The internal structure is only there to keep the part alive during normal handling, i.e. in a factory but not for the situation described above.  If the current in this structure is allowed to go high enough, it looks like an SCR and "Latches" up.  When latch up occurs the device, like an SCR, will keep conducting as much current as the power supply rails are capable of until the current is removed and usually results in device destruction.  The way around this is to limit the current that may flow into a pin, and prevent current from forward biasing the ESD structure:  http://www.tayloredge.com/reference/Electronics/EMIESD/InputProtection.pdf


body:
I recently came across [this][1] nice `SerialPrint()` implementation:

    void StreamPrint_progmem(Print &out,PGM_P format,...)
    {
      // program memory version of printf - copy of format string and result share a buffer
      // so as to avoid too much memory use
      char formatString[128], *ptr;
      strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
      // null terminate - leave last char since we might need it in worst case for result's \0
      formatString[ sizeof(formatString)-2 ]='\0';
      ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
      va_list args;
      va_start (args,format);
      vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
      va_end (args);
      formatString[ sizeof(formatString)-1 ]='\0';
      out.print(ptr);
    }

    #define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
    #define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

I want to use it in my more complex projects to save precious RAM space.

This works really well when I have just one *.ino file where I'm using the SerialPrint() function.
When I try to use it in my more complext projects, which consist of a central *.ino files and several *.cpp/*.h files (mostly one cpp/h pair per class).
The problem is if I put the code below into the *.ino file, it will not be known inside any of the *.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.

Any ideas how to fix it?
I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).

Thanks in advance!-

  [1]: http://www.utopiamechanicus.com/article/low-memory-serial-print/

title: How to define function/macro so it is accesible throughout various cpp files

Answers: 1

body:
Have you thought of turning it into a small library?

libraries/StreamPrint/StreamPrint.cpp:

    #include <StreamPrint.h>

    void StreamPrint_progmem(Print &out,PGM_P format,...)
    {
      // program memory version of printf - copy of format string and result share a buffer
      // so as to avoid too much memory use
      char formatString[128], *ptr;
      strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
      // null terminate - leave last char since we might need it in worst case for result's \0
      formatString[ sizeof(formatString)-2 ]='\0';
      ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
      va_list args;
      va_start (args,format);
      vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
      va_end (args);
      formatString[ sizeof(formatString)-1 ]='\0';
      out.print(ptr);
    }

libraries/StreamPrint/StreamPrint.h:

    #include <Arduino.h>

    extern void StreamPrint_progmem(Print &out,PGM_P format,...);

    #define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
    #define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

Then in your code, wherever you want to use it:

    #include <StreamPrint.h>

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial


body: I am working on a project for my final in a first year programming course at my high school. I would like to make an Arduino based data logging device that I can bring with my on the mountain biking trails around where I live to create a map. I have found a lot of great sources online but I do not have a small budget. I have an Arduino Uno and a breadboard. My first question is whether it is easy to interface between an Uno and my phone for data logging, or if it would just be easier to buy a microSD card shield? And I need help finding a GPS unit. I have no preference and size is not really a problem. I just need to know how to interface with the Uno. Also if you have any links to other sources I can use that would be greatly appreciated!

title: Data Logging GPS with Arduino

Answers: 2

body:
first questions; is it easy? Very, do it all the time. But easy to me (30+ year programmer with some embedded experience) may not mean easy to you. Seek out a local make group or friend to help guide you if you are just starting out. I would look into a simple bluetooth adapter for the arduino, they are cheap, $5 in some places like [eBay][1]. Then find or write a phone app that log bluetooth.

second question;
Pick a GPS unit from SparkFun or somewhere like that.

If it is a serial unit it may need need some sort of FTDI adapter, which can sometimes be just a cable (and it might not need it, depends).  You really need to match the GPS with the appropriate way to hook it up and there are so many options I don't think someone will be able to cover them all. Depending on which arduino, you will use softSerial, since the hardware serial pins are probably being used by the bluetooth adapter. BTW, did this exact thing for a robot project not too long ago, work ok. I used XBees instead of bluetooth. If I did it again I would try Bluetooth as the XBee reliability wasnt very good.

Another type of connection is called I2C, and that would attach directly to Arduino UNO SDA/SCL (pins A4/A5 I think).

In both cases there are 3V and 5V devices and again you need to match things up on your own.

Now, to spoil your fun, you realize if you are carrying a phone and it is on, you are already being tracked and they are ways to view the history on the web?

In some cases it is easy to find (used to be called google tracks I think). Others are a little harder and I wont give out details, but I used to follow my ATV excursions on fire roads in the mountain all the time after I got back home.

[http://junkee.com/google-maps-has-been-tracking-your-every-move-and-theres-a-website-to-prove-it/39639][2]

Update:  gps (https://www.sparkfun.com/products/11571) -> softSerial on UNO -> tx/rx -> bluetooth (http://www.ebay.com/itm/New-Slave-UART-Wireless-Bluetooth-Transeiver-RF-Module-Serial-for-Arduino-AVR-/121643226124) -> phone logging app.

I picked that bluetooth because it claims it can do 3.3v-6v - the others I looked at said 3.3V but I bet they are all the same.  Technically, you probably do not even need the arduino in the middle, but said you wanted to learn.

  [1]: http://www.ebay.com/bhp/bluetooth-uart
  [2]: http://junkee.com/google-maps-has-been-tracking-your-every-move-and-theres-a-website-to-prove-it/39639

body:
I've been looking at the same problem, and there is a lot of new stuff now that may still count as a DIY project, but cut out a lot of the leg-work.

On kickstarter there are a lot of new boards that can make it easy:
Here is a ready to go GPS tracking band:
https://www.kickstarter.com/projects/blipperbands/blipper-bands-safety-wherever-you-go?ref=nav_search

Spark-IO has a board that gives you 20,000 messages per month, so you could use it instead of a cellphone to send out the data.
https://store.particle.io/?product=particle-electron

U-Blox makes gps higher-end consumer GPS units that are used in autonomous drones.
There are also a lot of instructables that show how to do the GPS datalogging with while building a drone. These would be small enough and light enough to use while cycling.


body:
I am sending data from an Arduino Uno to an Arduino Mega via serial communication.

The data is analog value. I'm getting that data and converting it to an int. There is no problem there. However, when I connect the servo to the attached pin, the serial communication on mega becomes disconnected. When I  remove the PWM pin, the serial communication is working again. Why does the servo stop serial communication?

Wiring: Mega-- 5v and gnd pins linked to servo ( 13kg/cm ), PWM 2 pin is linked to servo's pwm input, rx2 pin is linked to uno's tx pin

title: Servo - Serial communication problem

Answers: 2

body: If you are using delay function then I guess the problem is due to that. Just try once using millis function to generate PWM signal at Mega.

body: If you draw too much current from an Arduino microcontroller it can reset itself (brownout), that results in it not responding. To solve this do not power your servo directly from the Arduino, use an external power supply.


body: I am using arduino leonardo for moving mouse pointer with head tracking using MPU6050. It works fine in general. But as soon as I connect an external lcd screen to my laptop via hdmi cable, it stops transmitting. (that is the TX led goes off altogether and the mouse stops moving) I am not able to figure out what the issue is here Will using a teensy 3.0 instead of leonardo solve this problem?

title: arduino leonardo stops transmitting once hdmi cable is connected to a screen

Answers: 1

body:
The issue is that the mouse coordinates are being set by the display device that it's attached to.

The computer sends a descriptor about the display to the HID device ( the mouse ) the mouse then uses the information about the logical size of the screen to co-ordinate the movements.

For example, to move with `Mouse.move(100,100,0);` you are not actually moving by 100 pixels, but by 100/(127-((-127)).

The only option is can suggest is to STOP the mouse and Restart it again - this will be easier to restart calculations again.

Heres my Logic Function to convert Percentage to appropriate values for Mouse.move();
 `
int percentToLogic(int percent)
{
     return percent*254/100;
}
`


body:
I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.

**Problem**: My watch is getting wrong, this is set **2165/165/165 165:165:85**. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:

    //tempDate -> May 19 2015
    //tempHour -> 09:25:14
    rtc.adjust(DateTime(tempDate, tempHour));

Does anyone know the cause of this error?

    #include <Ethernet.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <RTClib.h>
    RTC_DS1307 rtc;

    byte server[] = { 192, 168, 0, 8 };
    byte ip[] = { 192, 168, 0, 237 };
    byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED };

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

    void loop() {
        getServerTime(getSiteData());
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(' ');
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();
        Serial.println();
        delay(5000);

    }

    char * getSiteData()
    {
        EthernetClient http;
        unsigned char startRead = 0, i = 0;
        char inString[50];

        if (http.connect(server, 80)) {
            http.println("GET /util/date.php HTTP/1.1");
            http.println("Host: ");
            http.println("Connection: close");
            http.println();

            while (http.connected()) {
                while (http.available()) {
                    char c = http.read();

                    if (c == '<' )
                        startRead = 1;

                    else if (startRead) {

                        if (c != '>') {
                            inString[i] = c;
                            i++;
                            inString[i] = '\0';
                        } else {
                            startRead = 0;
                            http.stop();
                            http.flush();
                            return inString;
                        }
                    }
                }
            }
            Serial.println(inString);
            http.stop();
            http.flush();
        }
        else
            Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel");
    }

    //May 19 2015-09:17:24
    void getServerTime(char* siteData)
    {
        char *tempDate, //May 19 2015
            *tempHour; //09:17:24

        tempDate = strtok(siteData, "-");
        tempHour =  strtok(NULL, "-");

        rtc.adjust(DateTime(tempDate, tempHour));

    }

title: Set dynamically hour - DS1307

Answers: 1

body:
The numbers you are reporting are very familiar to me.  They are telling me that it is not possible to obtain the time from the RTC chip.

You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine.  This snippet works perfecty:

    #include <RTClib.h>

    char siteData[] = "May 19 2015-09:17:24";

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

     char *tempDate = strtok(siteData, "-");
        char *tempHour =  strtok(NULL, "-");
     DateTime now(tempDate, tempHour);

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(' ');
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();
        Serial.println();
    }

    void loop() {
    }

So it must be in the passing of the data through the RTC chip that is failing.

Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.


body:
We have an arduino pro mini, we are trying to trying to upload sketch the controller but we are prohibited, as the arduino attempt to upload the sketch, it display an error of: not in sync.

We are pretty new in this are, so any help would be much appreciated.

Our setup is: -Breadboard -Connection to adapter: USB Serial. -Arduino Pro Mini as a controller

Through the Arduino Programming Client.

The processor and the port are setup op properly.

The strange thing is, it has worked sometimes these past days..

Much Thanks.

Mieer

title: Arduino stk500_getsync(): not in sync

Answers: 1

body: If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.


body:
I seem to be getting the right response on single LED but with multiple LEDS or a relay connected LED strip the voltage outputs seem to be insuffiecient.
What kind of analogWrite values does an LED respond to?

title: Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity?

Answers: 1

body:
Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin).

LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.

![relay arduino connection](https://i.stack.imgur.com/Oqukb.png)

If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a [MOSFET](http://bildr.org/2012/03/rfp30n06le-arduino/). It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.

![mosfet arduino connection](https://i.stack.imgur.com/SAKF3.png)


body:
The circuit contains a relay interfacing with 12v power supply and LED strip. Can the brightness for this strip of LEDs be controlled using the `analogWrite` command?
This works perfectly for a single LED, but when i replace the LED with a relayed LED strip with its own adapter, it doesnt produce any perceivable output

title: It is possible to control brightness of an LED strip (connected using a relay and having a seperate power supply ) using output from an arduino?

Answers: 2

body:
As Gerben said relays are only for on/off control. If you need to fade led you should use transistor.

 - `What kind of transistor?`

It depends on power consumption (how many LEDs).

 - `How to connect Arduino, LEDs, transistor?`

This is schematics how to connect the strip. As i assume resistors are already on the strip.

 ![enter image description here][1]

And little bit simpler image :)

![enter image description here][2]

  [1]: https://i.stack.imgur.com/ljDVH.png
  [2]: https://i.stack.imgur.com/C1dYD.png

body:
Yes!

In the simpler image replace R2 with a 10 Ohm resistor and Q1 with a N channel Logic Level FET.  This will allow  you to switch (PWM) amps with R1 removed.

My LED strips pull about 3 amps at 12V. Depending on the FET you use you may have to add a heat sink.  You will need to connect the low side (Ground) on the Arduino power supply to the low side on the power supply for the LED strip.  The Arduino can then operate at 5 volts and the LED at 24V or whatever depends on the rating of the MOSFET.  I would suggest using one of the PWM outputs, they will work fine with this circuit.  This works for motors but additional parts will need to be added.

Enjoy.


body:
I'm trying to simulate a certain µController to characterize and measure a certain chip.

I need to write my data on the negative edge of the master clock and read the data coming from the slave in the positive edge of the master clock. Is there any way I can have this kind of freedom in my code? Or do I have to do it manually without using the predefined SPI interface?

Also, I would like to have my master clock running continuously without going idle… is there a way to do that too?

title: Reading and Writing on different clock edges with Arduino SPI interface

Answers: 1

body:
To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).

[More info here][1]

  [1]: http://www.arduino.cc/en/Reference/SPI

To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.


body: i do have sketch from various people out there who have build nice code to do what i need done BUT not for my application and well they grant us permission to use and or modify their code so this is what i attempt to do with your help.

title: how to multi merge code

Answers: 1

body:
Unfortunately there is no easy way to do this. All you can hope to do if you see multiple sketches, which if combined would achieve your desired goal, is to splice the code into a single sketch (by copying and pasting), and hope that there are no conflicts resulting from the merging of the different sets of code.

For simple things like two sketches using the same pins, you may be able to fix that by changing which pins are used (unless they are special purpose pins such as PWM or hardware interrupts).

For harder to diagnose problems like two libraries not working if used the same sketch, that is almost impossible to resolve unless you know the hardware or library well enough. Best option there is to find another that does the same job, but differently.


body:
My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter?

TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.

title: Supplying near perfect DC signals from Arduino UNO

Answers: 2

body:
Would 0-4.095V in 1mV (or 0.5mV 0-2.047V) steps do for you?  Then why not use some [MCP4822](http://www.microchip.com/wwwproducts/Devices.aspx?product=MCP4822) SPI SAC chips?  You get 2 channels on each 8-pin chip (DIP chips are available, yes), and if you need a different voltage range you could always amplify it with a simple op-amp buffer.

So 6 ports would be 3 chips, which would entail using SCK, MOSI and three CS pins, so 5 pins in all.

body:
(1) A multipole active lowpass filter works wonders.
Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD & LT and NatSemi all have good free active filter design programs.

(2) A Simple sample & hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.

With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&H and update them occasionally top compensate for drift.  If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R  resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading.

If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept.