body:
The `float` type has slightly over 7 digits of precision. See <https://en.wikipedia.org/wiki/Floating_point>.

>I want x to be:
>
>        x = 31.5468112;

Bad luck. That's 9 digits of precision. You can get around 7 digits by converting it appropriately, eg. as Majenko said:

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

      float x = 3154681.124 / 100000; //x = 31.54;
      Serial.println(x, 7);

However that printed:

    31.5468101

It got 7 digits right, as advertised.

---

You can use the [BigNumber Library](http://www.gammon.com.au/forum/?id=11519) that I wrote. Available from [GitHub](https://github.com/nickgammon/BigNumber).

Using that, you can get all the precision you want, within reason:

    #include "BigNumber.h"

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

      BigNumber::begin (7);  // 7 digits after the decimal place

      BigNumber x ("3154681.124");
      BigNumber y = x / BigNumber ("100000");

      Serial.println(y);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output:

    31.5468112


sender: user

message:
Wifi101 ad-hoc network

I've reviewed the WiFi101 library but have found no way to make the 101 an ad-hoc network.  Am I missing something?  I'd like to be able to emulate the RedFly example:
http://notebook.kulchenko.com/embedded/storing-wifi-configuration-in-eeprom-on-arduino

Can the 101 become an ad-hoc network?  I understand the security problem with the ad-hoc capability so it would make sense that Arduino prohibits it.

sender: assistant

body:
Apparently you can have an ad-hoc network, you can see the example on the github here:
https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino

It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".


message:
Switching Many Switches with one Input

I have a situation where I need to select between two signals, lets say 1A or 2B and route it to output 3C. I need to do this six times (2A or 2B to output 2C, 3A or 3B to output 3C, etc.).

These all need to switch based on one output from my chip.

What sort of component do I need for this? I think it's something like a 2:1 spdt multiplexer, but something doesn't seem quite right.

I've been looking at a bunch of data sheets and I cannot seem to find a chip which switches many 2:1 switches based on ONE input. Does such a thing exists? Or am I just way of the mark here? Not sure.

Any help appreciated.

Thanks.

body:
Almost, you will need two [74157][1] (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.

[![enter image description here][2]][2]

  [1]: https://www.calstatela.edu/sites/default/files/groups/Department of Electrical and Computer Engineering/labs/74157.pdf
  [2]: https://i.stack.imgur.com/oVliX.gif


message:
wrong leds lit in matrix display - wrong coding?

I wrote the following code for displaying a bitmap (small size) on a  LED matrix (formed using APA102 led strip):

    //for 24-bit bitmaps

    // the header files for the RGB data

     #include <FastLED.h>
     #include "redarray.h"
     #include "greenarray.h"   //g data header file (hex or dec)
     #include "bluearray.h"   //b data header file (hex or dec)*/

    //matrix parameters

    #define MatrixWidth 36 //columns
    #define MatrixHeight 7 //rows
    #define numled (MatrixWidth * MatrixHeight)

    //pin details

    #define datapin 7

    #define clockpin 8

    CRGB leds[MatrixWidth * MatrixHeight];

    const bool  MatrixSerpentineLayout = true;

     void setup() {

         FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
         FastLED.clear();
      }

    void loop() {

      for(uint8_t x=0 ; x<MatrixWidth ; x++)  {

          for(uint8_t y=0; y < 3; y++) {

                leds[XY (x, y)].setRGB(redarray[x][y],greenarray[x][y],bluearray[x] [y]);

               FastLED.show();

               delay(1);
             }
          }
       }

          uint16_t XY( uint8_t x, uint8_t y)
     {
       uint16_t i;

         if( MatrixSerpentineLayout == true) {
           if( y & 0x01) {
            // Odd rows run backwards
              uint8_t reverseX = (MatrixWidth - 1) - x;
              i = (y * MatrixWidth) + reverseX;
         } else {
           // Even rows run forwards
              i = (y * MatrixWidth) + x;
        }
       }

      return i;
    }

The following is the data in one of the header files - its of same type for the other two colors.

const unsigned char redarray[36][3] PROGMEM  = {
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
};

The matrix is in a serpentine form (evident from the XY function in code). I am using an Arduino Due. The problem is that the code compiles and runs...but the bitmap is incorrect. Although I am sure, I am somewhat along the correct path because some LEDs do light up as they should as per the bitmap. But most of them are wrongly lit.

Could you somebody plz guide where I am going wrong with the coding? I fear there is some mistake in reading the color data from array and allocating it to leds[XY(x,y)].I do not know how a 2D array is read or dealt with by Arduino.

Thanks!

body:
Initialize your arrays like this:

    int a[3][4] = {
       {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
       {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
       {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
    };

...you can read more about it [here][1].

Added later...

The following explanation came from [here][2]:

Arrays that are not explicitly divided into rows:

    int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

...are filled like this:

    int M[4][5] =
    {
      {10,  5, -3, 9, 0},
      { 0, 32, 20, 1, 0},
      { 0,  8,  0, 0, 0},
      { 0,  0,  0, 0, 0}
    };

As only you understand your data you will have to verify if your data is populating the array as you expect.

  [1]: http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm
  [2]: https://stackoverflow.com/questions/18157251/multidimensional-array-initialization-in-c


message:
How to calibrate a load cell?

I'm working with a load cell and HX711. There was no weight on the sensor but I kept getting strange values, I thought it was broken or something so I used my second load cell but the same thing happened again.
I'm wondering what is wrong with it ?
If anyone have worked with it or have an idea how to work with it, please don't hesitate to give your opinions.

     #include "HX711.h"
    #include <Wire.h>

    #define DOUT  A0
    #define CLK   A1

    #define DEC_POINT  2
    #define STABLE  1

    float offset=0;
    float calibration_factor = 1;
    //float real_weight = 1.560;//kg
    float real_weight = 0.5;//kg

    HX711 scale(DOUT, CLK);

    unsigned char state=0;
    long  FindZeroFactor();
    float get_units_kg();
    void  ReadWeight();
    void  FindCalibrationFactor();

    void setup()
    {
      Serial.begin(115200);
      Serial.println();
      Serial.println("Auto Calibrate Program");
      Serial.println("Send 'a' to Find Zero Factor (Please Remove all weight from scale)");
      Serial.println("Send 'b' to Find Calibration Factor (Please insert know the weight on the scales)");
      Serial.println("Send 'c' Show weight on the scales");
    }
    void loop()
    {
      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp=='a')
          state=1;
        if(temp=='b')
          state=2;
        if(temp=='c')
          state=3;
      }

      switch(state)
      {
        case 0:
        break;
        case 1:
          FindZeroFactor();
       //   ReadWeight();
          state=0;
        break;
        case 2:
         FindCalibrationFactor();
         state=0;
        break;
        case 3:
          ReadWeight();
          delay(200);
        break;
        case 4:

        break;

      }
    }

    long FindZeroFactor()
    {
         Serial.println("Find Zero Factor");
         Serial.println("Please wait .....");
         scale.set_scale();
         scale.tare();
         long zero_factor = scale.read_average(20);
         Serial.print("Zero factor: ");
         Serial.println(zero_factor);
         return(zero_factor);
    }

    void FindCalibrationFactor()
    {
      unsigned char flag_stable=0;
      unsigned int decpoint=1;
      for(unsigned char i=0;i<DEC_POINT+1;i++ )
        decpoint = decpoint*10;
      while(1)
      {
          scale.set_scale(calibration_factor); //Adjust to this calibration factor
          Serial.print("Reading: ");
          float read_weight = get_units_kg();
          String data = String(read_weight, DEC_POINT);
          Serial.print(data);
          Serial.print(" kg");
          Serial.print(" calibration_factor: ");
          Serial.print(calibration_factor);
          Serial.println();
          long r_weight      = (real_weight*decpoint);
          long int_read_weight = read_weight*decpoint;
          Serial.print(r_weight);
          Serial.print(" , ");
          Serial.println(int_read_weight);
          long x;
          if(r_weight == int_read_weight)
          {
            flag_stable++;
            if(flag_stable>=STABLE)
            {
              Serial.print("Calibration Factor is = ");
              Serial.println(calibration_factor);
              break;
             }
            }
           if(r_weight > int_read_weight)
              {
                x = r_weight - int_read_weight;
                if(x > 100)
                  calibration_factor -= 1000;
                else if(x > 100)
                  calibration_factor -= 10;
                else
                  calibration_factor -= 1;
                flag_stable=0;
              }
              if(r_weight < int_read_weight)
              {
                x =  int_read_weight-r_weight;
                if(x > 100)
                  calibration_factor += 1000;
                else if(x > 10)
                  calibration_factor += 10;
                else
                  calibration_factor += 1;
                flag_stable=0;
               }
      }
    }

    float get_units_kg()
    {
      return(scale.get_units()*0.453592);
    }
    void ReadWeight()
    {
      scale.set_scale(calibration_factor); //Adjust to this calibration factor
      Serial.print("Reading: ");
      String data = String(get_units_kg()+offset, DEC_POINT);
      Serial.print(data);
      Serial.println(" kg");
    }

body:
    scale.set_scale(calibration_factor);
needs to be changed to :

    scale.set_scale(calibration_factor/[the reference weight you have used]);


body:
The first thing that about Load Cells that always comes to my mind is the circuit which amplifies the load cell's signal, Usually the load cell signal changes in a low mv range, so you have to put a high gain circuit in the way of the signal, which amplifies signal and NOISE. You have to use an instrumentation amplifier for this purpose, otherwise, your signal would become so noisy.

 And try to implement a low pass digital filter too, it should compensate the fluctuations and would give you smoother signal.


message:
Cannot directly connect Arduino Ethernet to PC

I have been following various tutorials (especially: [this][1]) to connect an Arduino Ethernet board to my Ubuntu PC via Ethernet directly.

The IP address of the computer was found to be 10.100.31.128, and so I tried addresses in this range (10.100.31.67, 10.100.31.121, ...) without success. DHCP also doesnt seem to work. For the MAC address I used the sticker on the back of the board. I am using a patch cable, maybe that's the problem?

  [1]: https://startingelectronics.org/tutorials/arduino/ethernet-shield-web-server-tutorial/basic-web-server/ "Starting Electronics"

body:
Network problems can be complex.  If these suggestions are not right I can change the answer later if other solutions present themselves.

If you are connecting two Ethernet devices directly you may need a cross over cable.

To test your connection with out using IP addresses, try to follow what is discussed in [this answer][1] where the MAC address is used on a Ubuntu system instead of the IP address.

You also might try using wireshark to monitor the Ubuntu box's Ethernet port.

  [1]: https://askubuntu.com/questions/429901/how-can-i-ping-a-computer-or-a-printer-using-its-mac-address


body:
When you connect your Ethernet Shield to your Ubuntu PC your PC 'looks' at the Ethernet shield as if it were a router and therefore tries to connect to it as an internet source, thus it tries to get an IP and other related stuff from the Ethernet shield.

**BUT**

What you want is that the Ethernet shield should use the ubuntu PC as an internet/local network source. For this you must have active internet on your PC from Wifi/ USB data etc.

You will have to **BRIDGE** the connections of your Ethernet shield and your internet source in order to do so.

The link to accomplish Bridging networks in Ubuntu [is here][1]

  [1]: https://help.ubuntu.com/community/NetworkConnectionBridge

When you bridge two Ethernet networks, the two networks become one single (larger) Ethernet network. Thereby making the Ethernet shield a part of the larger network (Internet in this case). You can now upload any of your sketches onto the Arduino as per your requirements and accomplish your task.


message:
Is it possible to increase the Arduino's input and output pins?

I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.

I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.

In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?

I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

[![Arduino with shift registers][2]][2]

I am good at coding however when it comes to hardware sometimes I'll need some push.

Thanks a lot.

  [1]: https://i.stack.imgur.com/TzOGS.jpg
  [2]: https://i.stack.imgur.com/RRzqX.png

body:
You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.

Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf

As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.


body:
You can either use [external hardware][1] or [communicate to a 2nd Arduino][2] and control the 2nd Arduino's digital and analog ports.  Being good at coding would suggest you would prefer communicating to a 2nd Arduino.  Also, most hardware solutions only add digital pins, not analog pins.

  [1]: http://playground.arduino.cc/Code/I2CPortExpander8574
  [2]: https://www.arduino.cc/en/Tutorial/MasterWriter


message:
How to put 2 variables in a macro?

In a previous question (https://arduino.stackexchange.com/questions/21782/append-text-to-variable-names-please-help-me-shorten-this-code/21799#21799) I learned that in order to shorten this code:

    fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);

I could define a macro at the top of the script like this:

    #define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

And then just use the following shorter code:

    readEE(foo);

Which would be expanded out to:

    foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

----------

My current question is: **How can I write a macro that accepts 2 arguments instead of just 1?** I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.

In particular, I would like to learn if it's possible to shorten the following code:

    void writeToEE(byte location, bool value, bool &var) {
      writeEE(loc, value); var = value;
    }
(*Sidenote*: the `writeEE` function looks like this: `void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }`. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).

Since whenever I'm using `writeToEE`, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):

    #define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)
so that when I write this:

    wrEE(fanSpeed, 3);

it will be expanded out to:

    writeToEE(fanspeedPos, 3, fanspeed);

I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"

body:
In the parameter list of the `#define` for the macro, separate the second argument from the first with only a comma.  For example:

    #define wrEE(speed,var) writeToEE((etc))

The "void value not ignored as it ought to be" error message is a consequence of trying to store the `void` result of `writeToEE`.  The solution is to not try to store it.

In C, variable, parameter, and constant names are case-sensitive.


message:
Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it?

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

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

Ethernet shield problem. When running the WebServer example sketch, the Serial Monitor shows that `server is at 0.0.0.0`. Any suggestions how to debug it?

body:
That's what it's supposed to be. It's called INADDR_ANY. Read an introductory text on networks and you'll understand what that means.

If you try to connect to the IP address you specified, you'll see that you can indeed connect.


body:
The arduino only tells what it reads from the ethernet module and 0.0.0.0 is what you get when Arduino is not connected to it. It's a hardware problem, you either didn't connect the wires right or something's fried. I think it can also happen if your ethernet cable is unplugged.

This is absolutely not a sign that your module is accepting all connections. It would be the case if you set it that way but you are obviously expecting another ip adress. Someone should delete that answer.


body:
If possible, try running the same code on an identical Arduino. I had a similar issue, and it turned out one of my ICSP pins were burned.

Contrary to other answers here, the IP address will show the correct value in the Serial Monitor even though nobody is connected.


message:
split serial.readString() output

I'm trying to read a string like this one:

    2;12;42;43;34

over a serial connection and split this string afterwards by a ";".
So the output would be this array:

    (2,12,42,34)

All the stuff runs on an arduino uno. So I made some code:

    String read_input;
    char read_input_char[20];
    char *read_values;

    void setup() {

      Serial.begin(9600);
      Serial.setTimeout(10);

    }

    void loop() {
      if(Serial.available()){
        read_input = Serial.readString();
        read_input.toCharArray(read_input_char, 20);

        read_values = strtok(read_input_char, ";");
        Serial.println(read_values[2]);
      }
    }

However now instead of outputting the 3rd array element it outputs only an '1'. What's wrong?

body:
This is a C question, not an arduino question, but anyway:

From the man page:

    DESCRIPTION
       The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
       string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
       NULL.

You are only calling `strtok()` once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.


body:
Your code as is checks for a non-empty Serial buffer (the Serial.available() bit), and then reads it all into a String. Be careful doing this, as if this happens to execute part-way through the data arriving, you will get a partial data String. This may be cut off part way through one of your integers.

Also, the String object is very memory-intensive. Maybe not an issue for you, but try to use char arrays, or read directly from the Serial buffer.

In your case, there is a great function that you could use; parseInt().

Details are at; https://www.arduino.cc/en/Serial/ParseInt

More or less, this reads successive chars from the serial buffer, and once digits are encountered, forms an int. This continues until a non-digit char, or a (configurable) timeout. Something like this might do the job for you;

    int data[10]; // Or however long you need it to be!
    int arrayPointer = 0;

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

    void loop() {
      if (Serial.available()) {
        int incomingInt = Serial.parseInt();
        Serial.println(incomingInt);
        data[arrayPointer] = incomingInt;
        arrayPointer++;
      }
    }

Hope this helps!


message:
What is the output of Software Serial .read() function

Hi I am new to arduino development i was using esp8266 using software serial library
>here is the code

    #include<stdlib.h>
    #include <SoftwareSerial.h>

    SoftwareSerial monitor(2, 3); // RX, TX

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

      sendDebug("AT");
      delay(5000);
      Serial.println("Hello");
      if(monitor.find("OK"))
      {
       Serial.println(monitor.available());
       Serial.println((int)monitor.read());
       Serial.println((int)monitor.read());
        Serial.println(monitor.available());
       Serial.println("RECEIVED: OK");
        //connectWiFi();
      }
      else
      {
        Serial.println("RECEIVED: None");
      }
    }

    void loop(){

    }

    void sendDebug(String cmd){
      monitor.println(cmd);
      Serial.println("Command: "+cmd);
    }

>Output

    Command: AT
    Hello
    2
    13
    10
    0
    RECEIVED: OK

*All I know is `monitor.available()` return the available bytes that can be read and i can also deduce that these two **bytes** are **O** and **K** but the integer value doesn't corresponds to the **ascii** value of **O** and **K***

can anyone explain what is actually getting printed on the serial monitor what is **13** and **10** ? ??

body:
It is just like https://www.arduino.cc/en/Serial/Read :

The `monitor.find("OK");` already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive `monitor.read()`s, then zero more bytes in monitor.available().


message:
Is ATMEGA328P the same as 16U2?

I've been playing with my Arduino for a few months.

But, I just bought a shield that says it needs to be used with ATMEGA328P.  My box says I have a 328P, however, reading the chip, it's inscribed with "ATMEL MEGA16U2".

Does that mean the box is wrong, or is that the same as 328P somehow?

Thanks!!

body:
The 16u2 is related to the ATmega328p, and includes USB, but is more limited in resources.   While it would be *possible* to make an Arduino-type board from alone, this is unlikely to be what you have.

Rather, it is likely that you have a board with an ATmega328p as the main processor, and *also* a 16u2 which serves as a USB interface for it.

You could know for sure from what board type you select in the dropdown menu of the Arduino IDE.  If you are selecting something like "Uno" or "Duemilanove" you have a 328p as the main processor.

(The other presently common type of board is the "Leonardo" style where a 32u4 - essentially a bigger version of the 16u2 - is used as a single-chip solution that is both the primary processor and the USB interface.  But if that is what you had, it would not say 16u2 on it, unless it was an attempt to make a more limited "budget" version).


body: the 328p is the microcontoller. It's the larger chip located in the middle of the arduino board surface. This one handles the code/ sketch/ programme that you write). The 16u2, on the other hand, is the smaller chip located near the USB port. This handles data communication through the USB port.


message:
Arduino Pro Micro clone clock cycle issue

I have several Arduino Pro Micro clones that are giving me an issue where they work immediately after being programmed while the USB cable is still connected, but as soon as I disconnect and reconnect the USB cable the program fails. I was able to break it down to the simplest form and found that the clock cycle is off by what I estimate to be almost a factor of 10.

For testing, the only command in the loop is `Serial.println(millis());`. Immediately after programming you can watch the milliseconds scroll by in the serial monitor at the expected rate. Unplug and plug the USB, reconnect the serial monitor and now the milliseconds scroll by at about 1 second interval.

The Arduino IDE version is 1.6.8 and have tested it from both a Mac and Ubuntu with the same results. Also tested on 4 different boards with the same results. I also tested the latest Arduino beta with no change. Next I'm going to download some older Arduino IDE versions.

Any suggestions?

body:
The fix for this issue was to reload the bootloader.  I used the [SparkFun Caterina bootloader][1].

  [1]: https://github.com/sparkfun/Arduino_Boards/tree/master/sparkfun/avr/bootloaders/caterina


message:
How do I connect velostat to an arduino?

I have some [velostat][1] that I'd like to hook up to an Uno. At the risk of sounding dense...how do I do that?

Ultimately wanting to get readings of pressure from the velostat, just not sure how or what wires to connect where.

  [1]: https://www.adafruit.com/products/1361

body:
Usually a variable resistance sensor is used in a voltage divider circuit:

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

In the above example a thermistor is connected to the positive supply and a pull down R1 is connected to ground.  The voltage where they meet is measured using one of the Arduino's analog inputs pins.

Choosing R1 is tricky.  If it is too large compared to the variable resistance sensor the voltage fluctuation at Vout will be too small to measure.  The same problem exists if R1 is too small compared to the variable resistance sensor.  Also, you need to mind the current through the sensor.  If the combined resistance of R1 and the sensor is too small the current may damage the sensor, over heat R1 and / or put a heavy drain on your power source.

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


message:
How would I refactor this code, given how similar most of the lines are?

I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (`button1pin`, `button2pin`, etc) so there's almost certainly a more efficient way of coding this.

Any ideas?

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

    // Buttons
    const int button1pin = 3;
    const int button2pin = 4;
    const int button3pin = 5;
    const int button4pin = 6;
    const int button5pin = 7;
    const int button6pin = 8;
    const int button7pin = 9;
    const int button8pin = 10;
    const int button9pin = 11;

    const int led1 = 0;
    const int led2 = 1;
    const int led3 = 2;
    const int led4 = 3;
    const int led5 = 4;
    const int led6 = 5;
    const int led7 = 6;
    const int led8 = 7;
    const int led9 = 8;

    void setup() {
      strip.begin();
      strip.show();

      pinMode(button1pin, INPUT_PULLUP);
      pinMode(button2pin, INPUT_PULLUP);
      pinMode(button3pin, INPUT_PULLUP);
      pinMode(button4pin, INPUT_PULLUP);
      pinMode(button5pin, INPUT_PULLUP);
      pinMode(button6pin, INPUT_PULLUP);
      pinMode(button7pin, INPUT_PULLUP);
      pinMode(button8pin, INPUT_PULLUP);
      pinMode(button9pin, INPUT_PULLUP);
    }

    void loop() {
      if (digitalRead(button1pin) == LOW){
        strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button2pin) == LOW){
        strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button3pin) == LOW){
        strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button4pin) == LOW){
        strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button5pin) == LOW){
        strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button6pin) == LOW){
        strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button7pin) == LOW){
        strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button8pin) == LOW){
        strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
      }
      if (digitalRead(button9pin) == LOW){
        strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
      }

      strip.show();
    }

body:
    #include <Adafruit_NeoPixel.h>
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
    // The maximum pin number for the buttons
    const int MaxButton = 11;
    // The value if the pin is not connected to an LED
    const int NotConnected = -1;
    // The connections from buttons to leds.
    const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

    void setup()
    {
      strip.begin();
      strip.show();
      for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
      {
     if (Connections[pinNumber] != NotConnected)
     {
      pinMode(pinNumber, INPUT_PULLUP);
     }
      }
    }

    void loop()
    {
      for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
      {
     if (Connections[pinNumber] != NotConnected)
     {
      if (digitalRead(pinNumber) == LOW)
      {
       strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
      }
     }
      }
      strip.show();
    }

I can't test it, so I have no idea if it works, but it should do.


message:
ESP8266 - CIPSEND & external power supply Hangs program

**Updated**:

I connected my esp to external power, the blue light stays on, I start getting garbage data.
I used voltage regulator which was giving 3.4v, power supply tested with 1A &  2A.

**Old problem :**

I have been trying to make ESP8266 since my last semester exams & now 2nd semester exams are going on. So i've been trying to make ESP8266 work for very long time.
Earlier it was firmware problem, i updated it.

After a lot it worked. I tried many libraries - but none worked, either some are using specific port or some want specific firmware version which is really hard to find & then flash.

I am using telnet to check.
When i disable code to send data - i can send data madly, it works & never hangs up. But as i use `AT+CPISEND` after 1-2 read/write - it stops responding.

I am powering using arduino with/out voltage divider. Its firmware - `0020000903`, `AT Firmware v1.5`, 4mb flash size, I changed baudrate to `9600`.

Below is code i worte :
( I intentionally didn't remove comments)

    #include <SoftwareSerial.
    #define DEBUG true

    SoftwareSerial esp8266(9,10); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {

      pinMode(11,OUTPUT);
      digitalWrite(11,LOW);

      pinMode(12,OUTPUT);
      digitalWrite(12,LOW);

      pinMode(13,OUTPUT);
      digitalWrite(13,LOW);

      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different

    Serial.print("Sending at..");
      sendData("AT",2000,DEBUG);
      //sendData("AT+RST",2000,DEBUG); // reset module
      sendData("AT+CWMODE=1",1000,DEBUG);
     // sendData("AT+CWLAP",1000,DEBUG);
     //sendData("AT+CIOBAUD=9600",1000,DEBUG);
     //sendData("AT+UART=9600,8,1,0,0",1000,DEBUG);
     //sendData("AT+IPR=9600",1000,DEBUG);
     // sendData("AT+CWJAP_DEF=\"mad\",\"agentis47?orBond?\"",15000,DEBUG);
     //sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
      sendData("AT+CIFSR",1000,DEBUG); // get ip address
      sendData("AT+CIPMUX=1",1000,DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80",1000,DEBUG); // turn on server on port 80
    }

    void loop()
    {

      if(esp8266.available()) // check if the esp is sending a message
      {

        while(esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
        }

        //Serial.println("IPD Search "+(len));
        if(esp8266.find("+IPD,"))
        {

         delay(20); // wait for the serial buffer to fill up (read all the serial data)
         // get the connection id so that we can then disconnect
         int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48

         esp8266.read(); //skip the comma ','
         //(CIPMUX=0): + IPD, <len>:
         //(CIPMUX=1): + IPD, <id>, <len>: <data>
         int len = (readUntil(":")).toInt();
         if(len>500) len = 500; //prevent extra data we won't be sending more than 500bytes in one go.
         char data[len];

         esp8266.readBytes(data, len);
         //data[len-2]='\0';

          int pinNumber = (data[0]-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
         pinNumber += ((data[1])-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

           digitalWrite(pinNumber, !digitalRead(pinNumber));
        Serial.println(String(len));

         /*Serial.println("===");

         Serial.println("--");
    */
        //cleanBuffer();
        //delay(10);
         //Serial.println("Sendddiddding data");
         //sendData(connectionId,String("OK"));
         //Serial.println("Sent");
         //closeConnection(connectionId);

         //digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

         // make close command
         //String closeCommand = "AT+CIPCLOSE=";
         //closeCommand+=connectionId; // append connection id
         //closeCommand+="\r\n";

         //sendData(closeCommand,1000,DEBUG); // close connection
        }
      }
    }

    void cleanBuffer(){
      while(esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
        }
    }

    String sendData(int connectionId, String data){
      //Serial.println("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()));
      //sendData("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()),1000,DEBUG);
      //sendData(data,100,DEBUG);
      //closeConnection(connectionId);
      String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

         String cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         webpage="<button>LED2</button>";

         cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId; // append connection id

         sendData(closeCommand,3000,DEBUG);

     /*
      Serial.println("finding prompt");
      if(esp8266.find(">"))    //prompt offered by esp8266
      {
        Serial.println("Sending data");
       // Serial.println("found > prompt - issuing GET request");  //a debug message
        esp8266.println(data);  //this is our http GET request
      }
      else
      {
        closeConnection(connectionId);
        Serial.println("No '>' prompt received after AT+CPISEND");
      }
    */
    }

    String closeConnection(int connectionId){
        sendData("AT+CIPCLOSE="+String(connectionId),100,DEBUG);
    }

    String readUntil(String delimiter){
      String response = "";
      char c;
      unsigned int dLen = delimiter.length(),n=0;

        while(esp8266.available()&&(c= esp8266.read())){
          n= (c==delimiter[n])?n+1:0;
          if(n==dLen) break;
          response+=c;
        }
       return response;
    }

    void sendRaw(String data){
    esp8266.print(data);
    }

    String sendCommand(String command){
      esp8266.print(command); // send the read character to the esp8266
      esp8266.print("\r\n");
      esp8266.flush();
    }

    String sendData(String command, const int timeout, boolean debug)
    {
        String response = "";
        esp8266.print(command); // send the read character to the esp8266
        esp8266.print("\r\n");
        esp8266.flush();
        long int time = millis();

        do
        {
          while(esp8266.available())
          {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }while( (time+timeout) > millis());
        if(debug)
        {
          Serial.print(response);
        }
        return response;
    }

Please help, I am stuck, Is there any other cheaper & better solution ? I am only looking for Wifi.

body:
If you are powering it using Arduino 3.3V pin it is no wonder it does not work.
ESP8266 uses more power than Arduino can provide. Power pin on arduino is about 50ma. ESP8266 in receive or send mode uses much more and either halts or restarts.

[A table of ESP8266 power consumption can be found here][1]

  [1]: http://bbs.espressif.com/viewtopic.php?t=133


message:
connect arduino to battery with 12V motor

I am looking  at this([instructable with circuit picture][1]) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino. I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply. How should I get a charger cable and solder on the battery wires to the charger? If so are there any tutorials? Is the connection to the Arduino necessary?

(please look at the Firizing diagram in the instructable)
Thanks

  [1]: http://www.instructables.com/id/Chappie-Self-Balancing-Robot/

body:
> I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot.
> However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino.
Which is bullshit.

You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

> I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.

I'm not sure what you mean by "Green device", the HC-05 or the L293D?
Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino).
You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

> How should I get a charger cable and solder on the battery wires to
> the charger?

You can't charge regular 9V batteries.

> Is the connection to the Aruino necessary?

The specific connection he shows? No.
Power to the Arduino board? Yes.


message:
What does this error mean?? Arduino Due loop warning

I am getting this error on compilation of the code given further below;

> warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations]
>
> leds[XY (x, y)].r = redarray[x][y];
> note: containing loop
> for(uint8_t x=0; x < MatrixWidth; x++){

Code:

     // the header files for the RGB data

    #include <FastLED.h>
    #include "redarray.h"
    #include "greenarray.h"   //g data header file (hex or dec)
    #include "bluearray.h"   //b data header file (hex or dec)*/

     //matrix parameters

    #define MatrixWidth 36 //columns (x)
    #define MatrixHeight 1 //rows (y)
    #define numled (MatrixWidth * MatrixHeight)

    //pin details

    #define datapin 7

    #define clockpin 8

    CRGB leds[MatrixWidth * MatrixHeight];

    const bool  MatrixSerpentineLayout = true;

    void setup() {

       FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
       FastLED.clear();
             }

    void loop() {
       for(uint8_t y=0 ; y<1 ; y++){
         for(uint8_t x=0; x < MatrixWidth; x++){
             leds[XY (x, y)].r = redarray[x][y];
             leds[XY (x, y)].g = 0;
             leds[XY (x, y)].b = 0;

             FastLED.show();
             delay(50);
         }
       }
     }

      uint16_t XY( uint8_t x, uint8_t y)
      {
          uint16_t i;

          if( MatrixSerpentineLayout == true) {
              if( y & 0x01) {
              // Odd rows run backwards
              uint8_t reverseX = (MatrixWidth - 1) - x;
              i = (y * MatrixWidth) + reverseX;
        } else {
             // Even rows run forwards
             i = (y * MatrixWidth) + x;
        }
    }
       return i;
    }

The following is redarray header -

//RED
const byte redarray[3][36] PROGMEM = {
{0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}

};

How to remove this warning. The redarray is not being read properly by arduino. THe above code should make the 36 LEDs turn off (black) as per the header file. They are randomly lit red... I am totally perplexed!

Plz help if somebody can.
Thanks!

body: `MatrixWidth` is 36. `redarray[]` has 3 elements. The compiler has detected that your code will likely blow up on the 4th go through the loop. Make sure your code is accessing the dimensions correctly.


message:
Electric interference from cnc spindle

I've got a CNC machine and I recently started using a spindle for it. At first it was running smoothly with no issues, but after the first brush pair wore off (I've replaced them later on) it started interfering with the Arduino/gshield and pc monitor. The monitor displays a "no signal" message, although after turning off the spindle or turning it to a low speed the signal comes back. The other problem is that after running a long job, sometimes the gshield disconnects and the job stops midway.

- What part could be causing all this interference?
- How can I shield that part so it stops interfering with other electronics?

I am using the following hardware:

- 600 watt spindle
- 600 watt power supply with variable speed
- the wires from the spindle to the power supply are not shielded, although Ive tried covering them with aluminium foil, not sure if that should be of any benefit, I've read it somewhere so I gave it a try.
- Gshield with Arduino, connected to a Raspberry pi.

All the electronics are within 70 cm radius.

body: I would guess that arcing in the spindle causes spikes that travel through the power supplies and power wires. One thing you could try is to use a really long extension cord (say 15 meters or more) to power the spindle power supply. You can insert this cord to a different power outlet to gain additional distance.


message:
Need Help with Switch Case commands/receiver and lcd screen project?

I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working.
**Edit:**

`

    #include <LiquidCrystal.h>
    #include <VirtualWire.h>
    LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
    byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
    byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
    void setup()
    {
      Serial.begin(9600);
      Serial.println("Device is ready");

      // Initialize the IO and ISR
      vw_setup(2000); // Bits per sec
      vw_rx_start(); // Start the receiver
      lcd.begin(16, 2);

      // Print a message to the LCD.
    }

    void loop()
    {
      if (vw_get_message(message, &messageLength)) // Non-blocking
      {
        switch(message[1])
        {
        case 0:
          lcd.setCursor(0, 1);
          lcd.print("O.O");
          break;
        case 1 :
          lcd.setCursor(0, 1);
          lcd.print("Hi! :)");
          break;
        }
        {
          Serial.print("Received: ");
          for (int i = 0; i < messageLength; i++)
          {
            Serial.write(message[i]);
          }
          Serial.println();
        }
      }
    }

body:
Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

- The output you get (both in the LCD and the serial console)

- The message sent

One thing that strikes me as a potential problem is the

    switch(message[1])

line. If you want to check the first character received, it should be

    switch(message[0])

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):

      lcd.setCursor(0, 0);
      lcd.print("Initialised!");

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.

Give us more information and we 'll be able to help more.


message:
Arduino Uno's RX and TX lights not blinking. Unable to upload sketches!

When arduino starts up, RX TX lights doesn't blink. Only the PIN 13 and Green light turns on. Pin 13 light blinks thrice before getting stable. RX TX lights are not blinking at all. I am not able to upload any sketches. The error I get is "Not in sync resp=0x00" or "Programmer not responding" or "Not in sync resp=0x95" or "Not in sync resp=0x69" and so on. A new error everytime. Most probably the error is with serial communication.

A brief history of what I have done

I have a Relay which is operated at 12V. But Arduino works at 5V logic. So I used a comparator (IC741) to improve the logic (By setting Vcc and -Vcc at 12 and 0 and the input pins connected to arduino). I also connected HC-05 bluetooth module to use the relay using my cellphone. You know what I was trying was home automation. Also Arduino was connected to 12V DC supply (I think this was my mistake). Everything was going right.

 Suddenly IC741 started burning,maybe I shorted some pins when I was trying to measure the voltages using multimeter. I quickly removed it. Suddenly HC 05 started burning. I immediately removed all the connections. After some time I turned on Arduino again (This time using USB connected to laptop). I connected HC05. The bluetooth module heats up again. I thought the module is now gone. I turned to check Arduino and as I stated I am unable to upload any more sketches. Most probably the bluetooth module cause an error in serial communication. May be not.

So my question is
1. What's the real problem. Is my bluetooth module gone? Or is Arduino gone? If arduino is still fine, how can I get the serial to work back and enable me to upload sketches?
2. If Arduino is gone, most probably the microcontroller Atmega328 is still fine. How can I use it now without Arduino (I don't have any extra Arduino)?

Things I have already tried :

1. Loopback test : No echo back. Serial data can neither be sent nor received.
2. When I open the Serial window, Arduino doesn't resets as it it earlier.
3. RX TX Vin and 5V pin reads 4.99V. I hope they are fine.

body:
Can you test the bluetooth module separately? i.e. just connect the power pins directly to the correct voltage source, and check if it overheats.  In this way you may be able to find the source of the short circuit.

If you shorted one or more of your arduino's I/O pins, you may have damaged your Atmega328 chip, since there's no protection between the chip and IO headers.  The other circuitry on the Arduino board is mostly power conditioning/regulation.  So I'm assuming that's not the problem.
Check if your 328 is getting the correct voltage at the VCC pin, to eliminate the power circuitry as the problem.


body:
If you are getting three blinks, most likely bootloader is fine but don't take it for granted. Also, post a schematic and picture of your original setup to get better answers in future.

Here is how you should start the debugging process:

1) Disconnect everything from Arduino especially from Tx Rx pins, and try to dump the blinky sketch. If it works, then arduino is good. If it doesn't work, follow [this article](https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard) to burn a fresh bootloader in your atmega. Check again. If not able to burn bootloader or code afterwards, get a new atmega IC for cheap and replace the damaged one.

2) Check the voltage requirements for HC-05 whether it's 3.3V or 5V. Make sure you are not giving it a higher voltage. If it starts to smoke as soon as you connect the GND VCC, then probably it has been damaged. Measure the resistance between GND and VCC of HC-05 before attaching. If it's less than 10-20 ohms, you already know that it's damaged.


body:
> Pin 13 light blinks thrice before getting stable.

It is supposed to do exactly that. See <https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader>

> RX TX lights are not blinking at all.

That's not so good. See <https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board>


message:
Ethernet Shield: Failed to configure Ethernet using DHCP

I am currently making a design that uses the Arduino's Ethernet shield. I am using the PushingBox API for Arduino, and have tried it with my Arduino Mega (2560) with the ethernet shield attached to the router. When I did this, however, it displayed a message on my serial monitor saying `Failed to configure Ethernet using DHCP`. The model for my Ethernet Shield is a [W5200 Seeed Studio Ethernet Shield][1], and I am using the libraries that Arduino provides. I do not have an SD card inserted and the DHCP on all other wired devices works. Any help is greatly appreciated.

The code (in case):

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

      /////////////////
     // MODIFY HERE //
    /////////////////
    byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x19 };   // Be sure this address is unique in your network

    //Your secret DevID from PushingBox.com. You can use multiple DevID  on multiple Pin if you want
    char DEVID1[] = "{[I have replaced this with my DevID]}";        //Scenario : "The mailbox is open"

    //Numeric Pin where you connect your switch
    uint8_t pinDevid1 = 3; // Example : the mailbox switch is connect to the Pin 3

    // Debug mode
    boolean DEBUG = true;
      //////////////
     //   End    //
    //////////////

    char serverName[] = "api.pushingbox.com";
    boolean pinDevid1State = false;                // Save the last state of the Pin for DEVID1
    boolean lastConnected = false;                 // State of the connection last time through the main loop

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      Serial.begin(9600);
      pinMode(pinDevid1, INPUT);

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        Serial.println("Please reconfigure the settings and try again.");
        // no point in carrying on, so do nothing forevermore:
        while(true);
      }
      else{
        Serial.println("Ethernet ready");
        // print the Ethernet board/shield's IP address:
        Serial.print("My IP address: ");
        Serial.println(Ethernet.localIP());
      }
      // give the Ethernet shield a second to initialize:
      delay(1000);
    }

    void loop()
    {
          ////
          // Listening for the pinDevid1 state
          ////
          if (digitalRead(pinDevid1) == HIGH && pinDevid1State == false) // switch on pinDevid1 is ON
          {
            if(DEBUG){Serial.println("pinDevid1 is HIGH");}
            pinDevid1State = true;
            //Sending request to PushingBox when the pin is HIGH
            sendToPushingBox(DEVID1);
          }
           if (digitalRead(pinDevid1) == LOW && pinDevid1State == true) // switch on pinDevid1 is OFF
          {
            if(DEBUG){Serial.println("pinDevid1 is LOW");}
            pinDevid1State = false;
            //Sending request to PushingBox when the pin is LOW
            //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable
          }

          //DEBUG part
          // this write the respons from PushingBox Server.
          // You should see a "200 OK"
          if (client.available()) {
            char c = client.read();
            if(DEBUG){Serial.print(c);}
          }

          // if there's no net connection, but there was one last time
          // through the loop, then stop the client:
          if (!client.connected() && lastConnected) {
            if(DEBUG){Serial.println();}
            if(DEBUG){Serial.println("disconnecting.");}
            client.stop();
          }
          lastConnected = client.connected();
    }

    //Function for sending the request to PushingBox
    void sendToPushingBox(char devid[]){
      client.stop();
      if(DEBUG){Serial.println("connecting...");}

      if (client.connect(serverName, 80)) {
        if(DEBUG){Serial.println("connected");}

        if(DEBUG){Serial.println("sendind request");}
        client.print("GET /pushingbox?devid=");
        client.print(devid);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(serverName);
        client.println("User-Agent: Arduino");
        client.println();
      }
      else {
        if(DEBUG){Serial.println("connection failed");}
      }
    }

If the code for the DHCP error is removed, it does display an external IP address, but actual HTTP requests do not work. I tried port forwarding and that did not work either.

EDIT:
Now, unusually, it gives me an IP address WITHOUT the ethernet cord connected.

  [1]: http://www.seeedstudio.com/depot/W5200-Ethernet-Shield-p-1577.html?user_country=CN

body:
If I understood your problem correctly then you might want to check this out,
it's more or less the same thing :D

https://arduino.stackexchange.com/questions/13834/dhcp-failing-on-arduino-uno/32744#32744


message:
Getting RGB values from camera

I have a camera I'm planning on attaching to an arduino uno, that I want to take pictures and extract the average RGB value from each image.
[This is the camera](https://www.adafruit.com/product/397) I have, but I've now realized that it takes pre-compressed JPEG images, and so I cannot make use of the data it's giving me.

I realize that an arduino is not the optimal tool to use in this case, but I'm curious as to whether there would be any way to decompress the images and convert them to a format I could use. It does not need to be fast, and I do not need to take the pictures quickly. I have experience with programming but have not done many projects with the arduino, so any help or advice is appreciated.

body:
No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.

I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.

You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.

Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.


message:
How can I maintain PWM output while still performing other tasks?

I want to generate a PWM signal that I can turn on and off with a button press without using interrupts.  Is there a way to keep the PWM output going while running other processes?

body:
PWM just runs once started. It's all managed by a completely separate bit of silicon inside the chip.

Once you have done `analogWrite(...)` the PWM will just keep going until you tell it otherwise.


message:
Error saying an included library is not

The IDE tells me the included library isn't? I tried restarting the IDE and my computer but it doesn't work. The other libraries work fine it's only with Keyboard that it fails.

My code:

    #include <Keyboard.h>

    int buttonState = 0;

    void setup() {
      pinMode(2, INPUT);
      pinMode(13, OUTPUT);

      Keyboard.begin();
    }

    void loop() {
      buttonState = digitalRead(2);
      if (buttonState == HIGH) {
        digitalWrite(13, HIGH);
        Keyboard.press('A');
      } else {
        digitalWrite(13, LOW);
        Keyboard.releaseAll();
      }
    }

Error log:

    Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

    D:\Documents\Test\Test.ino: In function 'void setup()':

    Test:9: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
       Keyboard.begin();

       ^

    D:\Documents\Test\Test.ino: In function 'void loop()':

    Test:16: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
     Keyboard.press('A');

     ^

    Test:19: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
         Keyboard.releaseAll();

         ^

    exit status 1
    'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

body:
I see you are using an Arduino Uno.

An Arduino Uno cannot act as a USB keyboard - therefore the Keyboard library doesn't exist for it (the file Keyboard.h is seen as being empty).

You can only use Keyboard.h on boards where using Keyboard.h makes any kind of sense, such as the Leonardo.


message:
Enabling keyboard feature on Arduino with CH340G

I've seen [here][1] that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?

  [1]: http://hackaday.com/2012/06/29/turning-an-arduino-into-a-usb-keyboard/

body: No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.


message:
Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device

When I try to upload my program on the Arduino Uno Chinese clone, It says

     -> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device

 - My Arduino Programmer: ArduinoISP
 - My Arduino Software version: 1.6.8
 - My OS: Linux Mint

Can you help me fix this error?

body:
This could be any number of different problems.  Here are several common causes:

1. You have multiple USB serial port devices connected to your computer. Try using the command `ls -l /dev/ttyUSB*` to check if your computer thinks there are more than one terminal USB device.  Disconnect all of them, then only connect the Arduino Uno.  Then repeat the check.

2. You do not have permissions.  This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm.  **You should NOT make a habit of this**, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.

3. You have a counterfeit FTDI chip on your Arduino Uno that has been [rendered useless by certain versions of the Windows FTDI Driver][1].  The USB IDs can get reset to useless values.  I believe the current FTDI Windows Driver no longer does this.

4. You did not install the Linux FTDI driver.  A driver is a program to abstract the hardware from the application.  In this way, different hardware can be treated the same by the application, simplifying the application.  However, the wrong driver/hardware combination may not work as expected.

  [1]: http://hackaday.com/2016/02/01/ftdi-drivers-break-fake-chips-again/


body:
I had the same problem and solved with the suggestion of [ndemou][1]:

    sudo chown root:YOURUSERNAME /dev/ttyUSB0

  [1]: https://arduino.stackexchange.com/questions/24125/error-on-unor3-avrdude-ser-open-cant-open-device-dev-ttyusb0-no-such/30601#comment58820_24133


message:
Using Blynk to control stepper motor is jerky

I am using [Blynk][1] to try and control a 28byj-48 stepper motor using the ULN2003 driver and an Arduino UNO from my iphone via USB withe the iOS Blynk App.

Without using Blynk, my stepper is smooth and works fine:

   #include <Servo.h>
   #include <Stepper.h>

   const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,
   const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
   const int motorpin1 = 8;                    //Assign motor  pins to Arduino pins
   const int motorpin2 = 9;                    //
   const int motorpin3 = 10;                   //
   const int motorpin4 = 11;                   //

   // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4
   Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);

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

   void setup() {
  myStepper.setSpeed(600);
   }

   void loop(){
   myStepper.step(-500);
   }

But when I use Blynk, the stepper is so jerky and stutters terribly:

   #include <SoftwareSerial.h>
   SoftwareSerial SwSerial(10, 11);
   #define BLYNK_PRINT SwSerial
   #include <BlynkSimpleSerial.h>
   #include <Stepper.h>

   const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,4-step mode
   const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
   const int motorpin1 = 8;                    //Assign motor pins to board pins
   const int motorpin2 = 9;                    //
   const int motorpin3 = 10;                   //
   const int motorpin4 = 11;                   //

   // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4 blah blah
   Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);
   char auth[] = "my auth key here";

   void setup(){
  SwSerial.begin(9600);
  Blynk.begin(auth);
  myStepper.setSpeed(600);
   }

   BLYNK_WRITE(1){
  myStepper.step(param.asInt());
   }

   void loop(){
  Blynk.run();
   }

I am using a slider on the app to control the stepper by the way. I am not sure what I am doing wrong, any suggestions?
  [1]: http://www.blynk.cc/

body: Blynk runs over a network and therefore cannot respond in real-time nor consistently. You could have the Blynk slider control set a local variable which the motor controller would use for motor speed, but the basic motor-drive timing needs to be locally controlled and independent of network operations. The SimpleTimer library is one way; a timer interrupt would be another.


body:
My guess would be you are suffering from a comms latency issue.

 1. Are you using a local server or the cloud?
 2. Is you iOS device connected over WIFI or 2G, 3G or 4G?

 3. Is you device on the same subnet as you iOS device and local server?

I've never used blynk (I might do this weekend though), my best thought as to how to fix it would be to revise your approach.  When you are controlling devices over an unpredictable connection (Ethernet) you can't rely of messages to arrive in a certain order or at certain times.  You need to tell the device to do something and keep doing it until its done or its told to stop.
So in this case tell the device to rotate clockwise at a certain rate until it travels n degrees or it is told to stop.  Now you can't just tell the motor to make 20 turns, because that will make your app unresponsive.  What you need to do it tell it to turn 50 steps and then return to the control loop, if no new order has come in it should then go and do another 50 steps, if there is a new order then off it goes with the new task.

Hope that makes sense and helps.


message:
BMP280 sensor not initializing

I am successfully using a BMP280 sensor via SPI connection with an Arduino Uno R3 board. I'm trying to run the same code with the same setup on an Arduino Ethernet. However the sensor is not initializing.

The setup function looks as follows:

    void setup() {
        delay(1000);
        dht.begin(); // starts DHT sensor
        chk = dht.read(DHTPIN); // reads DHT status
        while ((!bmp.begin()) || (chk != 1) ) {
          // checks DHT and BMP status and shows red LED, in case one of them
          // wasn't found. Loops and resets timeout each time.
          wdt_reset();
          Serial.println("Could not find a valid sensor, check wiring!");
          digitalWrite(RED, HIGH);
          delay(300);
          digitalWrite(RED, LOW);
          delay(1000);
          chk = dht.read(DHTPIN);
        }
    }

The code only returns the error message and does not initialize the BMP sensor (DHT is fine).

Full code:

    #include "ThingSpeak.h"
    #include <SPI.h>
    #include <DHT.h>
    #include <Ethernet.h>
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xE5, 0xBF};
    IPAddress ip(10,42,0,69);
    EthernetClient client;

    // --- Libraries --- //
    #include <avr/wdt.h> // Watchdog, interrupts and reboots
    #include <Adafruit_BMP280.h> // BMP library for BMP280

    // --- Constants --- //
    // DHT22
    #define DHTPIN 7
    // BMP280 (SPI)
    #define BMP_SCK 13 // Serial clock pin for BMP (10k pullup to +5V)
    #define BMP_MISO 12 // SDO, has 10k pullup
    #define BMP_MOSI 11 // SDI, no pullup
    #define BMP_CS 9 // CS, has 10k pullup
    // LEDs
    #define RED 5 // pin for LEDs
    #define YELLOW 3
    #define GREEN 2

    unsigned long myChannelNumber = 115634;
    const char * myWriteAPIKey = "***"; // removed for privacy reasons
    float dht_temp;
    float dht_hum;
    float bmp_temp; // values from sensors
    float bmp_press;
    int chk; // DHT status (0 or 1)
    int k; // counter variable
    int number;
    char COLOR;

    // --- Initialization --- //
    DHT dht(DHTPIN, DHT22); // initializes sensors
    Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);

    void setup() {
      wdt_disable(); // disables watchdog for initial communication
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);
      pinMode(YELLOW, OUTPUT); // LED pins set as output
      pinMode(RED, OUTPUT);
      digitalWrite(YELLOW, HIGH); // starts yellow LED
      Serial.begin(9600); // begin serial connection with 9600 baud
      delay(500); // delay to get connection and sensors ready
      wdt_enable(WDTO_8S); // start watchdog timeout (4 sec might be too short)
      blink(RED, 3);
      Serial.println(bmp.begin());
      dht.begin(); // starts DHT sensor
      chk = dht.read(DHTPIN); // reads DHT status
      if ((!bmp.begin()) || (chk != 1) ) {
        // checks DHT and BMP status and shows red LED, in case one of them
        // wasn't found. Loops and resets timeout each time.
        wdt_reset();
        Serial.println("Could not find a valid sensor, check wiring!");
        digitalWrite(RED, HIGH);
        delay(300);
        digitalWrite(RED, LOW);
        delay(1000);
        chk = dht.read(DHTPIN);
      }
      Ethernet.begin(mac, ip);
      ThingSpeak.begin(client);
    }

    // --- Loop --- //
    void loop() {
      wdt_reset(); // resets watchdog
      pinMode(GREEN, OUTPUT); // gets green LED ready
      digitalWrite(GREEN, LOW);
      delay(1600); // delay for sensors to be read. In total, at least 2 sec!
      dhtread();
      delay(5000);
      wdt_reset();
      bmpread();
      ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
      delay(5000);
      wdt_reset();
      delay(5000);
    }

    void blink(char COLOR, int number) {
      for (k = 1; k <= number; k = k + 1) {
        // blinks 3x to show that Arduino rebooted
        digitalWrite(COLOR, HIGH);
        delay(100);
        digitalWrite(COLOR, LOW);
        delay(100);
      }
    }

    void bmpread() {
      bmp_temp = bmp.readTemperature(); // reads BMP sensor
      bmp_press = bmp.readPressure();
      Serial.println(bmp_temp);
      Serial.println(bmp_press);
      if (bmp_press > 0.0) {
        // if sensor isn't attached, it shows 0.0 or negative pressure.
        // This is used as check criterion
        digitalWrite(GREEN, HIGH); // blinks green for good BMP values
        Serial.println("bmp ok");
        ThingSpeak.setField(3,bmp_temp);
        ThingSpeak.setField(4,bmp_press);
        delay(150);
        digitalWrite(GREEN, LOW);
      } else {
        // if pressure is 0.0 or negative, blink red
        // and print 0.0 to keep formatting
        digitalWrite(RED, HIGH);
        Serial.println("Error, BMP280 missing");
        delay(150);
        digitalWrite(RED, LOW);
      }
    }

    void dhtread() {
      chk = dht.read(DHTPIN); // checks if connection to DHT sensor is ok (0: no connection, 1: ok)
      if (chk == 1) {
        dht_temp = dht.readTemperature();
        dht_hum = dht.readHumidity(); // reads DHT sensor
        digitalWrite(GREEN, HIGH); // blinks once for successful DHT sensor values
        ThingSpeak.setField(1,dht_temp);
        ThingSpeak.setField(2,dht_hum);
        delay(150);
        digitalWrite(GREEN, LOW);
        delay(100);
      } else {
        // if no connection, blink red instead and print "nan"
        // (keeps formatting ok)
        digitalWrite(RED, HIGH);
        Serial.print("Error, DHT22 missing");
        delay(150);
        digitalWrite(RED, LOW);
        delay(100);
      }
    }

The problem now is that it seems to initialize (`bmp.begin()` returns 1), but the sensor is still not reading a correct value (either 0.0 for both pressure and temperature, or a large negative pressure and very large temperature (-2602 Pa, 185°C). What might be the problem? I have tried it with another sensor of the same type, same result. Where else can I attach the CS wire to?

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

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

body:
The software must be OK, because it runs on the other board, so it has to be a hardware fault. The sensor is OK, because it works on the other board. Assuming the board isn't defective then it must be the way you have connected it.

You haven't included your pin designations. Some Ethernet shields use certain pins and prevent them being used by other devices. Is it possible that this could be the cause of you problems?


message:
problem in integrating the slave code in attiny 84

I tried the whole process by using two arduino unos.It worked perfectly.
Though when i tried to replace the slave uno with attiny 84 uC it showed following errors in compiling.

    Arduino: 1.6.7 (Windows 7), Board: "ATtiny24/44/84, ATtiny84 @ 1 MHz  (internal oscillator; BOD disabled)"

    WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
    C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void setup()':

    sketch_may12c:12: error: 'SPCR' was not declared in this scope

       SPCR |= bit (SPE);

       ^

    In file included from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/WProgram.h:12:0,

                     from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/Arduino.h:4,

                     from sketch\sketch_may12c.ino.cpp:1:

    sketch_may12c:12: error: 'SPE' was not declared in this scope

       SPCR |= bit (SPE);

                    ^

    C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/wiring.h:158:25: note: in definition of macro 'bit'

     #define bit(b) (1UL << (b))

                             ^

    sketch_may12c:15: error: 'MISO' was not declared in this scope

       pinMode (MISO, OUTPUT);

                ^

    sketch_may12c:22: error: expected unqualified-id before '.' token

       tinySPI.attachInterrupt();

              ^

    C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void SPI_STC_vect()':

    sketch_may12c:30: error: 'SPDR' was not declared in this scope

     byte c = SPDR;  // grab byte from SPI Data Register

              ^

    exit status 1
    'SPCR' was not declared in this scope

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

body:
You are trying to compile the wrong program for the wrong chip.

The nice thing about the Arduino core library is that it enables you to
write code that is portable across various Arduino boards. However, this
library provides very limited access to the capabilities of the
underlying hardware. Then, it is quite common for users to mix Arduino
code with C statements that directly access the hardware registers.
Doing this provides full control over the hardware, at the cost of
reduced portability.

Just an example from your code:

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

    SPCR |= bit (SPE);

This line is accessing the control register of the SPI port (SPCR means
“SPI Control Register”) in order to set to 1 the bit named SPE (for “SPI
Enable”). This is the “bare metal” way of turning on the SPI port.

Now, your problem is that, unlike the ATmega328P powering your Unos, the
ATtiny84 does _not_ have a hardware SPI port. Thus the line above just
makes no sense.

The solution: you have to figure out some other means for your chip to
talk SPI. You could emulate it purely in software, but it would
certainly be more efficient to use the USI port. The USI (“Universal
Serial Interface”) is a multipurpose serial port found in many ATtinies.
It can be configured to do SPI, I2C or simplex/half-duplex UART.

Recommended readings:

* [AVR319: Using the USI module for SPI
  communication](http://www.atmel.com/images/doc2582.pdf), an
  application note by ATmel
* [Using an ATtiny2313/4313 as SPI
  master](http://playground.arduino.cc/Code/USI-SPI) on the Arduino
  Playground

You may be able to find ready-made libraries for doing this.


message:
Arduino Mousecontroller library doesn't work

I am working on a project with the Mousecontrol library. This causes me a lot of problems with loading the library. I imported the library but it gives me errors everytime. I think it is a mistake in the library folders but I can't seem to figure it out.

    #include <MouseController.h>

    // Initialize USB Controller
    USBHost usb;

    // Attach mouse controller to USB
    MouseController mouse(usb);

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

    void loop(){
      usb.Task();
    }

    void mouseMoved() {
      Serial.print("Move: ");
      Serial.print(mouse.getXChange());
      Serial.print(", ");
      Serial.println(mouse.getYChange());
    }

I get this error:

    Arduino: 1.6.0 (Mac OS X), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    In file included from /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/MouseController.h:22:0,
                     from Muis_Bevrijding.ino:1:
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*)':
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:62: error: 'UOTGHS_HSTPIPCFG_PTYPE_INTRPT' was not declared in this scope
       pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                  ^
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:93: error: 'UOTGHS_HSTPIPCFG_PTOKEN_IN' was not declared in this scope
       pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:151: error: 'UOTGHS_HSTPIPCFG_PBK_1_BANK' was not declared in this scope
       pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: there are no arguments to 'UHD_Pipe_Alloc' that depend on a template parameter, so a declaration of 'UHD_Pipe_Alloc' must be available [-fpermissive]
       pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual uint32_t HIDBoot<BOOT_PROTOCOL>::Release()':
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: there are no arguments to 'UHD_Pipe_Free' that depend on a template parameter, so a declaration of 'UHD_Pipe_Free' must be available [-fpermissive]
      UHD_Pipe_Free(epInfo[epInterruptInIndex].hostPipeNum);
                                                          ^
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'uint32_t HIDBoot<BOOT_PROTOCOL>::Release() [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
    Muis_Bevrijding.ino:22:1:   required from here
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: 'UHD_Pipe_Free' was not declared in this scope
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*) [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
    Muis_Bevrijding.ino:22:1:   required from here
    /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: 'UHD_Pipe_Alloc' was not declared in this scope
       pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^

Thanks a lot for your time!

body:
> # USBHost
> ### Compatible with Arduino Due only

source


message:
Simple memory chip for Arduino?

My basic question is: **What is a good alternative to EEPROM chips for external memory on the Arduino Unor R3?**

I know that there are EEPROM chips when one would like an external memory chip. It, in fact, seems like this is the standard choice. I am wondering if there are any other good ways to work with external memory. Are there, for example, memory chips that work a bis simpler? Like, a chip that doesn't require any specific libraries in the Arduino?

(I do not have extensive experience working with the Arduino.)

body: No. There is no external memory interface on the ATmega328P, so all external memory requires some sort of library to use.


body:
There is no DRAM, SRAM nor flash interface in ATmega, so you can't extend your chip memory. You can only connect serial (SPI, I2C) or parallel memory (usind GPIO).

Neither SPI nor I2C require any specific libraries.
SPI is much simpler to program than I2C and much faster, but require more wires.

Instead of using rather slow EEPROM, you can try FRAM (non-volatile) or SRAM (volatile, but may be battery-sustained). They are usually available with the same interface as EEPROM, but don't suffer from limited number of erase cycles. FRAM can withstand ridiculous number of erasures, SRAM is virtually indestructible.


body: Personally I like the Amtel 24C256 chip/module. It is I2C enabled and the standard Wire library is all you need to talk to it. It is 256 bits or 32K 8 bit bytes in size. Data is sent and read in byte chunks. Addressing is at the bit level. It can run on 3.3V and 5V. Ebay has a bunch of suppliers for it. There's a number of good How-To's on line.


message:
Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error

I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:

`C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
        -i -d --port=COM4 -U false -e
        -w true
        -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
        -R bossac.exe: extra arguments found
    Try 'bossac.exe -h' or 'bossac.exe --help' for more information`

body:
I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).

This error occurred because of the **true** after the **-w** switch. To fix it I modified the package to tell the IDE not to use that switch.

 1. Go to: `%USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8` (where `%USER_PROFILE%` is your windows user directory, for me it was `C:\Users\user`) in Windows Explorer.
 2. Make a copy of the platform.txt file (I called it platform_backup.txt).
 3. Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:

    `tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R`

 4. This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:

    `tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R `

 5. Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.


body:
Tim's solution is also applicable to Version 1.6.9 of the SAM tools. I just installed it in my Arduino IDE V1.6.8 and had the same parameter problem as originally reported. Following Tim's solution fixed the problem right away. As this is clearly a configuration issue on the Arduino IDE side, it should happen on any supported Windows platform, mine was Windows 7.
The only difference I encountered was the path to the SAM tools directory. On my Enterprise version of Win7, the path was not in `AppData\Roaming` but in `AppData\Local` , so
`%USER_PROFILE%\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\` for the full pathname.


body:
There's a better option:

(For Windows)

1/ Download the latest IDE release.

2/ Uninstall the IDE completely.

3/ Reboot PC

4/ Go to %USER_PROFILE%\AppData\Local\Arduino15 and delete it (the entire folder). If the path doesn't match then find it in AppData folder, it's in there somewhere.

5/ Reinstall the IDE, problem fixed.


body:
I tried this solution in linux Fedora, it worked fine, but the location of the file "platform.txt" was
`/home/{user}/.arduinoxx/packages/arduino/hardware/sam`
It is a hidden folder, so make it visible so you can handle it. No sudo access was necessary.


message:
How to store a function in a constant?

I'm trying to do something to this affect:

`const string first_color = strip.Color(0, 60, 0, 0);`

With the intended outcome being that I could use `first_color` wherever I'd have used `strip.Color(0, 60, 0, 0)` before.

body:
You pretty much need a helper function to do that; a small local function that calls `strip.Color()` with the intended arguments and returns `strip.Color()`'s return value if there is any.

    int first_color(void)
    {
       return(strip.Color(0, 60, 0, 0));
    }

(assuming `strip.Color()` returns an `int`) which you would call with:

    value = first_color();

If `strip.Color()` is a `void` function, then delete the 'return(' and one ')', fix the definition of first color to be `void` instead of `int`, and of course, don't try to use any return value from `first_color()`.


body:
It sounds like you might want a preprocessor macro:

    #define FIRST_COLOR strip.Color(0, 60, 0, 0)

And then later

    FIRST_COLOR;

This is basically just text substitution at the initial stage of the compilation process.  It is somewhat conventional to make macros all caps, but not required.  You can also define function-like macros which take arguments.


message:
AVR-STL Library

I have a project that I need to use a vector, I have tried to get several libraries to compile with out luck. The one that has gotten the closest is  [Andy Brown's AVR-STL][1]. I keep getting the error:

    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'

I am sure that this is a simple fix, I just have no idea how. If this library is no longer viable then can someone else recommend another one?

Here is the code I am trying to compile

    #include "Arduino.h"
    #include "iterator"
    #include "vector"
    #include "pnew.cpp"

    std::vector<int> test;

    void setup(void) {

     Serial.begin(57600);
    }

    void loop(void) {

     test.push_back(1);
     Serial.println("Pushed");
    }

And the full output:

    14:57:27 **** Incremental Build of configuration Release for project MegaTesting ****
    "C:\\Eclipse\\eclipse\\arduinoPlugin\\tools\\make\\make" all
    'Building file: ../.ino.cpp'
    'Starting C++ compile'
    "C:\Eclipse\eclipse\arduinoPlugin\tools\arduino\avr-gcc\4.8.1-arduino5/bin/avr-g++" -c -g -Os -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR     -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\cores\arduino" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\variants\mega" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility" -MMD -MP -MF".ino.cpp.d" -MT".ino.cpp.o" -D__IN_ECLIPSE__=1 -x c++ "../.ino.cpp"  -o  ".ino.cpp.o"   -Wall
    cc1plus.exe: warning: C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility: not a directory [enabled by default]
    In file included from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/stl_iterator_base.h:38:0,
                     from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/iterator:40,
                     from ../.ino.cpp:8:
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _TrivialIterator_concept_specification<_TrivialIterator>::_TrivialIterator_requirement_violation(_TrivialIterator)':
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:572:16: warning: typedef '__T' locally defined but not used [-Wunused-local-typedefs]
         value_type __T;
                    ^
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _Allocator_concept_specification<_Alloc>::_Allocator_requirement_violation(_Alloc)':
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:799:39: warning: typedef '_Tp' locally defined but not used [-Wunused-local-typedefs]
       typedef typename _Alloc::value_type _Tp;
                                           ^
    In file included from ../MegaTesting.ino:3:0,
                     from ../.ino.cpp:14:
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp: In function 'void* operator new(size_t, void*)':
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'
     void* operator new(size_t size_,void *ptr_){
           ^
    In file included from ../.ino.cpp:10:0:
    C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: 'void* operator new(size_t, void*)' previously defined here
     void* operator new(size_t size_,void *ptr_){
           ^
    subdir.mk:24: recipe for target '.ino.cpp.o' failed
    make: *** [.ino.cpp.o] Error 1

    14:57:28 Build Finished (took 600ms)

  [1]: http://andybrown.me.uk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/

body:
It looks like `new` is redefined. I see that you include `cpp` file, that contains *implementation* - this is rather unfortunate design, but that's how it is done.

Anyway, it seems that this file is already being compiled elsewhere. Have you tried to remove this include? What happens if you remove it?

Apart from that problem, you must be aware that dynamic memory management in such small system yelds risk of memory fragmentation that eventually leads to failed allocations.


message:
How did I burn out this ESP8266 unit?

ESP8266 -> FTDI -> USB Mac

I followed the wiring on this page: http://williamdurand.fr/2015/03/17/playing-with-a-esp8266-wifi-module/

[![ESP8266 to FTDI Wiring][1]][1]

I was communicating with it via Serial at 115200.  I issued a `AT+UART_DEF=9600,8,1,0,0` and a few seconds later I looked over and it was smoking.

[![Burnt ESP8266][2]][2]

I bought 2 of these.  The previous one I had wired to an Arduino Nano running through a logic level converter.  That one only returns `Exception (28)` over and over again after issuing that same command.

On both units `AT+GMR` returned:

    AT+GMR
    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0

Are these units too hard to use? What did I do to burn it out?

[UPDATE]

Answer given was that I fed it 5v instead of 3.3v. Obvious. I didn't think I did but I checked the output of the FTDI and sure enough it was 5.1v.  So why does the output on it say 3V3 ?  I thought that meant that it was 3.3v...

[![3V3 Doesn't mean 3.3v?][3]][3]

Should have checked it first.

  [1]: https://i.stack.imgur.com/XAhbE.png
  [2]: https://i.stack.imgur.com/GIe82.jpg
  [3]: https://i.stack.imgur.com/otZDR.jpg

body: You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.


body:
I checkmarked Ignacio's answer because it was correct.  But I wanted to leave an answer also as to HOW I supplied 5v when I thought I was supplying 3.3v.  Maybe it will help someone else.

[![FTDI backside showing 3.3 or 5v jumpers][1]][1]

The backside of this FTDI module has a jumper to select 3.3 or 5v and the default is set to 5v.  I needed to cut the default trace line connecting to 5v and solder my own jumper to switch it to 3.3v.  I should have double checked the voltage before powering it up.  New ESP01's on order.

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