message:
Atmel STK500 and Atmel Studio

Is the [Atmel STK500][1] worth using as a AVR programmer and Dev board? I am starting to get to into AVR programming with Atmel studio. I plan on purchasing the [AVRDragon][2] and also looking into purchasing the Atmel STK500. This might be too broad of a question, but are their any benefits in using the Atmel STK500?

**Atmel STK500**

![Atmel STK500][3]

  [1]: http://store.atmel.com/PartDetail.aspx?q=p:10500070;c:100114#tc:description
  [2]: http://store.atmel.com/PartDetail.aspx?q=p:10500053;c:100112#tc:description
  [3]: https://i.stack.imgur.com/blQAZ.jpg

body:
Benefits of STK500? Sure:

- It has push buttons

- It has LEDs

- It has easy accessible connectors to any controller pin

Actually that's all. If you want/need to make use of this, buy both. Use the STK for "rapid prototyping" and the Dragon for debugging.

But if your budget allows it, have a look at the STK600 instead of 500. It's more expensive, but not so "old-fashioned", and it has much more features.


sender: user

message:
Newbie has difficulty compiling unedited svn Arduino code that should work

I'm having some trouble getting this arduino code to compile. It's not my project, but it should compile totally fine. Having never worked with the Arduino before, these errors are a bit intimidating, but I'll try to be specific enough for someone to get a guess. So...

I have this directory with these files: ![here][1] .

I found that the ArduCAM_OSD.ino has the loop and setup functions. When I try to compile the ino and solution I get these errors:

    In file included from ArduCam_Max7456.cpp:4:

    ArduCam_Max7456.h:78: error: expected class-name before '{' token

    ArduCam_Max7456.h:84: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:84: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:87: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:91: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:91: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:98: error: 'size_t' does not name a type

    ArduCam_Max7456.h:99: error: 'uint8_t' has not been declared

    ArduCam_Max7456.h:100: error: 'BetterStream' has not been declared

    ArduCam_Max7456.h:102: error: 'uint8_t' does not name a type

    ArduCam_Max7456.cpp: In member function 'void OSD::init()':

    ArduCam_Max7456.cpp:38: error: 'video_mode' was not declared in this scope

    ArduCam_Max7456.cpp: In member function 'void OSD::setMode(int)':

    ArduCam_Max7456.cpp:109: error: 'video_mode' was not declared in this scope

    ArduCam_Max7456.cpp:110: error: 'video_center' was not declared in this scope

    ArduCam_Max7456.cpp: In member function 'int OSD::getMode()':

    ArduCam_Max7456.cpp:123: error: 'video_mode' was not declared in this scope

    ArduCam_Max7456.cpp: In member function 'int OSD::getCenter()':

    ArduCam_Max7456.cpp:138: error: 'video_center' was not declared in this scope

    ArduCam_Max7456.cpp: At global scope:

    ArduCam_Max7456.cpp:162: error: prototype for 'void OSD::setPanel(uint8_t, uint8_t)' does
    not match any in class 'OSD'

    ArduCam_Max7456.h:84: error: candidate is: void OSD::setPanel(int, int)

    ArduCam_Max7456.cpp: In member function 'void OSD::openPanel()':

    ArduCam_Max7456.cpp:177: error: 'row' was not declared in this scope

    ArduCam_Max7456.cpp:177: error: 'col' was not declared in this scope

    ArduCam_Max7456.cpp: In member function 'void OSD::closePanel()':

    ArduCam_Max7456.cpp:206: error: 'row' was not declared in this scope

    ArduCam_Max7456.cpp: At global scope:

    ArduCam_Max7456.cpp:212: error: prototype for 'void OSD::openSingle(uint8_t, uint8_t)' does
    not match any in class 'OSD'

    ArduCam_Max7456.h:91: error: candidate is: void OSD::openSingle(int, int)

    ArduCam_Max7456.cpp:236: error: no 'size_t OSD::write(uint8_t)' member function declared in
    class 'OSD'

    ArduCam_Max7456.cpp:251: error: prototype for 'void OSD::control(uint8_t)' does not match
    any in class 'OSD'

    ArduCam_Max7456.h:87: error: candidate is: void OSD::control(int)

    ArduCam_Max7456.cpp:268: error: prototype for 'void OSD::write_NVM(int, uint8_t*)' does not
    match any in class 'OSD'

    ArduCam_Max7456.h:99: error: candidate is: void OSD::write_NVM(int, int*)

The most notable of these is the first error. Here's the class, in a header file, throwing the error:

    class OSD: public BetterStream
    {
      public:
        OSD(void);
        void init(void);
        void clear(void);
        void plug(void);
        void setPanel(uint8_t start_col, uint8_t start_row);
        void openPanel(void);
        void closePanel(void);
        void control(uint8_t ctrl);
        void detectMode(void);
        void setMode(int mode);
        void setBrightness();
        void openSingle(uint8_t x, uint8_t y);
        int getMode(void);
        int getCenter(void);
        virtual int     available(void);
        virtual int     read(void);
        virtual int     peek(void);
        virtual void    flush(void);
        virtual size_t write(uint8_t c);
        void write_NVM(int font_count, uint8_t *character_bitmap);
        using BetterStream::write;
      private:
        uint8_t start_col, start_row, col, row, video_mode, video_center;
    };

 Now, since I know confidently that this should compile, I'm convinced that I've made some
small syntactical error that can be fixed easily. In case anyone needs to see more of the files, you can access them all on the google code page [here][2]. Alternatively, please feel free to ask any questions.

  [1]: https://i.stack.imgur.com/qmhbv.png
  [2]: http://arducam-osd.googlecode.com/svn/trunk/ArduCAM_OSD/

sender: assistant

body:
It sounds like you are missing the libraries that the project was build for. BetterStream was part of the library system of the Ardu projects at diydrones.com

Normally for Ardu projects they use a modified version (their own) of the Arduino IDE but I don't know if the Arducam project works the same way.

I think you will find a better answer over in the support forum as [http://www.diydrones.com][1] which is where Arducam comes from.

Some of the source files look like they replace libraries so it might be that you just need a different core from diyd

  [1]: http://www.diydrones.com


message:
Arduino output pin from 5V to 3.3V

I just have a question regarding Arduino output-pins and Voltage divider, because I am getting other results than what my calculations are giving me.

I have measured the output-pin (from the Arduino) at 4.74V, according to my caulculations I will have and output voltage of 3.39V, with R1 = 4k ohm and R2 = 10k ohm, but when I use my multimeter to measure I read a voltage of 0.97V.

I have tested with a 9V battery, measured to 8.72V. With the same resistors, the calculations gives me 6.23V as output, when I use my multimeter I can read a output of 6.21 which I consider as ok.

So my question is, why is my output from the Arduino only 0.97V with the voltage divider?

For information: I am using Arduino OSEPP Uno R3 Plus.

Hope someone can give me helpfull information.

***************************************update********************************************

My code:

    int echoPin = 7;
    int trigPin = 6;

    int SignalPin = 10;

    void setup(){

      pinMode(echoPin, INPUT);
      pinMode(trigPin, OUTPUT);

    }

    void loop(){

      float distanceCentimeters;
      int pulseLenMicroseconds;

      digitalWrite(trigPin, LOW);
      delayMicroseconds(20);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(100);
      digitalWrite(trigPin, LOW);

      pulseLenMicroseconds = pulseIn(echoPin, HIGH);

      distanceCentimeters = pulseLenMicroseconds / 29.387 / 2;

      if(distanceCentimeters <= 35 && distanceCentimeters >= 10){

          digitalWrite(SignalPin, HIGH);

      } else {

          digitalWrite(SignalPin, LOW);

      }

      delay(400);

    }

Image of the setup (not with Raspberry Pi).

![enter image description here][1]

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

body:
Your code does not configured SignalPin as an output, but only trigPin.

As already explained in comments, your observed voltage is due not really to the voltage divider you constructed, but rather one formed by the "weak" internal pull-up resistance and your external resistors.  From your measurement, it appears the value of the weak internal pull-up is about 35K, which is within the range of expectations.  That and your 4K external form the top of the divider (39K) while your 10K forms the lower half, yielding about a fifth of the supply voltage.

In *some* versions of the Arduino library, writing to an input pin enables and disables the internal pull-up resistor, so you could have observed your program seeming to control the pin - but at minimal drive strength.

To get the desired behavior, you merely need to add

    pinMode(SignalPin, OUTPUT);


message:
Pixy(CMUcam5) robot Distance code

Can anyone help me with the code-ing to allow the robot to stop at a certain distance when the robot is approaching the tracked object. I am trying to implement it as a colour tracking wheel chair. For Example, the motorized wheelchair is able to track the colour of the shirt of the person infront is wearing and follow the person, and at the same time it is able to leave a distance between the person infront and the wheelchair to prevent collision.

the pixy robot : https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/overview

The code :https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code

Currently the code is only able to track the object till it reaches the object. But my objective is to let it chase the object, but at the same time, leaving a 1 metre distance
away from the object.

Please help me. Thank you

body:
Try to play with this one:

    int forwardSpeed = constrain(400 - (size/256), -100, 400);

By changing the value of 256 and 400, not at the same time though, you better use 2 potentiometer to change those values. That's a trial and error though, I hope this will give you an idea.


body:
Old question, but I'd simply use the angle of the Pixy tilt mechanism. If the camera is mounted low (on a wheelchair) and looking up (to see a t-shirt), the angle will be more "up" when the t-shirt is close.

    void loop()
    {
       if(tiltAngle < 45) // Angle in degrees
          moveWheelChairForward();
    }

However, if someone bends down, the tilt angle will go down, so the wheelchair will ram them! Thus, a proximity sensor is probably still going to be needed.


message:
Arduino GSM Shield not responding?

I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.

Would greatly appreciate it if someone can tell me where I could have gone wrong.

EDIT : I'm currently using the Arduino Mega. The shield I'm using is the [Arduino GSM Shield][1]. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see [Sending a SMS message][2]. Attached is what is shown on the monitor.

I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.

![Console output][3]

  [1]: http://arduino.cc/en/Main/ArduinoGSMShield
  [2]: https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9
  [3]: https://i.stack.imgur.com/euw7D.png

body:
This is an old post, but for future people:

The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.


message:
What is the use of ISP and ICSP in Arduino?

I am trying to connect gsm module with my arduino uno. confused about the use of isp and icsp

body:
ISP/ICSP has no role when utilizing a typical, properly functioning Arduino, as the program code compiled from sketches is instead downloaded via a bootloader (either serial, often behind an on-board USB-serial converter, or else directly USB).

The role of ISP in the Arduino ecosystem is mostly limited to:

- Loading a bootloader into new chips which do not have one, or have somehow lost theirs (note however that you can buy pre-loaded ATmega328's from many sources at a small premium)

- As an alternative program loading scheme when the tiny amount of program memory used by the bootloader must be re-claimed for a particularly large sketch

- Programing alternate targets to which the Arduino libraries have been partially ported, especially resource-constrained ones where the bootloader takes up a larger fraction of the total memory, such as the the ATtiny25/45/85

- Replacing or modifying the firmware of an on-board USB-serial micro such as the 16u2 on an Uno to perform a different function, such as emulate a keyboard or mouse.  However, this chip can also be programmed over its USB interface in DFU mode.

- Programming other non-Arduino devices used in a project (though these often have a different ISP scheme than the ATmega series).

But a typical project using purchased board(s) will involve none of these.

----------

SPI vs. ISP

As jfpoilpret points out, a very popular way of interfacing chips to a microcontroller is the Serial Peripheral Inteface, or SPI.  Like ISP, this is a synchronous (has a distinct clock line) serial interface with a master and a slave, a mode or enable pin, and a distinct data line in each direction.  Some Arduinos use MCUs like the ATmega328p which re-use their SPI pins for ISP (with the reset functioning as the mode pin).

In effect, ISP is a sort of special "SPI-like" interface mode for programming an ATmega - often using the master-mode SPI engine of the programer to do the actual transfers.  But "ISP" applies only when programming an ATmega - the more generic case of communicating with a peripheral would be "SPI".

It's my impression that most GSM modules use asynchronous serial interfaces (ie, utilizing a UART engine), but there may be some which use SPI or other synchronous schemes, at least as an option.


message:
Send Processing color data into Arduino

I am trying to send color() data from Processing to Arduino.

Here is my code from Processing:

    import processing.serial.*;
    Serial myPort;

    void setup(){
      myPort = new Serial(this, Serial.list()[7], 9600);
    }

    void draw(){
      color[] c1 = {color(99,0,0),color(255,0,0) };
      for (int i = 0; i < c1.length; i++ ){
        int value = int(red(c1[0]));
        myPort.write(value);
        println(value);
        delay(2000);
      }
    }

It sends the 99.0 data to Arduino. Here is the Arduino code for getting:

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

    void loop(){
      while(Serial.available() > 0){
        int recieved = Serial.read();
          Serial.print(recieved);
        }
    }

The problem is when Arduino receive data it doesn't take one by one. When i watch Arduino serial monitor, the data comes at different chunks like, 9...99...999..9.. etc.

I am trying to send several color info from Processing into arduino, it might be a long array of value. What is the best way to achieve this?

body:
The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.

There seems to be some inconsistencies in your question.

You wrote "It sends the 99.0 data to Arduino", which has a decimal point.

Yet the code is printing an `int` i.e.

    int value = int(red(c1[0]));
    myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:

    int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.

There are a few basic strategies to write data that can be easily read. Two popular ways are:

 - send fixed length messages, or prefix a message with the size of the
   data, and have a fixed format of data. For example, use a one byte
   count to say how many colours are being sent, then send three bytes,
   in the same order, for each colour
 - use non-data bytes to separate the data. For example use a ','
   between R, G or B and '\n' to mark the end of the data. To keep
   things simple, never use those values as data values. That is pretty
   much how programming languages work. It is much more complex to read
   than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.

Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.

Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.


body:
`int value = int(red(c1[0]));` gives you **99** not **99.0**

You could read a byte (that's what `Serial.read` returns; **not an int**), and make some decision based on that character, then read again.

Or, you could read all the available data till `'\n'` new line character comes. What `println(value);` line does it sends `99`+`'\n`

Code:

    // Buffer to store incoming commands from serial port
    String inData;

    void setup() {
        Serial.begin(9600);
        Serial.println("Waiting for Processing color...\n");
    }

    void loop() {
        while (Serial.available() > 0)
        {
            char recieved = Serial.read();
            inData += recieved;

            // Process message when new line character is recieved
            if (recieved == '\n')
            {
                Serial.print("Arduino Received: ");
                Serial.print(inData);

                inData = ""; // Clear recieved buffer
            }
        }
    }

In case this is not working change your processing code line:

`myPort.write(value);`

to

`myPort.println(value);`

or

    myPort.write(value);
    myPort.write('\n');


body:
You have to implement a serial protocol.

This can be either binary or ASCII. Binary has the advantage that the messages are short and well structured due to fixed parameter size. ASCII has advantage that you can type the messages into the serial monitor for debugging and typically data bytes are numerical ('0', '1' etc) while message bytes are text ('setcolour' etc) which means conflicting bytes do not have to be escaped.

To get started, try the [Messenger library][1]. Note that `#include "WProgram.h"` has to be changed to `#include "Arduino.h"` in the `.cpp` and `.h` files.

For the set colour message, if you used something like:

`setcolour,99,0,0,255,0,0\n`

You could use `Messenger` to parse it like:

Preamble:

    #include "Messenger.h"
    Messenger message = Messenger(','); //Message values separated by ','

In `setup()`:

    message.attach(messageCompleted);

In `loop()`:

    while(Serial.available()) {
        byte inbyte = Serial.read();
        message.process(inbyte);
    }

Then implement the callback function:

    void messageCompleted()
    {
        if (message.checkString("setcolour")) {
            colour1[0] = message.readInt();
            colour1[1] = message.readInt();
            colour1[2] = message.readInt();
            colour2[0] = message.readInt();
            colour2[1] = message.readInt();
            colour2[2] = message.readInt();
        }
    }

where `colour1` and `colour2` store the two RGB values.

  [1]: http://playground.arduino.cc/Code/Messenger


message:
Arduino mini requires uploading on every power up?

My Arduino mini is experiencing some really strange problem.

I'm using the BlinkWithoutDelay example sketch for testing:

    const int ledPin =  13;
    int ledState = LOW;             // ledState used to set the LED
    long previousMillis = 0;        // will store last time LED was updated
    long interval = 1000;           // interval at which to blink (milliseconds)

    void setup() {
        pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
        unsigned long currentMillis = millis();

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

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

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

The program basically turns pin 13 on and off every 1000ms.

When I uploaded this sketch into the mini (via Arduino Uno board, sans Atmega chip), the scope reading of pin 13 shows nice square waves (1s pulsewidth, 2s period), as expected.

I then unplug the USB cable powering the mini through the Uno board, wait for a few seconds for the scope traces to settle (I only have an old analog one at hand), and then plug it back in to turn on the board. However, the pin output is different - I now get a train of three pulses (60ms wide, 60ms between pulses) at sporadic intervals.

Uploading the sketch then yields the desired square waves again.

What is going on here? I'm fairly sure the mini has nonvolatile memory and it's intact (otherwise the bootloader through which I upload the sketch would not work).

body:
There was a defective bootloader that shipped on some Arduino devices which caused the symptom you describe. See:

http://forum.arduino.cc/index.php?topic=51172.0

http://forum.arduino.cc/index.php?topic=74090.0

If that's the case, your options are to re-write the bootloader yourself (if you have the capability) or return to the manufacturer.


message:
I want to be able to upload a batch of tweets to a twitter bot to be qued' for tweeting

I have built a twitter bot with my Arduino and an Ethernet shield
right now, the way to make it tweet something is to manually add a phase into the code and upload it to the board for each new tweet,

I would like to create a simple way of scrolling through a queue of phrases and tweeting each consecutive one after a given amount of time (several hours).
the issue I'm seeing is that, the code needs to rerun for each tweet, and I can't figure out what needs to be in what loop. Also the entire thing needs to delay for 3.6e^6(1 hour) milliseconds (the code takes delays in milliseconds) so that I don't spam the feed,
the twitter for this project is @ether_bot.

Code is below:

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

    /*
    void speech()
    {
      //this is where i would put the que of tweets
    }
    */

    // the next three lines connect the ethernet shield to the local network and establish a link with the twitter account
    byte ip[] = { 192,168,1,104 };
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEU }; //address for the shield
    Twitter twitter("2790106893-5ljE7WPyyGe16SqTMEm8CN5gpwDquhGnyjH2TCM");
    char msg[] = "hello again, im getting some major work done soon!"; // message to tweet

    void setup()
    {
      delay(30000);
      Ethernet.begin(mac, ip);  // makes the connection
      Serial.begin(9600); //opens a serial interface similar to the prnt window in bluejay
    }

    void loop()
    {
      Serial.println("connecting ...");

      if (twitter.post(msg))
      {
        int status = twitter.wait();

        if (status == 200)
        {
          Serial.println("OK.");
        }
        else
        {
          Serial.print("failed : code ");  //stuff happens here idk
          Serial.println(status);
        }
      }
      else
      {
        Serial.println("connection failed.");
      }

      do {} while(1);
    }

body:
First create an array of all the messages:

    #define NUM_MESSAGES 3
    const char *msg[NUM_MESSAGES] = {
        "This is the first message",
        "This is the second",
        "Third time lucky" };
    int msg_num = 0;

Then in the loop, switch between messages and add a delay

    void loop()
    {
      Serial.println("connecting ...");
      if (twitter.post(*msg[msg_num]))
      {
        int status = twitter.wait();
        if (status == 200)
        {
          Serial.println("OK.");
        }
        else
        {
          Serial.print("failed : code ");  //stuff happens here idk
          Serial.println(status);
        }
      }
      else
      {
        Serial.println("connection failed.");
      }

      //Next message
      msg_num++;
      if (msg_num >= NUM_MESSAGES) msg_num = 0;
      delay(1000*60*60);
    }


message:
Can I have backup power for an Arduino device?

I have an arduino project that will work while plugged into a generic outlet. But I want to connect a battery in case the power goes out. I know there are various power sources ([coin cell][1], [polymer lithium][2], [9V][3], etc.). But if I code my project to use the backup power if the main power goes down, would that mean the backup always has to be running? How would I go about this?

Thanks for the help! Every time you help me you save a kitten!!

  [1]: https://www.sparkfun.com/products/337
  [2]: https://www.sparkfun.com/products/8483
  [3]: https://www.sparkfun.com/products/10512

body:
You could set up a relay to work in reverse with the mains power.

Have your backup battery connected to the gate contacts of the relay, and then use the mains power running your project to open the relay and keep it open as long as there is power. If the mains turns off, then the relay closes and the battery is connected.

You might want to put something in line with the power to the Arduino to make sure you don't get any spikes when things switch.

I hope this helps as I love kittens


body:
I have been looking into this myself.  After getting some advice online I have come up with this circuit :

![Comparator][2]
http://everycircuit.com/circuit/5059191601364992

The top left power source is the mains supply and the bottom  left is the battery.

A voltage divider is connected to both that then feeds into an OPAMP comparator.  For illustrative purposes there is a switch at the top left you can toggle to see the circuit in action.

When the mains power gets cut off the op amp comparator sends a logic level signal through the diode and into the mosfet which enables the battery circuit.   the capacitor is there to keep power while the comparator makes the switch.

The link on every circuit is interactive, so feel free to have a play about with it.  The LED represents your Arduino.  The OpAmp is powered by the Positive and negative rails of thi diagram (impossible to draw on EveryCircuit)

Be sure to attach a voltage regulator to this circuit (at the input of the Arduino) so that the voltage doesn't change to your Arduino.

Here's where I researched about comparator OPAMPS ... [Setting up a comparator OpAmp circuit]
[3]

The LM358 is a good very cheap OPAMP for this circuit.   All parts well sourced will cost you about £1 (or less).

Or if your battery is rechargeable you can try this circuit :

![battery Backup Circuit 2][4]
http://everycircuit.com/circuit/5232232327282688

Again this is just for illustrative purposes.   You will need a 5V step-up converter to get 5v from a 3.7v battery.  Also the battery I am using has a builtin protection circuit, if yours doesn't it's important you include it in your schematic.

**Here's a video of it working for me with a 3.7V Li-Polymer Battery:**
https://www.youtube.com/watch?v=Sv2rjVqQg3U

  [2]: https://i.stack.imgur.com/CU9E5.png
  [3]: http://www.dummies.com/how-to/content/electronics-components-how-to-use-an-op-amp-as-a-v.html
  [4]: https://i.stack.imgur.com/fXiGI.png


body:
I suggest this "[Battery boost][1]" circuit from AdaFruit. It's designed to do exactly what you describe. An Arduino needs a smooth, steady 5 V supply with no "blips". The AdaFruit unit does just that, and charges the battery while on Mains supply.

  [1]: http://www.adafruit.com/products/1944


body: You could solve this very simply with some diodes or get creative with a bridge rectifier.  Connect both positive sources to the ac input one on each leg.  then the positive side of the bridge rectifier would be your positive source.  the grounds need to be all tied together


body:
You can use https://www.regaldreamtech.com/micro-ups/ for the backup 5V power supply to Arduino in absence of main power. It has 5000mAh battery and 5V 2A output. It will handle the switching on its on between main and battery power.

Disclosure: We manufacture this product.


message:
Cannot compile C++11 code via Makefile

I am building my Arduino project with a makefile:

    BOARD_TAG = uno
    ARDUINO_PORT = /dev/ttyACM0
    USER_LIB_PATH = /home/prakhar/dev/alfred/arduino/libraries
    CPPFLAGS=-x c++ -std=c++11 -Wall -DUNIX_ENVIRONMENT -DHAVE_NAMESPACES -DHAVE_STD
    include /usr/share/arduino/Arduino.mk

I keep getting this error:

    cc1plus: error: unrecognized command line option "-std=c++11"

I googled and [this][1] says that I need to update g++/gcc. I already have the newset versions:

    prakhar@sim74stic ~ $ avr-g++ --version
    avr-g++ (GCC) 4.9.1
    Copyright (C) 2014 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    prakhar@sim74stic ~ $ avr-gcc --version
    avr-gcc (GCC) 4.9.1
    Copyright (C) 2014 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    prakhar@sim74stic ~ $ g++ --version
    g++ (GCC) 4.9.1 20140903 (prerelease)
    Copyright (C) 2014 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I installed `arduino` from the `AUR` (packages `aur/arduino 1:1.0.6-1` and `aur/arduino-mk 1.3.4-2`).
Can anybody point out what I'm doing wrong?

  [1]: https://stackoverflow.com/questions/14674597/cc1plus-error-unrecognized-command-line-option-std-c11-with-g

body:
As I turns out, the `avr-gcc (GCC) 4.9.1` goodies weren't being used at all! The arduino package was using a decrepit version of gcc,

    prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ --version
    avr-g++ (GCC) 4.3.2
    Copyright (C) 2008 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-gcc --version
    avr-gcc (GCC) 4.3.2
    Copyright (C) 2008 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

**All I had to do was specify**:

    AVR_TOOLS_DIR = /usr

to exexute with `-std=c++11` flag (I also had to add an `-fpermissive` flag to compile `C` with `g++`).


message:
Setting data pin with NanodeUNIO

I'm using a sketch that helps to reset Da Vinci XYZPrinter cartridge EEPROMs, and it's based on the NanodeUNIO library. It uses digital pin 7 for data. I want to use my TFT Touch Shield to set the extruder temperature, but the shield also makes use for digital pin 7. Being that the sheild is wired to use pin 7, it can't be changed. But any pin that can be used as a digital pin should be useable with NanodeUNIO (at least, that is my assumption), but I can't find where in NanodeUNIO it sets the data pin. Where is that pin set, and how can it be changed?

body:
`xyz_dv_eprom.ino` uses low-level access rather than Arduino calls to manipulate PD7, most likely for speed reasons. Lines 96 through 104 (specifically 96, 97, 100, and 104) need to be modified in order to change both the port and the bit used.

ATmegaXX8 pin mapping
ATmegaXXX0 pin mapping
ATmegaXXU4 pin mapping


message:
Counting pulses with interrupt

I have been trying to count pulses from a 12,500 Hz square wave to trigger an output. Here's the code I have so far. When the Arduino is reset it prints 315 to the serial over a 25 ms sample. 315 x 40 = 12600. Which seems to me it's working perfectly.

My only problem is it only returns this number once upon reset of the board. Now if I move that same code down into `void loop`, it counts consecutively giving me inconstant returns.

I am not understanding what I need to put in the loop section so I can repeatedly and accurately count how many toggles of the input pin I am getting over a period of time so I can do something to the output based off the presence of the 12,500 Hz signal or not.

<!-- language: c++ -->

    volatile int IRQcount;
    int pin = 2;
    int pin_irq = 0; //IRQ that matches to pin 2

    void setup() {
       // Put your setup code here, to run once:
      Serial.begin (9600);
      attachInterrupt(pin_irq, IRQcounter, RISING);
      delay(25);
      detachInterrupt(pin);
      Serial.print(F("Counted = "));
      Serial.println(IRQcount);
    }

    void IRQcounter() {
      IRQcount++;
    }

    void loop() {
      // Put your main code here, to run repeatedly:
    }

Using the above code, every time I press the reset button I get one line in the serial window.

    Counted = 441
    Counted = 442
    Counted = 441
    Counted = 441
    Counted = 441

Now I want to get the same result, but repeating over and over. That way if the signal drops out I can trigger an output to turn off (LOW). When the signal is present the output will go high.

My attempt was to move the attach interrupt down into `void loop`, so it would repeat. Here's what it looks like.

<!-- language: c++ -->

    volatile int IRQcount;
    int pin = 2;
    int pin_irq = 0; //IRQ that matches to pin 2

    void setup() {
      // Put your setup code here, to run once:
      Serial.begin (9600);
    }

    void IRQcounter() {
       IRQcount++;
    }

    void loop() {
      // Put your main code here, to run repeatedly:

      attachInterrupt(pin_irq, IRQcounter, RISING);
      delay(25);
      detachInterrupt(pin);
      Serial.print(F("Counted = "));
      Serial.println(IRQcount);
    }

The return I get is self-updating, but the "count" instead of starting from 0 each time starts from the previous count. So it gets larger and larger. I am looking to return a constant value that represents my 12500 Hz signal so that, and only that, will trigger my output.

    Counted = 442
    Counted = 886
    Counted = 1330
    Counted = 177
    Counted = 2221
    Counted = 2667
    Counted = 3112
    Counted = 3557
    Counted = 4002
    Counted = 4448
    Counted = 4893
    Counted = 5338
    Counted = 5784
    Counted = 6229
    Counted = 6674
    Counted = 7120
    Counted = 7565
    Counted = 8010
    Counted = 8456
    Counted = 8901
    Counted = 9347
    Counted = 9792
    Counted = 10237
    Counted = 10683
    Counted = 11130
    Counted = 11576
    Counted = 12022
    Counted = 12469
    Counted = 12915
    Counted = 13361
    Counted = 13808
    Counted = 14254
    Counted = 14700
    Counted = 15147
    Counted = 15593
    Counted = 16040
    Counted = 16486
    Counted = 16932
    Counted = 17378
    Counted = 17825
    Counted = 18271
    Counted = 18717
    Counted = 19164
    Counted = 19610
    Counted = 20056
    Counted = 20503
    Counted = 20949
    Counted = 21395
    Counted = 21842
    Counted = 22288
    Counted = 22735
    Counted = 23169
    Counted = 23616
    Counted = 24062
    Counted = 24508
    Counted = 24955
    Counted = 25401
    Counted = 25730
    Counted = 25756
    Counted = 26200
    Counted = 26646
    Counted = 27093
    Counted = 27539
    Counted = 27985
    Counted = 28432
    Counted = 28878
    Counted = 29324
    Counted = 29770
    Counted = 30217
    Counted = 30663
    Counted = 31110
    Counted = 31556
    Counted = 32002
    Counted = 32449
    Counted = -32641
    Counted = -32195
    Counted = -31748
    Counted = -31302
    Counted = -30855
    Counted = -30408
    Counted = -29962
    Counted = -29515
    Counted = -29069
    Counted = -28622

body:
You need to reset IRQCount back to `0` before attaching the interrupt again. Otherwise it will just continue counting from where it stopped last time.

I would actually keep the interrupt attached and just reset the variable just before the delay. That way the overhead of attach/detachinterrupt doesn't get added to the 25ms delay.

    volatile int IRQcount;
    int pin = 2;
    int pin_irq = 0; //IRQ that matches to pin 2

    void setup() {
      // put your setup code here, to run once:
      Serial.begin (9600);
      attachInterrupt(pin_irq, IRQcounter, RISING);
    }

    void IRQcounter() {
      IRQcount++;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      IRQcount = 0;
      delay(25);
      int result = IRQcount;
      Serial.print(F("Counted = "));
      Serial.println(result);
    }

Since an int is 2 bytes an interrupt might occur in the middle of setting/reading those two bytes. This might result in an occasional wrong value. To prevent that you should disable interrupt while setting/reading the value

    volatile int IRQcount;
    int pin = 2;
    int pin_irq = 0; //IRQ that matches to pin 2

    void setup() {
      // put your setup code here, to run once:
      Serial.begin (9600);
      attachInterrupt(pin_irq, IRQcounter, RISING);
    }

    void IRQcounter() {
      IRQcount++;
    }

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

      cli();//disable interrupts
      IRQcount = 0;
      sei();//enable interrupts

      delay(25);

      cli();//disable interrupts
      int result = IRQcount;
      sei();//enable interrupts

      Serial.print(F("Counted = "));
      Serial.println(result);
    }


message:
Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P

I have posted this on the Arduino forum also, but I give it more chance if posted here also.

I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.

I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.

First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:

avrdude: Yikes! Invalid device signature
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51
I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.

I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?

I appriciate all the help I can get!

body:
This worked for me dude :)

See this:

http://www.instructables.com/id/Bootloading-ATmega328-with-Arduino-Mega2560/?ALLSTEPS


message:
Are all Arduino shields compatible with all Arduino boards?

Like is the Wi-Fi one compatible with the Arduino Nano & Micro as well as the Uno, etc., or do I need to be careful when buying shields that they'll be compatible with my board? Also, the shields just plug into the boards, don't they?

body:
For the most part, all the shields are compatible with all the boards that have a matching shield footprint. For example, the Uno, Leonardo, and the front half of the mega all have their header pins laid out in the standard arduino shield shape. If your board has this shield footprint, then all you have to do is plug the shield in on top and upload the right code to make it work.

The nano and micro have a different size and shape than a standard arduino, and so shields will not have a handy way of attaching to them. Since they do have standard arduino chips on them, they are technically compatible, but you would have to make your own wiring to attach them.


body:
When you want to choose a shield for your board you should check:

1- **Pin-out**, this one is the least concerning one , Most arduino boards are Shield pin-out compatible and you can verify it visually, for others, normally there are some converter boards (e.g for NANO), and in the worst case, building a converter board or wiring the shield to board is trivial in most situations.

2- **Shield operating voltage should match your board's**, most shields operate at 5V, 3.3V or both. Normally AVR-based boards (e.g. UNO, Mega, ...) operate at 5V and ARM based ones (e.g. Due, ...) operate at 3.3V, So we should choose the shield accordingly _(just keep in mind that most shield are designed with Arduino UNO in mind so it's more likely that your shields operate at 5V)_.

3- **Library**, Lots of Libraries for Arduino shields bypass Arduino library abstraction (mostly for performance reasons) and use hardware specific features (e.g directly write on specific ports), here is source of some incompatibilities between your board and the shield, for example there are handful of TFT LCD shields in the market which their library only supports UNO boards, in these cases you should either port it to your board's (based on micro-controller model and it's architecture, sometimes its as easy as changing some pin/port definitions and sometimes as hard as writing the library from scratch).


message:
What are the 5V and VIN pins for?

I believe I can supply the Arduino with power in three different ways:

 - Use USB. The design trusts the 5V to be regulated, and does not regulate it in any way.
 - Use a regulated power source, trusted to be 5V, and connect it to GND and 5V.
 - Connect an unregulated power source, eg a battery, to GND and VIN. This should be above 6.2V (since the dropout voltage is 1.2V) and preferably between 9V and 12V. There is a built-in regulator that will supply the Arduino with exactly 5V.

But can I use any of those pins to power other components. E.g. if the Arduino is powered with USB, can I use the 5V pin to power a diode? I thought I could, but the voltage is 4.70V, while the USB is 5.07V. The VIN is 4.26V btw.

Are the 5V and VIN only for powering the Arduino?

body: They can also be used to draw power from the barrel jack (Vin) or from USB or the on-board regulator (5V). The schematic of the board shows all exact power paths.


body:
No. You can draw power from the 5v and VIN pins on the arduino. VIN is the completely unaltered input power before the regulator (it will be useless if regulated 5v is supplied directly). Outputting power is what the 5v pin is intended to be used for, not as a power input.

From the [arduino website][1]:
> 5V. This pin outputs a regulated 5V from the regulator on the
> board. The board can be supplied with power either from the DC power
> jack (7 - 12V), the USB connector (5V), or the VIN pin of the board
> (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the
> regulator, and can damage your board. We don't advise it.

  [1]: http://arduino.cc/en/Main/arduinoBoardUno


body:
`5V` pin can be used to power up shields like Bluetooth, RFID, ultrasonic sensors etc..

`vin` pin is used to power up the Arduino. For example, when using shields such as L298 motor shield which is providing 5V output while operating from 12V.


body:
The MBR0520 Schotky Power Rectifier (Surface Mount
Schottky Power Rectifier) is connected in the Series path of 5v pin present on Nano which can handle maximum of 12V reverse voltage and according to datasheet 20v typical valur thus we can power ON arduino NANO using 5v pin also provided you supply proper 5v through any type of DC-DC Converter to it.
https://www.onsemi.com/pub/Collateral/MBR0520LT1-D.PDF
http://malylubo.sk/wp-content/uploads/2013/01/Arduino_Nano_Schematic-1024x676.png


message:
uBlox LEA 6H and UNO no data

While using NEO 6M and getting close-to-perfect accuracy, connecting the 3dr uBlox LEA 6H shows incoming characters, but gibberish data (at 38400) like it is connecting to a wrong baud rate (although it isn't, i've checked it with u-center and works when connected to Ardupilot).
So i guess it is some kind of configuration to show only certain parts of NMEA (if it is showing NMEA and not something else).

body:
Your uBlox LEA 6H is most likly configured to use the UBX binary protocol and not NMEA at all. This protocol, as well as how to switch your LEA 6H between NMEA and UBX is in this document, from the uBlox website:
http://www.u-blox.com/images/downloads/Product_Docs/u-blox6_ReceiverDescriptionProtocolSpec_(GPS.G6-SW-10018).pdf

You may be able to use the code from the ArduPilotMega project to communicate in UBX, they use the UBX protocol and the code is open source, but I can't guarantee its very good quality.


body:
You can configure the ublox lea6H GPS to read either through NMEA protocol or the UBX protocol. You just need to send some configuration messages. For good data rate it is better to use UBX protocol as it gives data in binary format inducing less delay.In case you need to test your device you can use my GPS code for arduino mega - customized ardupilot gps code  - UBX protocol.

https://github.com/ksskarthik/Team_Pushpak/blob/master/TP_GPS


message:
How to store gps values in EEPROM arduino?

I have two successfully working individual programs,
**1.GPS coordinate extract program.**
**2.EEPROM saving and reading program.**
now all I want to do is combine them both, whenever GPS location is updated ,I want to save that latitude data to EEPROM memory repalcing the previously saved data, but I guess my program is unable to save it,its just showing blank spaces when reading EEPROM,please help me guys..here is my code.

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    #define RXPin 8
    #define TXPin 9
    #define GPSBaud 9600
    #define ConsoleBaud 9600

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

    // The TinyGPS++ object
    TinyGPSPlus gps;
    #include <EEPROM.h>
    int address = 0;
    int read_value = 0;
    char data;
    void setup()
    {
      Serial.begin(ConsoleBaud);
      ss.begin(GPSBaud);
      Serial.println("Previous value stored :");
      for(address = 0; address < 25; address ++)        // read the entire EEPROM memory
      {
        read_value = EEPROM.read(address);
        Serial.write(read_value);
      }
      Serial.println("\n");

    }

    void loop()
    {

      while (ss.available() > 0)
        gps.encode(ss.read());

      if (gps.location.isUpdated() || gps.altitude.isUpdated())
      {
        Serial.print("Location: ");
        Serial.print(gps.location.lat(), 6);
        Serial.print(",");
        Serial.print(gps.location.lng(), 6);
        Serial.println("\n");

        data=(gps.location.lat(), 6);

        for(address = 0; address < 25;  )
        {
          EEPROM.write(address, data);
          address ++;
        }
      }
    }

body:
You might try using `sprintf`. First define a buffer:

    char data[25];

Then use `sprintf` to print to the buffer:

    sprintf(data, "Location: %.3f,%.3f\n", gps.location.lat(), gps.location.lon());

`%.3f` prints a float with 3 decimal places. Check out the [printf][1] reference for details.

Then write the buffer to EEPROM:

    for(address = 0; address < 25; address++ )
    {
      EEPROM.write(address, data);
    }

  [1]: http://www.cplusplus.com/reference/cstdio/printf/


body:
Consider TinyGPS++ over TinyGPS only if you are running on Due or processor which can take advantage of the higher precision of 64-bit “double” floating-point.

`char data;` should be `double data;`. You're wasting resources otherwise.

`data=(gps.location.lat(), 6);` isn't how you do it. You only need to specify precision when writing to `Serial`, like `Serial.print(gps.location.lat(), 6);`. Make it `data = gps.location.lat();`.

`address ++;` should be `address = address <=512-sizeof(address) ? (address + sizeof(data)): 0 ;`

`address <=512-sizeof(address)` ensures that the last value written to the `EEPROM` is written in it's entirety.

Alternatively, I would recommend [this][1] to save you data structure directly to `EEPROM`, and what @jfpoilpret mentions.

  [1]: http://playground.arduino.cc/Code/EEPROMWriteAnything


message:
Communication between Arduino and iOS device

How can I get weight that has been measured by an Arduino device to show up on an iOS mobile or tablet device as a number?

Thanks.

Warmly,
N.

body:
There are cables that let you plug in to the 30 pin connector and get a connection.

You could also use a BLE shield and write code for both platforms that communicate via BLE, or a WiFi shield.


body: There are a couple apps for this application but first you need the Arduino connected to the internet. It's called Iarduino and the instructables can be found [here]( http://www.instructables.com/id/Control-Arduino-Board-Wirelessly-With-iPhone-iPad/). I don't believe that you can communicate with your ios device with blue tooth. The app should allow for serial communication but I am not an expert on serial.


message:
Arduino function to fade from one RGB color to the next

For my Arduino project I have a [Neopixel RGB Strip][1] with 72 LED's.

I can successfully change the colour of any of the LED's (at the moment I'm only setting the first one 0 for testing purposes) so I know my wiring isn't the problem here, it's my coding.

What I would like to do is be able to select a color and then another color and have the first color fade to the next color and so forth (much like the LIFX bulbs behave when using the iPhone application).

This is what I have at the moment:

I am logging output of all the variables to give you an indication of what's going on. I'm not 100% sure on where I'm going wrong or whether there's a much easier way to do what I'm after (I'm open to suggestions).

The function takes a parameter called `command`, which is a string separated by commas:

e.g. `255, 0, 0` (RED) or `0, 255, 0` (GREEN).

    /*******************************************************************************
     * Function Name  : tinkerSetColour
     * Description    : Sets the strip with the appropriate colour
     * Input          : Pin and value
     * Output         : None.
     * Return         : 1 on success and a negative number on failure
     *******************************************************************************/
    int Rstart = 0, Gstart = 0, Bstart = 0;
    int Rnew = 0, Gnew = 0, Bnew = 0;

    int tinkerSetColour(String command)
    {
        sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
        Spark.publish("rgb", rgbString);

        sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
        Spark.publish("rgb", rgbString);

        // Clear strip.
        strip.show();

        int commaIndex = command.indexOf(',');
        int secondCommaIndex = command.indexOf(',', commaIndex+1);
        int lastCommaIndex = command.lastIndexOf(',');

        int red = command.substring(0, commaIndex).toInt();
        int grn = command.substring(commaIndex+1, secondCommaIndex).toInt();
        int blu = command.substring(lastCommaIndex+1).toInt();

        int Rend = red, Gend = grn, Bend = blu;

        sprintf(rgbString, "Rend %i, Gend %i, Bend %i", Rend, Gend, Bend);
        Spark.publish("rgb", rgbString);

        // Larger values of 'n' will give a smoother/slower transition.
        int n = 200;
        for (int i = 0; i < n; i++)
        {
            Rnew = Rstart + (Rend - Rstart) * i / n;
            Gnew = Gstart + (Gend - Gstart) * i / n;
            Bnew = Bstart + (Bend - Bstart) * i / n;

            // Set pixel color here.
            strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));
        }

        sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
        Spark.publish("rgb", rgbString);

        Rstart = red, Gstart = grn, Bstart = blu;

        sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
        Spark.publish("rgb", rgbString);

        return 1;
    }

The problem is the colors are not fading between themselves.

Apologies if any of this is confusing. I can provide more information if necessary.

Here's the **output** selecting **RED** to begin with:

    Rstart 0, Gstart 0, Bstart 0
    Rnew 0, Gnew 0, Bnew 0
    Rend 255, Gend 0, Bend 0
    Rnew 253, Gnew 0, Bnew 0

Here's the **output** selecting **GREEN** directly afterwards:

    Rstart 255, Gstart 0, Bstart 0
    Rnew 253, Gnew 0, Bnew 0
    Rend 0, Gend 255, Bend 0
    Rnew 2, Gnew 253, Bnew 0

And then the **output** selecting **BLUE** after that:

    Rstart 0, Gstart 255, Bstart 0
    Rnew 2, Gnew 253, Bnew 0
    Rend 0, Gend 23, Bend 255
    Rnew 0, Gnew 25, Bnew 253

  [1]: https://learn.adafruit.com/downloads/pdf/adafruit-neopixel-uberguide.pdf

body:
There is no delay in there. It will fade very quickly, add a delay e.g. 5ms with `n` = 200 for a 1 second fade:

    int n = 200;
    for (int i = 0; i < n; i++)
    {
        Rnew = Rstart + (Rend - Rstart) * i / n;
        Gnew = Gstart + (Gend - Gstart) * i / n;
        Bnew = Bstart + (Bend - Bstart) * i / n;

        // Set pixel color here.
        strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));

        delay(5);
    }

The other thing is your last value of `n` in the loop is 199, not 200, and thus `Rnew` etc don't have the correct final value. Change the comparison to be `<=` not `<`:

    for (int i = 0; i <= n; i++)


message:
What is the execution context of the function registered via the Wire.onReceive() method?

I'm basically wondering if it's OK to `Serial.write()` or print in the function I register to be called when I2C data is received.  I can't seem to find the execution context or any warnings.

http://arduino.cc/en/Reference/WireOnReceive

body:
Looking at `twi.c` in the Arduino libraries, it seems the callback function is called from within the I2C interrupt service routine (ISR). Any code in the call back will lengthen the ISR so it will have to be short. I don't think `Serial.write` will be too much of a problem; the TX interrupt will be delayed to the end of the I2C ISR which finishes straight after the callback and the `Serial.write` function is fairly short.

If you need to have a longer function run, you could instead have the callback store bytes in a ring buffer, then check for any available bytes in the main `loop()`.. but this is what the `Wire` class helps with already.


message:
Ruby and Arduino over Serial

I'm trying to send data over serial and pick it up in a ruby script. I'm using the serialport gem (https://rubygems.org/gems/serialport) as stated in the Arduino docs (http://playground.arduino.cc/Interfacing/Ruby).

My question is, I'm trying to print out some gyroscope data, particularly the x, y, and z. This is what my arduino sketch looks like:

    void setup() {
      Serial.begin(9600);
      // ... do some gyro stuff here
    }

    void loop() {
      gyro.read();

      Serial.print((int)gyro.g.x);
      Serial.print(" ");
      Serial.print((int)gyro.g.y);
      Serial.print(" ");
      Serial.print((int)gyro.g.z);

      delay(500);
    }

My ruby script is pretty straight forward as well:

    require "serialport"
    port_str = "/dev/tty.usbmodemfa141"
    baud_rate = 9600
    data_bits = 8
    stop_bits = 1
    parity = SerialPort::NONE

    sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
    while true do
      message = sp.gets
      if message
        message.chomp!

        puts message
      end
    end

However, the output that I get is choppy. What I mean by that is that the numbers don't come out as a single line as I intend:

    52 9
    5
    250
     -28
     85
    25
    9 -5
    1 69

Even if I replace it with "Hello World", it'll come out as:

    He
    llo
    Wor
    ld

or similar.

Any ideas why? Thanks in advance for any help.

body:
Yes Arduino code is fine although your should use println() as a terminator.

I think you should read the message into a tmpMessage var. If tmpMessage is empty then break out the loop otherwise concatenate tmpMessage into the message var.

Then print the message var after the loop when no more data arrives.

It must be ruby inserting the line breaks when you use puts


body:
Firstly, let's look into documentation for [Ruby IO#gets][1]:

> Reads the next "line" from the I/O stream; lines are separated by sep ...

Secondly, look into documentation for [Arduino Serial.print][2]:

> Prints data to the serial port as human-readable ASCII text ...

Finally, you don't print new line char `\n` in your "arduino sketch" above.

I recommend you to use `Serial.println` in the last line from your sketch:

    void setup() {
      Serial.begin(9600);
      // ... do some gyro stuff here
    }

    void loop() {
      gyro.read();

      Serial.print((int)gyro.g.x);
      Serial.print(" ");
      Serial.print((int)gyro.g.y);
      Serial.print(" ");
      Serial.println((int)gyro.g.z);

      delay(500);
    }

  [1]: http://www.rubydoc.info/stdlib/core/IO:gets
  [2]: http://arduino.cc/en/Serial/Print
  [3]: http://arduino.cc/en/Serial/Println


message:
Are there any reasons to pick Nano over Micro?

Nano is from 2008, and micro from 2012. Micro seems better on every parameter, in particular in having a better (I think) microcontroller, ATMega32u4, over ATMega328P.

However, all the shops I've checked out, both local and online, sell the Nano, and only some sell Micro. And Nano is always more expensive than Micro. E.g. at RS-Online 26GBP for Nano ([link][1]) and 16GBP for Micro ([link][2]).

Why do many shops only sell the inferior product?

Why is the older and less capable Nano more expensive?

Why would anyone buy the Nano over the Micro?

  [1]: http://uk.rs-online.com/web/p/processor-microcontroller-development-kits/6961667/
  [2]: http://uk.rs-online.com/web/p/processor-microcontroller-development-kits/7717667/

body:
It depends on what's your focus on. From pure microcontroller view, the 328P compared to the 32u4

- is 4MHz faster
- has two Touch Channels more
- has picoPower technology
- has an RTC
- has a lower minimum supply voltage

If one or more of these features are essential for your project, the Nano may be the better choice.

Regarding the price:

I'm not sure if it can have such a high influence, but there may have been a technology shrink. That's why a modern 32bit micro is cheaper than an old-fashioned 8 or 16bit micro, at least in B2B pricing.


body:
The main difference between the ATmega32u4 and the ATmega328P is that the 32u4 has onboard USB. When ATmega328P are used in an Arduino they are often coupled with an FTDI USB to serial chip. The FTDI chip is about $5 so this may be where the extra cost comes in.

Having the USB chip separate is actually not a bad thing:

 - The Atmega328P consumes less power than the ATmega32u4
 - FTDI chips are common, so the drivers are on most computers, whereas the 32u4 requires an .inf file to be loaded on Windows.
 - The FTDI chip uses the FTDI vendor and product ID and thus can be used in large-quantity commercial projects whereas the ATmega32u4 would require purchase of a vendor id and product id from the USB group. (My conclusion after reading around the net a bit, please correct if wrong).


body:
I'd buy the NANO and STEER CLEAR of the micro with that 32u4 chip. The good ol' 328p chip also has a FTDI chip to handle USB to serial while the other chip handles it on its own. The problem is that the Micro's bootloader ONLY allows trying to program it with USB and requires a special driver. With Linux, only a few select versions have the needed driver. If your Linux version doesn't have the driver, you're out of luck. In that case, take it back or donate it to a hackerspace. You will NEVER make it work.

I was at the arduino.cc site about this and tried everything only to get increasingly annoyed about that lemon of a card. You know it's time to give up when you get flamed.


message:
Arduino: How does digitalRead read a value? And what is this value?

I have a Arduino Uno with 14 digital pins. I believe they have an output of 5V.
But they can also *input* values. I'm not sure of what exactly it reads when it does that (amperage, voltage ...). Also, *how* do they read it? How can such a tiny thing possibly know what it's receiving?

Just to provide a little more context to the reading part of this question, here's an example circuit. I have a 5V battery connected to an LED and a 220 Ohm resistor. Next thing in the circuit is a wire, which exits the main circuit and connects to a digital pin on the Arduino Uno (here it reads the value). Then the main circuit closes by connecting to ground.

Hope my question is clear enough :)

body:
**It measures voltage**.

The input circuit is conceptually similar to this:

![CMOS input][1]

 - Voltages close to 5V will turn the lower transistor on and the upper one off.
 - Voltages close to 0V will turn the upper one on and the lower one off.
 - Voltages in the middle will turn both on to some extent, which is not recommended, and may be read as either 0 or 1 with a threshold in the middle.

"Such a tiny thing" contains tens or hundreds of thousands of transistors.

  [1]: https://i.stack.imgur.com/TUJaw.gif


body:
Modern digital electronics is made from many tiny electronic components called MOSFETs (a type of transistor). They can be switched on and off using a voltage, and a very small amount of current. They use the majority of the power when they are switching on and off; the rest of the time they use virtually no power. It this very low-power capability which allows us to make complex digital electronics.

Electronically, a MOSFET looks like a tiny capacitor, which triggers a very low-power switch, on and off. Once there is charge on the MOSFETs capacitor, the switch will stay on or off.

A modern large-scale processor, for example the type of device Intel makes, contains billions of MOSFETs, but requires less than 100W, and switches billions of times/second. So we can be confident that a MOSFET can be switched using much less than 1/10,000,000W. At 5V, that means 1/50,000,000A, or 0.000,000,02A, i.e. 0.02µA.

So, the input circuit, connected to an Arduino's pin has some protection, to protect the MOSFETs from static electricity (which could damage or destroy the capacitor), then a complementary pair of MOSFETs (called N-Chanel and P-Chanel). The input voltage switches one on, and the other off. It typically requires less than a micro-amp of current, but at a voltage close to ground or 5V. See pjc50's diagram.

So an Arduino input pin, connected to the 5V end of the resistor and LED will take a tiny amount of current, for a short time, to switch on.

If that pin is connected between the LED and resistor, at some voltage less than 5V, but more than 0V, then it might not switch fully. It might not give a reliable value of digital 0 or digital 1, and might switch high and low rapidly influenced by electrical noise in the environment.


body:
If somebody(like me) is looking for a explanation in terms of registers, the voltage at a pin when it's a digital input can be accessed with the `PINx` register, with a bit being used per a pin. Based on the value in the specific bit of the `DDRx` register, if it's `0` (an input), the voltage at the pin is represented by the bit in the `PINx`. When it's `1` (an output), the bit at the `PINx` register will be the value in the `PORTx` register for the specific bit(the value written). If the bit in the `DDRx` register for the pin is `0`(an input), the bit in the `PORTx` register represents whether the internal pull-up resistor should be connected to the pin. `x` is used to mark the port (`A`,`B`, for example).

Edit: I've started working with the ATtiny10 for a specific, but most likely just-on-paper project. It has the separate `PUEx` register for the internal pull-ups. It has only 6 pins, with 4 or those being accessible as GPIOs. The pins have specific modes where every pin requires slightly different flag changes for changing the mode.


message:
Arduino Due SD Card

I have an Arduino Due and want to save data to an SD card. For this I use a 3.2 'display of ITead with integrated SD slot (http://imall.iteadstudio.com/im120419006.html). This I connected to the Arduino.

However, the Arduino doesn’t detect the SD card (I've tried two different cards and also reformatted both). I wired the three SD ports correctly to the SPI. I wired the CS output on to pin 4, 10 or 52 (each one once tested), without success. I have also tried using ICSP instead of SPI, which the Arduino website suggests. Again, without success.

The test program I used is a  test program on the Arduino website for SD cards (the program in the end of the post, changes marked in bold). Is the problem in the program code or is it a hardware problem? If it is a software problem, could you send me a test program that is designed for Arduino Due?

I have invested several hours and read tens of forums but found nothing comparable. Also, the proposed solutions never worked.

<!-- language: c -->

    /*
      SD card test

     This example shows how use the utility libraries on which the'
    SD library is based in order to get info about your SD card.
    Very useful for testing a card when you're not sure whether its working or not.

     The circuit:
      * SD card attached to SPI bus as follows:
    ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
    ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
    ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
    ** CS - depends on your SD card shield or module.
            Pin 4 used here for consistency with other Arduino examples

     created  28 Mar 2011
    by Limor Fried
     modified 9 Apr 2012
    by Tom Igoe
    */
    // include the SD library:
    #include <SD.h>
    **#include <SPI.h>**

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    const int chipSelect = **10**;

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

      Serial.print("\nInitializing SD card...");
      // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
      // Note that even if it's not used as the CS pin, the hardware SS pin
      // (10 on most Arduino boards, 53 on the Mega) must be left as an output
      // or the SD library functions will not work.
      pinMode(**chipSelect**, OUTPUT);     // change this to 53 on a mega
      **SPI.begin(chipSelect); //habe ich eingeführt, da es in einigen Foren erwähnt wird, funktioniert jedoch mit und ohne nicht. //I made this, becaus it’s mentioned in severals forums, but it didn’t workt wiht it and whitout it**     // change this to 53 on a mega

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card is inserted?");
        Serial.println("* Is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
       Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch(card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }
      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster(); // clusters are collections of blocks
      volumesize *= volume.clusterCount(); // we'll have a lot of clusters
      volumesize *= 512; // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      root.openRoot(volume);
      // list all files in the card with date and size
      root.ls(LS_R | LS_DATE | LS_SIZE);
    }

    void loop(void) {
    }

body:
I use SD card with Arduino UNO. I connected SD card to the Arduino and I saw the Arduino don’t detect the SD card. Then  I see [this tutorial][1] and Arduino detect the SD card now.
Don't connect the SD card breakout board to Arduino and use non-inverting hex buffer(4050).

  [1]: http://www.instructables.com/id/Arduino-DIY-SD-Card-Logging-Shield/?ALLSTEPS


body:
Thank you very much. I solved part of the problem. I tried it whit a new SD Card. When I use pin 52, I am able to read the card information with the program above. But only if I use SPI.

Pin 10 doesn't work at all and Pin 4 a bit. If I work with Pin 4, it accepts the card, but it can't find out what format the SD card has. This is kind of weird, I think, because Arduino say alls three pins should work (http://arduino.cc/en/Reference/SPI). Does anybody knows something about this?


message:
Problems with substring loop

Hey folks … I was hoping some of you might cast your eye over my code.

It splits up a string read from EEprom into an array of separate strings. Based on String length information stored in a separate array. (tempArray[])

It reads fine … and also seems to process fine (ie. it does turn one long string into separate array items)      for some reason it stops working no the 8th array item?

The splitting code (problem) starts on line 80 and i have included the output above it in comments.

http://pastebin.com/Ax4R6t6J   << Full code also available here.

    void reJigFromMemory(){

      Serial.print("Eeprom read 1 :");
      Serial.println(eepromReadOne);
      Serial.print("EEprom read 2 :");
      Serial.println(eepromReadTwo);
      String tempArray[10];

      int charLength=eepromReadOne.length()+1;
      char charBuff[charLength];
      eepromReadOne.toCharArray(charBuff, charLength);

      //// GET MEMORY LOCATIONS
      /*
    converts long string of numbers:
       13161717171717252533
       into separate strings:
       13
       16
       17
       17
       17
       17
       17
       25
       25
       33

       And stores them in an array.
       */
      for (int i = 0; i <10 ; i++){
        tempArray[i]+=charBuff[i*2];
        tempArray[i]+=charBuff[(i*2)+1];
        Serial.print("I just translated :");
        Serial.println(tempArray[i]);
      }
      /// GET THE STRINGS USING THE ABOVE ARRAYS
      /*
    converts long list of data ie:
       |0|Bingo#999#|1|Retest2#9222#|2|Retest3#92299#|3|Retest4#99339#|4|Retest5#95599#|5|Retest6#96699#|6|Retest7#99119#|7|User Defined eighth#0#|8|User Defined ninth #0#|9|User Defined tenth (last) .#0#

       into individual array strings:

       From Number = :0
       To number : 13
       Record 0 :          |0|Bingo#999#
       From Number = :13
       To number : 29
       Record 1 :          |1|Retest2#9222#
       From Number = :29
       To number : 46
       Record 2 :          |2|Retest3#92299#
       From Number = :46
       To number : 63
       Record 3:           |3|Retest4#99339#
       From Number = :63
       To number : 80
       Record 4:           |4|Retest5#95599#
       From Number = :80
       To number : 97
       Record 5:           |5|Retest6#96699#
       From Number = :97
       To number : 114
       Record 6 :          |6|Retest7#99119#
       From Number = :114
       To number : 139
       Record 7 :               <<<<<< THIS ONE IS MISSING ? WHY?
       From Number = :139
       To number : 164
       Record 8 :               <<<<<< THIS ONE IS MISSING ? WHY?
       From Number = :164
       To number : 197
       Record 9 :               <<<<<< THIS ONE IS MISSING ? WHY?

       */
      String tempArray2[10];
      int fromLocation = 0;
      int toLocation=0;

      for (int i = 0; i <10 ; i++){                 /////// LINE 80

        toLocation += tempArray[i].toInt();

        fromLocation += tempArray[i-1].toInt();
        tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
        Serial.print("From Number = :");
        Serial.println(fromLocation);
        Serial.print("To number : ");
        Serial.println(toLocation);
        Serial.print("I just translated :");
        Serial.println(tempArray2[i]);

      }
    }

body:
Your 2nd for loop should look something like this:

    int fromLocation = 0;
    int toLocation=0;

    for (int i = 0; i <10 ; i++)
    {                 /////// LINE 80

        toLocation += tempArray[i].toInt();

        tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
        Serial.print("From Number = :");
        Serial.println(fromLocation);
        Serial.print("To number : ");
        Serial.println(toLocation);
        Serial.print("I just translated :");
        Serial.println(tempArray2[i]);
        fromLocation += tempArray[i].toInt();
      }
    }

On the first pass through the loop, fromLocation is 0. toLocation starts at 0 and gets the value in tempArray2[0] added to it.

After extracting a string, you add the current array value to fromLocation to advance the pointer to the beginning of the next string.

Note that String objects are very inefficient way to save 2 digit numbers. It would be better use an array of ints, and write code that extracts 2 characters at a time into int values.

With only 20 String objects it's not a huge deal, but bear in mind that String objects take a lot of memory overhead on a memory-starved platform like an Arduino. Better to learn how to use C strings.