title: Cannot drive DC motor with Arduino PWM

text:
# Question
Title: Cannot drive DC motor with Arduino PWM
I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.

But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.

How can I fix that??

# Answer
I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.
> 1 votes

# Answer
It's hard to know without an oscilloscope, but as a guess you might be seeing voltage spikes on Vcc at the reset pin due to inductive load dumps from the motor. Per Atmel app note AVR042, you might try a 5V zener diode from the reset pin to ground and/or a capacitor to snub the spikes.
> 0 votes

# Answer
You might also want to consider purchasing a simple and popular L293D motor driver chip. I teach basic Arduino classes and learning to use this chip is much easier than using transistors and diodes. The other advantage is the motors can go both forward and backward!

On the following link you can purchase one chip for under $1.00 USD and each chip will driver two motors both forward and backward.

http://www.ebay.com/itm/New-L293D-L293-L293B-DIP-SOP-Push-Pull-4-CH-Four-Channel-Motor-Driver-IC-/371198300958
> -1 votes

---
Tags: arduino-uno, motor, pwm
---


# Question
Title: 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.

# Answer
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 \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" 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 votes

---
Tags: serial, arduino-yun, ethernet, baud-rate
---


# Question
Title: Which board/shield to generate (non-PWM) analog outputs?
I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board.

Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like "MCP4725" but it would be nicer to just have a single board with no additional parts.

The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)

Is there a board I haven't found so far? Or have I missed a completely different approach?

# Answer
For 12-bit dual DAC you want the MCP4822 which has two channels of 0-4.095V in 1mV steps.

The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V. The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V. If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.

It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.
> 2 votes

---
Tags: analogwrite
---


title: Motion sensor large areas

text:
# Question
Title: 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 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.

# Answer
> 2 votes
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.

# Answer
> 0 votes
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.

---
Tags: led
---


# Question
Title: Disabling a push button after being under pressure for some time?
Disabling a push button after being under pressure for some time?

I need to disable a button where the user is pressing for a time it is disabled.

Code:

```
int ledPin = 13;

int inPin = 7;

int val = 0;

void setup() {

pinMode(ledPin, OUTPUT);

pinMode(inPin, INPUT);

}

void loop(){

val = digitalRead(inPin);

if (val == HIGH) {

digitalWrite(ledPin, LOW);

} else {

digitalWrite(ledPin, HIGH);

}

}

```

# Answer
> 1 votes
```
int ledPin = 13;
int inPin = 7;
int val = 0;
int oldVal = 0;

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

void loop(){
  val = digitalRead(inPin);
  if (val == HIGH && oldVal == LOW) {
    digitalWrite(ledPin, LOW);
    oldVal = HIGH;
  } else if (val == LOW && oldVal == HIGH) {
    digitalWrite(ledPin, HIGH);
    oldVal = LOW;
  }
}

```

# Answer
> 0 votes
I think the question is about activating something on a switch push, but only for x seconds. For example, you press a button to sound an alarm, but it stops after 5 seconds.

---

This should do it:

```
const byte ledPin = 13;
const byte inPin = 7;

const unsigned long MAX_PUSH_TIME = 2000;  // ms
const unsigned long DEBOUNCE_TIME = 20;    // ms
unsigned long whenPushed;

bool switchState;
bool awaitingRelease;

void setup()
  {
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT_PULLUP);
  }  // end of setup

void switchPushed ()
  {
  // we want them to let go now, ignore it
  if (awaitingRelease)
    return;

  // is LED already on?
  if (digitalRead (ledPin) == HIGH)
    {
    // held for too long? turn off LED, remember it
    if (millis () - whenPushed >= MAX_PUSH_TIME)
      {
      awaitingRelease = true;
      digitalWrite(ledPin, LOW);
      }
    return;  // all done
    }

  // turn LED on, remember when
  digitalWrite(ledPin, HIGH);
  whenPushed = millis ();
  delay (DEBOUNCE_TIME);
  }  // end of switchPushed

void switchReleased ()
  {
  digitalWrite(ledPin, LOW);
  awaitingRelease = false;  // they released it!
  delay (DEBOUNCE_TIME);
  }  // end of switchReleased

void loop()
  {
  switchState = digitalRead(inPin);
  if (switchState == LOW)
    switchPushed ();
  else
    switchReleased ();
  }  // end of loop

```

---

**Note:** I used an input pull-up resistor on the switch to avoid having to use extra components. Thus the switch is wired between pin 7 and **ground**. That is why the test for the switch being pressed is for it to be LOW.

---

## Reference

---
Tags: arduino-uno
---


# Question
Title: How do pins on an arduino mega 2560 work?
I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).

I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?

Here let me tell you how pins are arranged on mine:

```
IOREF                                                                         GND

                                         13
RESET                                                                         12
3.3V     //this left group marked power                                        .
5V                                  //right group marked PWM                   2
GND            //right groupmarked communication                          TX0 -1
GND                                                                       RX0- 0

V1N                                                                       TX3-14
                                                                         RX2 -15
A0                                                                         ..
A1                                                                      SCL -21
..   //THIS left GROUP MARKED ANALOG IN
A7

A8
A9 //I believe it is part of the above group
..
A14
A15

     //the pins below marked DIGITAL
     52-50-`48-46...........................................................22`

```

# Answer
> 4 votes
> there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a **common** "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked **GND** on the board.

---

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.

You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

---

> Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

> Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

* PWM: Pulse-width-modulated output
* COMMUNICATION: Serial input/output (4 serial ports)
* ANALOG IN: Analog-to-digital converter (ADC) input
* DIGITAL: Digital (not analog) input/output
* SDA/SCL: I2C communications
* Pins 50-53: SPI communications (not marked on the board)

However **all** pins, as you noted, can - if you wish - be used for digital input or output.

# Answer
> 3 votes
Any IO pin can be set to either be an input, where it reports to your program if the voltage present on that pin (relative to ground) is above or below a certain threshold (HIGH or LOW voltage), or it can be an output, where it can either be set to be a HIGH output (pin is connected internally to +5V) or a LOW output (pin is connected internally to GND).

To drive an LED you would connect one side of a small resistor (say 470Ω) to any IO pin you choose. The other side of the resistor would connect to the anode of the LED. The cathode of the LED would then connect to ground. When you set the IO pin to HIGH it will provide 5V to the LED through the resistor (which is needed to limit the current as the LED is a non-linear, current driven, component) and the circuit is completed by the return path through ground.

Note that you *must not* exceed 40mA going into or out of any IO pin, and you *should not* exceed 25mA going into or out of any IO pin. The total current going into or out of *all* IO pins *must not* exceed 200mA.

---
Tags: arduino-mega, arduino-ide
---


# Question
Title: Having issues with sending output to WiFi Shield
I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).

In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.

Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one

I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:

```
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include<iostream>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512          //Default buffer length of port
#define DEFAULT_PORT "7"        //Change this to change port

int main()//int argc, char **argv
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
        *ptr = NULL,
        hints;
    char *sendbuf = "100";
    char recvbuf[DEFAULT_BUFLEN];
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;
    /*
    // Validate the parameters - not necessary for use
    if (argc != 2) {
        printf("usage: %s server-name\n", argv[0]);
        system("pause"); return 1;
    }
    */

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        system("pause"); return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        system("pause"); return 1;
    }

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            system("pause"); return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program
    {
        printf("Unable to connect to server!\n");
        WSACleanup();
        system("pause"); return 1;
    }

    // Send an initial buffer
    iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0)
        {
            printf("Bytes received: %d\n", iResult);
            std::cout << recvbuf << std::endl;
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError());

    } while (iResult > 0);
    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
}

```

# Answer
> 0 votes
At no point in your program are you telling it where to connect to. You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to. Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.

You need to specify the IP address of the WiFi shield as the first parameter to `getaddrinfo()` (currently `NULL`):

> `int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);`
>
> `node` specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by `inet_aton(3)`; for IPv6, hexadecimal string format as supported by `inet_pton(3)`), or a network hostname, whose network addresses are looked up and resolved. If `hints.ai_flags` contains the `AI_NUMERICHOST` flag, then node must be a numerical network address. The `AI_NUMERICHOST` flag suppresses any potentially lengthy network host address lookups.
>
> If the `AI_PASSIVE` flag is not set in `hints.ai_flags`, then the returned socket addresses will be suitable for use with `connect(2)`, `sendto(2)`, or `sendmsg(2)`. **If node is `NULL`, then the network address will be set to the loopback interface address** (`INADDR_LOOPBACK` for IPv4 addresses, `IN6ADDR_LOOPBACK_INIT` for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.
>
> -- Extract from the `getaddrinfo(3)` manual page

---
Tags: arduino-uno, c++, wifi, adafruit
---


# Question
Title: How to wirelessly communicate with I2C infrared thermometer
I've been getting involved with arduino recently as a means of improving a heating device which is quite small, a box about 15x10x5cm which I would like to rig with an MLX90614 infrared sensor.

The box is already "wired" with many small flexible tubes, so I would like to set up the sensor so that I can read from it wirelessly, to keep it from getting anymore complicated than it needs to be.

What would be the most compact way to set up a transceiver capable of I2C (ideally with arduino uno coding compatibility) and to then communicate with another arduino? (I already have an Uno to act as the base station)

The reason I mention that the device should be codable with Arduino is that the MLX90614 uses a communication protocol that is beyond my skill level and which I can only operate with open source code libraries for arduino.

I've been doing some research and the best thing I've found so far is the PanStamp, but I have never soldered before, and they are not in business at the moment.

Another limitation is size. I would prefer not to use another entire arduino Uno, with shield.

And of course low cost is a plus :)

So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

-Ryan

# Answer
> So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

See Solar powered Arduino \- I used a standalone Atmega328P on a prototyping board for that. That used the NRF24L01 to send information (the current voltage in this case) to another Arduino.

For small and simple you could get an Arduino Nano or Arduino Pro Mini. The Pro Mini is around $US10, and is quite small.

They have the same processor (Atmega328P) so you can connect your I2C sensor to it, and the NRF24L01 as well.

> I have never soldered before ...

I think you will have to do a little soldering, to connect up the sensor, and the transmitter, but soldering on connecting wires isn't too onerous.
> 0 votes

---
Tags: i2c, datalogging, wireless
---


title: Arduino messing up as slave over I2C

text:
# Question
Title: 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:

```
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!

# Answer
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).
> 1 votes

---
Tags: arduino-mega, i2c
---


# Question
Title: I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope
I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?

# Answer
You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.
> 0 votes

# Answer
Look at the ATtiny85 MCU. It's a small 8pin device, and pretty easy to get up and running using Arduino code. You could also use the ATtiny84 which has more pins and still very small.

Start here: https://code.google.com/p/arduino-tiny/

Also, there are plenty of tutorials on setting up and programming them.

Regarding a custom board, your least expensive route would be to design your own. Otherwise you would need to outsource the design.
> 0 votes

# Answer
No, there is no software specifically for designing custom Arduinos. However, the Arduino is open source, so you can design your own if you have the skills.

You can download the schematics for your chosen base design from the Arduino website, then use any PCB design software you like to design your own PCB.

You can then send that PCB design off to China (for example) to have it fabricated, and when you get them back you can solder the components on and hope it works.

Of course, designing and building very small circuits well is a talent that few possess. Hand building circuits with the very tiny components you will need to make it fit into a watch is very difficult and normally requires specialist equipment. That is unless you want your watch to be the size of a dinner plate, like most of the watch kits you can buy.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: 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, 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):

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.

# Answer
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 ~~good~~ 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:

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:

---

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

---

These were the hardware IDs:

---

It also showed up as a Composite Device:

---

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:

---

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

---

However the keyboard worked (eg. in Notepad).

---

It shows up in the Device Manager:
> 2 votes

---
Tags: arduino-leonardo, keyboard
---


# Question
Title: Need assistance with program for POV Project
I've created a very basic POV project.

It has a 12V DC motor with a piece of wood on it. The wood has 6 LEDs on it as well as a copper ring. The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)

I need help (please) with the program.

This is the code that I am using:

```
int pin = 13;
volatile  int tcnt = 0;
volatile  int lastcount = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  if (tcnt != lastcount)
  {
     digitalWrite(pin, HIGH);
     delay(10);
     digitalWrite(pin, LOW);
     delay(10);
     lastcount = tcnt;
  }

   delay(10);

}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

```

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.

The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?

Any help is greatly appreciated.

# Answer
> 0 votes
Your **third** delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:

```
const byte pin = 13;
volatile bool detected;

void setup() {
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  if (detected)
    {
    delay(10);
    digitalWrite(pin, LOW);
    detected = false;
    }

}

void blink() {
  digitalWrite(pin, HIGH);
  detected = true;
}

```

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.

---
Tags: arduino-uno, programming
---


title: ISP - Wrong direction frying ATmega

text:
# Question
Title: ISP - Wrong direction frying ATmega
I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.

My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?

Connecting it the wrong way around would give me the following connections:

```
USBasp  ---  ATmega

MOSI    -|
NC      -|-  GND
RST     -|
SCK     -|

MISO    ---  Vcc
Vcc     ---  MISO

         |-  MOSI
GND     -|-  NC
         |-  RST
         |-  SCK

```

# Answer
No, connecting it backwards shouldn't do any damage, it just won't work. The clue is in these two connections:

```
NC      -|-  GND
GND     -|-  NC

```

With it backwards the ground connection doesn't go anywhere. Without that ground connection there's no circuit. With no circuit, no current flows.

The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer. The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode. That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.
> 3 votes

---
Tags: isp
---


# Question
Title: Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working
Recently I've bought an Arduino Mega 2560 R3 and a Shield Model Wireless SD R3 from http://www.amazon.de/Arduino-A000065-Netzwerkkarte-Wireless-SD-Shield/dp/B00L1FO860. I try to run the example from https://www.arduino.cc/en/Tutorial/ConnectWithWPA

Before running the sketch I turn the DIP switch to the position USB. It seems like the WIfi Shield is correct connected to the Arduino since the LEDs TX and RX are blinking during upload the Sketch.

Sadly as output I got only: WiFi shield not present

Currently I'm not sure if the hardware itself provide Wifi functionality. Does somebody know if it should work with this hardware?

# Answer
> 1 votes
You see that double row of 10 pin headers? That's an XBee connector.

https://www.sparkfun.com/pages/xbee\_guide

You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.

Note that XBee is not WiFi, it's Wireless. The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc). XBee *cannot* talk WiFi in the same way that I can't talk Chinese.

For WiFi you need a WiFi shield.

https://www.arduino.cc/en/Main/ArduinoWiFiShield

---
Tags: arduino-mega, wifi
---


# Question
Title: How to update the character table of MAX7456
I've got a MAX7456 chip and I am using this 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 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?

# Answer
> 2 votes
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.

UPDATE: In the end I solved it this way.

Many thanks to Charlie Hanson & Nick Gammon.

---
Tags: atmega328
---


# Question
Title: Updating a sketch to work with IDE 1.6.6
I've got a MAX7456 chip and I am using this (this is the unmodified one) library with it. There's a sketch inside the examples folder (Max7456WriteTable) that I need to get to work to update the character table.

I modified three lines and then I got really stuck as I do not know how to continue. This is the modified one.

```
In file included from Max7456Write.ino:2:0:
/tmp/build4608284042510222737.tmp/sketch/Max7456WriteTable.h:29:69153: warning: narrowing conversion of '243' from 'int' to 'const char' inside { } is ill-formed in C++11 [-Wnarrowing]

```

This happens for every item in the array. But that is not the only problem. (I'll skip a few hundred lines)

```
/tmp/build8855411239666100148.tmp/sketch/Max7456Write.cpp.o: In function `setup':
/home/t/Max7456Write.ino:13: undefined reference to `Max7456::Max7456(unsigned char)'
/home/t/Max7456Write.ino:19: undefined reference to `Max7456::activateOSD(bool)'
/home/t/Max7456Write.ino:44: undefined reference to `Max7456::getCARACFromProgMem(char const*, unsigned char, unsigned char*)'
/home/t/Max7456Write.ino:46: undefined reference to `Max7456::sendCharacter(unsigned char const*, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status
Error compiling.

```

It takes a huge amount of time for it to abort the compilation.

# Answer
> 1 votes
If I change `prog_uchar` to `unsigned char` in both max7456.h and max7456.cpp the hello world example sketch compiles.

In Max7456WriteTable change

```
Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i); //We send currentChar at address i.

```

to

```
Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i, 0); //We send currentChar at address i.

```

`0` is probably the wrong value, but at least it compiles.

---
Tags: atmega328
---


title: IR frequency difference

text:
# Question
Title: IR frequency difference
I want to create a device that interfaces with the Light Strike Lasertag system using an Arduino Leonardo.

The Light Strike system uses not laser but regular infrared signals. According to a site that I found (http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/) it uses 37.8 khz signals. I only found IR-receivers using 37.9 or 38 khz. Can I use them? How far can the modulation frequency differ?

Is there anything else I need to watch out for when creating an IR-interface?

# Answer
> Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?

Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)

---

I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.
> 1 votes

---
Tags: arduino-leonardo, ir
---


# Question
Title: Getting values from multiple thermistors - one value glitches all over the place
I have a circuit with preferably long wires that get data from thermistors. The Arduino sends this data (formatted in JSON) to a web server where it can be collected by another program. Some of these values appear correct, while others do not.

```
[
{
    "dht11": {
        "temperature": 73.4,
        "humidity": 41,
        "heat-index": 77.15
    },
    "thermistors": {
        "therm1": {
            "temp": 71.21,
            "resistance": 12727.27
        },
        "therm2": {
            "temp": 76.22,
            "resistance": 12045.51
        },
        "therm3": {
            "temp": nan,
            "resistance": -19393.41
        }
    }
}
]

```

code:

```
#define THERMISTORPIN A0
#define THERMISTORNOMINAL 10000
#define TEMPERATURENOMINAL 25
#define NUMSAMPLES 25
#define BCOEFFICIENT 4050
#define SERIESRESISTOR 10000
#define THERMISTORPIN2 A5
#define THERMISTORPIN3 A3
#define DHTPIN 2
#define PHOTORESISTOR 3
#define DHTTYPE DHT11
int samples[NUMSAMPLES];
int samples_two[NUMSAMPLES];
int samples_three[NUMSAMPLES];
int stuckintime;
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
byte mac[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0xEE
};
IPAddress ip(192, 168, 1, 3);
EthernetServer server(80);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  dht.begin();
  analogReference(EXTERNAL);
}

void loop() {
  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }
          average /= NUMSAMPLES;
          average = 1023 / average - 1;
          average = SERIESRESISTOR / average;
          float tempreading;
          tempreading = average / 10975;
          tempreading = log(tempreading);
          tempreading /= BCOEFFICIENT;
          tempreading += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreading = 1.0 / tempreading;
          tempreading -= 273.15;
          tempreading = tempreading * 9 / 5 + 32;
          average_two /= NUMSAMPLES;
          average_two = 1023 / average_two - 1;
          average_two = SERIESRESISTOR / average_two;
          average_two = average_two;
          float tempreadtwo;
          tempreadtwo = average_two / 11811;
          tempreadtwo = log(tempreadtwo);
          tempreadtwo /= BCOEFFICIENT;
          tempreadtwo += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadtwo = 1.0 / tempreadtwo;
          tempreadtwo -= 273.15;
          tempreadtwo = tempreadtwo * 9 / 5 + 32;
          average_three /= NUMSAMPLES;
          average_three = 1023 / average_three - 1;
          average_three = SERIESRESISTOR / average_three;
          float tempreadthree;
          tempreadthree = average_three / THERMISTORNOMINAL;
          tempreadthree = log(tempreadthree);
          tempreadthree /= BCOEFFICIENT;
          tempreadthree += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadthree = 1.0 / tempreadthree;
          tempreadthree -= 273.15;
          tempreadthree = tempreadthree * 9 / 5 + 32;
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          float f = dht.readTemperature(true);
          float hif = dht.computeHeatIndex(f, h);
  EthernetClient client = server.available();
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println("Connection: close");
          client.println("Refresh: 0");
          client.println("");
          client.println("[");
          client.println("   {");
          client.println("    \"dht11\": {");
          client.print("          \"temperature\": ");  client.print(f);        client.println(",");
          client.print("          \"humidity\": ");         client.print(h);        client.println(",");
          client.print("          \"heat-index\": ");   client.print(hif);  client.println("");
          client.println("     },");
          client.println("    \"thermistors\": {");
          client.println("        \"under-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreading);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average);  client.println("");
          client.println("       },");
          client.println("        \"side-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadtwo);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average_two);  client.println("");
          client.println("       },");
          client.println("        \"top-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadthree);        client.println(",");
          client.print("             \"resistance\": ");    client.print(average_three);    client.println("");
          client.println("       }");
          client.println("     }");
          client.println("   }");
          client.println("]");
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
  }
}

```

I have no idea what is causing this to happen - pushing RESET doesn't fix it at all, reconnecting wires does not fix it, any help?
(Please tell me what else to include if you need it.)

# Answer
Here's a major problem:

```
void loop() {

  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }

```

The variables *average*, *average\_two*, and *average\_three* have **undefined** values. Thus it isn't surprising that when you add something to them, they are still undefined.

Local variables must be initialized (eg. to zero in your case).

Also, you have two variables named *stuckintime* \- I would do something about that.
> 3 votes

---
Tags: arduino-uno, ethernet, web-server, analog-sampling
---


# Question
Title: Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins
I am working in my project and I want to see the output of my sensors as (0 or 5). The maximum read was 770 and the minimum read was 0. So, how can I see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins. I did the following code, but it didn't work:

```
void setup(){
Serial.begin(9600);
}
void loop()
{
if (analogRead(0)<385)
      Serial.print("0");
 else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(2)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(3)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(4)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(5)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

delay(1500);
}

```

Note: I have 5 light sensors in my circuit.

# Answer
Try this code - it should help you see what is going on more clearly:

```
const int threshold = 385;

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

void loop()
{
  int reading = analogRead(0);
  Serial.print("Analog 0 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(1);
  Serial.print("Analog 1 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(2);
  Serial.print("Analog 2 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(3);
  Serial.print("Analog 3 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(4);
  Serial.print("Analog 4 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(5);
  Serial.print("Analog 5 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  Serial.println();

  delay(1500);
}

```
> 0 votes

# Answer
You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.
> 0 votes

# Answer
Your code has multiple issues.

```
if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

```

Note that `Serial.print(' ');` is not at all the same as `Serial.print(" ");`

---

Also, by the indentation it looks like you should be using braces. Amended code:

```
if (analogRead(1)<385)
      Serial.print("0");
   else
      {
      Serial.print("5");
      Serial.print("  ");
      }

```

Without the braces only the first statement after the *else* is conditionally executed.

If I am wrong about that, you should indent differently, eg.

```
if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
Serial.print("  ");

```
> 0 votes

---
Tags: serial, analogread
---


# Question
Title: Better method for PROGMEM data access with multiple indirection?
-edit-
This is a simplified recreation of personal learning project I have ongoing. My issue is in accessing data in flash, the path to which includes multiple layers of indirection. When the data was in RAM I found accessing it easy and all worked as expected.

In flash I have created a struct mylist, aa in the example, containing a pointer to an char\* array (item\_list\[ \])(in flash) pointing to char\[ \] (in flash).

Problem: (refer to example) Given a pointer to struct aa (pml) and an index into item\_list\[\] (ndx), how to correctly retrieve the string from flash. My example illustrates the only method I can find that works. It seems kludgy at best, in particular needing to twice read pointers from flash as well as calculating the array item offset. Have I missed a proper cast or perhaps become confused about 32 vs 16 bit pointers? Or, as strange as it seems, is this the correct and/or best approach?

All help and constructive criticism will be appreciated.

Code:

```
#include "Arduino.h"
#include <avr/pgmspace.h>

const char x[] PROGMEM = {"Item x"};
const char y[] PROGMEM = {"Item y"};
const char* const item_list[] PROGMEM = {x, y};

struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

const mylist* pml = &aa;

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

  char cbuf[11] = {"__________"};

  // two line with declared intermediate pointer
  uint8_t ndx = 0;
  const char* pitem = (const char*)pgm_read_ptr_near(&pml->list) + (ndx * sizeof(const char*));
  strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pitem));
  Serial.print("item[0]: /");
  Serial.print(cbuf);
  Serial.println("/");

  // one line without declared intermediate pointer
  ndx++;
  strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pgm_read_ptr_near(&pml->list)
                                                + (ndx * sizeof(const char*))));
  Serial.print("item[1]: /");
  Serial.print(cbuf);
  Serial.println("/");
}

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

}

```

Output:

```
item[0]: /Item x/
item[1]: /Item y/

```

-edit-

After many more hours trying many more variations, I feel the approach shown in the following example is workable for me. I have chosen to keep the extra level of indirection to maintain all the flash data for a particular Field in one struct ‘package’. @NickGammon and his excellent examples greatly helped my understanding and comfort level with pointers in and to flash.

The listing is meant to give context to my point in question and is summarized in the method \_copyitem( ) (hope the underscore is ok):

```
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

```

This listing recreates a very small subset of the overall codebase, but the one part that has stopped my progress.

```
#include "Arduino.h"
#include <avr/pgmspace.h>

struct FieldDefinition {
  uint8_t nitems;
  const char** list;
  uint8_t row;
  uint8_t column;
  uint8_t length;
  // etc, etc
};

class Field {
public:
  Field(const FieldDefinition*  /* other parameters */);
  ~Field();  // -edit-
  char * selectItem(uint8_t);
  uint8_t getLength();
  char * selectItem(uint8_t);
  uint8_t getLength();
private:
  const FieldDefinition * _fp;
  char * _value;
  uint8_t _ndx;
  void _copyitem(uint8_t);
};

Field::Field(const FieldDefinition* fp ) : _fp(fp) {
  _ndx = 0;
  char * _value = new char[getLength()];
 _copyitem(_ndx);
};
Field::~Field(){  // -edit-
  delete _value;
};
char * Field::selectItem(uint8_t ndx){
  _ndx = ndx;
  _copyitem(_ndx);
  // display item
  // do more here . . .
 return _value;
}
uint8_t Field::getLength(){
  return pgm_read_byte(&_fp->length);
}
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

// Setup flash data
// selection list
const char f1_0[] PROGMEM = {"Item 0"};
const char f1_1[] PROGMEM = {"Item 1"};
const char f1_2[] PROGMEM = {"Item 2"};
const char* const f1_list[] PROGMEM = {f1_0, f1_1, f1_2};
// create in-flash struct
const FieldDefinition f1 PROGMEM = {4,(const char**)f1_list,1,1,10};
// global instance and pointer to Field
Field * s1f1 = new Field(&f1);

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

  Serial.println();
  Serial.print("Field Length: ");
  Serial.println(s1f1->getLength());
  Serial.println();
  for (uint8_t i = 0 ; i < 3; i++) {
    Serial.print("Selection at index ");
    Serial.print(i); Serial.print(" : ");
    Serial.println(s1f1->selectItem(i));
  }
}

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

}

```

Output

```
Field Length: 10

Selection at index 0 : Item 0
Selection at index 1 : Item 1
Selection at index 2 : Item 2

```

I could very wrong (as previously demonstrated) so comments please.

-edit-

Point taken and completely understood. Destructor added for completeness. In my actual application, multiple fields are constructed by a screen class when a screen is displayed, user interaction accepted, configuration data stored in EEPROM (my next endeavor), then destroyed on screen exit. Selecting from a list is one method available to populate the field value. The whole interface consists of multiple fields, for multiple screens, driven by an underlying state engine, stepped during each ‘loop’ to minimize impact. It functions as expected in an Xcode simulation, and has been a wonderful learning experience moving it to Arduino. I thought all this was non sequitur to my question and regret any confusion I may have caused.

To restate my issue: how to get from

```
// ram based
strcpy(value, _fp->list[ndx]);

```

to

```
// flash based
PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
strcpy_P(value, pitem);

```

using best/correct form with multiple layers of indirection as posted. Is it possible I have missed a proper cast or other mechanism that would allow the compiler to handle the ‘pointer magic’? It appears I have not. @NickGammon I greatly appreciate your input.

# Answer
> 1 votes
```
const char x[] PROGMEM = {"Item x"};
const char y[] PROGMEM = {"Item y"};
const char* const item_list[] PROGMEM = {x, y};

struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

```

It seems to me this is way too wordy for what appears to be trying to store a list of a couple of strings.

---

First:

```
const char* const item_list[] PROGMEM = {x, y};

```

You have a array of pointers to strings. OK.

---

Now:

```
struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

```

Now you have a *list* of an *array*? This is where I am confused.

---

Compare to an adaptation of the code on Putting constant data into program memory (PROGMEM):

```
const int NUMBER_OF_ELEMENTS = 2;

const char Message0000 [] PROGMEM = "Item X";
const char Message0001 [] PROGMEM = "Item Y";

const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
   {
   Message0000,
   Message0001,
   };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    char * ptr = (char *) pgm_read_word (&messages [i]);
    char buffer [80]; // must be large enough!
    strcpy_P (buffer, ptr);
    Serial.println (buffer);
    }   // end of for loop

  }  // end of setup

void loop () { }

```

---

## Edited to comment on new code

You have a major problem here:

```
Field::Field(const FieldDefinition* fp ) : _fp(fp) {
  _ndx = 0;
  char * _value = new char[getLength()];
 _copyitem(_ndx);
};
char * Field::selectItem(uint8_t ndx){
  _ndx = ndx;
  _copyitem(_ndx);
  // display item
  // do more here . . .
 return _value;
}
uint8_t Field::getLength(){
  return pgm_read_byte(&_fp->length);
}
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

```

What I gather you are doing here is, to get the string for an item (for printing) doing a `new` (which allocates memory), copying from PROGMEM into that memory, displaying that item, and then ignoring the allocated memory. Well, you can't do that. You will run out of RAM very quickly.

The code doesn't even have the word `delete` in it. Every `new` should have a corresponding `delete`. It's a fundamental principle.

It looks too complex still. Make a function that just displays the item (menu or whatever it is) without actually making a copy of it. Certainly don't allocate memory and not free it.

---
Tags: flash, progmem
---


# Question
Title: Why does the standard Arduino IDE not include the CH341G USB Drivers?
Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?

I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.

Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.

Here is the link to the official drivers.

Here is a good article on how to download the drivers.

BTW, the command to disable the digital signature check on the mac we need to do the following:

In the Mac "Terminal" application enter:

```
sudo nvram boot-args="kext-dev-mode=1"

```

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:

```
sudo nvram boot-args="kext-dev-mode=0"

```

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -\> Port Menu within the Arduino application.

```
/dev/tty.SerialPort
/dev/cu.SerialPort

```

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?

Tags: Driver CH340 Setup Installation

# Answer
> 5 votes
This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.

What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.

Or you could shift to another board that uses the ATMEGA32u4 as this **might** not require anything special. Have a look here. I don't have tested this board so you will need to check the quality and whether it works with your projects.

# Answer
> 5 votes
> I should mention that the CH340G are also used in many "Arduino Nano" clones from China.

I believe that the Arduino company already has concerns about the number of unofficial clones (many pretending to be genuine) and have lost a considerable amount of revenue to those knock-off products.

I imagine they are not going to make things worse for themselves by including drivers for unofficial boards, so that the job of the clone-makers is even easier.

---
Tags: ide
---


# Question
Title: How to measure the state of charge of a battery in arduino
This questions has been formulated several times with not clear answer, and I wonder if there is one.

it is well stablished from several sources that measuring the voltage of a battery alone is not good indicator of the State of Charge (SOC) of the battery because voltage does not decline proportional to the soc.

Another solution (http://fritzing.org/projects/battery-charge-level/) suggest measuring the voltage (with analogread) between two resistors connected to the gnd and vcc of the circuit (I presume this constantly draw power) and then choose what is the critical voltage of the circuit.

However, my question is how to measure the SOC of a battery using units of 0 to 100% in arduino?

# Answer
To do it correctly, you need a coulomb counter. Something like this.

Even that is not fully sufficient, as the charge that can be obtained from a battery depends on various factors, such as temperature and ageing.

More recent batteries have somewhat flat discharge curve, when it comes to voltage, till they run flat, then the voltage drops significantly. Which means that you would need a very accurate voltage meter.

However the starting point is that you must be able to count how much charge is going in and out.
> 1 votes

---
Tags: voltage-level, battery
---


# Question
Title: Connect multiple modules to arduino micro
I have an Arduino Micro and I want to connect an LCD and Bluetooth module to it. The problem I face is that there are not enough power pins for them both.

I understand that I probably need some external power supply for them, but I have no idea how to do this properly.

# Answer
> 1 votes
You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient. As long as you have a shared Vcc-to-GND reference, it's enough.

To verify that the power supply you choose is ok, do the following:

* check that the modules are compatible with its voltage (ex: all at 5V)
* check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

* check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
* check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.

---
Tags: power, arduino-micro
---


title: Help choosing a servo motor

text:
# Question
Title: Help choosing a servo motor
I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo". The Links are:

Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773

Servo2: http://www.ebay.in/itm/251928442829?aff\_source=Sok-Goog

My Problem is that **I am confused with the name "Digital Servo"**. Its cheaper but I a afraid that will it work as normal. Please help me.

Are both the **same** product, but with a different name?

# Answer
> 1 votes
Servos are digital by definition. All you have there is two sellers that are selling the same product, but they are describing them slightly differently. They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).

However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them. That's about ¢5 or 3p.

---
Tags: servo
---


title: arduino boards manager configuration

text:
# Question
Title: arduino boards manager configuration
I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.

I am using c++11 in my project so i need to add the `compiler.cpp.extra_flags=-std=gnu++11` like i did in the `/Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt` file (i am on MacOSX). It seems that arduino is ignoring that file and using a configuration coming from somewhere else.

Where is the downloaded package installed? Can it be configured?

# Answer
> 1 votes
Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino-\>Preferences (under macosx) at the bottom of the window there is the clickable path of the `preferences.txt` file. In the same folder as that file you will find a `packages` folder, where the plugins are downloaded.

---
Tags: c++, arduino-due, compile
---


title: Is it correct to use pulseIn() in ISRs?

text:
# Question
Title: Is it correct to use pulseIn() in ISRs?
Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?

# Answer
It is quite OK to use `millis()` or `micros()` inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is `unsigned long` and `volatile`. Eg.

```
volatile unsigned long whenItHappened;
volatile bool eventHappened;

void myISR ()
  {
  whenItHappened = millis ();
  eventHappened = true;
  }

```

Now in your main loop you can test the `eventHappened` flag, so you will know if this event has happened, and `whenItHappened` is when.

It is **not** a good idea to use `pulseIn()` because that can wait quite a long time for a pulse. The default timeout for `pulseIn` is 1 second, which is far too long to wait inside an ISR.

If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

---

## Example

Example code which times how long a ball passes a sensor:

```
const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if low, ball is in front of light
  if (digitalRead (photoTransistor) == LOW)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

```

That code used `micros()` for a more accurate timing.

---

## Reference
> 1 votes

# Answer
You shouldn't really use anything much in interrupts. Using anything that runs for a period of time is usually bad since no other interrupts can happen at the same time.

It is more normal to use the interrupt to set a flag that is then checked within your main loop to determine what should be done.
> 0 votes

---
Tags: isr, millis, pulsein
---


# Question
Title: Timer 2 interrupt with ATmega328p and make measurement in ISR
I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :

```
void setup(){

cli();

  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;
  OCR2A = 99;
  TCCR2A |= (1 << WGM21);
  TCCR2B |= (1 << CS21);
  TIMSK2 |= (1 << OCIE2A);
sei();

Serial.begin(9600);
}
void loop()
{
Serial.print(digitalRead(1));
Serial.print(' ');
Serial.print(digitalRead(2));
Serial.print(' ');
Serial.print(digitalRead(3));
Serial.print(' ');
Serial.print(digitalRead(4));
Serial.print(' ');
Serial.print(digitalRead(5));
Serial.println(' ');

}

```

# Answer
> 1 votes
Well let's start from the start ...

---

## Analog readings

> to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

```
Serial.print(digitalRead(1));

```

That is not reading **analog** pin A1, it is reading **digital** pin 1. If you want to read A1 you need:

```
Serial.print(analogRead(1));

```

---

## Check the time

By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.

Example:

```
void setup()
{
  Serial.begin(115200);
}  // end of setup

unsigned long lastReading;
const unsigned long INTERVAL = 100;  // ms

void loop()
{

  // is time up?
  if (millis () - lastReading >= INTERVAL)
    {
    lastReading = millis ();  // when we took this reading
    Serial.print(analogRead(1));
    Serial.print(" ");
    Serial.print(analogRead(2));
    Serial.print(" ");
    Serial.print(analogRead(3));
    Serial.print(" ");
    Serial.print(analogRead(4));
    Serial.print(" ");
    Serial.print(analogRead(5));
    Serial.println();
    }  // end of if time up

  // do other things here

}  // end of loop

```

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

---

## Using timers

If you really want to use timers (and I don't see what they achieve here) I have a page about timers that describes using them, and interrupts, in some depth.

The very least you would need is a timer 2 "compare A" interrupt like this:

```
ISR (TIMER2_COMPA_vect)
  {
  // Timer 2 has reached its comparison value
  }

```

---
Tags: arduino-uno, interrupt, atmega328
---


# Question
Title: w5100 and nrf24l01 - SoftSPI - Radio not starting
I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.

The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time

The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.

What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.

Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:

```
radio.printDetails();

```

does nothing.

I'm using manicbug's library.

I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.

Pinouts:

CSN -\> 10 CE -\> 9 MISO -\> 12 MOSI -\> 11 SCK -\> 13 VCC -\> Separate 3.3 source, not the arduino GND -\> GND

My guess is this is because both are using SPI.

Tried the softspi method http://pastebin.com/4mv612B7 .

Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..

EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago. I can get details now. still having communication issues. Will post more debugging information in a bit.

# Answer
> 0 votes
The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.

# Answer
> 0 votes
Issue one: .printDetails(); uses printh. If you don't have that included you won't get the information.

Issue two: The ide gets confused when you have two libraries with the same file. I compiled my receiver with the softspi file. Once I put the right library in it works.

---
Tags: ethernet, nrf24l01+
---