body:
> My RF units are both nrf24l01. I have tried working with the sample
> code and I think the issue is I don't understand how the unit works
> well enough.

[Start here, this is the absolutely best resource][1] I could find. I use MIRF libary and there are [send and receive examples][2].  They are really, really simple. Get them working first.

> What is the nature of the data sent between units? I want to send
> integers, possibly even text. Is that possible? Do I need to convert
> to binary or something?

*Technically*, you send between 1 and 32 *bytes* of information. However, the libraries (see examples above) will take care of the technicality and allow you to send nums, chars or strings.

> My understanding of "ping" and "pong" is that ping sends a message
> then pong sends that same message back to ping... is this correct?

Not necessarily. Since [tag:NRF24L01+] does all the signal checking for you, and you know that your TX device is the only one sending, you can just reply with "data received".

Anyways, why are even concerned with this? Pinging and ponging have nothing to do with your task at hand.

> Are RF units very different? Is this one particularly difficult?

Yes, they are different in frequencies, protocols, power etc. No, this one isn't. It's an amazing, cheap and robust piece of Norwegian ingenuity.

> If I just want to send with one receive with the other shouldn't this
> simplify the code?

Simplify compared to what exactly? It will simplify the code compared to a two-way communication, obviously.

> What are pipes? How many can I open?
As someone said before me, read the bloody manual, or a tutorial, or the data sheet, or something. The answer is 6.

Any unit can send on ONE pipe and receive on SIX pipes. Imagine having 6 phones on your table. You can simultaneously listen to all 6 phones but you can only TALK INTO ONE. You can choose which one to talk into to, at any point. Unless you have a lot of devices talking to each other (more than TWO), don't bother, forget the pipes.

> If I have 3 or more of these what changes will I need to make to the
> code?

Get two Arduinos talking to each other first. No one has succeeded at making anything work by getting ahead of themselves.

Now here is [a video of two Arduinos talking][3]. There's only one button but you can easily change it to a 20-button setup.

The code for sending:

<!-- language-all: lang-C++ -->

    #include <SPI.h>
    #include <Mirf.h>
    #include <MirfHardwareSpiDriver.h>
    #include <MirfSpiDriver.h>
    #include <nRF24L01.h>

    const int buttonPin = 2;
    const int ledPin =  3;

    // sends a string via the nRF24L01
    void transmit(const char *string)
    {
      byte c;

      for( int i=0 ; string[i]!=0x00 ; i++ )
      {
        c = string[i];
        Mirf.send(&c);
        while( Mirf.isSending() ) ;
      }
    }

    void setup() {
      //RADIO
      Serial.begin(9600);
      Mirf.spi = &MirfHardwareSpi;
      Mirf.init();
      Mirf.payload = 1;
      Mirf.channel = 90;
      Mirf.config();
      Mirf.configRegister(RF_SETUP,0x06);
      Mirf.setTADDR((byte *)"serv1");

      //BUTTON AND LED
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);

      Serial.println("Sending ... ");
    }

    void loop() {
      int buttonState = digitalRead(buttonPin);
       if (buttonState == LOW) { //pressed
        digitalWrite(ledPin, HIGH);
        transmit("X");
      }
      else {
        digitalWrite(ledPin, LOW);
      }
    }

The code for receiving:

    #include <SPI.h>
    #include <Mirf.h>
    #include <MirfHardwareSpiDriver.h>
    #include <MirfSpiDriver.h>
    #include <nRF24L01.h>

    unsigned long lasttime;
    unsigned long delaytime;
    unsigned long time;
    const int ledPin = 3;

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

      //RADIO
      Mirf.spi = &MirfHardwareSpi;
      Mirf.init();
      Mirf.setRADDR((byte *)"serv1");
      Mirf.payload = 1;
      Mirf.channel = 90;
      Mirf.config();
      Mirf.configRegister(RF_SETUP,0x06);

      //LED
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, HIGH);
      Serial.println("Listening ... ");
    }

    void loop() {
      byte c;

      if( Mirf.dataReady() ) {
        Mirf.getData(&c);
        Serial.write(c);

        if (c == 'X') {
          digitalWrite(ledPin, HIGH);
        }
      } else {
          digitalWrite(ledPin, LOW);
      }
    }

  [1]: https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
  [2]: https://arduino-info.wikispaces.com/nRF24L01-Mirf-Examples
  [3]: https://www.youtube.com/watch?v=plDPBVjcckw


sender: user

message:
Toggle Button For LED Strip not executing properly

I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.

    #include "LPD8806.h"
    #include "SPI.h" // Comment out this line if using Trinket or Gemma
    #ifdef __AVR_ATtiny85__
    #include <avr/power.h>
    #endif

    int nLEDs = 160;

    // Chose 2 pins for output; can be any valid output pins:
    int dataPin  = 2;
    int clockPin = 3;

    // First parameter is the number of LEDs in the strand.  The LED strips
    // are 32 LEDs per meter but you can extend or cut the strip.  Next two
    // parameters are SPI data and clock pins:
    LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);

    int inPin = 4;
    boolean lastState = LOW;//storage for last button state

    void setup(){
       pinMode(inPin, INPUT);//this time we will set the pin as INPUT
       Serial.begin(9600);//initialize Serial connection
       #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
       clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
       #endif

       strip.begin();
       // Update the strip, to start they are all 'off'
       strip.show();

     }

    void loop(){

       if (digitalRead(inPin) == HIGH && lastState == LOW){//if button has just
       been pressed
       // Start up the LED strip
            theaterChase(strip.Color(127, 127, 127), 50); // White
            delay(100);
        } else if(digitalRead(inPin) == LOW && lastState == HIGH){
            digitalWrite(dataPin, LOW);
            digitalWrite(clockPin, LOW);
        }
        lastState = digitalRead(inPin);
        }

        //Theatre-style crawling lights.
        void theaterChase(uint32_t c, uint8_t wait) {
             for (int j=0; j<10; j++) {  //do 10 cycles of chasing
                  for (int q=0; q < 3; q++) {
                       for (int i=0; i < strip.numPixels(); i=i+3) {
                          strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();

          delay(wait);

          for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
      }

sender: assistant

body:
<!-- language-all: lang-C++ -->

If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:

[![Floating input on switch][1]][1]

There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:

[![Pull-down resistor][2]][2]

There are other possible techniques as discussed on [this page](http://gammon.com.au/switches).

One is to change:

       pinMode(inPin, INPUT);//this time we will set the pin as INPUT

to:

       pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT

Then wire the switch to **ground**, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.

  [1]: https://i.stack.imgur.com/dbixU.png
  [2]: https://i.stack.imgur.com/eYepo.png


message:
Arduino LED lighting up when signal is reading low on multimeter

My code is designed to play a tone when ever pin 3 is high on my Arduino. When I am examine the pins voltage with a multimeter it is always reading below 1 volt. When I examined the voltage off of a osiliscope it is reading the voltage pretty steady at 0.2 to 0.3.

**My multimeter reads at 0.26**

[![][1]][1]:

**My code is:**

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    }
    void loop() {
      // put your main code here, to run repeatedly:
    int input = digitalRead(3);
    Serial.println(input);
    if(input == 1){
      tone(A5,4000);
      }
    }

**My board looks like:**
[![enter image description here][2]][2]
**The bottom of the board looks like:**
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/VDZrq.jpg
  [2]: https://i.stack.imgur.com/WxcKw.jpg
  [3]: https://i.stack.imgur.com/VmlpH.jpg

body:
You left pin 3 floating. The multimeter will lower the voltage, resulting the the led lighting. Try enabling the pull-up resistor in pin 3 by adding `pinMode(3, INPUT_PULLUP)`.

PS you might want to add a resistor in series with that led, or it will burn out and/or damage pin 3 on the arduino.


message:
Does SMS format depend on the sender's mobile?

I want to read the SMS using Arduino and GSM module, I want to perform conditional programming based on the received SMS.

What I found really interesting is SMS format is different if I send message from different phones.

Output of my code is

Case 1:(From a smartphone)

Mobile Number is: +91954xxxxxxx
Message Text: 5+22" Hello Arduino

Case 2:(From a normal phone)

Mobile Number is: +91984yyyyyyy
Message Text: Hello Arduino

----

Does it really depend on the sender's mobile phone? If yes, how to move further to make my code independent on the sender mobile.

----
My code is

    //===final code

    char RcvdMsg[200] = "";
    int RcvdCheck = 0;
    int RcvdConf = 0;
    int index = 0;
    int RcvdEnd = 0;
    char MsgMob[15];
    char MsgTxt[50];
    int MsgLength = 0;

    void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
    {
       delay(1000);
       Serial.print("ATE0\r");
       Response();
       Serial.print("AT\r");
       Response();
       Serial.print("AT+CMGF=1\r");
       Response();
       Serial.print("AT+CNMI=1,2,0,0,0\r");
       Response();
    }

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

    void loop()
    {
       RecSMS();
    }

    void Response() // Get the Response of each AT Command
    {
       int count = 0;
       Serial.println();
       while(1)
       {
          if(Serial.available())
          {
             char data =Serial.read();
             if(data == 'K'){Serial.println("OK");break;}
             if(data == 'R'){Serial.println("GSM Not Working");break;}
          }
          count++;
          delay(10);
          if(count == 1000){Serial.println("GSM not Found");break;}

       }
    }

    void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
    {
       if(Serial.available())
       {
          char data = Serial.read();
          if(data == '+'){RcvdCheck = 1;}
          if((data == 'C') && (RcvdCheck == 1)){RcvdCheck = 2;}
          if((data == 'M') && (RcvdCheck == 2)){RcvdCheck = 3;}
          if((data == 'T') && (RcvdCheck == 3)){RcvdCheck = 4;}
          if(RcvdCheck == 4){RcvdConf = 1; RcvdCheck = 0;}

          if(RcvdConf == 1)
          {
             if(data == '\n'){RcvdEnd++;}
             if(RcvdEnd == 3){RcvdEnd = 0;}
             RcvdMsg[index] = data;

             index++;
             if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
             if(RcvdConf == 0)
             {
                Serial.print("Mobile Number is: ");
                for(int x = 4;x < 17;x++)
                {
                   MsgMob[x-4] = RcvdMsg[x];
                   Serial.print(MsgMob[x-4]);
                }
                Serial.println();
                Serial.print("Message Text: ");
                for(int x = 46; x < MsgLength; x++)
                {
                   MsgTxt[x-46] = RcvdMsg[x];
                   Serial.print(MsgTxt[x-46]);
                }

                Serial.println();

                //****Resetting all the variables*****//

                //RcvdMsg[200]={0};
                RcvdCheck = 0;
                RcvdConf = 0;
                index = 0;
                RcvdEnd = 0;
                MsgMob[15];
                MsgTxt[50];
                MsgLength = 0;

                Serial.flush();

             }
          }
       }
    }

body:
If you're not trying to capture the mobile number or whatever SMS text was sent, but only react to specific SMS messages, then don't try to parse the whole message, but design the protocol between any arbitrary phone and your Arduino to be detectable independent of everything else, e.g.:

    #L 5 on        ; set an LED state

    #M 3 137       ; set a motor speed


message:
Arduino Uno not Detecting on Laptop

I have an Arduino Uno. The story is I installed Arduino IDE and Drivers before even buying an Arduino Board. I used it a little and when I bought and connected an arduino board, I was unable to make it detect. I smacked a little usimg google and was able to somehow Fix this. but again another day, It worked a little and started creatimg problems. now its not detecting. Please suggest me a way To make it work...
Should I format my windows 7 and Reinstall all the drivers as per rules?

body:
under the IDE make sure you have set the correct board and comm port. go to tools>>board then choose your board then tools>>Comm to choose the correct comm port.

is the IDE saying anything about having problems connecting to the board?

and no re-installing all drivers should not be necessary.


message:
Arduino messing up as slave over I2C

I have an Arduino Mega2560 and a Raspberry Pi hooked up through I2C. The Pi is acting as the master, while the Arduino is the slave. While sending data over I2C, the int message gets messed up and will either send the address or the data. Then I can't even receive any useful data from the Arduino.

So if I turn the receiving function off it sends the data just fine, but when I ask the Pi to start receiving data again it slows down the entire bus and data starts conflicting between the Pi and Arduino. Also it only happens with the Arduino. Every other device works flawlessly.

Here's what my code looks like on the Pi side. I'm using SMBus to send and receive bytes. I didn't bother to put up code for it because I don't have the source code for SMBus. I just trust that they work because my other I2C devices work without a hitch.

    while True:
        #if alternating == true then get the imu if not then get the motor speed
        if alternating == True:
            try: #need the try because an error will stop the program completely
                ypr = IMU.getYPR()
                yaw = int(ypr['yaw'] * 180 / math.pi)
                savedYaw = yaw
            except:
                yaw = savedYaw
                #print "exception"
                pass
                #write yaw to arduino
                i2c.writeByte(yaw)
                alternating = False
            else:
                #start reading data from arduino
                #readArduino()
                alternating = True
                pass

Then on the Arduino side these are my `onReceive` and `onRequest` functions:

<!-- language-all: lang-C++ -->

    void readPI(int byteC) {
        if(Wire.available()) {
            reference = Wire.read();
        }
        pid1.getReference(reference);
        pid2.getReference(reference);
    }

    void sendPI() {
        int values[] = {(int)out, (int)outReversed  };
        Wire.write(values[count]);
        count++;
        if(count > 1) {
            count = 0;
        }
    }

Is there something about the Arduino that I don't know? Maybe it's a timing issue? Is there a way to set up registers? I can either receive or send, but I can't do both, and Googling the problem only leads to an example of someone sending 1 - 9 over the Pi. I can't find examples of anyone actually doing something complicated with an Arduino and a Rasp Pi over I2C. Any and all help would be amazing!

body:
<!-- language-all: lang-C++ -->

I find your onRequest function obscure:

    void sendPI(){
         int values[] = {(int)out, (int)outReversed  };

         Wire.write(values[count]);
         count++;
         if(count > 1){
         count = 0;

         }
     }

Why only send one byte? I think you have a number of problems:

* The size of `int` on the Arduino Uno is 2 bytes, on a Pi it is 4 bytes. So there is a mismatch there for a start.

* `Wire.write` (written like that) sends one byte, so that is only going to be half of your `int`. So that is even less.

* It isn't obvious what the Pi end is doing, but to make the `int` sizes match, I would be sending the lot in one hit like this:

        void sendPI(){
             long values[] = {(int)out, (int)outReversed  };
             Wire.write((byte *) &values, sizeof values);
         }

    Now you just read 8 bytes on the Pi (two ints).


message:
Tone() working on all digital pins?

Looking at my Arduino Uno board, it appears the digital PWM pins are #11, #10, #9, #6, #5 and #3.

When playing around with the Theremin, it seems that the `Tone()` message works on all pins regardless of whether they are marked PWM or not?

Can anyone explain what is happening or how this is possible?

body:
The Tone library doesn't use the PWM mode timer functions on the atmega, instead it uses an interrupt routine to toggle the pins. You can find the source code for Tone libary here for reference:

https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/


message:
Will the Uno bootloader work in the Duemilanove?

I had an old duemilanove lying around (Which was not working because i accidentially busted the atmega) and I recently bought some atmegas pre-flashed with the UNO bootloader. So I tried to put one of those in it, and it seems to work fine except that I have to select the UNO board in the arduino IDE.

My question is: Is there anything problematic to be aware of when using the UNO bootloader in an duemilanove?

body:
So I researched it a bit, and there does not seem to be any problems with running the UNO bootloader on a Duemilanove board.

The biggest difference between the two seems to be the USB interface:

**USB interface**

Duemilanove uses FTDI, UNO uses another microcontroller (ATmega8u2).

Since the USB to serial is transparent for me as an end user for the most parts, it doesn't really matter to me.

**Leaner bootloader**

The UNO bootloader is smaller than the duemilanove.


message:
Passing class member function as argument

I need to pass a class member function to server.on, unfortunately i get an error.

> error: no matching function for call to 'ESP8266WebServer::on

I have done some searching but could not understand anything I found. No simple explanation.

This works:

    void handleRoot(){}
    server.on("/", handleRoot);

This doesn't:

    void myClass::handleRoot(){}
    void myClass::setup(){
        server.on("/", handleRoot);
    }

The second argument to server.on is

    typedef std::function<void(void)> THandlerFunction;

Unfortunately I have no idea what it means.

body:
It's quite common question related to C++ programming.

The extensive explanation can be found [here][1].

The short answer is: it's very different from taking the address of a regular function.

Workarounds (that might or might not work for you, depending on what else you need that function to do) are:

 - make it static
 - declare it as friend function, rather than member function

Either way, the point is that it should not be something associated to an instance of the class, but rather to the class as a whole.

  [1]: http://www.parashift.com/c++-faq/pointers-to-members.html


body:
I've ben hitting this same problem.
Some further research on c++ syntax helped me find this clean solution, based on the

std::bind syntax:

    server.on("/", std::bind(&myClass::handleRoot, this));


body:
This will get the job done - using anonymous function syntax:

    server->on("/", [&]() {
       handleRoot();
    });


message:
Reading RFID tags with Arduino IDE, not using Arduino

I am completely new to this technology, but I'm hoping to build a fairly simple program through the Arduino IDE that takes the serial numbers of RFID cards read through my ID-20LA Innovations RFID reader and send those serial numbers to an API endpoint all through the IDE (as in without using a physical Arduino).

Is this possible? Are there any tutorials out there that walk through a stripped down version of this? I don't know where to start code wise, and all tutorials I've found use physical Arduinos to accomplish this.

body:
**Short answer:**
NO

**Long Answer:**

Option 1:
 Use a USB RFID reader and create a basic processing/python/<place your preferred language here> app to read from the USB RFID reader and post it where ever you want it to

Option 2:
Use the arduino to read from the ID-20LA and send the data via UART to your computer and then create a windows app using processing/python/<place your preferred language here> to send it to your API endpoint

Option 3:
Use the arduino YUN to read from the ID-20LA and then create a basic python program to run on the YUN itself. Such that it will read data from the atmel microcontroller (on the YUN) and post it to your API endpoint. This is a much cleaner yet slightly more expensive way of doing this.


message:
Can't get Arduino Leonardo working as a USB keyboard in Windows 7

I can't believe I am stumped by this, but this is my issue and I can't see any other solution for this anywhere.

I have an official Arduino Leonardo loaded up with the following code:

    void setup() {
      Keyboard.begin();
    }

    void loop() {
      char keyToPress = random('A', 'Z'); // choose a random letter between 'A' and 'Z'
      delay(1900);
      Keyboard.press(keyToPress);
      delay(100);
      Keyboard.release(keyToPress); // overall loop time is ~2s, with a 100mS keypress length
    }

On OSX and Linux, I get a predictable output - random capital letters typed by a keyboard, two seconds apart: FWTDXJP etc.

However, on Windows 7(x64), I get... nothing. I have the Leonardo appear correctly as a CDC COM port, drivers were installed from the latest 1.6.5 installer on their website. I have tried uninstalling the Leonardo in device manager while checking the "remove software" box so as to be sure that the driver I install is the one being used.

Has anyone seen this before? A search of the Arduino forum reveals some people having the same issue, a bit of a discussion and then usually "I don't know what I did but the problem has gone now".

This is the output from [USB Device Tree Viewer][1], which seems to correctly show the USB HID descriptor:

        =========================== USB Port2 ===========================

    Connection Status        : 0x01 (Device is connected)
    Port Chain               : 1-2

          ======================== USB Device ========================

            +++++++++++++++++ Device Information ++++++++++++++++++
    Friendly Name            : Arduino Leonardo (COM3)
    Device Description       : Arduino Leonardo
    Device Path              : \\?\usb#vid_2341&pid_8036#5&18f54cb7&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
    Device ID                : USB\VID_2341&PID_8036\5&18F54CB7&0&2
    Driver KeyName           : {4d36e978-e325-11ce-bfc1-08002be10318}\0001 (GUID_DEVCLASS_PORTS)
    Driver                   : C:\Windows\system32\DRIVERS\usbser.sys (Version: 6.1.7601.18247  Date: 2013-08-29)
    Driver Inf               : C:\Windows\inf\oem6.inf
    Legacy BusType           : PNPBus
    Class                    : Ports
    Service                  : usbser
    Enumerator               : USB
    Location Info            : Port_#0002.Hub_#0001
    Location IDs             : PCIROOT(0)#PCI(0600)#USBROOT(0)#USB(2)
    Container ID             : {2d5fa232-297c-11e5-9565-080027ccdb00}
    Manufacturer Info        : Arduino LLC (www.arduino.cc)
    Capabilities             : 0x84 (Removable, SurpriseRemovalOK)
    Address                  : 2
    Problem Code             : 0
    Power State              : D0 (supported: D0, D3, wake from D0)
    COM-Port                 : COM3 (\Device\USBPDO-3)

            ---------------- Connection Information ---------------
    Connection Index         : 0x02 (2)
    Connection Status        : 0x01 (DeviceConnected)
    Current Config Value     : 0x01
    Device Address           : 0x02 (2)
    Is Hub                   : 0x00 (no)
    Number Of Open Pipes     : 0x04 (4)
    Device Bus Speed         : 0x01 (Full-Speed)
    Pipe0ScheduleOffset      : 0x04 (4)
    Pipe1ScheduleOffset      : 0x00 (0)
    Pipe2ScheduleOffset      : 0x00 (0)
    Pipe3ScheduleOffset      : 0x00 (0)

            ------------------ Device Descriptor ------------------
    bLength                  : 0x12 (18 bytes)
    bDescriptorType          : 0x01 (Device Descriptor)
    bcdUSB                   : 0x200 (USB Version 2.00)
    bDeviceClass             : 0x02 (Communications and CDC Control)
    bDeviceSubClass          : 0x00
    bDeviceProtocol          : 0x00
    bMaxPacketSize0          : 0x40 (64 bytes)
    idVendor                 : 0x2341
    idProduct                : 0x8036
    bcdDevice                : 0x100
    iManufacturer            : 0x01 (String Descriptor 1)
     Language 0x0409         : "Arduino LLC"
    iProduct                 : 0x02 (String Descriptor 2)
     Language 0x0409         : "Arduino Leonardo"
    iSerialNumber            : 0x00 (No String Descriptor)
    bNumConfigurations       : 0x01

            ------------------ String Descriptors -----------------
                 ------ String Descriptor 0 ------
    bLength                  : 0x04 (4 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language ID[0]           : 0x0409 (English - United States)
                 ------ String Descriptor 1 ------
    bLength                  : 0x18 (24 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language 0x0409          : "Arduino LLC"
                 ------ String Descriptor 2 ------
    bLength                  : 0x22 (34 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language 0x0409          : "Arduino Leonardo"

            -------------- Configuration Descriptor ---------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x02 (Configuration Descriptor)
    wTotalLength             : 0x0064 (100 bytes)
    bNumInterfaces           : 0x03
    bConfigurationValue      : 0x01
    iConfiguration           : 0x00 (No String Descriptor)
    bmAttributes             : 0x80
     D7: Reserved, set 1     : 0x01
     D6: Self Powered        : 0x00 (no)
     D5: Remote Wakeup       : 0x00 (no)
     D4..0: Reserved, set 0  : 0x00
    MaxPower                 : 0xFA (500 mA)

            ------------------- IAD Descriptor --------------------
    bLength                  : 0x08 (8 bytes)
    bDescriptorType          : 0x0B
    bFirstInterface          : 0x00
    bInterfaceCount          : 0x02
    bFunctionClass           : 0x02 (Communications and CDC Control)
    bFunctionSubClass        : 0x02
    bFunctionProtocol        : 0x01
    iFunction                : 0x00 (No String Descriptor)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x00
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x01 (1 Endpoint)
    bInterfaceClass          : 0x02 (Communications and CDC Control)
    bInterfaceSubClass       : 0x02
    bInterfaceProtocol       : 0x00
    iInterface               : 0x00 (No String Descriptor)

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x00 (Header Functional Descriptor)
    bcdCDC                   : 0x110 (CDC Version 1.10)

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x01 (Call Management Functional Descriptor)
    bmCapabilities           : 0x01
    bDataInterface           : 0x01

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x04 (4 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x02 (Abstract Control Management Functional Descriptor)
    bmCapabilities           : 0x06

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x06 (Union Functional Descriptor)
    bControlInterface        : 0x00
    bSubordinateInterface[0] : 0x01

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x81 (Direction=IN  EndpointID=1)
    bmAttributes             : 0x03 (TransferType=Interrupt)
    wMaxPacketSize           : 0x0010 (16 bytes) (16 bytes)
    bInterval                : 0x40 (64 ms)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x01
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x02 (2 Endpoints)
    bInterfaceClass          : 0x0A (CDC-Data)
    bInterfaceSubClass       : 0x00
    bInterfaceProtocol       : 0x00
    iInterface               : 0x00 (No String Descriptor)

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x02 (Direction=OUT  EndpointID=2)
    bmAttributes             : 0x02 (TransferType=Bulk)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x00 (ignored)

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x83 (Direction=IN  EndpointID=3)
    bmAttributes             : 0x02 (TransferType=Bulk)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x00 (ignored)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x02
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x01 (1 Endpoint)
    bInterfaceClass          : 0x03 (HID - Human Interface Device)
    bInterfaceSubClass       : 0x00 (None)
    bInterfaceProtocol       : 0x00 (None)
    iInterface               : 0x00 (No String Descriptor)

            ------------------- HID Descriptor --------------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x21 (HID Descriptor)
    bcdHID                   : 0x0101 (HID Version 1.01)
    bCountryCode             : 0x00 (00 = not localized)
    bNumDescriptors          : 0x01
    Descriptor 1:
    bDescriptorType          : 0x22 (Class=Report)
    wDescriptorLength        : 0x0065 (101 bytes)
      05 01             Usage Page (Generic Desktop Controls)
      09 02             Usage (Mouse)
      A1 01             Collection (Application)
      09 01               Usage (Pointer)
      A1 00               Collection (Physical)
      85 01                 Report ID (0x01)
      05 09                 Usage Page (Buttons)
      19 01                 Usage Minimum (1)
      29 03                 Usage Maximum (3)
      15 00                 Logical Minimum (0)
      25 01                 Logical Maximum (1)
      95 03                 Report Count (3)
      75 01                 Report Size (1)
      81 02                 Input (Var)
      95 01                 Report Count (1)
      75 05                 Report Size (5)
      81 03                 Input (Const, Var)
      05 01                 Usage Page (Generic Desktop Controls)
      09 30                 Usage (Direction-X)
      09 31                 Usage (Direction-Y)
      09 38                 Usage (Wheel)
      15 81                 Logical Minimum (-127)
      25 7F                 Logical Maximum (127)
      75 08                 Report Size (8)
      95 03                 Report Count (3)
      81 06                 Input (Var, Rel)
      C0                  End Collection
      C0                End Collection
      05 01             Usage Page (Generic Desktop Controls)
      09 06             Usage (Keyboard)
      A1 01             Collection (Application)
      85 02               Report ID (0x02)
      05 07               Usage Page (Keyboard)
      19 E0               Usage Minimum (-32)
      29 E7               Usage Maximum (-25)
      15 00               Logical Minimum (0)
      25 01               Logical Maximum (1)
      75 01               Report Size (1)
      95 08               Report Count (8)
      81 02               Input (Var)
      95 01               Report Count (1)
      75 08               Report Size (8)
      81 03               Input (Const, Var)
      95 06               Report Count (6)
      75 08               Report Size (8)
      15 00               Logical Minimum (0)
      25 65               Logical Maximum (101)
      05 07               Usage Page (Keyboard)
      19 00               Usage Minimum (0)
      29 65               Usage Maximum (101)
      81 00               Input ()
      C0                End Collection

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x84 (Direction=IN  EndpointID=4)
    bmAttributes             : 0x03 (TransferType=Interrupt)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x01 (1 ms)

And this is a screenshot from Device Manager, showing just one HID device (my keyboard / trackpad on my laptop):

[![Device Manager screenshot][2]][2]

Any ideas? I have obviously tried the example USB keyboard code from the Arduino IDE too - my code was just to get a minimum system to simplify testing. All help gratefully received.

  [1]:http://www.uwe-sieber.de/usbtreeview_e.html
  [2]: https://i.stack.imgur.com/HPEeG.png

body:
Let me try to help. This isn't a definitive "answer" but I need to post screenshots etc., so I am making it an answer.

I tried your code with my Arduino Micro. I believe it is the same as the Leonardo except for a byte difference in the bootloader identification (for the USB device).

First the <s>good</s> bad news. It worked under Windows 7. And let me tell you something: It is incredibly annoying to try to use the Windows 7 device manager when something is typing a key every two seconds! I recompiled it to type a key every minute to save my sanity.

I don't usually use Windows 7 (I use Ubuntu normally) so the device driver was not installed. It offered to install it, I told it to skip going to Windows Update, and it installed it thus:

[![USB installation][1]][1]

Note that I did **not** use the device drivers (if any) supplied with the Arduino installation. I never got asked that question.

---

Locating the device in the Device Manager I see I got Windows drivers:

[![Driver names][2]][2]

---

It showed up under Human Interface Devices as a USB Input Device:

[![USB input device][3]][3]

---

These were the hardware IDs:

[![Hardware IDs][4]][4]

---

It also showed up as a Composite Device:

[![USB composite device][5]][5]

---

This was the report from the program you linked:

        =========================== USB Port1 ===========================

    Connection Status        : 0x01 (Device is connected)
    Port Chain               : 1-1-3-1

          ======================== USB Device ========================

            +++++++++++++++++ Device Information ++++++++++++++++++
    Device Description       : USB Composite Device
    Device Path              : \\?\usb#vid_2341&pid_8037#7&171b751b&0&1#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
    Device ID                : USB\VID_2341&PID_8037\7&171B751B&0&1
    Driver KeyName           : {36fc9e60-c465-11cf-8056-444553540000}\0026 (GUID_DEVCLASS_USB)
    Driver                   : C:\Windows\system32\DRIVERS\usbccgp.sys (Version: 6.1.7601.18328  Date: 2013-11-27)
    Driver Inf               : C:\Windows\inf\usb.inf
    Legacy BusType           : PNPBus
    Class                    : USB
    Service                  : usbccgp
    Enumerator               : USB
    Location Info            : Port_#0001.Hub_#0005
    Location IDs             : PCIROOT(0)#PCI(1D00)#USBROOT(0)#USB(1)#USB(3)#USB(1)
    Container ID             : {821d8eeb-43cd-11e5-b4e1-10c37b50593b}
    Manufacturer Info        : (Standard USB Host Controller)
    Capabilities             : 0x84 (Removable, SurpriseRemovalOK)
    Address                  : 1
    Problem Code             : 0
    Power State              : D0 (supported: D0, D2, D3, wake from D0, wake from D2)
     Child Device 1          : Arduino Micro
      Device ID              : USB\VID_2341&PID_8037&MI_00\8&6467A9E&0&0000
      Class                  : Ports
      COM-Port               : COM8 (\Device\USBSER000)
     Child Device 2          : USB Input Device
      Device ID              : USB\VID_2341&PID_8037&MI_02\8&6467A9E&0&0002
      Class                  : HIDClass
       Child Device 1        : HID-compliant mouse
        Device ID            : HID\VID_2341&PID_8037&MI_02&COL01\9&F900E83&0&0000
        Class                : Mouse
       Child Device 2        : HID Keyboard Device
        Device ID            : HID\VID_2341&PID_8037&MI_02&COL02\9&F900E83&0&0001
        Class                : Keyboard

            ---------------- Connection Information ---------------
    Connection Index         : 0x01 (1)
    Connection Status        : 0x01 (DeviceConnected)
    Current Config Value     : 0x01
    Device Address           : 0x08 (8)
    Is Hub                   : 0x00 (no)
    Number Of Open Pipes     : 0x04 (4)
    Device Bus Speed         : 0x01 (Full-Speed)
    Pipe0ScheduleOffset      : 0x01 (1)
    Pipe1ScheduleOffset      : 0x00 (0)
    Pipe2ScheduleOffset      : 0x00 (0)
    Pipe3ScheduleOffset      : 0x00 (0)

            ------------------ Device Descriptor ------------------
    bLength                  : 0x12 (18 bytes)
    bDescriptorType          : 0x01 (Device Descriptor)
    bcdUSB                   : 0x200 (USB Version 2.00)
    bDeviceClass             : 0x00 (defined by the interface descriptors)
    bDeviceSubClass          : 0x00
    bDeviceProtocol          : 0x00
    bMaxPacketSize0          : 0x40 (64 bytes)
    idVendor                 : 0x2341
    idProduct                : 0x8037
    bcdDevice                : 0x100
    iManufacturer            : 0x01 (String Descriptor 1)
     Language 0x0409         : "Arduino LLC"
    iProduct                 : 0x02 (String Descriptor 2)
     Language 0x0409         : "Arduino Micro"
    iSerialNumber            : 0x00 (No String Descriptor)
    bNumConfigurations       : 0x01

            ------------------ String Descriptors -----------------
                 ------ String Descriptor 0 ------
    bLength                  : 0x04 (4 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language ID[0]           : 0x0409 (English - United States)
                 ------ String Descriptor 1 ------
    bLength                  : 0x18 (24 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language 0x0409          : "Arduino LLC"
                 ------ String Descriptor 2 ------
    bLength                  : 0x1C (28 bytes)
    bDescriptorType          : 0x03 (String Descriptor)
    Language 0x0409          : "Arduino Micro"

            -------------- Configuration Descriptor ---------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x02 (Configuration Descriptor)
    wTotalLength             : 0x0064 (100 bytes)
    bNumInterfaces           : 0x03
    bConfigurationValue      : 0x01
    iConfiguration           : 0x00 (No String Descriptor)
    bmAttributes             : 0x80
     D7: Reserved, set 1     : 0x01
     D6: Self Powered        : 0x00 (no)
     D5: Remote Wakeup       : 0x00 (no)
     D4..0: Reserved, set 0  : 0x00
    MaxPower                 : 0xFA (500 mA)

            ------------------- IAD Descriptor --------------------
    bLength                  : 0x08 (8 bytes)
    bDescriptorType          : 0x0B
    bFirstInterface          : 0x00
    bInterfaceCount          : 0x02
    bFunctionClass           : 0x02 (Communications and CDC Control)
    bFunctionSubClass        : 0x02
    bFunctionProtocol        : 0x01
    iFunction                : 0x00 (No String Descriptor)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x00
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x01 (1 Endpoint)
    bInterfaceClass          : 0x02 (Communications and CDC Control)
    bInterfaceSubClass       : 0x02
    bInterfaceProtocol       : 0x00
    iInterface               : 0x00 (No String Descriptor)

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x00 (Header Functional Descriptor)
    bcdCDC                   : 0x110 (CDC Version 1.10)

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x01 (Call Management Functional Descriptor)
    bmCapabilities           : 0x01
    bDataInterface           : 0x01

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x04 (4 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x02 (Abstract Control Management Functional Descriptor)
    bmCapabilities           : 0x06

            -------------- CDC Interface Descriptor ---------------
    bFunctionLength          : 0x05 (5 bytes)
    bDescriptorType          : 0x24 (Interface)
    bDescriptorSubType       : 0x06 (Union Functional Descriptor)
    bControlInterface        : 0x00
    bSubordinateInterface[0] : 0x01

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x81 (Direction=IN  EndpointID=1)
    bmAttributes             : 0x03 (TransferType=Interrupt)
    wMaxPacketSize           : 0x0010 (16 bytes) (16 bytes)
    bInterval                : 0x40 (64 ms)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x01
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x02 (2 Endpoints)
    bInterfaceClass          : 0x0A (CDC-Data)
    bInterfaceSubClass       : 0x00
    bInterfaceProtocol       : 0x00
    iInterface               : 0x00 (No String Descriptor)

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x02 (Direction=OUT  EndpointID=2)
    bmAttributes             : 0x02 (TransferType=Bulk)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x00 (ignored)

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x83 (Direction=IN  EndpointID=3)
    bmAttributes             : 0x02 (TransferType=Bulk)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x00 (ignored)

            ---------------- Interface Descriptor -----------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x04 (Interface Descriptor)
    bInterfaceNumber         : 0x02
    bAlternateSetting        : 0x00
    bNumEndpoints            : 0x01 (1 Endpoint)
    bInterfaceClass          : 0x03 (HID - Human Interface Device)
    bInterfaceSubClass       : 0x00 (None)
    bInterfaceProtocol       : 0x00 (None)
    iInterface               : 0x00 (No String Descriptor)

            ------------------- HID Descriptor --------------------
    bLength                  : 0x09 (9 bytes)
    bDescriptorType          : 0x21 (HID Descriptor)
    bcdHID                   : 0x0101 (HID Version 1.01)
    bCountryCode             : 0x00 (00 = not localized)
    bNumDescriptors          : 0x01
    Descriptor 1:
    bDescriptorType          : 0x22 (Class=Report)
    wDescriptorLength        : 0x0065 (101 bytes)
      05 01             Usage Page (Generic Desktop Controls)
      09 02             Usage (Mouse)
      A1 01             Collection (Application)
      09 01               Usage (Pointer)
      A1 00               Collection (Physical)
      85 01                 Report ID (0x01)
      05 09                 Usage Page (Buttons)
      19 01                 Usage Minimum (1)
      29 03                 Usage Maximum (3)
      15 00                 Logical Minimum (0)
      25 01                 Logical Maximum (1)
      95 03                 Report Count (3)
      75 01                 Report Size (1)
      81 02                 Input (Var)
      95 01                 Report Count (1)
      75 05                 Report Size (5)
      81 03                 Input (Const, Var)
      05 01                 Usage Page (Generic Desktop Controls)
      09 30                 Usage (Direction-X)
      09 31                 Usage (Direction-Y)
      09 38                 Usage (Wheel)
      15 81                 Logical Minimum (-127)
      25 7F                 Logical Maximum (127)
      75 08                 Report Size (8)
      95 03                 Report Count (3)
      81 06                 Input (Var, Rel)
      C0                  End Collection
      C0                End Collection
      05 01             Usage Page (Generic Desktop Controls)
      09 06             Usage (Keyboard)
      A1 01             Collection (Application)
      85 02               Report ID (0x02)
      05 07               Usage Page (Keyboard)
      19 E0               Usage Minimum (-32)
      29 E7               Usage Maximum (-25)
      15 00               Logical Minimum (0)
      25 01               Logical Maximum (1)
      75 01               Report Size (1)
      95 08               Report Count (8)
      81 02               Input (Var)
      95 01               Report Count (1)
      75 08               Report Size (8)
      81 03               Input (Const, Var)
      95 06               Report Count (6)
      75 08               Report Size (8)
      15 00               Logical Minimum (0)
      25 65               Logical Maximum (101)
      05 07               Usage Page (Keyboard)
      19 00               Usage Minimum (0)
      29 65               Usage Maximum (101)
      81 00               Input ()
      C0                End Collection

            ----------------- Endpoint Descriptor -----------------
    bLength                  : 0x07 (7 bytes)
    bDescriptorType          : 0x05 (Endpoint Descriptor)
    bEndpointAddress         : 0x84 (Direction=IN  EndpointID=4)
    bmAttributes             : 0x03 (TransferType=Interrupt)
    wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
    bInterval                : 0x01 (1 ms)

---

Hopefully you can compare this to your situation and see what is different.

---

*(Edited to add)*

I tried today on my son's Windows 7 PC, which I don't think had Arduino ever installed on it. Also I used my Leonardo instead of the Micro, just to be sure. First Windows tried to install the device drivers:

[![Leonard device driver install][6]][6]

---

Then it only succeeded with the composite device and the keyboard:

[![Leonard device driver install - keyboard][7]][7]

---

However the keyboard worked (eg. in Notepad).

[![Input device description][8]][8]

---

It shows up in the Device Manager:

[![Peripheral ID][9]][9]

  [1]: https://i.stack.imgur.com/UaMY1.png
  [2]: https://i.stack.imgur.com/GdZZS.png
  [3]: https://i.stack.imgur.com/fDf0Q.png
  [4]: https://i.stack.imgur.com/RTyBp.png
  [5]: https://i.stack.imgur.com/0j2jH.png
  [6]: https://i.stack.imgur.com/yQnhu.png
  [7]: https://i.stack.imgur.com/4gC41.png
  [8]: https://i.stack.imgur.com/wc8xs.png
  [9]: https://i.stack.imgur.com/A9kfk.png


message:
How do I use an Arduino as a USB output device for a 2x16 display?

Can I make a USB 2x16 display using an Arduino?
I want to control a 2x16 character lcd display using USB, not com port/serial.

I need it to appear as a HID device when connected to the computer.

Please advise me.

Thanks

body:
HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it.

So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require


message:
Solutions for displays?

I am trying to find cheap options for displays about 3 x 6 inches to display time, weather, simple clip-art type images, and other marquee messages.  What are my best options to work with arduino if my goal is cost-cutting?

* 2" x 4" or greater in size
* 40 dpi minimum
* readable from 15 feet in normal indoor conditions
* everything else is unimportant to me at this point: RGB, pitch, power draw, etc.

body:
www.aliexpress.com would be your first go for cheap stuff.

You can always chat with the guys and bargain a bit on the price. Do remember that the free shipping option means that it will take nearly a month to arrive


body:
One possible option would be these 8x8 pixel displays.

[![8x8 pixel LED][1]][1]

I got that from eBay for $8.50 (for the 4 modules).

They come pre-assembled, this is the back:

[![8x8 pixel LED back][2]][2]

Notice the data direction. You can connect them together like this:

[![8x8 pixel LED - 3 modules][3]][3]

That one (3 lots of 4 modules) is 25.4 cm long (10 inches) and 3.2 cm high (about 1.25 inches).

That's 96 pixels (8 x 4 x 3) in 10 inches, which is a lot less than 40 DPI, but really, if you want to read them from 15 feet away, that is probably OK.

Note: These were single-colour only.

---

If you want 40 DPI x 6 inches that means you must want 240 pixels horizontally and 120 pixels vertically. That would be `240 / 8` modules horizontally (30 modules) and `120 / 8` vertically (15 modules). That's a total of 450 modules. Since they come in lots of four that would be 116 in total (rounded up). 116 x $8.50 = $US 986.

I don't know if that is what you have in mind by "cost cutting" but that is one option.

You would need to assemble them yourself, connect them together, supply power, and have a suitable driver. I have some [code](http://www.gammon.com.au/forum/?id=11516) that drives those boards, although I certainly have not tested it with 450 of them at once.

As you can see those boards come with mounting holes on the back, and are designed to be physically adjacent to each other. Mounting 450 of them could be quite tedious. The LED modules on the front pull off to give access to the mounting holes, but it would be a long job.

---

You can get larger modules, as mentioned in another reply, I expect they would be more expensive, but you would of course get more pixels.

Example: [64x32 RGB LED Matrix - 4mm pitch](http://www.adafruit.com/products/2278). That one is 64x32 pixels for around $US 80.

You would probably need 4 of those horizontally (256 pixels) and 4 vertically (128 pixels). Thus, a total of 16 which would cost you around $US 1280. However for that at least you get RGB. Note that the Adafruit page mentions you cannot drive that many pixels with a Uno.

  [1]: https://i.stack.imgur.com/hw5UO.jpg
  [2]: https://i.stack.imgur.com/NFmlK.jpg
  [3]: https://i.stack.imgur.com/aIW09.jpg


body:
How about just a computer monitor? That would be reasonably large, have high resolution, and could display whatever you want it to. That would only be a few hundred dollars (if that). You could drive it from a cheap PC, or from an Arduino using something like the [MicroVGA](http://www.microvga.com/) board. That has 800x600 pixels resolution.

That would be cheaper, and less fiddly, than putting together a lot of LED display modules.

Also see <http://playground.arduino.cc/Main/MicroVGA>


message:
Streaming sensor data over UDP using an Arduino Yún - how to do it and how fast could it be?

The company where I work wants to do a proof of concept for our new product, a force-sensing platform.

The platform contains four three-axial load cells, so we have 12 channels, which are to be digitized at 2kHz and 16bits. This gives us 2.000 dataframes per second, with 24 bytes of payload each.

Our proposed architecture is as following:

 - The analog signals from the cells is acquired by a dedicated data-acquisition board;
 - The digital stream is sent to the ATmega on Yún over SPI;
 - The data is then relayed to the Atheros over Serial;
 - Finally, the data is transmitted over UDP (or TCP).

I wonder if it is a sensible way of doing it, with the following questions:

 - How would one normally use the Ethernet functionality? Can I call a function on the sketch, or do I need to put some program or script in the Linux, calling it from the sketch?
 - What would be the maximum transmission speed (in bytes per second) from the ATmega side to the Linux side?
 - What would be the maximum throughput of the Ethernet?

I have calculated 24 bytes * 2000 = 480 bytes per second, or a baud rate of 480 * 8 = 3840bps. Is that right?

I would appreciate any help, it could be just a link to the proper information resources.

body:
The Yun is really two different computers (one AVR and on Linux) connected by a serial link. Basically the AVR is connected to a serial console on the Linux machine, so you can "type" commands into Linux by sending strings out the serial port from the AVR.

The serial link normally comes up at 250,000 buad, so that should not be a bottleneck for your application.

Typically, the AVR will "type" a command to run a Python program on the Linux side (called the Bridge) that will then communicate with AVR code using a high level protocol. Unfortunately, this "bridge" connections tends to be slow and flaky.

But you could do what you want very easily by just pumping netcat commands into the Linux machine from the AVR machine every time you wanted to send a UDP packet out. The overhead would only be a few serial bytes per packet (you'd send "nc -u <host> <port> <data>\r" where everything but data is likely the same for every packet).

Here is an example of a program that runs on thew AVR and periodically reads some data from temperature sensors connected via 1-Wire, and then runs a "curl" command on the linux console to record  the readings to a server...

https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino

In your case, your replace the 1-Wire reading code with SPI reading code, and replace the "curl" that sends HTTP data command with an "[nc][1]" command that would send a UDP packet (using the "-u" parameter).

With this technique, I think you could get something working very very quickly and likely easily meet your data rate requirements.

Note that while this is a great technique for getting a proof-of-concept working quickly, I would not use a setup like this in production. Instead consider something like a BeagleBone Black where you could read the SPI data and send the UDP pack in a single C program that ran as a normal Linux process.

  [1]: http://linux.die.net/man/1/nc


message:
How to update the character table of MAX7456

I've got a [MAX7456 chip][1] and I am using [this][2] library with it.
But the issue is that the character table is not the one the library needs to function like it should. The "Hello world" example is nowhere near to what it should display, because the character table is wrong.

All the instructions that talk about character set updating require a USB FTDI cable (I don't have one), I am able to  program the board with [USBASP][3] programmer but that's it. I also have a few Nanos, if that helps.

How could I update the character table to what the library needs (without a FTDI cable) or how to make the sketch included to update the character set work properly?

[1]: https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf
[2]: https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=1
[3]: http://www.fischl.de/usbasp/

body:
To solve this problem one would need to get the builtin character updating sketch work (Max456WriteTable.cpp in examples folder). After the sketch has been compiled one would have to connect either FTDI cable or a USBASP programmer to the board and upload the sketch to it.

The character set (array) itself used in the code can be updated with the appropriate program available at [this site][1].

UPDATE: In the end I solved it [this way][2].

Many thanks to Charlie Hanson & Nick Gammon.

  [1]: http://theboredengineers.com/2012/12/a-max7456-library-for-arduino/
  [2]: https://arduino.stackexchange.com/questions/14739/character-updating-sketch-not-working


message:
Transient and reverse current

Does anyone know (1) how much transient current can be output from a pin and (2) how much (and how long) reverse current an output pin can take?  For instance, consider the following circuit (driven by a series of 10 ms pulses at 5V):

      o----------------
           |          |
           = 10µF    1k LOAD
           |          |
      o----------------

which would be a classical filtered (smoothed) PWM circuit.  When the pin goes to +5V, the capacitor would act like a short and allow very high current (assuming about 20 ohm impedance, maybe 250 mA) for a millisecond or so.  Similarly, when the voltage drops to 0V, the charged capacitor will discharge, leading to a reverse current until it bleeds through the load.  Will either of these damage the diodes in the pin or even the IC?  Thanks.  (Worse comes to worse, does this mean that a resistor and diode are needed to protect the pin?)

**More info**

1)  It's 10µF.  10 pF would be useless in a power supply, it would only store 0.05 µC of electricity at most, which would only be able to smooth the output for a few microseconds.

2)  The load is resistance, 1 k ohms.

3)  A diode would be handy if you wanted to prevent reverse current, since you could put a much larger diode outside than the protective diodes in the Arduino.  They are classically used with motors (inductive load) as a clamp diode.

4)  My general question is about high transient current or reverse currents.  A capacitor is just an example of a situation that could cause this.  Another example would be a pin that is putting out only occasional (for example) 1ms long 100 mA pulses, separated by many seconds.  Such a circuit is really not delivering much power, but for very short periods it exceeds that recommended 40 mA.  Would this burn out the pin or not?

5)  A capacitor in parallel with the load is pretty much the classic filtered DC power supply.  Open any wall wart you have and you'll see a transformer, a rectifier and several large (electrolytic) capacitors (along with a couple small ones) and a voltage regulator.  Closer to this example, say you want to deliver current at 2 volts DC.  You can do this by alternating 2 ms pulses (at 5V) with 3 ms at 0V.  Then have a capacitor in series to smooth it to closer to DC, making it more like analog output.  That is, in fact, exactly how adjustable power supplies often work.

body:
It sounds like you are trying to make a digital to analog converter driving some type of load.  Look at this link: http://emesystems.com/BS2PWM.htm
It will give you a start. Please note they use an opamp as a buffer.

This 'buffer' has a very high input impedance and a low output impedance.  It can drive from a few mills to over an amp depending on the opamp chosen.  Additional circuitry can get you into thousands of amps if desired.  The schematic is a 2 pole filter originally designed for the Stamp microcontroller.

The filter soothes it out but adds a delay on the final output value (settling time).  The greater the filter capactance the lower the ripple and the slower the response.  You can add another pole to filter if you want.

As a bit of information from an old semiconductor guy absolute ratings are just that.  If you exceed them even for a few nanoseconds you can be sure you damaged the device, you just do not know when it will fail.

I have seen a lot of microcontrollers damaged because of capacitors connected to the pins, power excluded, doesn't matter if the pin is input or output.  When the power supply collapses it will inject current into the microprocessor substrate possibly damaging it.

Good Luck


message:
SoftwareSerial Write to return Read in Serial Monitor?

Hoping someone can help me out in my conundrum here...

I currently am testing the SoftwareSerial library out to understand how I may use it in my project.

I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.

I have written the following:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

    void setup() {

      Serial.begin(1200);
      mySerial.begin(1200);
    }

    void loop() {

      mySerial.write('F');
      delay(100); // attempting to allow time between write and read commands

      while (mySerial.available()>0) {
      Serial.println(mySerial.read());
      }
    }

The whole point is just to see 'F' return in the Serial Monitor.

The output, unfortunately, is absolutely nothing! If I omit the `while(mySerial.available>0)` I just get -1 's down the lines of the Serial Monitor.

Thank you in advance!

body:
<!-- language-all: lang-C++ -->

SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.

Look at the code for `write` in SoftwareSerial:

    size_t SoftwareSerial::write(uint8_t b)
    {

    ...

      cli();  // turn off interrupts for a clean txmit

    ...

      // Write each of the 8 bits
      for (uint8_t i = 8; i > 0; --i)
      {
        if (b & 1) // choose bit
          *reg |= reg_mask; // send 1
        else
          *reg &= inv_mask; // send 0

        tunedDelay(delay);
        b >>= 1;
      }

    ...

      SREG = oldSREG; // turn interrupts back on

    ...

    }

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.


message:
Why use an int variable for a pin when const int, enum or #define makes much more sense

Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?

Many times I see an `int` being used for a pin definition,

    int led = 13;

when the use of a `const int`

    const int led = 13;

or [`enum`][1], or [`#define`][2]

    #define LED 13

makes much more sense.

It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, [Blink][3].

I [read somewhere][4] that `const int` is preferred over `#define`. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.

Memory/processing/computing wise is a `const int`, `enum`, or for that matter `#define`, better than a plain `int`, i.e. occupies less memory, stored in [different memory][5] (Flash, EEPROM, SRAM), faster execution, quicker to compile?

----

This may appear to be a duplicate of [Is it better to use #define or const int for constants?][6], but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.

  [1]: http://playground.arduino.cc/Code/Enum
  [2]: https://www.arduino.cc/en/Reference/Define
  [3]: https://www.arduino.cc/en/tutorial/blink
  [4]: https://stackoverflow.com/questions/16889213/how-to-use-define-to-assign-pins-in-arduino#comment-24383545
  [5]: https://www.arduino.cc/en/Tutorial/Memory
  [6]: https://arduino.stackexchange.com/questions/506/is-it-better-to-use-define-or-const-int-for-constants

body:
<!-- language-all: lang-C++ -->

    const int led = 13;

That is the correct method. Or even:

    const byte led = 13;

How many pins do you have?

Some of the tutorials did not quite go through as much quality control as they might have.

Performance will be better using `const byte`, compare to `int` however the compiler may be smart enough to realize what you are doing.

What you can do is gently encourage people to use more efficient techniques by using them in your own code.

---

### Responses to comments

1. A commenter has suggested that `byte` is not standard C. This is correct, however this is an Arduino StackExchange site, and I believe using standard types supplied by the Arduino IDE is acceptable.

    In Arduino.h there is this line:

        typedef uint8_t byte;

    Note that this is not exactly the same as `unsigned char`. See [uint8_t vs unsigned char](https://stackoverflow.com/questions/1725855/uint8-t-vs-unsigned-char) and [When is uint8_t ≠ unsigned char?](https://stackoverflow.com/questions/16138237/when-is-uint8-t-≠-unsigned-char).

2. Another commenter has suggested that using byte will not necessarily improve performance, because numbers smaller than `int` will be promoted to `int` (see Integer Promotion Rules if you want more on this).

    However in the context of a **const** identifier, the compiler will generate efficient code in any case. For example, disassembling "blink" gives this in the original form:

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

        00000086 <loop>:
          86: 8d e0        ldi r24, 0x0D ; 13
          88: 61 e0        ldi r22, 0x01 ; 1
          8a: 1b d1        rcall .+566     ; 0x2c2 <digitalWrite>

    In fact it generates the same code whether the `13`:

    * Is a literal
    * Is a `#define`
    * Is a `const int`
    * Is a `const byte`

---

The compiler know when it can fit a number into one register and when it can't. However it is *good practice* to use coding that indicates your *intent*. Making it `const` makes it clear that the number won't change, and making it `byte` (or `uint8_t`) makes it clear that you are expecting a small number.

---

### Confusing error messages

Another major reason to avoid `#define` is the error messages you get if you make a mistake. Consider this "blink" sketch which has an error:

<!-- language-all: lang-C++ -->

    #define LED = 13;

    void setup() {
      pinMode(LED, OUTPUT);      // <---- line with error
    }

    void loop() {
      digitalWrite(LED, HIGH);   // <---- line with error
      delay(1000);
      digitalWrite(LED, LOW);    // <---- line with error
      delay(1000);
    }

On the surface it looks OK, but it generates these error messages:

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

    Blink.ino: In function ‘void setup()’:
    Blink:4: error: expected primary-expression before ‘=’ token
    Blink:4: error: expected primary-expression before ‘,’ token
    Blink:4: error: expected `;' before ‘)’ token
    Blink.ino: In function ‘void loop()’:
    Blink:8: error: expected primary-expression before ‘=’ token
    Blink:8: error: expected primary-expression before ‘,’ token
    Blink:8: error: expected `;' before ‘)’ token
    Blink:10: error: expected primary-expression before ‘=’ token
    Blink:10: error: expected primary-expression before ‘,’ token
    Blink:10: error: expected `;' before ‘)’ token

You look at the first highlighted line (line 4) and *don't even see* a "=" symbol. Plus, the line looks fine. Now it's fairly obvious what the problem is here (`= 13` is being substituted for `LED`), but when the line is 400 lines further down in the code, it isn't obvious the problem is with the way LED is defined.

I've seen people fall for this many times (including myself).


body:
As Ignacio has rightly states, it's basically because they don't know better.  And they don't know better because the people who taught them (or the resources they used when learning) didn't know better.

Much of the Arduino code and tutorials are written by people who have never had any training in programming and are very much "self taught" from resources by people who themselves are very much self taught with no proper training in programming.

Many of the snippets of tutorial code I see around the place (and especially those that are only available within YouTube videos --- urgh) would be a fail mark if I were marking them in an exam.

Yes, a `const` is preferred over a non-const, and even over a `#define`, because:

* A `const` (like a `#define`, unlike a non-const) does not allocate any RAM
* A `const` (like a non-const, but unlike a `#define`) gives the value an explicit *type*

The second point there is of particular interest.  Unless specifically told otherwise with embedded type-casting (`(long)3`) or a type suffix (`3L`) or the presence of a decimal point (`3.0`), a `#define` of a number will always be an integer and all mathematics performed on that value will be as if it were an integer.  Most of the time that's not a problem, but you can run into interesting scenarios when you try to `#define` a value that is larger than an integer can store, such as `#define COUNT 70000` and then perform a mathematical operation with other `int` values on it.  By using a `const` you get to tell the compiler "This value is to be treated as this variable type" - so you would instead use: `const long count = 70000;` and all would work as expected.

It also has the knock-on effect that it checks the type when passing the value around the place.  Try passing a `const long` to a function that expects an `int` and it would complain about narrowing the variable range (or even completely fail to compile depending on the scenario).  Do that with a `#define` and it would just silently carry on giving you the wrong results and leave you scratching your head for hours.


body: My answer is... they do it because it works. I'm having a hard time not asking a question in my answer such as "why does it have to be 'wrong'?"


body: As a 2-week newbie to Arduino I'd pick up on the general idea of Arduino being occupied by non-programmers. Most sketches I have examined, including those on the Arduino site, show a total lack of order,  with sketches that do not work & barely a coherent comment in sight. Flow charts are non-existent, and the "Libraries" are an un-moderated jumble.


message:
Arduino LCD Simple Problem

Hi my lcd doesnt display that i was expected. Can anyone help me???

RS-->22
RW-->GROUND
E-->23
D4-->24
D5-->25
D6-->26
D7-->27

        #include <LiquidCrystal.h>

    LiquidCrystal lcd(22, 23, 24, 25, 26, 27);
    void setup() {

    lcd.begin(16,2);

    lcd.setCursor(0,1);
    lcd.print("Hello!");
    delay(1000);
    }
    void loop() {
    lcd.setCursor(0,1);
    lcd.print(millis()/1000);
    }

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

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

body: I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.


message:
How to develop or edit an Arduino library?

I'm not sure if I should split this question in two.
I had to edit some libraries and I plan to make some myself but didn't try yet.

Editing a library seems very laborious comared to editing a sketch.

I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.

What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.

I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?

And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.

How do you do all of this? Is there any trick that helps?

Thank you.

body:
I am going to split my answer into 2 parts

**1. Editing an Arduino library:**

It **doesn't** matter how you edit your library, you can do it in notepad for all I care. It just doesn't matter.

**2. Version Control:**

Git is a version control software used to track software/code changes and ensure that people don't screw up the files by adding code that's not tested.

If you want to contribute to a certain library here is what you need to do

Step 1: create a github.com account since most people host it there

Step 2: **fork** the required library, this basically creates a clone of the library in your account.

Step 3: **clone** the forked repo from your account to your computer. So now you have the files on your computer to mess around

Step 4: create a **branch** a branch is your personal workspace to mess around as you wish. The advantage of have a branch is that if you screw up.  You could always go to the main branch (master) and start over :)

Step 5: once you are done editing and testing and are sure the file is perfect, you **commit** your changes and then you create **pull request ** with the original author so  that he can review your work and if he is happy will accept your change and merge it to master.

Note: read about adding remote to your git repo and fetching from remote repo, once you understand these basics you will understand the power of git :)


body:
This is the common process for all open source projects, not just arduino (example using github svn)

**1. Fork a project**

When you fork a project, you create a separate "project" of your own from the original project on the SVN.

**2. Clone your project**

Clone your fork down to your local directory so you can make changes and use it.

    git clone https://github.com/<your-repo>/<project>

**3. Push changes up**

Push your changes up to your repo regularly. At this point your changes are not affecting the original project in any way.

    git push -u origin <branch>

**4. Pull updates from the original project**

The original author(s) can make changes and improve his/her code. You can make sure your fork is up-to-date by pulling/merging those updates into your fork.

    git pull https://github.com/<original-author>/<repo> <branch>

Some time there will be conflicts, which are normal since your changes and the author's may collide. You'll be prompted to fix the conflicts before committing your changes.

    <<<<<<< HEAD
        # this portion is your code at the current HEAD
    =======
        # this portion is the one from the original branch master
    >>>>>>> master

You'll have to fix the conflict manually by either accepting your change and deleting the master's or deleting your change, and get rid of the marks before committing to your svn.

**4. Creat a pull request**

After using your supercharged version of the project for a while, you think it might be useful for others. To contribute, you create a pull request to the original author. It works similar to you pulling in his changes, just he will review your changes then merge in.

All the while, others can do all these with your project too!

To edit the project/make changes, you can use any editor to open your local project, code away, save it and commit. It is not ideal to use Arduino IDE since it is an environment to run the code (but otherwise possible).


body:
<!-- language-all: lang-C++ -->

> I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development.

---

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.

Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:

    void blinkLED (const byte which, const int times)
      {
      for (int i = 0; i < times; i++)
        {
        digitalWrite (which, HIGH);
        delay (500);
        digitalWrite (which, LOW);
        delay (500);
        }  // end of for loop
      } // end of blinkLED

And some test code:

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (13, OUTPUT);
      blinkLED (13, 5);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Make a library

To turn that into a library we need three steps:

1. Make a folder for the library. This should be placed inside the **libraries** folder **in your sketchbook folder**. This folder:

    [![Sketchbook folder][1]][1]

    In my case: `/home/nick/sketchbook/libraries`. It does **not** go into anywhere associated with the IDE download.

    > but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

    No, **not** there.

   I will call my library `blinkLED`. So I make that folder, which is now: `/home/nick/sketchbook/libraries/blinkLED`

---

2. Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:

    **blinkLED.h**

        #include <Arduino.h>

        void blinkLED (const byte which, const int times);

    **Important**: You must include `<Arduino.h>` as in the example, or you will get compile errors.

---

3. Put the C++ code into a .cpp file, like this:

    **blinkLED.cpp**

        #include <blinkLED.h>

        void blinkLED (const byte which, const int times)
          {
          for (int i = 0; i < times; i++)
            {
            digitalWrite (which, HIGH);
            delay (500);
            digitalWrite (which, LOW);
            delay (500);
            }  // end of for loop
          } // end of blinkLED

    **Important**: You must include the .h file created in step 2, as in the example, or you will get compile errors.

---

That's it! Restart the IDE now so it notices the new folder with the library in it.

Now our test sketch can just use the new library.

    #include <blinkLED.h>

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (13, OUTPUT);
      blinkLED (13, 5);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Testing

For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).

You can make changes to the library source and save them. You **do not** need to restart the IDE if you do this. It will always pick up the latest version.

In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

---

## Git

Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:

    git init
    git add *.cpp
    git add *.h
    git commit -m "Initial commit"

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


body:
There is one component of your question that remains unanswered:
>I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

>Any good editor if Arduino IDE is not an option? Why is not an option?

The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:

Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at **File > Preferences > Sketchbook location**.

Create a file that matches the folder name that contains the source files with the .ino extension. For example:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_FooBar.ino
        |_FooBar.h
        |_FooBar.cpp
or:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_library.properties
        |_src
          |_src.ino
          |_FooBar.h
          |_FooBar.cpp
This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style:
<!-- language: lang-cpp -->

    #include "FooBar.h"

Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.

Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will [cause the library to be skipped](https://github.com/arduino/Arduino/issues/3512#issuecomment-128029263) by the job that fetches releases. I also add this filename to .git/info/exclude.

If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format

Now the structure of the example libraries above would look like this:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_.development
        |_FooBar.ino
        |_FooBar.h
        |_FooBar.cpp
        |_library.properties
or:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_.development
        |_library.properties
        |_src
          |_src.ino
          |_FooBar.h
          |_FooBar.cpp

Restart the Arduino IDE if it's running.

After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.


message:
MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()

<!-- language-all: lang-C++ -->

I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.

And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.

The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there.

This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there.

    #include <Arduino.h>
    #include <Wire.h>
    #include <inttypes.h>
    #include <SPI.h>
    #include "flanschcontrol.h"
    #define DEBUGOUTPUT
    #define PROTOV2
    typedef int elem_type;
    #define ADDRESS (0)
    #define    OPCODEW       (0b01000000)  // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3
    #define    OPCODER       (0b01000001)  // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3
    #define    ADDR_ENABLE   (0b00001000)  // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing
    uint8_t PexSSPin=7;

    void setup() {
       Serial.begin(9600);
     pinMode(PexSSPin, OUTPUT);
     SPI.begin();
       SPI.setClockDivider(2);
       SPI.setBitOrder(MSBFIRST);
       SPI.setDataMode(SPI_MODE0);

        delay(1000);
     PORTD &= 0b01111111;  // Slaveselect low

      SPI.transfer(OPCODEW | (ADDRESS << 1));
     SPI.transfer(IODIRB);
     SPI.transfer(0b10101010);
     PORTD |= 0b10000000; // Slaveselect high
     delay(1000);
    }

    void loop()
    {
     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b00000000);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("0");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b11111111);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("ff");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b00001111);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("0f");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b11110000);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("f0");
     delay(1000);

     int value;

     PORTD &= 0b01111111;  // Slaveselect low
       SPI.transfer(OPCODER | (ADDRESS << 1));  // Send the MCP23S17 opcode, chip address, and read bit
       SPI.transfer(GPIOA);                      // Send the register we want to read
       value = SPI.transfer(0x00);               // Send any byte, the function will return the read value (register address pointer will auto-increment after write)
       value |= (SPI.transfer(0x00) << 8);       // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte"
     PORTD |= 0b10000000; // Slaveselect high
     Serial.print("pindata: ");
     Serial.println(value);
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
      SPI.transfer(OPCODEW | (ADDRESS << 1));
     SPI.transfer(IODIRB);
     SPI.transfer(0b10101010);
     PORTD |= 0b10000000; // Slaveselect high
    }

Definitions of some preprocessor thingies:

    #define    IODIRA    (0x00)      // MCP23x17 I/O Direction Register
    #define    IODIRB    (0x01)      // 1 = Input (default), 0 = Output
    #define    GPIOA     (0x12)      // MCP23x17 GPIO Port Register
    #define    GPIOB     (0x13)      // Value on the Port - Writing Sets Bits in the Output Latch

body:
<!-- language-all: lang-C++ -->

You've fallen for the old "slave select pin is already low" trick!

Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):

    pinMode (2, OUTPUT);     // <--- pin 2 output
    delay(1000);
    PORTD |= bit (2);        // <--- pin 2 HIGH
    PORTD &= 0b01111111;     // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
    delay(1000);

This is the logic analyzer output of running your sketch:

[![Slave select low][1]][1]

Notice how SS is low all the time, and thus the chip does not respond to the command?

---

Now we add a line **before** the `SPI.begin`

    PORTD |= 0b10000000;    // Slaveselect high
    SPI.begin();
    SPI.setClockDivider(2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

Now look at the results:

[![Slave select high][2]][2]

This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.

So without bringing SS high, the **first** thing you sent was always going to fail.

---

It was nothing to do with it being in `setup` - it couldn't be. After all the logic is basically this:

    init ();
    setup ();
    while (true)
      loop ();

---

Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?

How about:

    digitalWrite (PexSSPin, LOW);
    /// write to chip
    digitalWrite (PexSSPin, HIGH);

Isn't that much more readable? And easier to change later?
  [1]: https://i.stack.imgur.com/c2IPr.png
  [2]: https://i.stack.imgur.com/Xu2HN.png


message:
Sending Data between two boards using SoftwareSerial

I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!

The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).

The idea, is to get Serial TX on the *"MWC"* FLIP 1.5 to Serial RX on the UNO.

These are my connections thus far:

MWC Pin ------->UNO Pin

Digital 3 (TX)--->Digital 6 (RX)

Digital 9 (RX)--->Digital 9 (TX)

This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)

    #include "attout.h"
    #include "SoftwareSerial.h"

    SoftwareSerial altSerial(9,3); // RX=9 TX=3

    void startaltserial(){

      altSerial.begin(9600);

    }

    void attout(){

    pinMode(3,HIGH);
    pinMode(9,HIGH);

      altSerial.print('1');

    }

NOTE: I also tried `altSerial.write('1')`. Same result (or lack of one).

Then, the RX Code on the UNO Board:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(6,9); // RX=6 TX=9

    void setup()
    {
      // Open serial communications:
      Serial.begin(9600);

      // Set the data rate for the SoftwareSerial port
      mySerial.begin(9600);

    }

    void loop()
    {
      while (mySerial.available()>0) {
        Serial.println(mySerial.read());
      }
    }

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!

This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.

Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.

Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

body:
Your problem here is that you are streaming out serial data non-stop.

See my answer in this thread: <https://arduino.stackexchange.com/questions/1569/what-is-serial-begin9600/14146#14146>

Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.

If you add one "character time" delay to the **sender**, the receiver works fine:

      altSerial.print('1');
      delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.


message:
Motion sensor large areas

I'm looking to build a motion sensor which detects if an object is in the monitored area. Doing some researched I found out that I can use [PIR motion sensor][1] for this but it seems the area it monitors is pretty small.

I need something that can monitor about 3 feet x 1 feet area. Is there something else that I can use for this?

My goal is to light up some LED lights when an object is detected in that area.

Thanks in advance.

  [1]: http://www.adafruit.com/products/189?&main_page=product_info&cPath=35&products_id=189

body:
A standard PIR motion sensor will work fine.  It can monitor motion in a very room.  You just need to make sure the PIR sensor is far enough away.

Here is one article that states it should work up to 10 meters away.

https://www.mobotix.com/eng_US/Support/FAQ/Configuration2/What-is-the-range-of-the-PIR-Passive-Infrared-motion-detector

Note that the device that the PIR sensor is mounted on must be stationary.  It will not work on a robot of anything that is moving.


body:
It sounds like what you want is an ultrasonic distance ("ping") sensor over the area where the car is.

When the car isn't there it will measure the height of the garage (say 3m).  With the car there it will measure the distance from the ceiling to the top of the car (say 1.5m).

Ultrasonic sensors have a limit to their range.  The cheap ones are usually around 2m, so may not work for you, or you may get away with it if it will return "infinite" for anything outside its range, in which case anything that is not "infinite" will be something present under the sensor.