# Question
Title: Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection
I'd like to create a process to programmatically turn-on/activate a separate USB device connected to my computer...Thinking another way to state the problem, I want the Arduino to complete the USB power circuit and then "turn off" on a schedule.

In an essence, I'd like to have my Arduino facilitate the manual process of un-plugging a USB into my computer (lets say for 5 seconds) and then re-plugging it in (let's say for 5 mins)-- rinse and repeat on a schedule....I'd like to have this coded/programmed though (I'm ok in the Arduino IDE -- sample code would really help me out a ton though) -- I'm not going to setup an actual servo to do this.

I thought getting a Arduino Shield would be the right place to start but I'm really lost. I also thought getting a USB cable with a flip power switch might be another way to tackle the problem too-- but I haven't started to mess with it yet.

Any ideas or resources to point me in the right direction are greatly appreciated. Thanks so much.

# Answer
I'm not aware of any off the shelf "shields" which would accomplish this goal. Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.

Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.

Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones. Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried. If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.

At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.

It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper. This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated. An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first. Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.

Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.

Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.
> 1 votes

# Answer
```
At the crude end you could probably use a relay board.

```

hmmm, you RAAAANNNNNGG? (yes finally a reason validating my existence!)

Sorry, but I just couldn't resist chiming in on this topic. So what I can add is:

I have a Teensy 3.2 - RPi2 contraption at a site which is impersonating a USB mouse, from the security NVR's perspective (think Fred Sanford meets Frankenstien) And since I just couldn't grok using the serial UART (I think) I did everything using relays and optocouplers. So I SSH my way into the RPi's using Putty to initialize a VNC connection (just once per restart; although ugly, this sure beats the trauma of BASHing commands into RPi which elf up its bootup behavior to autostart VNC) So now instead of dreary CLI hell I have an ARM friendly release of the latest Arduino 1.6.13 IDE(emphasis on GUI !!) which (as of like the last few months) NOW SUPPORTS Teensy 3.2 with Teensyduino! (meaning support for teensyloader as well) Pretty slick, huh? Write Arduino sketches "anywhere on earth" with full GUI support and flash them onto a Teensy (well at least it's impressive to me...)

OK, so now comes the crude hacking of ugly relays I salvaged dumpster diving (that's pronounced "F-R-EE") The flaw in my setup is how to get the freshly programmed Teensy to change hosts? So I built an mechanical A-B switcher (2 hosts sharing a single client). Originally I was way cautious so I used four double pole relays for pluging/unplugging in a 5 step process controlled by three of RPi's GPIOs. USB power supply lines from the Teensy feed the poles on a DPDT relay, disconnecting Teensy from all power if energized. N.C. contacts feed the poles on another relay that selects one of two hosts. The N.C. contacts on this relay feed the NVR, so that if control circuitry fails to deliver power to any given relay coil, the "normal" contacts default to Teensy being fully connected to the NVR, which normally doesn't shut down. The Rx & Tx lines were wired the same way.

When jumping from host to host, I used the rule for PA amplifiers to remember: last to power up, first to power down. The five step sequence is derived from this rule, which is: `ENERGIZE SIGNAL RELAY`, `ENERGIZE POWER RELAY`, `TOGGLE SWITCHING RELAY`, `KILL POWER RELAY`, `KILL SIGNAL RELAY` This is the weakness in my system, because I use the same script regardless of the host. The middle step is just "toggle" and led to a sloppy protocol. Rigorous fool-proofing shouldn't allow a script to end with the A-B selector having an energized relay since the fall-back safety configuration was hard-wired for all relays being in their normal, unenergized state. As long as a relay is energized, the script keeps running would be best practice. So, being lazy and absent-minded, it wasn't long before I rebooted the RPi with the Teensy still attched. Sheer terror. And the next time, merely anxiety. Subsequent breaches of protocol became simple annoyances. So now, protocol is a joke, reboot has all the dignity associated with an episode of Jersey Shore! (translation the signal/power concern hasn't been an issue in this situation)

Bottom line, mechanical port switchers have worked great for me. After the Teensy project is complete, I plan on using it to switch a USB drive between the NVR to archive important files, and a RPi for file sharing over the web. And remember, mechanical switchs (with relays belonging to the family) are still superior to Silicon based devices in many way. For example, leakage current in mechanical switches is almost nil, they have no polarity constraints, consume no current, and produce no noise in a static state.

And finally, regarding this passage:

`Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.`

I'd like to share a gem I unearthed on eBay: a finer link you cannot find and is as fresh as today's date. So here's a hub that I think matches your description:

http://www.ebay.com/itm/NEW-7-Port-High-Speed-USB-2-0-External-Multi-Expansion-Hub-with-ON-OFF-Switch-LO-/161831365420?hash=item25ade6ab2c

Yes, that a 7 port hub with a toggle switch and indicator led on each port. Delivered right to your door for the tidy sum of US$3.01 What kind of numbers does it benchmark at? Hmmm. you might be missing the point. It's a 7 port UBS hub with bells $ whistles with FREE SHIPPING for 3 BUCKS !!!

(CLEAR)
> 1 votes

---
Tags: arduino-uno, power, shields, usb, teensy
---


# Question
Title: What is the memory expense of creating a String from a char array?
I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?

What would be the best-practice in this kind of situation?

# Answer
> What would be the best-practice in this kind of situation?

To not use `String`.

> I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an `indexOf` function in your API. But you don't have to use `String` to implement that function when called. You can just use the `strstr` function on char arrays (reference here).

I should also point out that most Arduinos do not have enough RAM for storing an email.

### UPDATE 07-01-2016:

To answer the titular question, the fixed cost of using `String` is at least 1600 bytes of program space, more if you use more than a few methods. The linker can throw out methods you don't use.

Then for each `String` variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data. This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap. That's a total of 12 extra bytes per `String` instance.

However, I did not originally answer that question because you explicitly asked about the *memory* expense. This ignores other expenses that should not be ignored:

* execution time - Allocating memory from the heap is really a search for a chunk of the requested size. At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk. And when the `String` is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks. Reducing the size of a `String` does not free up any memory. The `String` maintains its maximum size until it is emptied or destroyed.
* long-term stability - Embedded Systems are supposed run *forever*. A primary characteristic of a system that can run forever is "deterministic." For whatever inputs it receives, it has a predictable response and end state. When you use the heap via `String`, the heap gets fragmented according to the data it handles. This is not predictable, and it may get into a state where no memory chunk of the requested size is available. Choke.
* maintenance - because the heap state depends on the processed `String` data, finding the cause of the failure can be difficult. It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of *these* expenses, `String` is rarely used by an experienced developer. Unfortunately, `String` is tempting to the beginner because it is easy to understand. What is difficult to understand is the complicated, non-deterministic behaviour under the hood that **inevitably** leads to system failure, rending of garments and gnashing of teeth.
> 7 votes

# Answer
\[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.\]

With a Mega, there's enough memory to *consider* doing what you propose ***if*** we make some assumptions and modifications:

1. We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);
2. We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.
3. Either the String object is modified to only use the new allocator or the system '*new()*' is replaced by it.

The obvious disadvantages are:

* The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).
* You'll need to know something about your application's memory needs to plan the buffer pools.
* You'll have to plan to prevent or handle allocation failure.

In exchange, you get:

* The allocator won't crash your system.
* The String object's programming advantages become available.
* You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.
> 1 votes

---
Tags: c++, string, memory-usage
---


# Question
Title: Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?
I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! \[nothing's worse than that miserable goose-egg :( \]

# Answer
No. the code burned in an Arduino is compiled not interpreted like Basic.

Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.

Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.

Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:

```
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}

```

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.

It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.
> 3 votes

---
Tags: sketch, progmem, memory
---


# Question
Title: How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator?
I need to program a ATMega328P on a breadboard, running on an external crystal at 8 MHz.

All of the guides I can find either use the arduino environment and describe a 16 MHz config, or using the 8 MHz internal oscillator - which is too inaccurate for this project.

How do I do this? Configure the chip to run at 8 MHz and upload the program?

# Answer
myself as of 3 hours ago.

1. Get an arduino or similar, install the ArduinoISP sketch
2. Connect the two as described here.
3. Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
4. Hit burn bootloader button
5. Load up the sketch that you want on the device
6. Without changing anything, use "Upload using programmer"
7. Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange for posterity. Or so I can find it when I forget next time...
> 2 votes

---
Tags: atmega328, oscillator-clock
---


title: Change select pin of USB Host library

text:
# Question
Title: Change select pin of USB Host library
### TL;DR

With regards to the USB host library:

* Which is the correct file to modify the Arduino pin used for the USB Host slave select (SS) line?

---

I would like to add USB host functionality, to a particular Arduino setup, whilst, also, being able to use an Ethernet/SD (or just SD) shield.

As both the Ethernet shield and USB Host shield use pin 10 to select the W5500 and MAX3421E respectively1, obviously I can not use a standard USB Host shield. However, I could employ one of the small form factor boards, such as the USB Host Shield 2.0 Arduino UNO MEGA ADK Compatible Google Android ADK which I found on eBay:

As this board is not in the usual shield "shape", one would not be constrained by which pin to connected to which MAX3421E input/output, in particular the chip select (SS) input. So, one could use a pin (or pins) that is not reserved by the Ethernet shield.

*However*, it does not appear to be possible to simply specify the "select pin" (i.e. the Arduino pin connected to the SS line) when using the USB Host shield library (or any of the pins used by the library), in `setup()`.

Therefore, I wondered if it was possible to modify the library, so that the pin used to select the USB/MAX3421E could be changed, either by:

* "Hardcoding" a *different* "select" pin number into a header file;
* Adding an argument to the `Init()` method, or;
* Adding a method to the `USB` class, such as `Usb.DefineSelect()`.

The latter two options, I could work through, given the time. However, as a quick and dirty hack, where would I hardcode in a change from pin 10 to a pin of my choosing? Does anyone know? Has anyone had to do this?

---

### Nitty-gritty

I have had a look through the library to see where pin 10 is defined as the chip select, and avrpins.h looked like a possible candidate for modification, although it would be rather "rude" (for want of a better word) and probably mess up the other boards.

usbhost.h seems a much better proposition. Looking at usbhost.h, the lines 88-91:

```
#if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
#elif  defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

```

Looking at the statement

```
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

```

the last argument appears to be the pin used for *select*. For the Uno (ATmega328P), in avrpins.h (line 535) `Pb2` is `P10` (pin 10), so I could substitute `Pb2` for some other pin definition, i.e. `Pd5` for `P5` (pin 5) (line 529 in avrpins.h).

However, what I don't understand is that for the statement

```
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;

```

which deals with the Mega (ATmega2560), in avrpins.h (line 512) `Pb0`is `P53` (pin 53). As `Pb4` is actually `P10` (pin 10) (line 466), why is `Pb0` en lieu of `Pb4` used? That doesn't tie up with the fact that Pin 10 is used for both the Uno and Mega boards. It seems to suggest the pin 10 is used on the Uno and pin 53 is used on the Mega. Unless I have misinterpreted the `typedef`.

---

### Footnote

1 For the USB host shield, from Arduino USB Host Shield

> Arduino communicates with the MAX3421E using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 10, 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the MAX3421E. Pins 7, 8 and 9 are used for GPX, INT and RES pins.

The key piece of information here is that pin 10 is used by *both* the Uno and Mega boards.

For the Ethernet shield, from Arduino Ethernet Shield V2

> Arduino communicates with both the W5500 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5500 and pin 4 for the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, 53, is not used to select either the W5500 or the SD card, but it must be kept as an output or the SPI interface won't work.
>
> Note that because the W5500 and SD card share the SPI bus, only one at a time can be active. If you are using both peripherals in your program, this should be taken care of by the corresponding libraries. If you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. For the W5500, set digital pin 10 as a high output.

Here, yet again, the key piece of information here is that pin 10 is used by *both* the Uno and Mega boards to select the Ethernet.

# Answer
> 3 votes
In order to change the Arduino pin used to select the USB Host board, in order words, where the device's SS line is assigned to an Arduino pin (with the Arduino as the SPI Master and the USB host is the SPI slave), the line to change is at line 43 in `UsbCore.h`:

```
typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

```

So to use pin 5, for example, en lieu of pin 10, the line would become:

```
typedef MAX3421e<P5, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

```

The clue was in the comment on line 27 in `UsbCore.h`

```
/* shield pins. First parameter - SS pin, second parameter - INT pin */

```

With this suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

---

This issue, I have subsequently discovered, is covered by the USB Host Shield Hardware Manual, under the **Interface modifications** section. I guess I should have just read the manual first! RTFM...

---

### Clarification of the issue

I must be honest that my question was somewhat confused. After having read the SPI library, it states that

> **Note about Slave Select (SS) pin on AVR based boards**
>
> All AVR based boards have an SS pin that is useful when they act as a slave controlled by an external master. Since this library supports only master mode, this pin should be set always as OUTPUT otherwise the SPI interface could be put automatically into slave mode by hardware, rendering the library inoperative.
>
> It is, however, possible to use any pin as the Slave Select (SS) for the devices. For example, the Arduino Ethernet shield uses pin 4 to control the SPI connection to the on-board SD card, and pin 10 to control the connection to the Ethernet controller.

With respect to the first paragraph, the Uno uses pin 10 and Mega uses pin 53 as the Arduino SS line - so that must be set as an output in order for the Arduino to be the Master. Are realising this as being my source of confusion, it became apparent that the `typedef` statements, in `usbhost.h`, were *not* where I should have been looking to change the device's Slave Select pin.

With respect to the second paragraph, I want to use pin 5 (for example) to control the Slave Select (SS) for the USB Host device, instead of the default pin 10.

---
Tags: usb
---


# Question
Title: Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?
Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

# Answer
> 1 votes
If you look at the PCB of the Adafruit Music Maker here:

https://learn.adafruit.com/assets/16643

You can see that there are no connections on the analog I/O of the Arduino.

---
Tags: shields, adafruit
---


title: Avrdude fails to verify after upload

text:
# Question
Title: Avrdude fails to verify after upload
I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:

```
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file ".build_ano/uno/firmware.hex"
avrdude: writing flash (30908 bytes):

Writing | ################################################## | 100% 5.01s

avrdude: 30908 bytes of flash written
avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.96s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7800
         0xff != 0xfe
avrdude: verification error; content mismatch

avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

```

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?

I tried uploading to a different Arduino Uno, and I received the exact same error.

# Answer
So here is my official answer ;-)

Your sketch goes above the 30k flash available on the Arduino Uno.

Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.

Try optimizing it.

A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.
> 1 votes

---
Tags: arduino-uno, uploading, avrdude, flash
---


title: Controlling a button

text:
# Question
Title: Controlling a button
I'm going to write a sketch that would light up the first LED (D1) of the training shield at the beginning, then move the LED light to the left or to the right whenever you press the S1 or S2 buttons, respectively. When the LED is already at the first (D1) or the last (D8), it should no longer move when going further to the left or right, respectively.

Looks exactly like this: https://www.youtube.com/watch?v=\_KQQTdDMgOU

Here's what I made so far:

```
int x = 0;

void setup() {
  for(int i=11; i <= 18; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  x = digitalRead(pushButtonPin);
  if (pushButtonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

# Answer
> 1 votes
What you made so far is only turn on and off LED according to button state. I believe there's more efficient code out there, but you can try:

```
int x = 11;

 void setup() {
 for(int i=11; i <= 18; i++) pinMode(i, OUTPUT); //assuming the led is on pin 11-18
 }

 void turnLED(int num)
 {
     for(int i=11; i <= 18; i++)
         if (num==i) digitalWrite(i,HIGH); else
                     digitalWrite(i,LOW);
 }

 void loop() {

    if (digitalRead(buttonRight))
    {
        x++;
        if (x>18) x=18;
    }
    else if (digitalRead(buttonLeft))
    {
        x--;
        if (x<11) x=11;
    }
    turnLED(x); //turn LED on according to value of 'x'
    delay(500);
}

```

---
Tags: arduino-uno, arduino-ide
---


title: Error code 10 for arduino device driver

text:
# Question
Title: Error code 10 for arduino device driver
How can I fix error code 10 while installing the device driver for Arduino in Windows 8.1? The LED on the board is blinking after connecting it to the laptop, so I don't think so that the board is damaged. What is the cause of this issue?

# Answer
> 1 votes
First of all, test if you even need a new driver. On Windows, the Arduino drivers for my Uno and my Mega were installed automatically by Windows. I'd advise to restart your computer, ***using the actual restart button, not manually shutting off and turning on... this is very important with Windows 8.1 and its Hybrid Boot default!!!*** A normal reboot doesn't fully reload all of the drivers. Next, open the Arduino IDE, and then see if you can successfully upload the "blink" example sketch.

If that doesn't work, let's try something else.

First of all, open up Device Manager and find your device:

>

It should be under the *Ports (COM & LPT)* section. After that, right click and click on *Properties*.

>

Then, let's go to the *Driver* tab and click on *Update Driver*. Then, click on *Search Online Automatically for this Driver.*

>

First, try seeing if an automatic update finds any drivers capable. If not, I've found previously that there's sometimes a *Reinstall* or *Fix* button somewhere if the driver isn't working correctly.

In addition, you can also update it manually using Device Manager. Instead of clicking on *Search Online Automatically for this Driver,* click *Browse My Computer Manually.* For me, there was a Mega driver under the *Let me pick from a list of compatible device drivers on my computer* and there was a Mega driver for me (although I don't know if that's because I have it installed already).

You can also use that same menu to point it to the location of the installation of the Arduino IDE and it will search for any compatible drivers.

Rolling back the driver is another option if the Arduino IDE tried to install a faulty driver that somehow got corrupt over a working driver installed by the computer.

The last thing I would suggest trying as a last resort is using the *Uninstall Driver* button and then trying to reinstall the driver manually. I've never done this with an Arduino board, although there have been some times with other drivers that this has helped to remove the faulty driver.

If none of this works, it may be a faulty board.

# Answer
> 1 votes
I had the same issue. The drivers, which shipped with Arduino IDE didn't work for me.

Actually, the reason was that I was using Arduino UNO clone. And it required another driver. This video helped me to find the answer: https://www.youtube.com/watch?v=r9MGJ16pRLc

In my case I had to install the CH340 chipset usb driver. The driver can be downloaded from this page: http://www.microcontrols.org/arduino-uno-clone-ch340-ch341-chipset-usb-drivers/

After I installed CH340 driver, the upload from Arduino IDE started working perfectly.

# Answer
> 0 votes
After wasting a huge amount of time trying get the Arduino IDE to upload the sketches to my new starter robot I came across the following document in the Arduino Website :"Guide to the Arduino Leonardo and Micro"... In this document they explain how the serial port communication work on the leonardo (which is the ME-Baseboard from MakeBlock)...They state that auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it... Whatever that means... I went into the makeblock driver setting (under windows 8.1 device manger) and change the baud rate to 1200... Surprise surprise... all works fine now, I can compile and upload the sketches for the starter robot... What frustration !!!! And for the people at Makeblock... I have been trying to create a community userid and while the system say that it will send me an email, it never does !!!

# Answer
> 0 votes
I am sad to report that what actually happened it that changing the baud rate also led to a change in board type in the arduino IDE... So the sketch did compile and load but assuming that the board is a UNO. End result, still facing same problem and robot behave a bit erratically probably because the upload was not performed for a leonardo board. I have tried counless times with countless different procedures on an acer laptop with Windows 8.1, an acer laptop with Windows 7 and a surface pro with Windows 7. Same problem everywhere. If someone from Makeblock read this blog, I would appreciate if you could send me the validating email so I engage this troubleshooting process on their community discussion board.

---
Tags: arduino-ide
---


title: Issue with Arduino Timing

text:
# Question
Title: Issue with Arduino Timing
I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:

```
#include <TimerOne.h>
#include <SPI.h>

const int LED_PIN = 3;
const int CHIP_SELECT = 12;

const int PERIOD = 4000;
const double DUTY_CYCLE = .5;
const int HIGH_TIME = PERIOD * DUTY_CYCLE;
const int LOW_TIME = PERIOD - HIGH_TIME;
const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

const int RESISTOR_VALUE = 255;

boolean triggered = false;
boolean data = false;

unsigned long triggeredTime;
unsigned long s;
unsigned long e;

boolean found;
int i = 0;

void setup()
{
  s = micros();

  Timer1.initialize(PERIOD);
  Timer1.attachInterrupt(trigger);

  pinMode(LED_PIN, 3);
  pinMode(CHIP_SELECT, OUTPUT);

  SPI.begin();

  digitalWrite(CHIP_SELECT, LOW);
  SPI.transfer(B00010001);
  SPI.transfer(RESISTOR_VALUE);
  digitalWrite(CHIP_SELECT, HIGH);

  e = micros();

  Serial.begin(115200);
  Serial.print("s: ");
  Serial.println(s);
  Serial.print("e: ");
  Serial.println(e);
}

void loop()
{
  if(triggered)
  {
    while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
    { }
    s = micros();
    digitalWrite(LED_PIN, data);
    while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
    { }
    digitalWrite(LED_PIN, LOW);

    data = !data;
    triggered = false;

    e = micros();
    //micros();

    if(s % 100 > 28 || s % 100 < 12)
    {
     found = true;
    }

    if(!found)
    {
      Serial.print("s: ");
      Serial.println(s);
    }
    else
    {
      Serial.print("ERROR: ");
      Serial.println(s);
    }
    //Serial.print("e: ");
    //Serial.println(e);
  }
}

void trigger()
{
  triggeredTime = micros();
  triggered = true;
}

```

(it should be noted that the first signal sent is always xx20, usually 5020).

So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:

```
.
.
.
s: 1141020
s: 1145020
s: 1149020
ERROR: 1153032
ERROR: 1157020
ERROR: 1161020
.
.
.

```

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

# Answer
the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

> if(s % 100 \> 28 || s % 100 \< 12)

I would use a few brackets to make it clear to the compiler what you want it to do.
> 1 votes

---
Tags: pwm, time
---


# Question
Title: Suse or Debian Linux Installation on Raspberry PI 3
Is I can install Suse or Debian Linux Installation on Raspberry PI 3. I yet to try. Based on the answer I can opt for it. Because I need in particular either of this OS for my requirement in classified project. Does this PCB design supports this OS.

Any advice or suggestions is greatly appreciated.

# Answer
> 1 votes
It is always best to try then post in one of the Stack Exchange groups.

This question is very general. So the answer will also be vague as the actual porting of a Linux OS distribution to a new platform is not trivial and contains many steps. And not all of them may have been completed to the extent to suit your needs.

Evidently you can run Debian on a Raspberry Pi. But there are a few issues. Look here and do the research to understand if these limitations will cause you to abandon this path.

As for Suse, evidently it is a "specially packaged version of SUSE". So may not actually have all the features a normal Suse distribution has. Look here to decide if it will work for you.

---
Tags: linux, raspberrypi, pcb-design
---


# Question
Title: Using both a stepper motor and a DC motor with Arduino motor shield R3
We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.

We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

# Answer
> 1 votes
You are right: Motor Shield R3 can drive two DC motors or one step motor.
So, there are 2 (maybe 3) solutions:
1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.
2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.

optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.

---
Tags: arduino-motor-shield
---


# Question
Title: SD test is taking long answer when it fails
I am working on an Arduino application that logs sensors values into SD files. It is essential that the SD is inserted and working when a test is started, thus I need to check the presence of the SD regularly (every 2 seconds or so) to prevent launching a test without SD inserted by the user.

When I run the following code, it runs very fast when the SD test succeeds (\<10ms), but it takes more than 2000ms when the test fails. Is there another test I could run that does not takes 2 seconds to indicate that the SD is not inserted (or not working)? All my buttons are frozen and they do not trigger any action while checking if no SD is inserted.

Here is my code (both loops have the same issue):

```
#define csSD   53
#include <SD.h>

Sd2Card card;

void setup() {
  Serial.begin(57600);
  bool SDOK = SD.begin(csSD);
  if(SDOK) {
    Serial.println("SD.Begin Setup OK");
  } else {
    Serial.println("SD.Begin Setup Fail");
  }
}

unsigned long t;
//void loop() {
//  t=millis();
//  if(SD.begin(csSD)){ // SD.Begin test runs fast when there is a SD, even though it return true when you try to begin SD a second time
//    Serial.print("SD.Begin loop OK : ");
//  }else {
//    Serial.print("SD.Begin loop Fail : ");
//  }
//  Serial.println(String(millis()-t)+"ms");
//  delay(500);
//}

void loop() {
  t=millis();
  if(card.init(SPI_HALF_SPEED, csSD)) {
    // card.init test returns true as it should (when SD is present and working), but runs fast only when SD is working
    Serial.print("card.init loop OK : ");
  } else {
    Serial.print("SD.Begin loop Fail : ");
  }
  Serial.println(String(millis()-t)+"ms");
  delay(500);
}

```

# Answer
> 1 votes
The SD library builds on the sdfatlib library, in which SD\_INIT\_TIMEOUT is defined as 2000 ms, which gives your 2 second timeout. You could try lowering that number to get a faster response, although that may run the risk of timing out even when a card is present.

Four different timeout periods are defined in the sdfatlib source:

```
/** init timeout ms */
uint16_t const SD_INIT_TIMEOUT = 2000;
/** erase timeout ms */
uint16_t const SD_ERASE_TIMEOUT = 10000;
/** read timeout ms */
uint16_t const SD_READ_TIMEOUT = 300;
/** write time out ms */
uint16_t const SD_WRITE_TIMEOUT = 600;

```

The 300 ms read timeout is faster, as @Paul suggests in his comment, so you could just use a card read as the test rather than an initialisation, or try setting the init timeout to 300 instead. A read test would be simpler, as it doesn't involve modifying library files. It might not cope with a re-inserted card, though - I suspect that requires reinitialisation each time.

Note: the version of sdfatlib included with the SDlib in my Arduino install appears rather older than the current version. The included version defines the timeouts in Sd2Card.h, while the latest has is in SdInfo.h. The snippet above is from the older, included code.

# Answer
> 0 votes
You could always try this very simple sketch. I have never measured how quick it runs, but it is pretty quick.

```
Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

```

Just make sure to change 4 in `!SD.begin(4)` to whatever your ChipSelect pin happens to be for your component.

Furthermore, you could add a `return` statement after your "initilization fails" loop because that will immediately stop the program, after all you do not want to run it if the SD card is not reading data! And last thing, it may be a little overkill to check the SD card after initial initilization, after all, it will be highly unlikely for an error to occur once everything is working fine unless you mess with the SD card alot while it is running, which I am sure you won't.

---
Tags: arduino-mega, sd-card, testing
---


# Question
Title: Wireless Sensor communication with 100Hz rate
I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

# Answer
> 1 votes
Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate. If not, maybe the main arduino loop has delays in it.

---
Tags: serial, wireless
---


title: Why is SD card failing to begin?

text:
# Question
Title: Why is SD card failing to begin?
I recently bought a micro SD storage shield for my arduino project, this is the link. My final goal is to log information every 100 ms about the temperature and pressure of my device using another one of my sensors. However, I started by testing out the SD card through the SdInfo class that comes as an example with the SdFat library. This is the outcome (through the Serial monitor):

```
SdFat version: 20160719

Assuming the SD is the only SPI device.
Edit DISABLE_CHIP_SELECT to disable another device.

Assuming the SD chip select pin is: 10
Edit SD_CHIP_SELECT to change the SD chip select pin.

type any character to start

init time: 748 ms

Card type: SDHC

Manufacturer ID: 0X28
OEM ID: BE
Product: 68BHO
Version: 0.8
Serial number: 0XD50B3A66
Manufacturing date: 11/2010

cardSize: 32026.66 MB (MB = 1,000,000 bytes)
flashEraseSize: 128 blocks
eraseSingleBlock: true
OCR: 0XC0FF8000

SD Partition Table
part,boot,type,start,length
1,0X0,0XC,8192,62543872
2,0X0,0X0,0,0
3,0X0,0X0,0,0
4,0X0,0X0,0,0

Volume is FAT32
blocksPerCluster: 64
clusterCount: 976992
freeClusters: 976905
freeSpace: 32011.22 MB (MB = 1,000,000 bytes)
fatStartBlock: 9310
fatCount: 2
blocksPerFat: 7633
rootDirStart: 2
dataStartBlock: 24576

type any character to start

cardBegin failed
SD errorCode: 0XA
SD errorData: 0X5

```

This is the code of the class SdInfo:

```
/*
 * This program attempts to initialize an SD card and analyze its structure.
 */
#include <SPI.h>
#include "SdFat.h"
/*
 * SD chip select pin.  Common values are:
 *
 * Arduino Ethernet shield, pin 4.
 * SparkFun SD shield, pin 8.
 * Adafruit SD shields and modules, pin 10.
 * Default SD chip select is the SPI SS pin.
 */
const uint8_t SD_CHIP_SELECT = SS;
/*
 * Set DISABLE_CHIP_SELECT to disable a second SPI device.
 * For example, with the Ethernet shield, set DISABLE_CHIP_SELECT
 * to 10 to disable the Ethernet controller.
 */
const int8_t DISABLE_CHIP_SELECT = -1;
SdFat sd;

// serial output steam
ArduinoOutStream cout(Serial);

// global for card size
uint32_t cardSize;

// global for card erase size
uint32_t eraseSize;
//------------------------------------------------------------------------------
// store error strings in flash
#define sdErrorMsg(msg) sdErrorMsg_F(F(msg));
void sdErrorMsg_F(const __FlashStringHelper* str) {
  cout << str << endl;
  if (sd.card()->errorCode()) {
    cout << F("SD errorCode: ");
    cout << hex << int(sd.card()->errorCode()) << endl;
    cout << F("SD errorData: ");
    cout << int(sd.card()->errorData()) << dec << endl;
  }
}
//------------------------------------------------------------------------------
uint8_t cidDmp() {
  cid_t cid;
  if (!sd.card()->readCID(&cid)) {
    sdErrorMsg("readCID failed");
    return false;
  }
  cout << F("\nManufacturer ID: ");
  cout << hex << int(cid.mid) << dec << endl;
  cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl;
  cout << F("Product: ");
  for (uint8_t i = 0; i < 5; i++) {
    cout << cid.pnm[i];
  }
  cout << F("\nVersion: ");
  cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl;
  cout << F("Serial number: ") << hex << cid.psn << dec << endl;
  cout << F("Manufacturing date: ");
  cout << int(cid.mdt_month) << '/';
  cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl;
  cout << endl;
  return true;
}
//------------------------------------------------------------------------------
uint8_t csdDmp() {
  csd_t csd;
  uint8_t eraseSingleBlock;
  if (!sd.card()->readCSD(&csd)) {
    sdErrorMsg("readCSD failed");
    return false;
  }
  if (csd.v1.csd_ver == 0) {
    eraseSingleBlock = csd.v1.erase_blk_en;
    eraseSize = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low;
  } else if (csd.v2.csd_ver == 1) {
    eraseSingleBlock = csd.v2.erase_blk_en;
    eraseSize = (csd.v2.sector_size_high << 1) | csd.v2.sector_size_low;
  } else {
    cout << F("csd version error\n");
    return false;
  }
  eraseSize++;
  cout << F("cardSize: ") << 0.000512*cardSize;
  cout << F(" MB (MB = 1,000,000 bytes)\n");

  cout << F("flashEraseSize: ") << int(eraseSize) << F(" blocks\n");
  cout << F("eraseSingleBlock: ");
  if (eraseSingleBlock) {
    cout << F("true\n");
  } else {
    cout << F("false\n");
  }
  return true;
}
//------------------------------------------------------------------------------
// print partition table
uint8_t partDmp() {
  cache_t *p = sd.vol()->cacheClear();
  if (!p) {
    sdErrorMsg("cacheClear failed");
    return false;
  }
  if (!sd.card()->readBlock(0, p->data)) {
    sdErrorMsg("read MBR failed");
    return false;
  }
  for (uint8_t ip = 1; ip < 5; ip++) {
    part_t *pt = &p->mbr.part[ip - 1];
    if ((pt->boot & 0X7F) != 0 || pt->firstSector > cardSize) {
      cout << F("\nNo MBR. Assuming Super Floppy format.\n");
      return true;
    }
  }
  cout << F("\nSD Partition Table\n");
  cout << F("part,boot,type,start,length\n");
  for (uint8_t ip = 1; ip < 5; ip++) {
    part_t *pt = &p->mbr.part[ip - 1];
    cout << int(ip) << ',' << hex << int(pt->boot) << ',' << int(pt->type);
    cout << dec << ',' << pt->firstSector <<',' << pt->totalSectors << endl;
  }
  return true;
}
//------------------------------------------------------------------------------
void volDmp() {
  cout << F("\nVolume is FAT") << int(sd.vol()->fatType()) << endl;
  cout << F("blocksPerCluster: ") << int(sd.vol()->blocksPerCluster()) << endl;
  cout << F("clusterCount: ") << sd.vol()->clusterCount() << endl;
  cout << F("freeClusters: ");
  uint32_t volFree = sd.vol()->freeClusterCount();
  cout <<  volFree << endl;
  float fs = 0.000512*volFree*sd.vol()->blocksPerCluster();
  cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n");
  cout << F("fatStartBlock: ") << sd.vol()->fatStartBlock() << endl;
  cout << F("fatCount: ") << int(sd.vol()->fatCount()) << endl;
  cout << F("blocksPerFat: ") << sd.vol()->blocksPerFat() << endl;
  cout << F("rootDirStart: ") << sd.vol()->rootDirStart() << endl;
  cout << F("dataStartBlock: ") << sd.vol()->dataStartBlock() << endl;
  if (sd.vol()->dataStartBlock() % eraseSize) {
    cout << F("Data area is not aligned on flash erase boundaries!\n");
    cout << F("Download and use formatter from www.sdcard.org!\n");
  }
}
//------------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);

  // Wait for USB Serial
  while (!Serial) {
    SysCall::yield();
  }

  // use uppercase in hex and use 0X base prefix
  cout << uppercase << showbase << endl;

  // F stores strings in flash to save RAM
  cout << F("SdFat version: ") << SD_FAT_VERSION << endl;
  if (DISABLE_CHIP_SELECT < 0) {
    cout << F(
           "\nAssuming the SD is the only SPI device.\n"
           "Edit DISABLE_CHIP_SELECT to disable another device.\n");
  } else {
    cout << F("\nDisabling SPI device on pin ");
    cout << int(DISABLE_CHIP_SELECT) << endl;
    pinMode(DISABLE_CHIP_SELECT, OUTPUT);
    digitalWrite(DISABLE_CHIP_SELECT, HIGH);
  }
  cout << F("\nAssuming the SD chip select pin is: ") <<int(SD_CHIP_SELECT);
  cout << F("\nEdit SD_CHIP_SELECT to change the SD chip select pin.\n");
}
//------------------------------------------------------------------------------
void loop() {
  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);

  // F stores strings in flash to save RAM
  cout << F("\ntype any character to start\n");
  while (!Serial.available()) {
    SysCall::yield();
  }

  uint32_t t = millis();
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  if (!sd.cardBegin(SD_CHIP_SELECT, SPI_HALF_SPEED)) {
    sdErrorMsg("\ncardBegin failed");
    return;
  }
  t = millis() - t;

  cardSize = sd.card()->cardSize();
  if (cardSize == 0) {
    sdErrorMsg("cardSize failed");
    return;
  }
  cout << F("\ninit time: ") << t << " ms" << endl;
  cout << F("\nCard type: ");
  switch (sd.card()->type()) {
  case SD_CARD_TYPE_SD1:
    cout << F("SD1\n");
    break;

  case SD_CARD_TYPE_SD2:
    cout << F("SD2\n");
    break;

  case SD_CARD_TYPE_SDHC:
    if (cardSize < 70000000) {
      cout << F("SDHC\n");
    } else {
      cout << F("SDXC\n");
    }
    break;

  default:
    cout << F("Unknown\n");
  }
  if (!cidDmp()) {
    return;
  }
  if (!csdDmp()) {
    return;
  }
  uint32_t ocr;
  if (!sd.card()->readOCR(&ocr)) {
    sdErrorMsg("\nreadOCR failed");
    return;
  }
  cout << F("OCR: ") << hex << ocr << dec << endl;
  if (!partDmp()) {
    return;
  }
  if (!sd.fsBegin()) {
    sdErrorMsg("\nFile System initialization failed.\n");
    return;
  }
  volDmp();
}

```

I have noticed that the SD card is detected only upon start up, after that it all goes to errors. I had the same situation using the default SdInfo class from the built-in Arduino examples, sometimes it would register the card, sometimes it wouldn't. **Why does this happen and how can I ensure it always reads the card?**

I have already read this question and ensured my wiring is proper and I have also formatted my card using the software and SdCard.org, it is a Fat32 format.

This is my setup:

and

# Answer
> 2 votes
SdInfo is an example, but I hope you know there's no reason to call `sd.begin` to re-initialize the SD library. The example is really intended to scan several different cards, not the same card.

`sd.begin` is normally something you would do once, in `setup`, even if something else is using SPI (e.g., Ethernet). You probably won't get this error in your "real" sketch.

**But to answer your question:**

I see that your card takes a long time to initialize (almost a full second). The error code says that the card does not re-initialize within 2 seconds. I had a similar problem, and the solution was to edit the SD library and slow down how quickly it asked the card, "Are you initialized yet?"

Error code 0x0A is SD\_CARD\_ERROR\_ACMD41, so perhaps you can use the same technique in this loop, line 171 of SdSpiCard.cpp:

```
  // initialize card and send host supports SDHC if SD2
  arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;

  while (cardAcmd(ACMD41, arg) != R1_READY_STATE) {
    // check for timeout
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_ACMD41);
      goto fail;
    }
    delay( 150 ); // <-- wait a little
  }

```

### Update

There is a related question and answer here. Calling `sd.begin` twice is actually an open issue in the library.

---
Tags: sd-card
---


# Question
Title: Is there any way to check with Arduino UNO if a sensor is connected and ready to be read?
I would like to check the status of the sensors with Arduino UNO. For example, when I turn on the robot, I would like to check if all the sensors are connected and ready to be read or not. Maybe one sensor is unplugged and I want to detect this situation.

I read something about pull up resistors, but I didn't find any clear example of my problem. Also, I don't have any idea how to connect the resistor, how to calculate the resistor needed, as well as how to use the pull up resistor for digital and analog sensors.

Any schema, explanations and example would be very helpful!

# Answer
> 4 votes
Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.

So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

---

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

---

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.

---
Tags: arduino-uno
---


title: Typedef Function Pointer Invoking Issue

text:
# Question
Title: Typedef Function Pointer Invoking Issue
I'm having an issue trying to use a normal non-member function of my main sketch file as a callback. I can't get the function pointer to invoke from a function other than it was saved. More info below;

MotorEncoder.h

```
typedef void (*cb)(int16_t,int16_t);
class MotorEncoder
  ...
  private:
    cb _motor_callback;

```

Program.ino

```
cb encoder_cb = NULL;
...
encoder_cb = function_that_accepts_2_int16
DC_Encoder_1.move(motor_pos, speed, motor_id, encoder_cb);

```

**EDIT:** I want to edit the description as to not confuse anyone. The code with the callbacks above is all correct. The issue was I was working with open-source software and another developer was setting the selected serial-port connection back to the bluetooth channel in-correctly. The callback was executed, I was connected to the ATMega2560 via serial connection to a raspberry pi and was looking for the callback to show there, not monitoring bluetooth so I didn't see any data come across. Document your code.

# Answer
> 1 votes
This answer contains a few debugging guidelines, as I don't know what the problem is and don't see how one could tell without a good deal more of information.

I suggest creating a Minimal, Complete, and Verifiable example (MCaVe) of your code, not just snippets, so that other people can compile and run the code, thus being able to observe what happens in more detail and perhaps with added debugging output.

I'm presuming your callback is triggered as a consequence of an interrupt occurring. I suggest you write the MCaVe to depend on a pin-change interrupt, rather than a motor-controller interrupt, to allow testing on a system consisting of no more than an Arduino with a button, a serial interface, and perhaps a few LED indicators. Pressing the button would change pin voltage and cause an interrupt; your ISR would turn on an LED to signal it handled the interrupt, then trigger the callback. The callback routine would turn on another LED as its signal. The main loop would read the pin register bits for the two LEDs, record and report the times they came on, and turn them off after a second or two. If you get a simple setup like this to work, the technique probably would carry over to your motor-controller case; or if not, probably being a smaller program and setup should be easier to debug and figure out why not.

---
Tags: programming, c++, sketch, callbacks
---


title: Fan dropping voltage?

text:
# Question
Title: Fan dropping voltage?
I have students using an arduino to control a fan. We have multiple types of fans. We want to turn the fan off/on with digital HIGH. When the 5V fan is plugged into 5V and ground, it runs. When I ground it and attached the power side to a pin set to HIGH the voltage drops down to 2.2V??? When the fan is not plugged into the pin there is 5V. Why would the power drop when the fan is plugged in?

# Answer
Most digital pins on Arduinos are qualified to handle up to 25 mA typically and 40 mA at most. If more current than that is drawn or sunk, the pin voltage will drop or rise, out of specification. This is due to resistance in the pin drivers, and by Ohm's law, voltage equal to current times resistance will develop. That “lost” power (voltage times current) is converted to heat within the microcontroller, and can damage it.

The fan motors probably draw rather more than 25 mA; they probably require a few hundred mA. You can add transistors or motor controllers between the Arduinos and the fans to deal with such current loads.
> 1 votes

# Answer
Absolute Maximum Current per Pin is 40mA (in Arduino Uno) so when you connect the fan with the I/O pins at that time the fan may draw more current from the pin and because of this the voltage level of the pin may drop down. Because Fan or Motor want more current then the capacity of Arduino pins capacity so if you want to On/Start the Fan/Motor then you have to connect Fan/Motor Driver between the Arduino Pin and Fan/Motor. And you have to provide external power source to the motor driver circuit. For your reference:
> 1 votes

---
Tags: voltage-level
---


# Question
Title: UART communication issue on Arduino Mega
I am using an MH-Z19 CO2 sensor with an Arduino Mega using UART. As per the specifications of this sensor, after we send a command, we expect the response in a particular 9 byte format (with starting bytes as 0xFF and 0x86).

```
byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
byte response[9];
Serial.flush();
Serial.write(cmd,9);
while (Serial.available()<9) {}
for(int n=0; n<9; n++) {
  response[n] = Serial.read();
}
if (response[0] != 0xFF) {
  //Error
  predictCo2 = 0;
} else if (response[1] != 0x86) {
  //Error
  predictCo2 = 1;
} else {
  predictCo2=((response[2]*256)+response[3]);
}

```

I wait till all the 9 bytes are filled in to read the values.

The problem here is that, when I turn the board ON, most of the times the response isn't in the required format (starting bytes aren't 0xFF or 0x86). But, if I press the Arduino reset button, it starts reading values in proper format straight away.

I'm wondering why this is happening. Why is the UART response not in the proper format immediately after I turn on the Arduino, and I have to explicitly do a reset? Is the reset button clearing the serial stream? How can this be achieved through software?

I included `serial.flush()` before sending the command, but that didn't help either.

# Answer
> 3 votes
`Serial.flush()` only empties the output buffer, so that won't achieve anything. Reading exactly 9 bytes and hoping they match the input stream is not very effective, as you found. If you are out of sync with the incoming bytes, you will stay out of sync.

It would be better to keep reading (single bytes) until you get 0xFF or 0x86 and then read the rest.

---
Tags: serial, arduino-mega, uart
---


# Question
Title: How to get each byte in byte array out and be able to work with them on their own?
I am currently sending data via my bluetooth and to it I send with me 4 different values looking like this:

```
byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

```

And now I am looking for a way to store all these Hello's in different values.

What I have started with is something like this:

```
if (Bluetooth.available())
{
 while (true)
 {
   delay (50);
   char c = Bluetooth.read();
   readString += c;

   if (readString.length() >0) {

    if (readString[0] == "HelloOne")
    {
       Serial.println ("Hello One has been sent!");
    }

    if (readString[1] == "HelloTwo")
    {
       Serial.println ("Hello Two has been sent!");
    }

    if (readString[2] == "HelloThree")
    {
       Serial.println ("Hello Three has been sent!");
    }

    if (readString[3] == "HelloFour")
    {
       Serial.println ("Hello Four has been sent!");
    }

   }

 }

}

```

And I have not actually been able to debugg (not currently at home but eager to get to fix this problem asap) so there is a slim chance that my current code might be working? Very unlikely though.

So my question is, what is the correct way to get each value out in a byte array that is being sent with bluetooth to arduino?

# Answer
> 1 votes
Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.

```
byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

```

You are assigning 4 strings to the array `mByte`. A string (lets ignore the Arduino type string for now) is a char\* or a char\[\], so:

```
char hello1[] = "HelloOne";
char hello2[] = "HelloTwo";
char hello3[] = "HelloThree";
char hello4[] = "HelloFour";

```

(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)

In English mByte should be an array of strings which in code is

```
char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

```

You could do it as

```
char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

```

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.

Assuming that `writeAsync` takes a byte as a parameter then the code to write the data becomes this:

```
for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
{
    // get a pointer to the first element of the string
    // & means get the address (so the value can be set to a pointer)
    // (byte*) means cast (change) the value into a byte pointer.
    byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
    // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
    // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
    while (currentLength != NULL || *currentLength != NULL)
    {
        // Write the thing pointed to by the pointer to the function.
        writeAsych(*currentLetter);
        currentLetter++;  // Move on the pointer
    }
}

```

Sorry I can't compile that at the moment, but it looks about write. I hope it helps you understand it.

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


title: Arduino and GPS module Neo 6m

text:
# Question
Title: Arduino and GPS module Neo 6m
I have an Arduino Leonardo and a GPS module "NEO 6M"

Pinout:

```
PPS->free
rxd->11
txd->10
gnd->gnd
vcc->5v

```

I'm running this code:

```
#include "SoftwareSerial.h"
SoftwareSerial gps(10,11);
void setup(){
  Serial.begin(9600);
  gps.begin(9600);
}

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

```

In serial monitor I'm getting random characters like this

Where am I going wrong?

I tried the same with an Arduino Mega but have the same result.

# Answer
> 1 votes
Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.

---
Tags: arduino-mega, arduino-leonardo, gps
---


# Question
Title: Following on ESP8266 Board pins, how do they map on the motor shield?
Here is the answer: All pins corresponding to the G row are connected to ground. All Pins corresponding to the V row are connected to NodeMCU's 3V3 pin.

D row pins tagged from 0 to 8 correspond to NodeMCU's D1-D8 pins. D row pins tagged with SD2, SD3 corresponds to NodeMCU's SD2, SD3 pin UTART/SPI section:

Tags corresponding to the pins are self explanatory. Near the white-colored power switch we have a pin called "AD". I couldn't figure how this motor shield's "AD" pin is interfaced to NodeMCU. Do you have any idea?

Following on Basic Question - ESP8266 Board Pins, I can't seem to map the pins on its motor shield to software (the ones named UART/SPI, the GPIOs and the Analog Inputs). See the third image, with a NodeMCU installed.

The GPIOs seem to conflict with the motors on Arduino, and I have no idea what to do here. Documentation is pretty much useless.

# Answer
You see the pins marked `PWMA`, `PWMB`, `DA` and `DB`? Those are the pins that control the motors (`PWMx` is the speed, `Dx` is the direction). Whatever pins on your ESP8266 board plug into those holes are the pins you need to use in your code. How those pins map to names and numbers in the Arduino API depends entirely on what the board is you're plugging in and what the author of the board definition files was thinking at the time.

In short, look at your board (*which we cannot see*) and see what GPIO pins are in the same location as the pins I pointed out. Then control those pins in your software.
> 3 votes

---
Tags: esp8266, motor, shields, nodemcu
---


title: SocketIO Arduino TCP Port ISSUE

text:
# Question
Title: SocketIO Arduino TCP Port ISSUE
Initially I was sending sensor data to NodeJS using socketIO and this worked perfectly. I had to add a function to control an RGB LED using this. This also works but I'm unable to perform these two functions simultaneously.

I have tried to use two different ports on my Arduino. One to send data and another to control the LED but one overrides the other.

**Question:** Is there a way around this ? Is it practical to use two different ports?

**arduino sketch**

```
if (client.connect(server, 4000)) {
    Serial.println("connected");
  }
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }

  pinMode(pin, OUTPUT);
}

void loop()
{

  //if you are connected and data is available
  if (client.available()) {
    char c = client.read();
   // Serial.print("Message is :  ");
    Serial.print(c);

    // '1' was received, return '1' for HIGH
    if (c == '1') {
      pinVal = HIGH;
    //  client.print("ON");
    }
    else if (c == '0') {
      pinVal = LOW;
    //  client.print("OFF");
    }

    //turn led pin to new position
    digitalWrite(pin, pinVal);

  }

int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;

          // send data to the server
        sendData(t, h);

  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
   delay(6000);

}

void sendData(int temperature, int humidity)
{
  if(!client.connected())
  {
    if (client.connect(server, 3000)) {

      Serial.println("Sending data...");
      // send the HTTP PUT request:
      client.print("GET /weatherserver/");
      client.print(temperature);
      client.print("/");
      client.print(humidity);
      client.print("/");

      client.println(" HTTP/1.1");
      client.println("Host: localhost");
      client.println("User-Agent: arduino-barom");
      client.println("Connection: close");
      client.println();
      client.stop();
    } else {
       Serial.println("Could not connect.");
       client.stop();
    }
  }
  delay(6000);
}

```

# Answer
> 0 votes
I'm not sure what you are doing, but you seem to be using two different protocols on two different ports. So does you server side code open two ports? and does it accept the two different protocols?

If I was you I would change the RGB control to use REST (like you are doing with the DHT) So you would send something like `GET /RGB/<id>/<state>`.

I'm not sure how your temperature is arriving at the server since you have sent a GET command rather than a PUT command (this could be the bug you are looking for).

# Answer
> 0 votes
I implemented a better solution differentiating the client as `EthernetClient clientA` & `EthernetClient clientB`

> Client A handles TCP port and Client B handles HTTP GET Request.

---
Tags: arduino-ide, temperature-sensor, rgb-led, node.js
---


title: Multithreading with Arduino

text:
# Question
Title: Multithreading with Arduino
Well I've just started learning the concept of multithreading with C++ and immediately a bunch of questions came to mind about the possibility of using multithreading with microcontrollers in general and Arduino specifically.

So, is it possible to use multithreading on any type of Arduino boards?

# Answer
> 7 votes
In Cosa you can find the following support for concurrent programming:

1. Events, interface interrupt service routines
2. Jobs, delayed, periodic or alarm functions with us, ms and seconds level timers (Watchdog, RTT or RTC).
3. FSM, object-state function
4. ProtoThreads, object-state pointer
5. Threads, Semaphores, etc, multiple stacks
6. UML Capsules and Connectors, dependency driven programming

There are plenty examples on how to use these. A good starting point is the Blink sketches. There is even a multi-threading Blink example with a thread that does the LED on/off and a controller thread that periodically changes the blink period. The thread stack size is only 64 bytes and it runs even on an ATtiny.

With all the AVR internal hardware modules (such as SPI, TWI, UART, etc) there is plenty of opportunities for concurrency.

A Scheduler library for the Arduino core is also available. This is a port of the Cosa Threads. Please see github for further details.

Cheers!

# Answer
> 3 votes
The really quick answer is "maybe" – it depends on what you mean by "Arduino" and what you mean by "thread." The answer is likely to be different for the AVR based Arduinos (Uno et al.) vs. the ARM based Arduinos (Due et al.) – I would expect there to be much better hardware support for "real" threads on the ARM processors. Another question you'd want to answer is "why threads?" Do you want the abstraction to help you organize your code? Or do you actually need "real" threads?

Before there was hardware thread support (e.g., the mid-80s) there are user thread implementations, it seems possible that they might be adaptable to run even on an AVR. I would expect it to be something of a project.

There is a threads package called Protothreads which may be interesting. The description says "Protothreads are extremely lightweight stalkless threads designed for severely memory constrained systems." I found another question asking about simple usage of Protothreads, so it seems that you may find some other users of the package.

You may also find some useful information in this Stack Exchange question on threads, a quick search for "C user threads" found this implementation on the first page – and I'm sure there are many more.

A search on "Arduino threads" found several more interesting looking links:

If you just want threads, a small and inexpensive board, and I/O pins it might be worth considering a Raspberry Pi – Linux has thread support.

# Answer
> 3 votes
There's one Arduino-like product that certainly could enable multi-threading, as it is multi-core: the Shield Buddy TC275.

So basically you have three `setup()` functions, and three `loop()` functions. True multi-threading.

# Answer
> 1 votes
I use Atomthreads on Atmega128, it is very lightweight with minimum overhead. Have task scheduler, mutex, semaphores and queue. Code is portable but might require some configuration to use with Arduino IDE (I use Atmel Studio). I primarily use task scheduler, never had problems. Just checked, the development is still active.

---
Tags: programming, c++
---


# Question
Title: How can I read delay of a note that I am playing
I am playing note tone with CapacitiveSensor and an output of tone like this

```
void loop() {
    time_before = millis();

    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);

    if((total1>200)||(total2>200)) {

        if(total1>200) {

            tone(12,261);
            time_after = millis();
            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
        if(total2>200) {
             tone(12,294);
             time_after = millis();
             Serial.print("Time: ");
             Serial.println(time_after-time_before);
        }
    }
}

```

How can I read how many seconds I play this note par example

# Answer
Your code currently will only measure the code execution time and **not** the duration of the note(s) being played.

You need to follow uint128\_t's suggestion and rewrite the code to detect the "button release", at which point you measure the time with `millis()`, **and** call `noTone()`. Only then will you be able to measure the note's duration.

I believe that the source of confusion is that you seem to think that `tone()` acts like `delay()` and waits for the note to finish - it **does not**. `tone()` merely starts the note and then the next instruction is executed, without waiting for the note to end.

So, using `millis()` straight after calling `tone()` will actually only measure the time it takes to execute the `tone()` statement (and a few `if` statements - depending on whether you use your original code, or Maximus's code).
> 1 votes

# Answer
Try this:

```
void loop(){
    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);

    if((total1>200)||(total2>200)){

        if(total1>200){
            time_before = millis();
            tone(12,261);
            time_after = millis();

            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }

        if(total2>200){
            time_before = millis();
            tone(12,294);
            time_after = millis();

            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
    }
}

```

Use code indentation if you can. Also, that first `OR` (`||`) is unnecessary. I think you need to re-write this, or is this what you wanted?
> 0 votes

---
Tags: arduino-uno, c#
---


# Question
Title: Motor Shield and HC-06 Bluetooth Module competing for pins
So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time?

Thanks in advance!

# Answer
The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins.

You could either solder some wires to the TX and RX pins, or use something like the proto shield to sandwich in the middle of it, and connect the BT module onto this shield.

You could also remove all the male headers from the motor shield, and replace them with stacking headers
> 0 votes

# Answer
Ok so i had the same problem but i found like the easiest solution. So what i did was scrape the wire end to the copper using a knife or a wire cutter. And then place it in the Arduino holes and then squeeze the motor shield on top of it. Works like a charm!
> 0 votes

---
Tags: arduino-uno, arduino-motor-shield, hc-06
---


title: How can I run HC-05 on 8MHz Pro Mini?

text:
# Question
Title: How can I run HC-05 on 8MHz Pro Mini?
I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.

The Arduino code is down below:

```
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial BT(10, 11);
byte value;
unsigned long pmillis_bt = 0;

void setup() {
  Serial.begin(19200);
  BT.begin(9600);
}
///////////////////main///////////////////

void loop () {
  if (millis() - pmillis_bt >= 100) {
    byte Data[3];
    byte cmmd[20];
    int insize;
    char str[256];
    int i = analogRead(A0);
    value = BT.read();
    Data[0] = 'a';
    Data[1] = i / 256;
    Data[2] = i % 256;
    sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
    Serial.println(str);
    if (value == 49) {
      for (int j = 0; j < 3; j++)
        BT.write(Data[j]);
      value = 0;
    }
    pmillis_bt = millis();
  }
}

```

# Answer
Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.

But in Pro mini 3.3 V level due to you need to Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module

using this you can easily convert the vlotage level.

if you have to make using simple component also using

SparkFun Logic Level Converter - Bi-Directional
> 1 votes

# Answer
You are probably using the HC-05 Module with a power regulator and levelshifter designed for use with Arduinos that typically run with 5V. What you need is the plain HC-05 as can be found on AliExpress. Those run with 3.3V but it can be tricky to use them in prototypes.
> 0 votes

---
Tags: bluetooth, softwareserial, arduino-pro-mini, hc-05
---


# Question
Title: Push to 2D array (log) but last value pushed is everywhere
I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).

What am I doing wrong here?

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

#define log_size 5
#define line_height 12
char *log_lines[log_size] = {"Hello", "World"};

void addToLog(char *text) {
  for(int i = log_size - 1; i > 0; i--) {
    log_lines[i] = log_lines[i-1];
  }
  log_lines[0] = text;
}

void printLog() {
  for(int i = 0; i < log_size; i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.println(log_lines[i]);
  }
}

void loop(void)
{
  char msg[20];
  sprintf(msg, "%d", millis());
  addToLog(msg);
  printLog();
  delay(1000);
}

```

The output after the first addToLog is

```
0 1000
1 Hello
2 World

```

second addToLog is

```
0 2001
1 2001
2 Hello
3 World

```

# Answer
It is easy - in your log you store POINTERS to strings.

And you then create variable on the stack (ouch) and put its address to the log.

Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log\_lines\[0\] points to UNALLOCATED place (where the variable msg once was).

Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log\_lines\[0\] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.

Then you overwrite the variable msg with a new value, so the log\_lines\[0\] point to that new value.

Then you move the content of log\_lines up, so the log\_lines\[1\] now points to the variable msg (and its NEW value) as well as log\_lines\[0\].

Then you assign log\_lines\[0\] with address of variable msg (which it accidetally already contains)

Then you wonder, why variable msg accesed via log\_lines\[1\] is exactly same as the (same) variable msg accesed vial log\_lines\[0\] and why it contains the last (NEW) value, which you assigned into it.

---

Some of possible solutions are:

1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate last log\_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.

2) allocate log\_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log\_line\[0\]

3) keep static index of last used log\_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)
> 1 votes

# Answer
Here is a solution which does not use dynamic allocation nor does it copy any log message. It's essentially a zero-copy implementation of gilhad's solution 3. The idea is: instead of having an `addToLog()` function that takes an already prepared message (which it would need to copy), you have a `get_log_buffer()` function that tells you where to write the message in the first place. This way you can `snprintf()` directly into the right place in memory.

```
const size_t LOG_SIZE = 5;
const size_t MSG_SIZE = 20;

char log_stack[LOG_SIZE][MSG_SIZE];  // circular log buffer
size_t log_index;  // next available slot in the circular buffer

// Return the address of the next available message slot.
char *get_log_buffer()
{
    char *buffer = log_stack[log_index];
    if (++log_index == LOG_SIZE) log_index = 0;  // increment index
    return buffer;
}

void print_log()
{
    Serial.println(F("--------"));
    for (size_t i = 0, j = log_index; i < LOG_SIZE; i++) {
        j = (j ? j : LOG_SIZE) - 1;  // decrement index
        if (log_stack[j][0]) {  // should be a non-empty message
            Serial.print(i);
            Serial.print(" ");
            Serial.println(log_stack[j]);
        }
    }
}

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

void loop()
{
    snprintf(get_log_buffer(), MSG_SIZE, "%lu", millis());
    print_log();
    delay(1000);
}

```

Note that `log_stack` and `log_index` are zero-initialized by the C runtime. Note also the use of `snprintf()` instead of `sprintf()` in order to avoid buffer overruns.
> 0 votes

---
Tags: c, string, array
---


title: Manipulating 3 IR led's on Arduino Uno

text:
# Question
Title: Manipulating 3 IR led's on Arduino Uno
I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.

However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.

e.g

**IR LED 1** connected to **pin 11** \- send signal **0xABCDEFGH**

**IR LED 2** connected to **pin 10** \- send signal **0xSJKLMNOP**

**IR LED 3** connected to **pin 09** \- send signal **0xZXYRWVUG**

I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.

```
//LED 1

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 11; i++) {
            irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED 2

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 10; i++) {
            irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED3

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 9; i++) {
            irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }

```

# Answer
> 1 votes
I think what you have done is a perfectly logical thing to do. You had three programs that worked and so you pasted them all into the same file and compiled it. The compiler spat its dummy out of the pram and you didn't understand what the h\*ll went wrong. Is that about right?

```
// You only need to include each header file once
#include <IRremote.h>

// You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
IRsend irsend_led1;
IRsend irsend_led2;
IRsend irsend_led3;

// This is where you do all the setup, it only gets executed once.
// You might need to assign the pin numbers to the irsend_ledX variables here.
void setup()
{
}

// This function is called repeatedly.  You can only have one of these.
void loop() {
    // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
    // I think the data is being sent multiple times, don't know why though
    for (int i = 0; i < 11; i++) {
        irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 10; i++) {
        irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 9; i++) {
        irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
        delay(1000);
    }
    delay(1000); //1 second delay
}

```

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.

Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.

# Answer
> 1 votes
@Matt has the main problem resolved, but I do want to add a note.

`<IRremote.h>` has the default IR led pin as pin 3 (last time I checked, maybe it has changed). I don't know how to change it, but if you are considering to use multiple IR leds, you might have to debug that problem!

So try to make 1 code work before you attempt to stick them togheter

---
Tags: arduino-uno, ir
---


# Question
Title: What's wrong with my undetected, unresponsive Arduino Robot?
I was wondering if someone could try and solve a major problem I've been having with a brand new Arduino Robot (similar to an Arduino Leonardo). Any input would be very much appreciated!

I've been working with an Arduino Robot on a summer internship for the last week with no major problems. However, a couple of days ago, it stopped running programs and couldn't be detected when being plugged into the computer.

When plugged in or turned on, the LCD turns on with nothing displayed on the screen and the power LED also switches on. However, no program is run (I had a working program involving the LCD uploaded at the time it stopped functioning, which would normally run). Also when plugged in, the Arduino is completely undetected by the computer, with the 'Serial Port' option under Tools grayed out, the device not showing up in device manager, and no signs that a device has been plugged-in. I've tried 3 different USB cables - one of which I tested on another device - and 3 different computers (with Windows 7, 8.1 and Linux Ubuntu installed). On the Linux computer, I ran lsusb before and after plugging in the device and saw no change. I've also tried various solutions such as re-installing the drivers and the Arduino software, using MProg and various rebooting/unplugging-replugging variations.

So I think the problem is almost definitely with the Arduino Robot itself. I'll give a little information about the problems I encountered previously, to see whether something I did affected it or not.

Problem 1:

The first problem I had with the robot was entirely by my own fault and was pretty foolish of me (I'm new to electronics - this being my first project involving it). I ran code from this website (the first set of coding on the page) to try and see whether I could get the LCD to work - not realizing that it wouldn't work for a different type of LCD. After uploading the code, the speaker made a loud constant buzzing noise. Fortunately after uploading a different code, the problem was resolved. I'm doubtful that this could have affected the robot, but since I'm so new to this I'll leave it to one of you to decide.

Problem 2:

The next problem was one to do with uploading. The robot worked fine for a couple of days after the first problem until I came across this one:

When uploading programs, there would be a 'device disconnecting' sound from the computer and the program would fail to upload (I can give details on the error messages if you need them). I managed to solve the issue using an odd solution involving hitting the reset button at just the right time while a program was uploading.

After this, the robot worked for a few hours. In this time I tried to play with the 'turn' function, which didn't seem to work very well at all (the robot would turn angles very different to the ones given) and started creating programs playing around with the LCD. It was at this point the robot stopped functioning properly.

So does anyone have any idea what might be wrong? I have no idea how to fix this problem and I've been trying to find a solution for almost 2 full days now. Any input at all would be greatly appreciated.

# Answer
I'm pretty sure and sadly to announce you that the usb communication of your Arduino Leonardo Compatible is dead and the arduino is connecting to the computer just like an alimentation Source no more. And since Arduino Leonardo based on The ATmega32U4 which has built-in USB communication ,so the Atmedga32U4 is dead(u-processor) too.

It's not a software matter but hardware one.
> 2 votes

# Answer
You should try to connect to the board using an in-system-programmer. If you have another Arduino lying around, you can upload the ArduinoISP sketch to and use it as a programmer. Alternatively you can buy a cheap programmer on ebay for a few dollars, just search for "avr programmer". You should look up the placement of the MOSI, MISO,SCK, and RESET pins on your board and connect them appropriately(GND connection is also needed and VCC unless you have another power source).

For ArduinoISP you can run avrdude like this:

```
avrdude -c avrisp -p atmega32u4 -b 19200 -P [serial port, eg. /dev/ttyUSB0 in Linux]

```

If avrdude can read the chip signature, then at least part of the chip is probably OK. Try to upload a sketch. If it works, you should locate the Leonardo bootloader and flash it to the board. See if it brings back the USB connection.

If you don't have any luck with these methods you might want to look into high voltage programming.
> 2 votes

# Answer
This incident exactly happened for me just now. I solved it by upload simple sketch and double click on the reset button (the board will be detected for around 8 seconds. once the sketch uploaded successfully, the board should be fixed that time.
> 1 votes

# Answer
Try this:

* Bring up a very simple sketch like blink or bare-minimum.
* Select the right board and serial port from the tools menu.
* Then click upload
* As soon as the IDE says 'Uploading' double tap the reset button on the board that you are programming.
* Hopefully the sketch should upload.
* You should then be able to upload any other sketch to the Robot like wheel calibration or line follow.

It works for me (since I had the same problem) for a few days until it stops working again. It's Just a design flaw with the ATMega32u4.
> 0 votes

---
Tags: serial, uploading, arduino-leonardo, bootloader, robotics
---


# Question
Title: Building a low voltage disconnect w/ timer - need help with the timer
I'm trying to build almost exactly this device:

http://www.reuk.co.uk/wordpress/reuk-shop-low-voltage-disconnects-lvd/buy-reuk-programmable-low-voltage-disconnect-with-display/

It is a low voltage disconnect but has an interesting feature that requires the "cutoff" and "reconnect" voltages to be reached for 10 seconds before the connection is actually cut/re-connected to prevent premature status changes from voltage spikes/sags (Such as starting a car, or a motor with high start draw)

I need some example code that handles the timer portion. I can handle the "if this voltage is reached, disconnect the relay" (or transistor in the link I provided) part.

I need help making it "If this voltage has reached XX for 10 seconds then -do something-"

# Answer
> 1 votes
Assuming you have a function `voltageIsReached()`, here's a very simple way of doing it, which is OK if you don't have anything else to do in the mean time.

```
if (voltageIsReached()) {
    long end = millis() + 10000;   // 10s from now
    boolean voltageWasReachedFor10s = false;
    while (voltageIsReached()) {
        if (millis() >= end) {
            voltageWasReachedFor10s = true;
            break;
        }
        delay(1);
    }
    if (voltageWasReachedFor10s) {
        // Do whatever you have to do
    }
}

```

If you *do* have something else to do while you're waiting for this 10s state, you will need to adapt this, but I hope it'll get you started.

# Answer
> 0 votes
Write a function that has a static variable that keeps the previous time that the voltage has not been reached. That routine will read the voltage and reset the static variable to current time whenever the voltage has not been reached.

Such a routines can either return a logic value or a time value , depending on your implementation.

---
Tags: sketch, timers, voltage-level
---