# Question
Title: Can an a Arduino make music or speech without a speaker?
I have an Arduino Leonardo that can turn a relay off and on and the click is audible on the relay -this is simply done by making one of the control wires HIGH in the program code to turn the relay on and make the same control wire LOW to turn the relay off. In this way it can turn a set of relays on and off. By varying the patterns of on and off timings to the relay it make distinct sounds-it reminded me of a piezoelectric speaker for some of the programmed values. At fast on or off puling this 6V relay makes a buzzing noise. I was wondering if the sound emitted from the relay could be used as a crude speaker- I'm not talking about a quality speaker- just good enough to recognise a melody or speech. So my question I was thinking the problem maybe be simplified if a set of relays is used buzzing at a certain frequency-corresponding to tones heard in the human voice to make it sound like speech. Im no expert in acoustics.

My questions are

1) is it theoretically possible to use the clicking noise from a set of relays only to act as a a crude speaker (so hear a crude known melody or a crude speech)?

2) Is there such a circuit (if so what is it exactly and the theory of how it works) that can be built with an arduino?-so it only used the noise from a relay to act as a crude speaker.

I personally think it possible it would be an interesting circuit to build as I have not seen a relay used like this before. I just think it sounds interesting that music or speech can possible be made by a circuit without using a speaker type component. Maybe there's another non-speaker component (i.e. a component that was not originally designed to make a sound) that can be used instead of a relay.

I'd love to know the answers.

Update I started on this. And the relays do make different tones-thats as far as I got. So music seems to be possible; something like a famous melody of a song. I havent got any ideas yet for a another component instead of a relay.

# Answer
Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.

To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.

A function that takes agreements of pitch and duration, something like:

```
 note(hz, ms)

```

would give you a fairly easy way to describe the music you wanted to play.

Just for fun, here are a few examples of "speakerless devices" making music:
> 3 votes

# Answer
The operate/release time for a typical relay is 10ms/4ms - that means it takes 14ms for the contacts to close and open again. 14ms equates to a maximum 'click' frequency of 71Hz.

Typical rates of cycles-before-failure are in the region of 100,000 minimum - but at a rate of 5 cycles per second. This will rapidly decrease as you increase the switching rate.

Furthermore, as alluded to in the above datasheet, must-operate and must-release voltages increase as the number of completed cycles moves into the tens-of-thousands. Thus, if you were to find a relay that switched fast enough you will eventually (and maybe only after a 100 seconds of non-continuous operation) run its operating voltage above a level that can be achieved.

---

Due to the maximum switching frequency of a relay you **cannot** use one, or many, to synthesise speech. Speech is an incredibly complex mixture of frequencies, the majority of which are well above those that can be produced by switching a relay on and off.

---

*Music* is a loose term. Simply switching the relay on and off once per second is technically a rythym, and therefore music. Different relay models will have different 'clicks' - the smaller the contacts the higher the click will be in pitch (logically speaking, that is). A collection of *different* relays could definitely create music, akin to percussion, but by their *individual clicks* and **not by the rapid switching thereof**.
> 2 votes

---
Tags: sketch
---


# Question
Title: What's the difference between ICSP vs ISP?
I'm not sure if these terms are interchangeable or not. What's the difference between ICSP and ISP? Is it simply the reset? I've shown two configurations in this question I just asked. Are they both ICSP?

# Answer
> 4 votes
The difference between ISP and ICSP is a hyphen.

ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.

Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.

# Answer
> 0 votes
According to the Atmega32U4 datasheet:

> The device is manufactured using ATMEL’s high-density nonvolatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program running on the AVR core.

I can't find the word "ICSP" in the datasheet. The quoted paragraph doesn't really explain the acronym. It could be an anagram of SPI. ;)

---

It seems clear to me that "in system" and "in circuit" are referring to the same thing. The program is serial rather than parallel as it uses SPI (Serial Peripheral Interface).

---

> I've shown two configurations in this question I just asked. Are they both ICSP?

Not really two configurations, because the ICSP header on the board is directly connected to the pins you showed in the other configuration. You may as well talk about using different ground pins as a "different configuration".

---
Tags: isp, icsp
---


# Question
Title: What is the proper way to turn an Arduino UNO into an ISP?
I have a bricked Arduino Uno and I want to try to flash the bootloader. I'm trying to figure out how to do it. On this tutorial from SparkFun you can see this diagram:

They also show this table of the pinout

That seems simple enough but it's totally different than the official tutorial, "Circuit (targeting Arduino Uno, Duemilanove, or Diecimila)"

Which also says

> An Arduino board serving as an ISP to program the ATmega on another Arduino board. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch). Note that you need access to the reset pin on the target board, which isn't available on NG or older boards.

So do I need a 10 uF capacitor between reset and ground? How do I put a 10 uF capacitor in between reset and ground when, in this configuration, reset is connected to PIN 10? Why are there two configurations? What's the upsides and downsides to either of them?

# Answer
> 1 votes
The wiring is actually identical. It just uses the ISP header (2x3 pins) on the target board, instead of the pins 5v, GND, RST, 11, 12, 13. Just like the table you added says.

The downside to using the ISP header, is you need a male to female wire for connecting. Upside is you can easily take of these 6 pins, and connect it to a different arduino to be programmed.

I always needed to add a capacitor between RESET and GND. The exact value isn't that critical.

The reset pin is the one to the left of 3v3.

# Answer
> 1 votes
Take a look at my circuit for a minimal "Arduino":

The top image in the question uses the ICSP header, which you can see from the schematic "mirrors" pins on the processor. That is:

* SCK is D13
* MISO is D12
* MOSI is D11
* Reset on the target goes to D10 on the programming board
* Vcc and Gnd are connected

Trace out the wires to the ICSP header and you will see.

---

> So do I need a 10 uF capacitor between reset and ground?

No you do not.

---

> I have a bricked Arduino Uno and I want to try to flash the bootloader.

See my page about programming a bootloader.

---

> Why are there two configurations?

Just different ways of connecting the same thing to the same thing.

---

> What's the upsides and downsides to either of them?

No difference.

---
Tags: arduino-uno, bootloader, isp, icsp
---


title: Best way to protect a digital output?

text:
# Question
Title: Best way to protect a digital output?
I am looking for a way to protect my Arduino's digital outputs from unwanted, outside voltages. My project uses about 20 different outputs, each connected to a wire (run) that can range from 20 to 100 feet (I used cat5 cable, with each inner wire (randomly chosen) dedicated to a single digital in, out, +5, +9 or ground.) There is a good change that outside voltages could impact these digital outs (or any other pin or power wire.)

I have a good resource on protecting digital in's but I ma not sure how to protect the digital outs. Each needs to be able to both pull a connect component to ground, and push it up to 5 volts (am I saying this correctly?)

This should be able to protect the digital outs from shorts or 12v spikes.

How can I build this circuit?

Edit: it is difficult for me to describe this problem without mentioning the danger to all components.

Note that ways of protecting digital *inputs* is HERE.

# Answer
> 3 votes
Some good results you can get with optocouplers.

It's electrically disconnects one part of your circuit from another.

For example, here is my IoT-ish device, which is detects water leaks in my bathroom:

I use the transformer (T1), which have two separate output windings, so, that windings does not connected electrically, only magnetically. The block in border "Sensing unit" doesn't have any wires with other scheme - only magnetic field, which is gives it power, and infrared light in the optocoupler (u2, PC817), which informs ESP01 about leak presence.

How does it work? Very simple! When the water shorts JP1 (long naked wires on the floor), Q1 opens and lights-up the IR diode in PC817. Light from this diode opens another transistor - and pulls the RxD PIN of ESP01 down.

Small sketch, written on Arduino for ESP8266 periodically sends pin state by `HTTPS` on my web server, where monitor software, Nagios, checks the information age and the pin state, and send to me notifications, when something goes wrong.

# Answer
> 1 votes
Add a resistor in the circuit to limit the current in case of a short.

Add clamping diode to prevent voltages higher than 5v (combined with the resistor from before). The AVR has internal clamping diodes, but those can only handle very little current. Since you are running such long wires, you probably need to add the lowest value resistor, to limit noise.

PS The possibility of have a external voltage applied to an output sound pretty troubling to me.

# Answer
> 1 votes
Check with your favorite automotive semiconductor supplier such as ST. In there automotive listings you will find drivers that will do exactly what you want and if shorted to long will shut down and come back when the short is removed. I am not going to make a recommendation as there are literally hundreds of possibilities. These come from 1 driver per unit to 8 that would be easy to purchase. They have parallel and serial interfaces depending on what you want. If you want to be nasty get a 50 amp driver and put a huge power supply behind it, then enjoy the looks and smoke when shorted and you get the last laugh your Arduino will be OK. Have Fun!

# Answer
> 0 votes
See 10 Ways to Destroy An Arduino

One of the suggestions there for output pins was:

> Put a 30mA resettable fuse (PTC) in series with every I/O pin. Not only is the current safely limited to 30mA under all conditions (more on this below), but the built-in 220 ohm resistance of the fuse naturally limits the current to 5V/220 = 23mA right off the bat.

You may also want to look at some of the suggestions on the question about protecting input pins which could help with keeping spikes out of the output circuits.

---
Tags: voltage-protection, digital-in
---


# Question
Title: Arduino potentiometer example: what limits the current?
I have a question regarding *potentiometer example*:

https://www.arduino.cc/en/Tutorial/AnalogReadSerial

If I turn the potentiometer to the marginal position and have 5V at A0 (and almost zero resistance at the pot), what limits the current flowing through the circuit?

# Answer
A0 input is high impedance, so very little current is flowing into A0. The value is so small that you can simplify that it flows only from +5V through the potentiometer to GND.

For some applications, when you are measuring high-impedance sources (a source that can deliver very little current) this simplification may not be correct.

You can find more detailed explaination in Atmel application note:

http://www.atmel.com/images/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters\_application-note.pdf
> 5 votes

# Answer
Assuming A0 is set to **input** then it is a high-impedance input. That is, the input has a high resistance, and only consumes enough current to "sample" the voltage.
> 3 votes

---
Tags: current, potentiometer
---


title: Problem with sending DMX

text:
# Question
Title: Problem with sending DMX
I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7

I tried the AVR -\> DMX source code from Ulrich Radig and also the layout for the RS-485 transmission.

I modified the code to fit the ATMega2560 but when I upload the code nothing happens.

The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?

Any idea?

Here is my circuit:

Here is the source

```
#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000
#include <util/delay.h>

#define DMX_BAUD 250000
#define DMX_BAUD_BREAK 80000
#define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
#define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

volatile unsigned char dmx_buffer[512];

//############################################################################
//DMX Senderoutine
ISR (USART_TX_vect)
//############################################################################
{
  static unsigned int  dmx_channel_tx_count = 0;
  static unsigned char dmx_tx_state = 0;

  switch (dmx_tx_state)
  {
    case (0):
      UBRR0   = DMX_BAUD_BREAK_UBBR;
      UDR0 = 0; //RESET Frame
      dmx_tx_state = 1;
      break;

    case (1):
      UBRR0   = DMX_BAUD_UBBR;
      UDR0 = 0; //Start Byte
      dmx_tx_state = 2;
      break;

    case (2):
      _delay_us(10);
      //Ausgabe des Zeichens
      UDR0 = dmx_buffer[dmx_channel_tx_count];
      dmx_channel_tx_count++;

      if(dmx_channel_tx_count == 512)
      {
        dmx_channel_tx_count = 0;
        dmx_tx_state = 0;
      }
      break;
  }
}

void setup() {
 //Init usart DMX-BUS
 UBRR0   = DMX_BAUD_UBBR;
  DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
  UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
  UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
  sei();//Globale Interrupts Enable
  UDR0 = 0;//Start DMX

}

void loop() {
  // put your main code here, to run repeatedly:
    dmx_buffer[4]=255;
    _delay_ms(1000);
    dmx_buffer[5]=255;
     _delay_ms(1000);
    dmx_buffer[6]=255;
    _delay_ms(1000);
    dmx_buffer[4]=0;
    _delay_ms(1000);
    dmx_buffer[5]=0;
     _delay_ms(1000);
    dmx_buffer[6]=0;
     _delay_ms(1000);

}

```

# Answer
> 0 votes
> The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a *huge* problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.

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


title: Arduino subtracting chars from strings

text:
# Question
Title: Arduino subtracting chars from strings
Hello I have an Arduino programme that has a string with the words hello in it. I can add characters and other strings to the end of that one using:

```
   String test = "hello";
   test+=" jack";

```

it would then say "hello jack" The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

# Answer
> 4 votes
You may use remove() method to remove last character.

```
String s = "1234567890";
while(s.length() > 0) {
    int lastIndex = s.length() - 1;
    s.remove(lastIndex);
    Serial.println(s);
}

```

# Answer
> 3 votes
> I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

This is how you could do that. Avoid using String and putting the string constants in program memory.

```
// A buffer for the message
const size_t MSG_MAX = 16;
char msg[MSG_MAX];

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

void loop()
{
  static int len = 0;
  // Check if it is time to create the initial message
  if (len == 0) {
    strcpy_P(msg, (const char*) F("hello"));
    strcat_P(msg, (const char*) F(" jack"));
    len = strlen(msg) - 1;
  }
  // Otherwise shorten the message
  else {
    msg[len--] = 0;
  }
  // And print current message
  Serial.println(msg);
  delay(2000);
}

```

# Answer
> 3 votes
You are best of learning about C-style strings rather than the String class. The String class can eventually fragment dynamic memory.

To shorten a string a simple method is to move the "string terminator" inwards by overwriting the last byte of the message with zero, like this:

```
const size_t MSG_MAX = 20;
char msg [MSG_MAX];

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

  strcpy (msg, "hello");  // initial message
  strcat (msg, " jack");  // concatenate more stuff
  }  // end of setup

  void loop ()
    {
    if (strlen (msg) > 0)
      {
      Serial.println (msg);  // display current message
      msg [strlen (msg) - 1] = 0;  // move null-terminator in
      delay (1000);
      }  // end of any message left

    }  // end of loop

```

Results:

```
hello jack
hello jac
hello ja
hello j
hello
hello
hell
hel
he
h

```

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


title: Funduino Joystick Shield with Bluetooth

text:
# Question
Title: Funduino Joystick Shield with Bluetooth
I have a Funduino Joystick Shield (See here Funduino on Gearbeast store) which has some Bluetooth pins.

Does anyone know what pins they are connected to, and has anyone successfully connected to a BT HC-05 device using SoftwareSerial?

# Answer
Well, it turns out that the tx/rx for the board are connected to the standard pins 0 and 1 on the Arduino. To use this, you can simply use Serial.write. Of course, remember to take of the module when trying to upload your code.....
> 2 votes

---
Tags: bluetooth
---


# Question
Title: Arduino motor control using digital pins
I am new to these Arduino things, and I am currently using an Uno board for my projects.

I don't know how to control the DC motor with the help of digital pins via L293D. But I cannot use the PWM pins of Arduino, since I have already used them for controlling servos and other things, which need higher accuracy.

I tried using the SoftPWM library to control motor, but it is conflicting with other things like ultrasonic sensor. I don't know what the problem is.

Could someone suggest me a solution?

# Answer
> 1 votes
You can implement PWM using digital pins by turning the pin on and off with respect to your duty cycle, because PWM (Pulse Width Modulation) depends upon the duty cycle the % amount during which the pin is HIGH or LOW

Let say pin 13 of arduino is connected to your l293D enable pin

Sample Code:

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

void loop() { digitalWrite(13, HIGH); delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz digitalWrite(13, LOW); delayMicroseconds(1000 - 100); }

Details are also on Arduino Help

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM

---
Tags: arduino-uno
---


# Question
Title: Communication between two Bluetooth modules of two Arduinos
I am designing a home automation project. I want to control different home appliances through GSM. I am designing it in such a way that each apparatus is connected to an Arduino and bluetooth module. There is a master unit with Arduino, Bluetooth and GSM modules. When the user sends a message, the GSM receives it and communicates via Bluetooth to the corresponding Bluetooth module and Arduino.

Is it possible to communicate between two Bluetooth modules of two Arduinos? Is there a better solution?

# Answer
> 2 votes
I'm not sure how many bluetooth devices can be connected to your smartphone. But if you use smartphone, the you can eliminate the master Arduino. But as I said, it still depends on the number of devices you'd like to control. This is supposed to go in the comment section.

# Answer
> 2 votes
How about little smart WiFi boards (such as Red Bear WiFi Micro or something similar), which are connected at your local home network? You can configure your own dyndns service or use a existing and built a web home appliances or web service for your own mobile application. In general please take care of security aspects, so that your home can not be manipulated...

# Answer
> 0 votes
You connect your different sensors or devices to many slave arduinos and each slave arduino has its own bluwtooth module that send the data to Master Arduino that contains the Bluetooth and GSM Module.

And yes you can connect max 7 bluetooth devices to 1 Bluetooth module at a time so in that manner you can connect 7 slave devices to Master Arduino

---
Tags: arduino-uno, bluetooth, gsm, wireless, home-automation
---


# Question
Title: Can I do parallel processing in Arduino?
I recently got to work with Arduino and I want to get parallel input from 5 LDRs and at the same instance I need to light a LED corresponding to that LDR if the resistance got high.

I read about a finite state machine, but I couldn't understand how it works.

Is it the only way for this type of problem or are there any other way?

# Answer
> 2 votes
You do not need parallel processing or finite-state machines for that:

```
// Vector with digital pin numbers for LEDs (with resistor to ground)
const int LED_MAX = 5;
const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

// Vector with analog pin numbers for LDR (with pullup resistor)
const int LDR_MAX = 5;
const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

// Analog value or lower when to light the LED
const int THRESHOLD = 200;

void setup()
{
   // All LED pins should be digital output pins
   for (int i = 0; i < LED_MAX; i++)
     pinMode(LED[i], OUTPUT);
}

void loop()
{
   // Read all LDRs and set LED pins according to threshold
   for (int i = 0; i < LDR_MAX; i++)
     digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
}

```

But if you really want to describe this as multiple tasks you could use the Simple Scheduler library:

```
#include <Scheduler.h>

const int THRESHOLD = 200;

template<int LED> void setup()
{
   pinMode(LED, OUTPUT);
}

template<int LED, int LDR> void loop()
{
   digitalWrite(LED, analogRead(LDR) < THRESHOLD);
   yield();
}

void setup()
{
   Scheduler.start(setup<2>, loop<2, A0>);
   Scheduler.start(setup<3>, loop<3, A1>);
   Scheduler.start(setup<4>, loop<4, A2>);
   Scheduler.start(setup<5>, loop<5, A3>);
   Scheduler.start(setup<6>, loop<6, A4>);
}

void loop()
{
   yield();
}

```

---
Tags: arduino-uno
---


# Question
Title: Using Rx and Tx pins(0 and 1) on Arduino Uno for GSM
I am using a GSM module sim800. My module responds to the output given by my PIR sensor and sends sms according to it. My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

# Answer
> 0 votes
> My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

TX =\> RX, RX =\> TX, that is Arduino TX to module RX, and TX to module RX. If you want to use Serial the pins are 0 for Arduino RX, and 1 for Arduino TX.

If you want to use SoftwareSerial you decide which pins to use (check the documentation for valid pins on your board).

```
// Use software serial with pin 2 for rx and pin 3 for tx
SoftwareSerial gsm(2,3);

```

Cheers!

# Answer
> 0 votes
You have a choice.

Always:

* GND =\> GND
* +5V =\> +5V

Then, either:

* TX =\> RX (0)
* RX =\> TX (1)

and use the hardware UART "Serial", but that then means that uploading new code to your Arduino becomes an arduous task since the usage pins 0 and 1 will interfere with that. So the other option:

* TX =\> Any pin
* RX =\> Any pin

And then use SoftwareSerial to set up a secondary "bit banged" serial port on the two pins you choose.

---
Tags: arduino-uno, sensors, gsm, sketch
---


title: Replicating Tx and Rx LEDs

text:
# Question
Title: Replicating Tx and Rx LEDs
In my application all of the Arduino Uno LEDs will be invisible inside an enclosure, so I wish to provide panel-mounted Tx and Rx LEDS just replicating their on-board counterparts. Is there a way to drive any of the digital outputs to replicate those LEDs? I seem to recall that the Tx and Rx LEDs are driven directly from the FTDI logic, does this preclude hacking their states and sending them to two digital outputs? How could this be done? I could de-solder the LEDs and hardwire the panel LEDS to their pads, but I think this should be a last resort.

# Answer
> 3 votes
The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).

If you look closely you'll see there are 4 pad near the chip, JP2 in the schematic. You could solder some wire to it to connect your leds. You could then slightly modify the firmware running on the ATMega16u2, and upload it using DFU.

I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.

In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change `DDRD` and `PORTD`, to `DDRB` and `PORTB` in LED.h.

# Answer
> 1 votes
The easiest thing to do would likely be to use an Arduino that does not have an on-board serial connection such as the Pro Mini and then add a separate USB-UART bridge with either bare pads you can solder panel-mount LEDs to or mounting holes that will allow you to mount it with the LEDs aligned to holes on the enclosure.

# Answer
> 1 votes
Personally I would wrap all serial reading and writing in my own functions which, as well as doing the reading and writing, turn on an LED on any chosen GPIO and set a timer variable which is then used in the main loop to turn the LEDs off after a short period (otherwise they flicker too fast to be properly seen). Something like:

```
uint32_t readLedTimer = 0;

// Call instead of Serial.read();
int mySerialRead() {
    if (Serial.available()) {
        digitalWrite(13, HIGH);
        readLedTimer = millis();
        return Serial.read();
    }
    return -1;
}

// Call from loop();
void cancelLeds() {
    if ((readLedTimer > 0) && (millis() - readLedTimer > 20)) {
        readLedTimer = 0;
        digitalWrite(13, LOW);
    }
}

```

Of course, replicate (with a different LED) for the any Serial.write or Serial.print functions you may want to do (use may use *overloading* to pass different variable types to similar functions).

Another option is to directly modify the serial reading and writing routines within the Arduino AVR core to do the same thing, but that gets rather tricky when you update the IDE or want other people to use your code to build these widgets of yours.

---
Tags: arduino-uno
---


title: Problem with my arduino board

text:
# Question
Title: Problem with my arduino board
I had attatched a GSM module to my arduino Uno board. The power had been switched on. The GSM 5V pin was connected to my board. I was still midway with my work so for some reason I gave an external power supply to my GSM module. Now smoke started coming out of my Uno board and a burning smell came from it. I immediately switched off the power supply. But now I am unable to burn sketches to my Arduino. It is showing error: Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions. On opening the serial monitor it says: Board at COM3 not detected.

Link from wher I bought the GSM module: http://www.ebay.in/itm/GSM-Module-SIM800-Quadband-better-than-SIM-900-or-SIM900A-Modem-with-SMA-Antenna-/252053758680?hash=item3aaf9322d8

# Answer
Oops.

You let the Magic Smoke™ escape from your Arduino. Your Arduino is now somewhat dead. Depending on *what* died it may be repairable by replacing components, or it may be beyond resurrection and it'll be easier to buy a new one.

Now - why did it happen? Looking at the board in your link it should have been OK with the 12V power you provided, since it has its own regulator on board that can supposedly take up to 12V. So one of two things may have happened:

1. What you thought was 12V was actually higher than 12V and the regulator didn't cope with it.
2. You connected the power backwards, so -12V was pumped straight through everything.

There seems to be no polarity protection on the board as far as I can see, and many regulators, if connected backwards, will just pass the power straight through with little or no change to it. So my money is on having connected the power backwards. Now, that might not be your fault, since on that site I can see no mention of which polarity the power connector uses - whether it is pin-positive or pin-negative. The normal way (the way the Arduino board uses) is pin-positive, but that is not always the case.

Either way, the Arduino is now dead, and the GSM module may be dead as well. In fact the whole lot may be dead.
> 1 votes

---
Tags: arduino-uno
---


title: SainSmart CO2 sensor module use?

text:
# Question
Title: SainSmart CO2 sensor module use?
I purchased this CO2 sensor a while back: SainSmart MG811 Gas CO2 Carbon Dioxide Sensor Module Sensor Module for Arduino UNO R3 Raspberry Pi

The module has four pins, Vin, GND, Dout and Aout. I assume Dout and Aout are digital output and analog output, respectively.

Other than that, the sensor came with no datasheet, instructions, or tutorial. I also searched online but fail to find anything useful.

I'm going simple for now, just hooking up the sensor module to Arduino board. I know I can probably connect the output pins to the analog pins, and analogRead them, but what I am looking for is how to convert the raw data readings into CO2 levels in PPM. Like a formula.

Also, I'm curious as to how the digital output works...

# Answer
The Dout is a TTL threshold indicator; basically it goes high when a certain threshold of the sensor is reached, which is adjusted by the pot. The Aout is the VRef of the sensor.

Now the MG-811 is not the best sensor in the world; I did look at the datasheet which shows this sensor outputs mV in relation to the PPM so a map function could be used such as 100-600mV maps to 400-10000ppm CO2, see MG-811 CO2 Sensor Module, so you could feed this into a `map()` function and get the result but since there is a signal conditioning circuit consisting of a op-amp I'm not sure what it does to the raw sensor voltage.

Now the sandbox electronics module may not be identical to the SainSmart module, so you may need to reverse engineer the module you have to determine what is going on or use the schematic from the sandbox site to build your own and de-solder the MG-811 from the SainSmart module.
> 2 votes

# Answer
You can not directly convert the reading to ppm because you do not know what value means what ppm. You'd need at least one calibration point to calculate how many particles per million there are. The sensor is both affected by temperature and humidity so you might wish to compensate that too.
> 0 votes

---
Tags: sensors, analogread
---


# Question
Title: How to check if a GSM module is working or not?
I wanted to know if my GSM sim800 is working or not. A mishap occured while I was experimenting around with my GSM module and I arduino uno. The link to the module which I bought: http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW I want to know ow can I check if my module is fine?

# Answer
> 1 votes
Power it up and check the 'status' light. If it blinks with a 1 blink per second cycle, it is attempting to connect to the network. If it connects, it does a slow blink at 1 blink/3s, it made the network connection.

I don't know if your board does an auto-power-on, but you might need to push the power button or reset button.

---
Tags: arduino-uno, gsm
---


# Question
Title: Upload with esptool fails with "espcomm_send_command: can't receive slip payload data"
Uploading a sketch to an ESP8266 board fails with:

```
error: failed reading byte
warning: espcomm_send_command: can't receive slip payload data
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

```

...or:

```
espcomm cmd: receiving 2 bytes of data
warning: espcomm cmd: no final C0
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

```

This is on OS X with a PL2303HXD USB-to-Serial cable, using the latest official Prolific signed OS X El Capitan-compatible drivers.

# Answer
This is a known issue with the included esptool, and for the Arduino IDE there are quite a few blog posts to be found on this problem. But most are outdated, and are not applicable when using PlatformIO with some other IDE. So, February 2016:

**Install esptool.py**

* `git clone https://github.com/themadinventor/esptool/` (or download the ZIP file)
* `cd esptool`
* `sudo python setup.py install`

**When using Arduino IDE**

* Open `~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/platform.txt`.
* Find the line `tools.esptool.upload.pattern` and disable that by prefixing with a hash. Check that your version only mentions `-ca 0x00000`, not `-ca 0x10000` as well (like in most outdated blog posts):

```
# tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"

```
* Add the following, referring to the `esptool.py` you installed above and also using different command line parameters:

```
# Fix for espcomm_send_command: cant receive slip payload data
tools.esptool.upload.pattern="/path/to/new/esptool.py" --port "{serial.port}" --baud {upload.speed} write_flash 0x00000 "{build.path}/{build.project_name}.bin"

```
* Restart the IDE.

(One might be tempted to just change `tools.esptool.path` and `tools.esptool.cmd` instead, but beware that the command line parameters need changing as well.)

**When using PlatformIO**

You will find the same `platform.txt` file somewhere in `~/.platformio/packages/framework-arduinoespressif/platform.txt`, but that file is not used for the upload. Instead:

* In `platformio.ini` add:

```
# ...or whatever your port is named
upload_port = /dev/cu.usbserial
extra_script = /path/to/platformio_extra_script.py

```
* Create a new file `/path/to/platformio_extra_script.py`:

```
# Custom settings, as referred to as "extra_script" in platformio.ini
#
# See http://docs.platformio.org/en/latest/projectconf.html#extra-script
# See https://github.com/platformio/platformio/issues/426

from SCons.Script import DefaultEnvironment

env = DefaultEnvironment()

# Must be full path, or use
# https://docs.python.org/2/library/os.path.html#os.path.expanduser

env.Replace(
    LOCAL_UPLOADER="/Users/arjan/path/to/new/esptool.py",
    LOCAL_UPLOADERFLAGS=[
        "--port", "$UPLOAD_PORT",
        "--baud", "$UPLOAD_SPEED",
        "write_flash", "0x00000",
    ],
    UPLOADCMD='$LOCAL_UPLOADER $LOCAL_UPLOADERFLAGS $SOURCE'
)

```
> 4 votes

---
Tags: uploading, esp8266, osx
---


title: Manual reset is required on power on

text:
# Question
Title: Manual reset is required on power on
I am powering a UNO through the 5V pin. I am using a tftlcd shield (2.8" mcufriend.com) on it.

To be able to use the shield with I2C I had to snip the RST leg from the shield. That was done because the shield used A4 which was required for I2C. When I power the UNO through the USB port the program starts correctly and a bitmap is loaded onto the screen. When I power up from the 5V pin or the power adapter, the screen remains white. I have to manually press the reset button on the UNO and then the program loads the bitmap.

The ladyAda examples had this to say;

```
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0
#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

```

Does that mean I should solder the lcd RST pin to the RESET on the UNO? (if so I am not sure how I can do that without taking the lcd shield to pieces).

# Answer
> 1 votes
It isn't clear from the description whether your setup has a hardware problem or a software problem. For example, the rationale for “I had to snip the RST leg from the shield” is unclear.

The comment in ladyAda's example, “Can alternately just connect to Arduino's reset pin”, means that it's suitable to hardware-reset the LCD at the same time the Arduino does a hardware reset. If the “RST leg from the shield” that you snipped is the LCD reset pin, as opposed to a pin driven by the small tactile reset switch on the 2.8" mcufriend shield, you probably should restore that pin. In other words, unsolder and remove the stub of the pin you snipped off, insert a new pin, and solder it in place.

Note, just reinstalling the pin might make things work. It's possible the LCD is sitting there in a permanently-reset state, due to its RST input hanging open. It's also possible the library is already driving RST properly but that drive isn't getting through, due to the missing pin. Whatever the case may be, with the pin in place you should be able to software-reset the LCD by pulsing A4. (Ie, with consecutive `digitalWrite()` commands, in `setup()` and before shield initialization, take A4 high and then low, or vice versa.)

*Edit:* If A4 isn't available for resetting the LCD (due to its use as the SDA signal for I2C, per comment) you might try adding a jumper wire from the shield's LCD\_RS pin (above A4) to an available pin, and adjust the `#define LCD_RESET` statement accordingly.

In general, to add a jumper wire, strip about 5 mm of each end of a short piece of #30 wire-wrap wire. Form a small hook at each end. Hold a hook onto the solder of the pin you wish to attach to and briefly heat the solder, letting the hook sink into the solder. If you don't have wire-wrap wire, use a single strand from some old stranded cable (eg, mouse or keyboard). Use thin heatshrink tubing or a bit of stripped-off cable insulation to insulate the jumper. To keep pins in place while soldering, seat the pins being worked on into an old disk-drive connector, or another shield, or if you have nothing else, an Uno.

In your particular case, an mcufriend shield on an Uno, no pins are available unless you co-opt one of the SD-card-slot signals. But before doing that, it's probably worthwhile to try your original idea of wiring to the Uno's RESET pin. Your jumper would run from J3's second pin (A4) to J4's last pin (Reset), installed on the LCD side of the shield. You should be able to see the trace between the Reset pin and the Reset switch, when identifying the Reset pin.

---
Tags: power, lcd
---


title: Multiple MPU9250 using Multiplexer

text:
# Question
Title: Multiple MPU9250 using Multiplexer
Anybody here have tried connecting multiple MPU9250 into multiplexer. Anyway, I've used the HD74LS151 as the substitute for the 74HC4051 multiplexer. I already tried running the program and just followed how it is connected as it is connected like in the picture. Please see the attached image in here.

Right after running the code I just only got zeros on the output. I hope someone could help me figure out what's going on with my program or the connections of my pins.

And here is the code I used:

```
    #include <I2Cdev.h>
    #include <MPU6050.h>

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE    implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu_0(0x68);
    MPU6050 mpu_1(0x68);
    MPU6050 mpu_2(0x68);
    MPU6050 mpu_3(0x68);
    //MPU6050 accelgyro(0x69); // <-- use for AD0 high

    int16_t ax_0, ay_0, az_0, ax_1, ay_1, az_1, ax_2, ay_2, az_2, ax_3, ay_3, az_3;
    int16_t gx_0, gy_0, gz_0, gx_1, gy_1, gz_1, gx_2, gy_2, gz_2, gx_3, gy_3, gz_3;

   // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
  // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
 // not so easy to parse, and slow(er) over UART.
 #define OUTPUT_READABLE_ACCELGYRO

 // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
 // binary, one right after the other. This is very fast (as fast as possible
// without compression or data loss), and easy to parse, but impossible to read
// for a human.
//#define OUTPUT_BINARY_ACCELGYRO

 #define LED_PIN 13
 bool blinkState = false;

 //Mux control pins
 int s0 = 5;
 int s1 = 6;
 int s2 = 7;

 //Mux in "SIG" pin
 int SIG_pin = 0;

 const int MPU=0x68;

 void setup() {

  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);

  //    delay(5);
  //    Wire.begin();
  //    Wire.beginTransmission(MPU);
  //    Wire.write(0x6B);  // PWR_MGMT_1 register
  //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
  //    Wire.endTransmission(true);
  //    delay(15);
 //
 //    digitalWrite(s0, HIGH);
 //    digitalWrite(s1, LOW);
 //    digitalWrite(s2, LOW);
//    delay(5);
//
//    Wire.begin();
//    Wire.beginTransmission(MPU);
//    Wire.write(0x6B);  // PWR_MGMT_1 register
//    Wire.write(0);     // set to zero (wakes up the MPU-6050)
//    Wire.endTransmission(true);
//    delay(15);

// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif

// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);

// ================= MPU: 0 =================
digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_0.initialize();
Serial.println("Testing device connections #0 ...");
Serial.println(mpu_0.testConnection() ? "MPU6050 connection #0 successful" :      "MPU6050 connection #0 failed");
delay(5);

// ================= MPU: 1 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_1.initialize();
Serial.println("Testing device connections #1 ...");
Serial.println(mpu_1.testConnection() ? "MPU6050 connection #1 successful" :  "MPU6050 connection #1 failed");
delay(5);

// ================= MPU: 2 =================
digitalWrite(s0, LOW);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_2.initialize();
Serial.println("Testing device connections #2 ...");
Serial.println(mpu_2.testConnection() ? "MPU6050 connection #2 successful" : "MPU6050 connection #2 failed");
delay(5);

// ================= MPU: 3 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_3.initialize();
Serial.println("Testing device connections #3 ...");
Serial.println(mpu_3.testConnection() ? "MPU6050 connection #3 successful" : "MPU6050 connection #3 failed");
delay(5);

// use the code below to change accel/gyro offset values
/*
Serial.println("Updating internal sensor offsets...");
// -76  -2359   1688    0   0   0
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
accelgyro.setXGyroOffset(220);
accelgyro.setYGyroOffset(76);
accelgyro.setZGyroOffset(-85);
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
*/

// configure Arduino LED for
pinMode(LED_PIN, OUTPUT);
}

void loop() {
// read raw accel/gyro measurements from device
//    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);

// ================= MPU: 0 =================
digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
mpu_0.getMotion6(&ax_0, &ay_0, &az_0, &gx_0, &gy_0, &gz_0);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#0\ta/g:\t");
    Serial.print(ax_0); Serial.print("\t");
    Serial.print(ay_0); Serial.print("\t");
    Serial.print(az_0); Serial.print("\t");
    Serial.print(gx_0); Serial.print("\t");
    Serial.print(gy_0); Serial.print("\t");
    Serial.println(gz_0);
  #endif
  delay(5);

// ================= MPU: 1 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
mpu_1.getMotion6(&ax_1, &ay_1, &az_1, &gx_1, &gy_1, &gz_1);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#1\ta/g:\t");
    Serial.print(ax_1); Serial.print("\t");
    Serial.print(ay_1); Serial.print("\t");
    Serial.print(az_1); Serial.print("\t");
    Serial.print(gx_1); Serial.print("\t");
    Serial.print(gy_1); Serial.print("\t");
    Serial.println(gz_1);
#endif
delay(5);

// ================= MPU: 2 =================
digitalWrite(s0, LOW);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
mpu_2.getMotion6(&ax_2, &ay_2, &az_2, &gx_2, &gy_2, &gz_2);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#2\ta/g:\t");
    Serial.print(ax_2); Serial.print("\t");
    Serial.print(ay_2); Serial.print("\t");
    Serial.print(az_2); Serial.print("\t");
    Serial.print(gx_2); Serial.print("\t");
    Serial.print(gy_2); Serial.print("\t");
    Serial.println(gz_2);
   #endif
   delay(5);

   // ================= MPU: 3 =================
   digitalWrite(s0, HIGH);
   digitalWrite(s1, HIGH);
   digitalWrite(s2, LOW);
   delay(5);
   mpu_3.getMotion6(&ax_3, &ay_3, &az_3, &gx_3, &gy_3, &gz_3);
   #ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#3\ta/g:\t");
    Serial.print(ax_3); Serial.print("\t");
    Serial.print(ay_3); Serial.print("\t");
    Serial.print(az_3); Serial.print("\t");
    Serial.print(gx_3); Serial.print("\t");
    Serial.print(gy_3); Serial.print("\t");
    Serial.println(gz_3);
    #endif
    delay(5);

   //    #ifdef OUTPUT_BINARY_ACCELGYRO
     //        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax &    0xFF));
     //        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
     //        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
      //        Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
      //        Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
     //        Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
     //    #endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
   }

```

Cheers!

# Answer
> 1 votes
Your concept sounded sensible enough so I gave it a try-out.

First point is: The master always generates the clock so we don't need to multiplex that. We only need to multiplex the data (SDA).

Code snippet:

```
// the multiplexer address select lines (A/B/C)
const byte addressA = 6; // low-order bit
const byte addressB = 5;
const byte addressC = 4; // high-order bit

int selectTarget (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
  }  // end of readSensor

```

All you have to do is call `selectTarget(n)` where `n` is 0 to 7, and you redirect SDA to the desired chip. I suggest a 4.7k pull-up on the target side so that the line is pulled high when not selected.

I tested it out and it seems to work OK.

---

The beauty of this setup is that you can multiplex 8 devices (eg. sensors) which happen to have the same I2C address, with only one additional chip. And, you can get 16-channel multiplexers if you want to take this further. Of course, in the code you still have to select the correct I2C address for the chip.

---
Tags: arduino-mega, mpu6050, multiplexer
---


# Question
Title: Upload Code on Arduino Mega using FTDI Cable
I would like to upload my code to the Arduino Mega 2560.

1. The USB is fried hence I have to use the FTDI
2. I've a FTDI cable, but it has only 4 wires, Vcc,GND,TX,RX

How do you upload, as the ATmega is not responding to anything?

# Answer
> 0 votes
FTDI cables usually have RTS which is used to bring `Reset` low. If you only have four pins, press the Reset button on the board the moment you start the upload.

---
Tags: arduino-mega, ftdi
---


# Question
Title: How to connect two IMU in one arduino board?
The code below works fine when one IMU (MPU9250). What I want to know is how can I edit this code to work perfectly with two IMU (MPU9250) in one arduino board ?

Hope someone can help me. THANKS :)

```
////////////////////////////////////////////////////////////////////////////
      //
      //  This file is part of RTIMULib-Arduino
      //
      //  Copyright (c) 2014-2015, richards-tech
     //
     //  Permission is hereby granted, free of charge, to any person           obtaining a copy of
    //  this software and associated documentation files (the "Software"), to deal in
    //  the Software without restriction, including without limitation the rights to use,
   //  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
   //  Software, and to permit persons to whom the Software is furnished to do so,
   //  subject to the following conditions:
   //
   //  The above copyright notice and this permission notice shall be included in all
  //  copies or substantial portions of the Software.
  //
  //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  //  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  //  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  //  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  //  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  //  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  #include <Wire.h>
  #include "I2Cdev.h"
  #include "RTIMUSettings.h"
  #include "RTIMU.h"
  #include "RTFusionRTQF.h"
  #include "RTPressure.h"
  #include "CalLib.h"
  #include <EEPROM.h>

  RTIMU *imu;                                           // the IMU object
  RTPressure *pressure;                                 // the pressure object
  RTFusionRTQF fusion;                                  // the fusion object
  RTIMUSettings settings;                               // the settings object

  //  DISPLAY_INTERVAL sets the rate at which results are displayed

  #define DISPLAY_INTERVAL  300                         // interval between   pose displays

 //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

 #define  SERIAL_PORT_SPEED  115200

  unsigned long lastDisplay;
  unsigned long lastRate;
  int sampleCount;

  void setup()
  {
  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
  imu = RTIMU::createIMU(&settings);                        // create the    imu object
  pressure = RTPressure::createPressure(&settings);         // create the  pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu-   >IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());
   if ((errcode = imu->IMUInit()) < 0) {
   Serial.print("Failed to init IMU: "); Serial.println(errcode);
   }

   if ((errcode = pressure->pressureInit()) < 0) {
   Serial.print("Failed to init pressure sensor: ");
   Serial.println(errcode);
   }

   if (imu->getCalibrationValid())
   Serial.println("Using compass calibration");
   else
   Serial.println("No valid compass calibration data");

    lastDisplay = lastRate = millis();
    sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
   // In-between gives the fusion mix.

   fusion.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

    fusion.setGyroEnable(true);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);
    }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
         continue;

      fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
      sampleCount++;
      if ((delta = now - lastRate) >= 1000) {
      Serial.print("Sample rate: "); Serial.print(sampleCount);
      if (imu->IMUGyroBiasValid())
      Serial.println(", gyro bias valid");
      else
      Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
       }
       if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
       //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());
                  // gyro data
        //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());
                     // accel data
       //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
          // compass data
        RTMath::displayRollPitchYaw("Pose:",   (RTVector3&)fusion.getFusionPose()); // fused output

        if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
        Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }
        }

```

EDITED CODE:

```
       #include <Wire.h>
       #include "I2Cdev.h"
       #include "RTIMUSettings.h"
       #include "RTIMU.h"
       #include "RTFusionRTQF.h"
       #include "RTPressure.h"
       #include "CalLib.h"
       #include <EEPROM.h>

       RTIMU *imu;                                           // the IMU object
      RTPressure *pressure;                                 // the pressure object
      RTFusionRTQF fusion;                                  // the fusion object
      RTIMUSettings settings;                               // the settings object

      //  DISPLAY_INTERVAL sets the rate at which results are displayed

      #define DISPLAY_INTERVAL  300                         // interval between   pose displays

     //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

     #define  SERIAL_PORT_SPEED  115200

    unsigned long lastDisplay;
    unsigned long lastRate;
    int sampleCount;

    // ================= MPU: 1 =================

   RTIMU *imu1;                                           // the IMU object
   RTPressure *pressure1;                                 // the pressure object
   RTFusionRTQF fusion1;                                  // the fusion object
   RTIMUSettings settings1;                               // the settings object

   unsigned long lastDisplay1;
   unsigned long lastRate1;
   int sampleCount1;

   const int CS_MAX = 2;
   const int CS[CS_MAX] = { 7, 8 };

   void setup()
   {
  for (int i = 0; i < CS_MAX; i++) {
  pinMode(CS[i], OUTPUT);
  digitalWrite(CS[i], HIGH);
  }

  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
   imu = RTIMU::createIMU(&settings);                        // create the imu object
  pressure = RTPressure::createPressure(&settings);         // create the pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
  while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu->IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());

  for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);
  if ((errcode = imu->IMUInit()) < 0) {
  Serial.print("Failed to init IMU: "); Serial.println(errcode);
  }

  if ((errcode = pressure->pressureInit()) < 0) {
  Serial.print("Failed to init pressure sensor: "); Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  lastDisplay = lastRate = millis();
  sampleCount = 0;

   // Slerp power controls the fusion and can be between 0 and 1
   // 0 means that only gyros are used, 1 means that only accels/compass are   used
  // In-between gives the fusion mix.

  fusion.setSlerpPower(0.02);

  // use of sensors in the fusion algorithm can be controlled here
  // change any of these to false to disable that sensor

   fusion.setGyroEnable(true);
   fusion.setAccelEnable(true);
   fusion.setCompassEnable(true);
   digitalWrite(CS[i], HIGH);
   }

   int errcode1;
   Serial.begin(SERIAL_PORT_SPEED);
   Wire.begin();
   imu1= RTIMU::createIMU(&settings1);                        // create the imu object
   pressure1 = RTPressure::createPressure(&settings1);         // create the pressure sensor

    if (pressure1 == 0) {
    Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
    }

    Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu1->IMUName());
    Serial.print(", pressure sensor "); Serial.println(pressure1->pressureName());

    for (int i = 0; i < CS_MAX; i++) {
    digitalWrite(CS[i], LOW);

    if ((errcode1 = imu1->IMUInit()) < 0) {
    Serial.print("Failed to init IMU1: "); Serial.println(errcode1);
    }

    if ((errcode1 = pressure1->pressureInit()) < 0) {
     Serial.print("Failed to init pressure sensor1: ");
     Serial.println(errcode1);
     }

     if (imu1->getCalibrationValid())
    Serial.println("Using compass calibration");
    else
    Serial.println("No valid compass calibration data1");

    lastDisplay1 = lastRate1 = millis();
    sampleCount1 = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion1.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

     fusion1.setGyroEnable(true);
     fusion1.setAccelEnable(true);
     fusion1.setCompassEnable(true);

     digitalWrite(CS[i], HIGH);
     }
     }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the   latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
        continue;

       fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount);
        if (imu->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
        }
        if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
        //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());

         // gyro data
         //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());

         // accel data
        //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
        // compass data
          RTMath::displayRollPitchYaw("Pose:",
          (RTVector3&)fusion.getFusionPose()); // fused output

         if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
            Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }

       unsigned long now1 = millis();
      unsigned long delta1;
      float latestPressure1;
      float latestTemperature1;
      int loopCount1 = 1;

      while (imu1->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount1 >= 10)
        continue;

      fusion1.newIMUData(imu1->getGyro(), imu1->getAccel(), imu1-  >getCompass(), imu1->getTimestamp());
      sampleCount1++;
      if ((delta1 = now1 - lastRate1) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount1);
        if (imu1->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount1 = 0;
        lastRate1 = now1;
    }
    if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
        lastDisplay1 = now1;
      //          RTMath::display("Gyro1:", (RTVector3&)imu1->getGyro());
      // gyro data
      //          RTMath::display("Accel1:", (RTVector3&)imu1->getAccel());
      // accel data
      //          RTMath::display("Mag1:", (RTVector3&)imu1->getCompass());
        // compass data
        RTMath::displayRollPitchYaw("Pose1:", (RTVector3&)fusion1.getFusionPose()); // fused output

        if (pressure1->pressureRead(latestPressure1, latestTemperature1)) {
            Serial.print(", pressure: "); Serial.print(latestPressure1);
            Serial.print(", temperature: "); Serial.print(latestTemperature1);
        }
        Serial.println();
    }
}

```

}

# Answer
> 1 votes
Before editing the code to support an additional MPU9X50 you will need to figure out a way to address them on the I2C bus. Hopefully the MPU9X50 module you are using has a pin named AD0.

There are two basic solutions to multiple MPU9X50.

The first solution is to use the two different addresses. AD0 pin LOW on one and AD0 pin HIGH on the other. The sketch above would require two instances (imu), one for each module/address.

The second solution, which works for several modules, is to hold the AD0 pin LOW for the module that is addresses and all other HIGH. The setting must be handled by a digital pin. One for each module. They will be used as chip/module select. Below the example code assumes that the MPU I2C address is with the lowest bit LOW.

In the setup() initiate these pins to output mode and high. The example code uses pin 7 and 8.

```
const int CS_MAX = 2;
const int CS[CS_MAX] = { 7, 8 };

void setup()
{
   ...
   for (int i = 0; i < CS_MAX; i++) {
     pinMode(CS[i], OUTPUT);
     digitalWrite(CS[i], HIGH);
   }
   ...
}

```

Set the digital pin LOW for the module you want to address before calling an MPU library function and back to HIGH afterwards.

```
digitalWrite(CS[0], LOW);
imu->someMemberFunction();
digitalWrite(CS[0], HIGH);

```

If several functions are called in a block it can be convenient to run all of them per module. An example section from the setup:

```
for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);

  if ((errcode = imu->IMUInit()) < 0) {
    Serial.print("Failed to init IMU: ");
    Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  digitalWrite(CS[i], HIGH);
}

```

Cheers!

---
Tags: arduino-mega, mpu6050
---


title: Sim800 sim card requirements

text:
# Question
Title: Sim800 sim card requirements
What kind of a sim card is required for sim800 module? I know it must be activated and must be valid. But about 2g, 3g or LTE...What kind of a sim card in overall should I use with this module?

# Answer
> What kind of a sim card is required for sim800 module?

*The SIM interface complies with the GSM Phase 1 specification and the new GSM Phase 2+ specification for FAST 64 kbps SIM card. Both 1.8V and 3.0V SIM card are supported. The SIM interface is powered from an internal regulator in the module.*

For more details see here and here. And remember "Google is your friend".

Cheers!
> 2 votes

---
Tags: gsm
---


title: LCDs measuring volts arduino

text:
# Question
Title: LCDs measuring volts arduino
How do we measure 100 Volts Arduino LCD Proje

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int analogInput = 0;
float vout = 0.0;
float vin = 0.0;
float R1 = 100000.0; // 100K ohm direnç
float R2 = 10000.0; // 10K ohm direnç
int value = 0;
void setup(){
   pinMode(analogInput, INPUT);
   lcd.begin(16, 2);
   lcd.print("DC VOLTMETRE-PROJEHOCAM");
}
void loop(){
   // read the value at analog input
   value = analogRead(analogInput);
   vout = (value * 5.0) / 1024.0;
   vin = vout / (R2/(R1+R2));
   if (vin<0.09) {
   vin=0.0;
}
lcd.setCursor(0, 1);
lcd.print("VOLTAJ V= ");
lcd.print(vin);
delay(500);
}

```

# Answer
> 1 votes
The project that you show as your reference : link in your question, shows this picture :

Change R1 to 200 K ohms. The Arduino will receive 4.76 volts when the input is 100 volts.

You will also need to change your program line for float R1 = 100000.0;

**CAUTION : Beware of high voltage. Also, the Arduino is not isolated from the 100 volts.**

---
Tags: arduino-uno, lcd, voltage-level
---


title: How to wire an LMD18200 and an arduino?

text:
# Question
Title: How to wire an LMD18200 and an arduino?
Ive been working with a motor project for a while and i bought this H-bridge(LMD18200). I dont understand how im supposed to connect it to the arduino.

Here is the datasheet for the lmd18200:

# Answer
> 1 votes
Most basic way would be to use only DIR, PWM and Break.

Use Break as enable (put high at begining of the program, put low when you want to start rotation).

Use Dir to change rotation of the motor (usually high is CV, low is CCV, but you need to check the datasheet)

And hook up PWM to PWM pin on arduino. This will control the speed.

---
Tags: h-bridge, wires
---


# Question
Title: driver is not showing up in Port assignments mac
arduino nano, the driver is not showing up in Port assignments. It has worked with this operating system before. I’ve messed something up. “OS X EI Capitan ver. 10.11.3 I have check the posts but the serial port is a no show

# Answer
If the port showed in earlier versions of OS X, but never showed after upgrading to El Capitan, then you probably used an unsigned driver, which is no longer allowed by Apple's new System Integrity Protection (a.k.a. "Rootless"; more details in a WWDC session).

Any unsigned drivers will have been disabled during the upgrade process. Even more, SIP does not allow *any* non-Apple files in `/System`, `/bin`, `/sbin` and `/usr` (except for `/usr/local`), so anything you had put in there will have been moved away as well. To see what has been disabled:

* `ls -l "/Incompatible Software"`
* `ls -lR /Library/SystemMigration/History/Migration-*/QuarantineRoot/*`

To get it working again: find a signed driver, or Switch off SIP.
> 2 votes

---
Tags: port-mapping
---


# Question
Title: Sending a floating point number from python to arduino
I am trying to send a floating point number from a python script to an Arduino. I am not sure how to do this, especially in a pythonic way.

A little bit of research brought me to this very similar question: How to send numbers to Arduino UNO via Python 3 and the module serial I vaguely understand why this would work for an int but don't know how to modify it.

1) In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

2) Why do they convert to a Char anyway?

3) What code do I run on the arduino to get this back into a float?

4) Can I use bitwise operators on floating point numbers?

I'm new to python and also to low level programming. I am also aware that python and low level don't mix to well. I am using Linux but ideally I need a cross platform solution. Although I would prefer to get it working then worry about cross platform later.

# Answer
> In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

Instead of using a format specifier of `B` for an unsigned byte, use `f` for a single-precision float. AVR-GCC doesn't support double-precision floats, so don't bother with `d`.

> Why do they convert to a Char anyway?

You don't. You convert it to bytes (hence the `b` prefix on the representation of the value) so that the byte-oriented serial protocol can transmit it. On Python 2.x `str` is already bytes, so no prefix is required there.

> What code do I run on the arduino to get this back into a float?

Use `Serial.readBytes()` to dump the bytes from the serial connection into a `float` variable.

```
float f;
 ...
if (Serial.readBytes((char*)&f, sizeof(f)) != sizeof(f)) {
   ...

```

> Can I use bitwise operators on floating point numbers?

... Well... no... because they may not necessarily remain valid floating point numbers afterwards.
> 0 votes

# Answer
Floating point numbers are (should) be stored in IEEE 754 format.

If you simply write the binary bytes of a floating point number down the serial line, it should be possible to unpack them at the other end.

To do this (Arduino C/C++), make a pointer from your variable, by casting the address of it to char\*. Void\* would probably work too.

```
 float my_value = 22.812;
 my_port.write((const char *)&my_value, sizeof(float)/*4*/);

```

And the unpacking - there's a few ways to do this, but I like:

```
 float incoming_value;
 unsigned char buffer[4];

 // If we read enough bytes, unpacked it
 if (my_serial.readBytes(buffer, sizeof(float)) == sizeof(float))
     memcpy(&incoming_value, buffer, sizeof(float));
 else
     // I/O error - no data, not enough bytes, etc.
     incoming_value = 0

```

On the other end (python), bytes are best handled with the **struct** module. This will handle the packing and unpacking for you.

```
import struct
...

try:
    ieee754_data = my_serial.read(4)
    my_float = struct.unpack('f', ieee754_data)
catch:
    # I/O Error, or junk data
    my_float = 0.0

```

And packing:

```
 ieee754_data = struct.pack('f', my_float)
 try:
     my_serial.write(ieee754_data)
 catch:
     pass #TODO - I/O Error

```

One more note - You might consider using doubles instead of floats for extra precision. Python floats have the precision of a C/C++ double already.
> 1 votes

---
Tags: serial, python, float
---


title: Pyserial and Arduino

text:
# Question
Title: Pyserial and Arduino
I am trying to send an integer value from Python to Arduino. The integer value is a position given by a webcam, which will determine how many turns a stepper motor moves.

Arduino:

```
#include <AccelStepper.h>
AccelStepper stepper(AccelStepper::DRIVER,8,9);

void setup() {
  Serial.begin(9600);
  stepper.setMaxSpeed(1000.0);
  stepper.setAcceleration(700.0);
}

void loop() {
  int val = 0;
  if(Serial.available()){
    val = map(Serial.parseInt(), 0, 1280, 0, 551);
    Serial.println(val);
  }
  stepper.runToNewPosition(val);
}

```

Python:

```
# source: http://www.steinm.com/blog/motion-detection-webcam-python-opencv-differential-images/

import cv2
import numpy as np
import serial
import time

def diffImg(t0, t1, t2):
    d1 = cv2.absdiff(t2, t1)
    d2 = cv2.absdiff(t1, t0)
    dif = cv2.bitwise_and(d1, d2)
    return np.fliplr(dif)

cam = cv2.VideoCapture(0)

#winName = "Movement Indicator" #camera window
#cv2.namedWindow(winName, cv2.WINDOW_NORMAL)

# Read three images first:
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

h, w = t.shape

winTest = "Test Window" #test window
cv2.namedWindow(winTest, cv2.WINDOW_NORMAL)

thresh = 100

ser=serial.Serial('/dev/cu.usbmodem1411',9600,timeout=0)
time.sleep(2)

while True:

    img = diffImg(t_minus, t, t_plus)

#    cv2.imshow(winName, img )

    nz = np.transpose(np.nonzero(img>thresh))
    a = 0
    b = 0
    c = 0
    d = 0
    avg=0
    if nz.size>0:
        a,b = nz[0]
        c,d = nz[-1]
        avg = (b+d)/2
        if 0<=avg and avg<=1280:
            print avg
            ser.write(str(int(avg))+" ")

    test = np.zeros((h,w))

    cv2.rectangle(test, ((avg-5),a), ((avg+5),c), (255), -1)
    cv2.imshow(winTest, test )

    # Read next image
    t_minus = t
    t = t_plus
    t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
    print ser.readline();

    key = cv2.waitKey(10)
    if key == 27:
       cv2.destroyWindow(winName)
       ser.close()
       break

print "Goodbye"

```

This works OK but occasionally 'val' will take some ridiculous value, say 7182, and the motor spins out of control. I realize I can check values with an if statement before I actually write to the stepper motor, but I think my problem is with reading and writing to the Arduino.

My other issue is I feel Arduino is not receiving some of the data sent to it via serial connection. This is hard to say, as Serial.print() is slow and mostly doesn't make it through to my terminal before it's already been rewritten.

# Answer
> 0 votes
Mr Gammon's comment about using a faster baud rate is an excellent idea.

You also seem to be sending the number as a string. Sending the integer as binary data (using python's struct module) would also reduce the amount of data that needs to be sent - significantly for larger numbers.

```
import struct

...

ser.write(struct.pack('I',int(avg)))

```

On the Arduino Side

```
uint8_t buffer[4];
uint32_t position;

if (my_serial.read(buffer, sizeof(uint32_t)) == sizeof(uint32_t))
    memcpy(&position, buffer, sizeof(uint32_t));

// alternatively in one step, without error checking
my_serial.read(&position, sizeof(uint32_t));

```

This assumes a 32-bit integer is needed.
Maybe you only need an unsigned short - this would halve the amount needed to transmit.

---
Tags: serial, python
---


# Question
Title: Temperature sensor reading is higher than the actual temperature
```
// Tells the Arduino to read A2 and stores the value in “Vin”
Vin = analogRead (tempSensor);

// Converts the voltage value to temperature and stores it into the “TC” variable (in °C)
TC = 500.0 * (Vin / 1024.0);

```

The temperature shown is about 50.25°C, sometimes it is showing 36-38°C degrees, but the actual temperature is about 25-26°C.

Why this is happening?

Code:

```
Vin = analogRead (tempSensor);
TC=(500.0*Vin)/1023.0;
TF = ((9.0*TC)/5.0)+32.0;
lcd.setCursor(0, 1);
lcd.print(TF);
lcd.print((char)223);
lcd.print("F ");
lcd.print (TC);
lcd.print((char)223);
lcd.print("C");
delay(1000);

```

# Answer
> 2 votes
Any chance you're printing Vin, and not TC?

500\*(50.25/1024) = ~24.5

If not, please post as much of your program as possible

# Answer
> 1 votes
I gave up on using a LM335, which is quite similar to your LM35. The problem is these devices self-heat due to the quiescent power they draw. The LM35 data sheet suggests you correct for this in software (footnote 5), and the LM335 datasheet dodges the bullet by quoting accuracy figures that can be achieved in an oil bath rather than free air.

But the figures you are quoting suggest you have a bigger problem, as I am talking of a few degrees inaccuracy, not tens of degrees.

I changed to a DS18B20 and never looked back - simple interface and self-heating is compensated for by the device.

# Answer
> 0 votes
It sounds like your voltage to temperature calculation is wrong. Assuming the temperature voltage relationship is linear you can work out the formula. Take two measurements at two known temperatures (quite far apart, perhaps outdoors and in) and note down the value Arduino measures for Vin. Lets call these VinA & VinB for TempA and TempB.

You can calculate measures per degree with...

MeasuresPerDeg = (TempB - TempA) /(VinB - VinA)

And the a constant as...

Constant = TempA - VinA\*MeasuresPerDeg

Your equation to calculate temperature should now be

TC=MeasuresPerDeg\*(Vin/1024.0) + Constant;

# Answer
> 0 votes
What are the variable types of `TC` and `TF` \- int/float/double? Something else?

If they're integers, you may be losing some numerical precision in the calculation.

When you get 50.25°C - have you checked the `Vin` is correct?

Also when you write the values out, the serial.print() can take the number of decimal points as a second argument.

```
// Print to three decimal places
Serial.print("TF=");
Serial.println((float)TF, 3);
Serial.print("TC=");
Serial.println((float)TC, 3);
Serial.print("Vin=");
Serial.println(Vin, DEC);

```

---
Tags: temperature-sensor
---


# Question
Title: Led issue with arduino controled by raspberry pi/python
I'm having an issue with my project. My project is 8 leds and a potentiometer on an arduino being read and controlled by a raspberry pi running python.

when I'm using a potentiometer the signal is received by my raspberry pi with python which then tells a set of leds to either turn on or off. However my leds flash on my low threshold when they shouldn't, the leds on my higher threshold work as expected and stay on till my pot is out of that range. How can I fix this?

Here is my script!

```
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
#this is the section that is blinking when it should stay solid
   if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.5)
# end of section
   if pot < 650 > 450:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.1)
    if pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.5)
    print pot

```

# Answer
Your second condition is written wrongly. It should be this way:

```
elif pot >= 450 and pot <= 650:
    # do stuff

```

Your code should be such that only an option is chosen at any time. There should be only one 'if' condition at the top and the rest should be 'elif'.
> 1 votes

# Answer
The problem is you're using multiple **if** statements, whereas the if-blocks should be mutually exclusive, so **elif** would be better. It's not really clear what you intend in the 2nd clause either, since it's a typo(?) - not valid python syntax anyway.

```
if (pot <= 450):
    Arduino.digitalWrite(LED1, Arduino.HIGH)
    ...
    time.sleep(0.5)
elif (pot > 450 and pot <= 650):
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.1)
else # pot > 650
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.5)

```

I think your LEDs were flashing because both the first and second **if** clauses were evaluating to True, thus both code segments were being executed (were only the first four LEDs flashing?) Using if/elif/else instead, ensures only ever one clause is run.

If I might make a suggestion, assuming you want an LED bar graph based on the POT reading...

The analogRead() will give you a result 0-1023. Graphed over 8 LEDs, this means one more LED should be illuminated roughly per 128 units. Since you want a full bar when rounding makes the value near 1023, maybe something like 120 is a better divisor (I just guessed this, it's probably calculable).

A simple loop over your LEDs, summing units over each iteration gives an easy way of turning the LEDs on or off.

```
Arduino.analogRead(POT)
led_bar_per_units = 120   # needs a better name

### illuminate the LED-bar
bar_length = 0
for led in (LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8):
    bar_length += led_per_bar_units
    if (bar_length <= pot):
        Arduino.digitalWrite(led, Arduino.HIGH)
    else:
        Arduino.digitalWrite(led, Arduino.LOW)
time.sleep(0.5)

```

EDIT: I know you don't need brackets around python **if** statements. I've been doing C/C++ code for so long I find bracketed-clauses easier to read, and thus code my python this way too.
> 0 votes

# Answer
I figured it out. Here is my new script.

```
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
    if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    elif pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.01)
    else:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    print pot

```
> 0 votes

---
Tags: serial, led, python, potentiometer, raspberrypi
---


# Question
Title: ATtiny85 communication with computer through USB
I am trying to receive and send some data from a computer to an ATtiny through USB. Can an ATtiny85 IC communicate with a computer through USB? If yes, how should it be connected?

# Answer
> 8 votes
Digispark made a lot of these as part of a "cheap Arduino USB interface" project a while back.

This is my Digispark, it's pretty cute:

They have a web page here.

---

I got them for about $2 each. The board has the ATtiny85, a voltage regulator, and a handful of other parts.

Schematic (courtesy of Digistump Wiki):

---

More information about the Virtual USB idea at USB-Keyboard with Arduino and V-USB library, an example.

# Answer
> 5 votes
> Can an ATtiny85 ic communicate with a computer through USB?if yes,how should be the connection?

Have you checked the web? There are many such projects. Here is a link to one:

http://www.instructables.com/id/Digispark-DIY-The-smallest-USB-Arduino/

Please remember "Google is your friend".

Cheers!

---
Tags: attiny
---


title: Serial monitor disconnecting itself

text:
# Question
Title: Serial monitor disconnecting itself
Problem: can't print to the serial monitor, it appears that the serial monitor disconnects itself after uploading a program.

I'm brand new to arduino, and I'm trying to upload a basic program to print to the serial monitor.

I use an arduino uno and my OS is Ubuntu. I am connecting the arduino to my PC via USB. Using Arduino Studio Release 0.0.5 experimental build 0.0.5-16058

(I am able to communicate via the digital output pins, tested by making a simple circuit to make the led light blink)

Here is the program:

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

void loop()
{
    Serial.print("test");
    delay(500);
}

```

Here is the result of the build, look at the last line and it says the serial monitor was disconnected? Why would this happen automatically?

```
[2/2/2016 8:51:26 PM] - Start Building
[2/2/2016 8:51:26 PM] - CPP File Created [/tmp/build1454471486915/test.cpp]
[2/2/2016 8:51:26 PM] - test.cpp compiled
[2/2/2016 8:51:26 PM] - CDC.cpp compiled
[2/2/2016 8:51:27 PM] - HID.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial0.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial1.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial2.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial3.cpp compiled
[2/2/2016 8:51:27 PM] - IPAddress.cpp compiled
[2/2/2016 8:51:27 PM] - Print.cpp compiled
[2/2/2016 8:51:27 PM] - Stream.cpp compiled
[2/2/2016 8:51:27 PM] - Tone.cpp compiled
[2/2/2016 8:51:27 PM] - USBCore.cpp compiled
[2/2/2016 8:51:27 PM] - WInterrupts.c compiled
[2/2/2016 8:51:27 PM] - WMath.cpp compiled
[2/2/2016 8:51:27 PM] - WString.cpp compiled
[2/2/2016 8:51:27 PM] - abi.cpp compiled
[2/2/2016 8:51:27 PM] - hooks.c compiled
[2/2/2016 8:51:27 PM] - main.cpp compiled
[2/2/2016 8:51:27 PM] - new.cpp compiled
[2/2/2016 8:51:28 PM] - wiring.c compiled
[2/2/2016 8:51:28 PM] - wiring_analog.c compiled
[2/2/2016 8:51:28 PM] - wiring_digital.c compiled
[2/2/2016 8:51:28 PM] - wiring_pulse.c compiled
[2/2/2016 8:51:28 PM] - wiring_shift.c compiled
[2/2/2016 8:51:28 PM] - CDC.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HID.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial0.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial1.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial2.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial3.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - IPAddress.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Print.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Stream.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Tone.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - USBCore.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WInterrupts.c.o linked to core.a
[2/2/2016 8:51:28 PM] - WMath.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WString.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - abi.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - hooks.c.o linked to core.a
[2/2/2016 8:51:28 PM] - main.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - new.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.ino linked to core.a
[2/2/2016 8:51:28 PM] - wiring.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_analog.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_digital.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_pulse.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_shift.c.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.elf linked to core.a
[2/2/2016 8:51:28 PM] - test EEPROM
[2/2/2016 8:51:28 PM] - test.hex builded
[2/2/2016 8:51:28 PM] - Uploading...
[2/2/2016 8:51:30 PM] - Uploaded
[2/2/2016 8:51:30 PM] - [arduino ide - serial monitor] Serial monitor connected to /dev/ttyACM0
[2/2/2016 8:51:36 PM] - [arduino ide - serial monitor] Serial monitor disconnected from /dev/ttyACM0

```

# Answer
I'm not sure why your IDE is doing that, but the official Arduino IDE from Arduino.cc works on Ubuntu and does not have that issue. Download from Arduino Software download page.
> 2 votes

---
Tags: arduino-uno, serial
---


# Question
Title: Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560?
I'd like to offer some context about what I'd like to do because I might have misundertood something.

I'm trying to reduce power consumption on my device, an Arduino Mega 2560, and I've found this library

https://github.com/rocketscream/Low-Power

which uses the Watchdog to put Arduino on power saving for a predetermined interval of time; after that it reactivates what has been disabled and let the program continue its flow.

I searched for more information about the Watchdog and I found out several warnings about dealing with Watchdog on an Arduino Mega 2560, stating that it would only work with a modified bootloader: This scared me a bit because I'm not very keen on risking to brick my Arduino (I absolutely need it to work on the next few days).

Now, I only have two Arduino Mega 2560 at my disposal and if I'm not mistaken, flashing the bootloader on an Arduino Mega 2560 using another Arduino Mega 2560 as a programmer can't be done because the procedure ends with errors:

( see http://forum.arduino.cc/index.php?topic=126160.0 )

Hence my most important question: if I test the watchdog functionality on my code (the sketch) and the Arduino happens to continually reset, can I fix the situation by powering off the Arduino?

(if you can help with my other issues as well, I'd be very grateful, I'm not sure I completely understood how these things work)

# Answer
> 0 votes
The problem you have is that once the watchdog is turned on it is very hard to turn it off again. There are certain procedures you have to go through to ensure it's turned off.

The default bootloader doesn't turn the bootloader off, and a reset doesn't turn it off either. The watchdog then fires whilst the bootloader is still waiting for communication from the PC thus making it reboot before your sketch has had a chance to run. Hence the change needed in the bootooader.

The only way to clear the watchdog is to remove the power. However as soon as your sketch runs and turns the watchdog back on you are then back at square one.

So you need to upload a new sketch to stop that happening, but that is tricky, since the watchdog keeps resetting and interrupting the bootloader. So what do you do? Well, there's a specific sequence you need to do.

1. Unplug the mega
2. Compile the new sketch
3. Hold the reset button on the mega
4. Plug in the mega
5. Press upload
6. As soon as avrdude starts release the reset button.

That way you have a chance of the bootloader running without your sketch having run first and enabled the watchdog. The bootloader runs just the once when the computer is tryung to upload the sketch, and with luck that will happen instead of your sketch running.

---
Tags: arduino-mega
---


# Question
Title: Sublime Text 2 with stino, compilation gives "filename ... is incorrect" Arduino IDE 1.7.8
I can't compile a simple blink sketch.

Error is:

```
[Stino - Start building "t5"...]
[  3%] Creating C:\Users\lov\AppData\Local\Temp\Stino_build\t5\t5.ino.cpp.o...
The filename, directory name, or volume label syntax is incorrect.

```

See also see similar question, that answer not working here.

Path to IDE app is `C:\Program Files (x86)\added\Arduino`.

# Answer
Sorry but this is too big for a comment.

Firstly please can you check the obvious, in Windows Explorer paste the path C:\Users\lov\AppData\Local\Temp\Stino\_build\t5 into the address bar and does the directory exist. (I have fallen for that so many times)

Secondly do you have permission to create a file there?

Have you updated the IDE? Does blink compile?

Have you tried running the IDE as admin?

Hopefully one of those will fix it.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: How to copy files from Yun to local computer?
I would like to copy a file that is in the root folder of my Yun, to my Macbook. They are connected with an ethernet cable and I am logged into the Yun through ssh. The Yun's IP is 192.168.2.16 while the Mac's is 192.168.2.1.

How can I copy a file from the Yun?

Once I tried to copy a file from the Macbook to the Yun using "scp" and it worked, but now I don't know how to do for the other direction

# Answer
You simply reverse the arguments. Whatever you used to copy a file *to* the Yun you just do the opposite to copy *from* the Yun.

For instance, if you copied to the Yun using:

```
scp /my/local/file root@192.168.2.16:/where/you/want/it

```

Then you would change it around to copy from the Yun thus:

```
scp root@192.168.2.16:/path/to/file /where/you/want/it/to/go

```
> 2 votes

---
Tags: arduino-yun
---


title: ESP8266 NodeMCU v3 basic questions

text:
# Question
Title: ESP8266 NodeMCU v3 basic questions
Can somebody please tell me what is the operating voltage of ESP8266?

What is the A0 voltage range?

I am powering it up from USB (5v) and have a sensor that comes back with Analog value, to calculate it correctly I am asked to provide "Logical Voltage" value that is either 3300 or 5000 (3.3v or 5v). Sensor is connected to 3.3V port as there is no 5v port on the board.

What do I choose here 3300 or 5000 for NodeMCU V3?

Thank you.

# Answer
> 2 votes
The subtle clue is in the voltage that is available. That is, the only voltage provided on the board is 3.3v. That's a slight hint that the board might run at 3.3v. And you would be right in that assumption.

The ESP8266 chips, as are most modern MCUs more powerful than 8-bit, 3.3v devices.

So you would choose 3300 as your "Logical Voltage" value. Or better still, measure the 3.3V and find exactly what it is and use that value x 1000 (for example 3317 or 3295).

---
Tags: esp8266
---


# Question
Title: Can I power a 9g servo from an arduino nano with USB power only?
I want to run a 9g servo off of the pins from an arduino nano board, using only the 5v USB connection.

The servo specifically is a SG90, which I have measured a stall current of ~250mA - I don't intend to stall it, just have it run with almost no load

I am not sure which pins to power it off of from the arduino itself - do I use the VCC or the +5v? does it matter which ground I use? should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something? does the arduino nano negotiate to get more than the default of 100mA from a USB power connection?

# Answer
The max current of the Arduino-Nano 5V Pin is 200mA. So if you draw more than that it might damage your Arduino.

Here is an interesting summary regarding the Maximum Ratings of the Arduino Nano: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

> The 5V pin of the arduino is not connected through the microcontroller. As such, it can source significantly more power. When you are powering your arduino from USB, the USB interface limits your total power consumption to 500 mA.

So yes, it actually seems you can draw 250mA out of the 5V PIN.

> do I use the VCC or the +5v?

You use +5V, because VCC is for powering your Arduino with an external Power Source. It allows you to use up to 7-12V (recommended), or up to 6-20V (limits).

> does it matter which ground I use?

Doesn't matter

> should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something?

A breadboard makes it easier for you, to test your circuit. But you can do it without if you like. Then you possibly have to solder some connections

See also the offical Arduino Page for the Nano.
> 2 votes

---
Tags: power, usb, arduino-nano, servo
---