# Question
Title: Arduino Keyboard - print() works but println() does not
I am recently seeing strange behavior in my Arduino Yun.

Just using the microcontroller, I enter the following:

```
#include <stdlib.h>
#include <string.h> // For string operations.
#include "Keyboard.h"
#include "Mouse.h"

void setup() {
  Keyboard.begin();
  Keyboard.println("Hello world.");
  Keyboard.print("Hello world.");
}

```

Rather than getting two lines as expected, I get `Hello world.Hello world.`.

It is a very strange error because println (docs) is so 'core' to Keyboard function. I've never had this issue before and I've been playing with it for months. I am running IDE 1.6.11.

### A possibly relevant detail

I had this working on my Yun months ago **without** the `#include "Keyboard.h"` and `#include "Mouse.h"`. I opened the IDE again just recently and, upon compiling, it failed saying I needed to add those lines. So I did, and it now `println` doesn't work.

# Answer
> 1 votes
> Please test: Keyboard.print("Hello world.\n");

...

> That works. println still doesn't.

I'm going to guess here that println is doing something odd in the Yun libraries. I note that the Keyboard.cpp file in my release has this in it:

```
#define SHIFT 0x80
const uint8_t _asciimap[128] =
{
    0x00,             // NUL
    0x00,             // SOH
    0x00,             // STX
    0x00,             // ETX
    0x00,             // EOT
    0x00,             // ENQ
    0x00,             // ACK
    0x00,             // BEL
    0x2a,           // BS   Backspace
    0x2b,           // TAB  Tab
    0x28,           // LF   Enter
    0x00,             // VT
    0x00,             // FF
    0x00,             // CR    <---------- note!

```

Notice that linefeed has a code mapped (0x28) but carriage return (CR) does not (unless you call 0x00 a mapping).

I *think* you'll find that when you hit Enter on a keyboard it is sending a CR (after all, it used to be labelled the "return" key) and not a LF.

However I thought that the Print class outputted both:

```
size_t Print::println(void)
{
  return write("\r\n");
}

```

Maybe yours doesn't. I'm not certain which exact `println` will be pulled in for a Yun. The fact that it used to work, and now doesn't, suggests a change there somewhere.

---
Tags: arduino-yun, keyboard
---


# Question
Title: GCC msg "note: in definition of macro 'max'" error message
I'm using the ATtiny x5 series board, compiling my project (.cpp.ino file). Whenever I use the **max(*a*,*b*)** macro, I receive this message:

```
"C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.3-arduino2/bin/avr-g++" -c -g -Os  -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=attiny85 -DF_CPU=8000000L -DARDUINO=10609 -DARDUINO_AVR_ATTINYX5 -DARDUINO_ARCH_AVR   "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny" "-IC:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\variants\tinyX5" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\Pins_xxxxx" "-IC:\Documents and Settings\<user>\My Documents\Arduino\libraries\TinyWireS" "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp" -o "C:\WINDOWS\TEMP\build18f8c74edd63168be814edc24cb0a11a.tmp\sketch\AT85PWM.ino.cpp.o"
C:\Documents and Settings\<user>\Local Settings\Application Data\Arduino15\packages\ATTinyCore\hardware\avr\1.1.1\cores\tiny/Arduino.h:54:24: note: in definition of macro 'max'
 #define max(a,b) ((a)>(b)?(a):(b))
                        ^

```

What does *note: in definition of macro 'max'* mean, do I need to do anything about it, and if so what?

Searching google for the message gives lots of compiler output listings with the message, but the posting is always for *another **different** message* that is causing trouble. None of the fixes from those posts address the max note: message.

# Answer
I can reproduce your message easily enough:

```
#define max(a,b) ((a)>(b)?(a):(b))

void setup() {
 int b = 66;
 unsigned int c = 42;
 analogWrite (3, max (b, c));
}

void loop() { }

```

I get these warnings:

```
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino: In function 'void setup()':
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:1:25: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 #define max(a,b) ((a)>(b)?(a):(b))
                         ^
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:6:18: note: in expansion of macro 'max'
  analogWrite (3, max (b, c));

```

The point is that the warning `note: in expansion of macro 'max'` is just telling you where the macro is *defined*, so you can make sense of the *real* warning. The *real* warning is: `warning: comparison between signed and unsigned integer expressions`

So, reading them together, you are comparing (in the macro) a signed and unsigned number, and the compiler is warning you about that.

> The message seems like a red herring, given that there is no problem with the max(a,b) macro definition. I suspect it is being flagged only because it was tangentially involved with a statement in error.

That's right. There is no problem in that macro per se. Macros can generate weird error message because they are just text replacements. For example:

```
max (the quick brown fox, jumps over the lazy dog);

```

That will generate a slew of errors, including a "note" to where `max` is defined. There is nothing wrong with `max` until you try feeding garbage into it.

---

# Templates

That's one of the reasons I prefer to avoid macros if possible. You can do "max" with a template. For example:

```
#undef max   // throw away the original macro in the Arduino header file

template<typename T> T max (T a, T b)
  {
  if (a > b)
    return a;

  return b;
  }

```

Now you get slightly more reasonable error messages:

```
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino: In function 'void setup()':
sketch_aug31a:14: error: no matching function for call to 'max(int&, unsigned int&)'
   analogWrite (3, max (b, c));
                            ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note: candidate is:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note: template<class T> T max(T, T)
 template<typename T> T max (T a, T b)
                        ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note:   template argument deduction/substitution failed:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note:   deduced conflicting types for parameter 'T' ('int' and 'unsigned int')
   analogWrite (3, max (b, c));
                            ^
exit status 1
no matching function for call to 'max(int&, unsigned int&)'

```

Of course, now you've gone from a warning to an error, because the template wants a single type.

Notice the notes? That's just the compiler trying to be helpful.

---

You could make the template take two types if you are prepared to guess the return type (will it be the first type, or the second type?):

```
#undef max

template<typename T1, typename T2> T1 max (T1 a, T2 b)
  {
  if (a > b)
    return a;

  return b;
  }

```

Now you don't get an error or a warning, however the result will be the first type (T1) which may or may not suit you.
> 2 votes

# Answer
Note to the future:

(My particular case was a function call with several parameters. One had the **max(a,b)**, and another parameter had an error. It used a different macro, which may have pushed the compiler to flag *every* macro in the whole call).

The message seems like a red herring, given that there is no problem with the **max(a,b)** macro definition. I suspect it is being flagged only because it was tangentially involved with a statement in error.

Since it wasn't part of the problem, the compiler couldn't say anything specific about it or the code it generated. Therefore the flagging message then ends up saying "in definition of macro" (kind of a default of last resort) since it couldn't say anything more specific.

If you ever get one of these, particularly from a system provided macro, ignore it until you've diagnosed your other problems.

Ignore the fact that the error message is first in the listing, and the statement using the macro doesn't get flagged until after several other statements are flagged.

Again, I suspect that compiler feels obligated to say something about the macro because it was used. But since it's not part of the problem in the statement where it appears, it doesn't get flagged there. Instead the compiler puts the message at the top because it has to go somewhere, but the compiler can't/doesn't want to associate it with the statement where it was used.

The solution worked for me, but a language lawyer or compiler developer may say my explanation has no basis.
> 1 votes

---
Tags: c++, compiler, gcc
---


title: Controlling 5 DC motors with Arduino

text:
# Question
Title: Controlling 5 DC motors with Arduino
I am looking to purchase the correct hardware to be able to control 5 DC Motors from an Arduino (UNO preferred, MEGA if necessary).

The Specs of the Motors are as follows: 12 V nominal, 3 → 12 V dc, 794 gcm, 100 rpm, 0.394 W

What would be your recommendations for how to set this up? As I am fairly new to circuitry a circuit diagram would be helpful along with the recommendation of what shield or drivers to use. Thank You

# Answer
There are currently no expansion boards (shields) for the Arduino platform that are designed to do what you're asking of it. At most you'll find shields that can support up to 2 maybe 3 motors. My recommendation for a beginner would be to experiment with a breakout board like this one: https://www.sparkfun.com/products/9457 It's compact and can easily control 2 of the motors you need, three together and you could control up to 6.
> 1 votes

# Answer
I would suggest to use the shield that is directly attachable to the Uno, for example: http://playground.arduino.cc/Main/AdafruitMotorShield. So everything you need is Uno, this shield and motors. No soldering.
> 1 votes

---
Tags: arduino-uno, arduino-mega, motor, shields
---


title: Arduino IDE programming help

text:
# Question
Title: Arduino IDE programming help
I am trying to write a program to control a stepper, and incorporate a selector switch and a rheostat.

The object is to make the stepper oscillate, and to be able to control the speed with the rheostat, and the amount of oscillation with the selector switch.

What would the best way to go about this?

# Answer
> 3 votes
Majenko provided the correct answer in his comment: you just have to write a program to do it! This site is not meant to provide you with a ready made solution, but to give help if you run into an issue while trying to *solve the problem yourself*.

That being said, before you attempt to write the program, you should learn how to interface with the hardware you are using. Here are the relevant Arduino tutorials:

And then there is plenty of material available on the Web for each of these topics.

Go through the tutorials, understand the programs given as examples, make them work with your hardware, then put the pieces together to solve your problem. If you run into an issue you cannot solve buy yourself, then come back here with a *specific* question and show us what you have attempted so far, including code and schematic. See also How do I ask a good question?.

# Answer
> 1 votes
Here are the code fragments that would help you.

Connect the three wires from the potentiometer to your board. The first goes from one of the outer pins of the potentiometerto ground. The second goes from the other outer pin of the potentiometer to 5 volts. The third goes from the middle pin of the potentiometer to the analog pin `A0`.

**Here is the connection schematic:**

Here is the code to read the analog value from port A0:

```
int sensorValue = analogRead(A0);

```

this would assign a value ranging fro 0-1023 to `sensorValue` according to the position of the Pot.

```
int stepsPerRevolution = 200;
//this variable holds the no of steps the motor rotates to complete a full circle rotation.

int stepCount = 0;  // number of steps the motor has taken

stepsPerRevolution = map(sensorReading, 0, 1023, 0, 200);

// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);

```

**Here is an example program for controlling the direction of stepper using microswitches:**

```
#define stepPin 2
#define dirPin 3
#define pinLimitswitchLeft 4  // these can be either left or right depending on motor wiring and dir pin.
#define pinLimitswitchRight 5 // these switches must be N.O. types
int stepDelay = 100; // this is the step delay in microseconds. Reduce this to speed up motor rotation and vice versa.

void setup()
{
    pinMode (stepPin, OUTPUT);
    pinMode (dirPin, OUTPUT);
    pinMode (pinLimitswitchLeft, INPUT_PULLUP);
    pinMode (pinLimitswitchRight, INPUT_PULLUP);
}

void loop()
{
    digitalWrite(dirPin, HIGH);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
    while (digitalRead(pinLimitswitchLeft) == HIGH) // move motor until left limit switch is pressed.
    {
        stepMotor();
    }

    digitalWrite(dirPin, LOW);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
    while (digitalRead(pinLimitswitchRight) == HIGH) // move motor until right limit switch is pressed.
    {
        stepMotor();
    }

}

void stepMotor()
{
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(stepDelay);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(stepDelay);
}

```

Change the control from the control switch to the number of steps taken by your motor when the switch is pressed and it will work as you require.

**I have not included the header files.**

Please edit the program as you require

---
Tags: arduino-ide
---


# Question
Title: Find RSSI of Mobile Device Without Connecting
I have a device in which a user connects their mobile device to an arduino uno via a HM-10 bluetooth transponder. I want to be able to calculate the approximate distance between the user and the transponder by hopefully using the RSSI methodology:

```
 d = 10 ^ ((TxPower - RSSI) / 20)

```

**My goal** is for the user to send a connection request to the HM-10, the uno to then calculate the distance, and if greater than x meters away, reject the request. I realize RSSI based distance is an estimate at best but that is fine for my purposes.

With that in mind, I have two questions:

```
1.) Is an HM-10 able to capture the RSSI strength of a mobile device to
    calculate distance?
2.) Can it do so WITHOUT connecting first based on the
    initial request of the mobile device?

```

# Answer
You have two questions, but what makes you think you can't find these out?

When you want to know what a device can do (and thus can't do) you should check the devices' datasheet. I believe it is this file.

Bluetooth (and gsm) devices often work by sending AT commands. For example: "AT+PIO" to set/query GPIO pins of the module. You can send "AT+RSSI?" to get a response on the RSSI value.

---

Not everything can be mentioned in the datasheet though. If you can't find any sources on it, it's most likely not a feature.

The only way to add a "validation function" within the bluetooth connection code, would be to re-write the firmware of the device.

But, you could:

1. Connect (with everyone using the right pin)
2. Check their RSSI
3. Disconnect if it doesn't match your criteria

I'm not sure if this module can have multiple connections, I didn't really see a way to disconnect a single connection. If not, you could even toggle the power to the module to "disconnect" the client(s).
> 1 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Design considerations for creating an Arduino 'shield' shield to limit EMI
I am building a shield that contains an AC power supply and relay for an Arduino-like board. The problem I am having is that the relay is quite noisy with respect to EMI, and I can see a few jitters or jumps in my system during normal operation even with a zero cross detector.

I have added in another shield between the 'relay' shield and the main board, which has helped the problem by creating a larger gap, but I would like a more permanent and robust solution.

I was thinking of building a simple shield that has nothing much on it and is simply a large ground plane that sits in between the relay shield and the main board. This would be a simple solution that does not involve making any shielding cages.

This ground plane would be connect to the chassis of my device, which is then earthed.

Since the device has both a DC ground voltage (0V DC) and a AC earth (0V AC) I was thinking maybe I should use both as part of my shielding. Since the board has layers on both sides perhaps I could design it to have the side facing the relays to be earthed, while on the other side, facing the CPU, would be DC ground. I could even couple the two planes with a capacitor, if it helps.

On the one hand I think the earthed option should be fine, but on the other hand I would like to know more about using the DC ground as an EMI shield. Would the simple earth only option work? Would even a DC ground only option work? Does it help to use the DC ground as an EMI shield for the DC components or am I over complicating it?

# Answer
> 1 votes
What would be helpful would be explanation of the type of AC you are using and then possibly a schematic or board layout.

That aside, there does seem to be noise between the two boards. The Idea of placing a PCB with just a large copper pour would work.

### DC Ground

If you connect the DC ground from the main board you should use a `ferrite bead`(FB) between the two grounds, this will ensure that you don't get noise getting back into the ground of the main board after you have tried to shield it. You should try to match the ferrite bead to the noise frequency you experiencing (use a scope if you have one).

Using the DC ground as a shield is often done, if you look at the EMI cages on cellular phones, WiFi modules, and other noise generating devices/susceptible-to-noise devices, they are connected to ground. It gives the noise somewhere to go, instead of your signal lines. Thus using the DC ground is defiantly an option

i.e.:

```
Main ground>--------[__FB__]-------<SHIELD

```

### AC Ground

You could use the AC earth line on the top part of the shielding board. The coupling part might be a bit over kill, leave space for it to test to see if it helps when you make the board. Also AC earth can be used for shielding but is used for the safety aspect of earth leakage.

Don't do a direct *DC ground* to *AC ground* unless you know what you are doing as this will create a ground loop, this will change the way stuff behaves and will make your circuit no longer a floating device.

### Other stuff

I would also make sure how you drive the relay is isolated from the control circuitry, although from what you describe:

> if I move the shield further away I also don't see the issues.

If you share power rails between the relay board and the main board, try filtering the power going to the CPU section. Also the control lines can be isolated between the controller and the relay with opto-couplers, this might stop noise coming back into the circuit from the relay part.

---
Tags: power, shields, electronics
---


title: Soldering issue with arduino

text:
# Question
Title: Soldering issue with arduino
I am trying to solder arduino nano onto a perfboard/solderable breadboard using rosin core solder. The connection is only working some of the time, when I check with a multimeter (+) at pin 29 (in image below) I and (-) at pin 17 there is power at the top of the pin sticking out of the via/hole but there is 0 volts if I check at the actual joint (lower portion of the pin). I see a little flux residue around pin 29 that could indicate a little burning around the area could that be causing this, it is only very minor .. anyway I can fix it?

Also is it normal to have a little yellow residue left over on the joints? I am new to soldering so not sure if a little flux reside is a bad thing on the joint...

# Answer
Fair play, that is a lot of flux residue. I am assuming you are using some quite chunky solder with lots of flux in it.

Flux is non-conductive, so the residue will be forming an insulating layer on the outside of the solder. That doesn't mean the joint is bad, only that you can't get to the joint because the flux residue is in the way.

If there is a conductive path between the tip of the pin and the pad next to it then all is fine. The fact that you can't see the signal through the outside layer of flux is neither here nor there.

If you want to clean it off you can use isopropyl alcohol (AKA PCB cleaner, AKA "rubbing alcohol") and use, for instance, a tooth brush to scrub it off.
> 2 votes

# Answer
“The connection is only working some of the time” does seem to indicate bad solder connections. (Another possibility is wires in wrong holes.)

To locate problems, clip (rather than hold) one lead of an ohmmeter (or a DVM set to Ohms), to a wire soldered to the beginning of the problematic chain of connections. Then advance step by step along the chain, looking for an open junction.

To fix problems, obtain a solder sucker and/or solder wick, a hot fine-point soldering iron (preferably temperature controlled), and thin (eg 1-2mm) 60-40 tin-lead rosin-core solder. Use the solder wick or solder sucker to remove the old solder from the joint. Apply new solder to make a nice shiny proper solder joint.
> 0 votes

---
Tags: arduino-nano
---


title: Port D isn't Working as Input

text:
# Question
Title: Port D isn't Working as Input
I'm using an Atmega328p SMD with 32 pins. I'm trying to get several pins on Port D to function as inputs. As outputs, they work fine, but for some reason, not as inputs. Here's a simple example of what I'm dealing with.

```
void setup() {

DDRB |= (1<<PB3);  //Set up an output on PB3 for an LED
DDRD = B00000000;  //All of Port D set as inputs
DDRC = B00000000;  //All of Port C set as inputs
}

void loop() {

int Power = (PIND & (1 << PORTD5));  //Read input

  if(Power == 1){
PORTB |= (1 << PORTB3);      //set high
  }
  else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

```

I get no response from my LED like this, no matter which pin on Port D I use as an input. But when I simply change over to Port C, it works fine.

```
int Power = (PINC & (1 << PORTC5));  //Read input

```

Ideas?

# Answer
You check if `power` is `1`, but it will never be `1`. Instead it will be `1<<5` or `32`. Better use:

```
if(Power != 0){
  PORTB |= (1 << PORTB3);      //set high
}
else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

```
> 1 votes

---
Tags: arduino-uno, port-mapping
---


title: Which bluetooth module should I buy?

text:
# Question
Title: Which bluetooth module should I buy?
I am doing a wireless rover using arduino mega 2560 that can be controlled by a smartphone and a PC. Which bluetooth module would fit me? Again I want to control it both by my Laptop(Built-in Bluetooth) and my smartphone. Thanks in advance.

# Answer
A little late but in case someone like me ran into this:

**HC-05** seems to be the DIY choice. Can work in slave or master mode and works with Android but not iOS.

**HC-06** is the same as HC-05 except that you can only use it in slave mode.

**HM-10** seems to be the option for iOS users.
> 2 votes

---
Tags: arduino-mega, bluetooth
---


title: How to increase current in Arduino uno?

text:
# Question
Title: How to increase current in Arduino uno?
How to increase current in O/P port in Arduino uno ? to make it 200mA How I can do this? It can in proggraming add more current Which sample way to increase current ? To control 2 Dc motor which normally work with 3 AA battery Thanks

# Answer
You add a transistor. Just like when you're controlling a relay, which *needs more current that the Arduino can provide*.
> 3 votes

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


# Question
Title: Arduino running at 8MHz with external crystal
I want to use my Atmega328P in 8MHz, but I noticed that the internal clock is not as accurate and cause problems in my application. To add an external crystal 8MHz I do like the image below or 22pF capacitors are only necessary when I use a 16MHz crystal?

# Answer
> 0 votes
Yes, you require the capacitors, and the capacitors have to be the right value for your crystal.

The datasheet will specify a *load capacitance* which you use in the following formula:

```
C1 = C2 = 2(CL - C_STRAY)

```

That is, the *load capacitance* of the crystal, minus the stray capacitance from your circuit (as long as your traces are short that is negligible and can be largely ignored unless you have very very tight timing requirements) multiplied by 2.

So for 22pF capacitors it is safe to assume that the crystal that is with them has a load capacitance of 11pF.

So check the datasheet for the load capacitance (it should be very prominent) and select the correct capacitors accordingly.

If you want to do away with the capacitors and your timing requirements aren't that precise you may get away with a ceramic resonator which doesn't require capacitors.

Another option is to use a MEMS® clock chip which generates a stable clock signal at a pre-set frequency. While this doesn't require capacitors for the clock signal it does still require a decoupling capacitor on the power supply for it, but of course that doesn't affect the timing of the clock signal, so precise selection of a specific value isn't needed.

---
Tags: arduino-uno
---


# Question
Title: FreeRTOS: Object not created properly from within task
I am encountering a very strange error using `freeRTOS` on an Arduino Mega2560:

In the setup block I can create an instance of my class:

```
MyClass* myClass = new MyClass(/*char*/ a, /*char*/ b, new Vector(42));
// new Vector(42) creates a new vector and pushes 42 in as first item

```

Using a `print()` method in this class, I get a legitimate output on the console, showing me all the chars and values in the vector.

Using the exact same line inside a task, causes the object not to be created properly. It seems like the fields are empty or there is something entirely wrong (like strange memory errors) with the instance. Printing it again results in an empty line (program doesn't crash) while printing a globally created instance gives the correct result.

Is there any trap in `freeRTOS` concerning the creation of new instances of an object inside a task? Below is the code for the task creation, increasing the task stack size doesn't help. For debug reasons this the only task running at the moment.

```
xTaskCreate(displayTask,
    "DisplayTask",
    configMINIMAL_STACK_SIZE + 300,
    NULL,
    tskIDLE_PRIORITY + 1,
    NULL);

```

# Answer
'Strange memory errors' you seem to be describing values that have gone out of scope.

This is all based on your code, so I may have misunderstood.

The third parameter is causing a memory leak, unless you happen to be deleting it within MyClass (which is normally, not always, bad practice).

It sounds to me that you are trying to access values that have gone out of scope.

Its also possible that this OS requires you to do something to allow the memory to be shared between the tasks.
> 1 votes

---
Tags: arduino-mega, c++
---


# Question
Title: How can I read Data from 150 Arduino Serially to a Single Arduino to display it via serial port.
I know that Arduino nano/Uno has one Serial port to read serial data. But if I use software serial can i read more than one serial data.

I have 150 Arduino's working on a project(Can be reduced to 50 if required) these arduino will generate serial data (150 serial data as of now). I wanna connect all these 150 serial data to a computer through a single COM port. How can i make it possible.

# Answer
If each source generates messages at a low enough rate, you can put them all in series.

Each Uno has a serial input, and a serial output, and they are all chained. Each Uno labels its message with who it's from, and passes on received messages unchanged.

Obviously this means that if you used (say) 9600 baud, or approaching 1000 bytes per second, each device would only be able to source 6 bytes per second of message.

If that's not fast enough for your application, then you would need a higher baud rate at the COM port.
> 1 votes

# Answer
You can attempt to connect your devices in a loop, if you are insisting on using a single serial port for each. How well all that works will depend on a lot of things.

simulate this circuit – Schematic created using CircuitLab

I have no idea what your computer is, but this is a common mention to string multiple units together where they only have a single serial port each. The software in each unit will need to pass along messages that belong to other units and you will have to device a method for achieving that process. But it can work. Message delays will exist, of course. And with from 50 to 150 units, you may find some serious frustration. But if the needs are modest, you may be able to get by with this mechanism.
> 1 votes

---
Tags: serial, communication, wireless
---


# Question
Title: Is it safe to use the same power source for Arduino and its Motor shield?
Is it safe to use a unique 12V 5A DC power source to feed both Arduino and its connected Motor shield, provided that

* the motor (connected to the shield) will eat 3A maximum
* the Arduino `Vin` will get the power

Arduino and the shield exchange information, and use both the same power supply, is there some risk of "interference" of some kind?

*edit*

This is the motor controller shield I intend to use. In the manual, the connections show that

* the Arduino and the shield have different power supplies
* the Arduino power pins are not used by the shield

# Answer
In my case, when I was running my DC motors at full load, I noticed a large voltage drop in the circuit. This could affect the signals or transmission of data on the Arduino.

It is definitely recommended to power the arduino and motor shield with separate power source. Make sure the the share a common GND.
> 3 votes

# Answer
I'm assuming your shield has its own power input and you feed the circuit from there. If you are sure that your motor shield can hold that much current there shouldn't be any problem. You should see your motor shield's specs for that.

And actually if your shield has the standard arduino layout, it probably has an header goes into `Vin` pin. So even if you try to supply arduino from USB or power jack along with your power supply, the auto selector circuit of arduino board will use the power from 12 volt power source.
> 2 votes

---
Tags: power, arduino-motor-shield
---


title: What's Leonardo 5V pin current limit?

text:
# Question
Title: What's Leonardo 5V pin current limit?
I'd like to know how much current can supply the 5V pin and the 3.3V pin on an Arduino Leonardo board. I've been lead not to trust the specs on Arduino's website. And, as an added question, can the 5V pin supply enough power for an LM741 opamp?

Thanks!

# Answer
The 5V pin is either supplied by the USB port, which has a limit of 500mA (imposed by a resettable fuse) if directly connected to the computer or a powered hub (or 100mA in an unpowered hub), or the on-board regulator (NCP1117ST50T3G), which is 1A, when powered externally.

The 3.3V pin is regulated using an LP2985-33DBVR which has a current limit of 150mA (the specifications on the website say 50mA. This is wrong. I think it is a left-over from the old Uno boards with FTDI chips where the 3.3V was fed directly by the internal 3.3V regulator of the FTDI chip and thus limited to 50mA).

Yes, the 5V pin has more than enough current to run an LM741 op-amp.
> 3 votes

---
Tags: arduino-leonardo, current
---


# Question
Title: Controlling a capacitive touch screen that doesn't have I2C/SPI
I have been searching for cheap slim 3" 16:9 capacitive touch screens for a while now. But I couldn't find any that had an I2C or SPI interface. The cheap displays always have these ribbon cables with a ton or pins and it's really hard to find a way to control them from an Arduino (or ESP-32 or ESP-8266).

I recently found this one, but how do you access such a touch screen that doesn't have an I2C or SPI interface? Do I need some sort of driver board? What exactly would I be look for?

# Answer
> Do I need some sort of driver board?

There are quite a few solutions around to interface with parallel devices like that. Some can be purchased off-the-shelf. I described a home-made solution on my page Connecting a graphical LCD via a I2C/SPI using a 16-bit port expander.

This isn't a touch screen, but from what I can make out of your (rather hard to read) image, it looks similar in concept.

I used a MCP23017 16-bit port expander (that is an I2C part, but you can get the MCP23S17 chips which has an SPI interface).

As you can see from the photo, there are only four wires from the Arduino to the LCD board: +5V, Gnd, SDA, SCL.

When I wrote that article it looks like the MCP23017 was $AUD 2.30. A quick Google search indicates it is still selling for around $US 2.50. On eBay they seem to be selling for around one dollar (eg. $5 for 5 chips).

Depending on the complexity of the driver (on the touch-screen board) writing suitable code may be moderately easy to slightly harder. It depends on how much you are used to coding for these port expanders, and how fiddly the interface requirements are.

Since Adafruit offer a driver shield, it can presumably be done.
> 1 votes

# Answer
There are two major parts to a capacitive touchscreen:

1. The touch panel
2. The controller chip

You have to have both in order to use the panel.

Basically the panel is like a matrix of capacitive sensors, and the controller chip has to rapidly cycle through each row of them (or column if you hold it the other way) sensing all the inputs on that row. It's quite a complex task, and so a special chip is really required for the job.

It's that chip, not the touch screen panel, that presents the SPI or I2C interface.
> 0 votes

---
Tags: i2c, spi, display
---


title: Help with a Memory Issue

text:
# Question
Title: Help with a Memory Issue
Below is some code that I'm writing to concurrently run "animations" on the same strip of NeoPixels. When I try to make use of the Serial monitor to control the program functions, I just get a bunch of garbled garbage and often, a reboot. I have similar code to this that is actually smaller that runs from a Bluetooth module attached to the same Arduino and has worked for years. Is there some obvious memory issue I'm missing, could my Arduino's SRAM finally be starting to eat it?

```
#include "TripCycling.h"
#include "CycleLight.h"
#include "Alternate.h"
#include "Collision.h"
#include "FluidColor.h"
#include "ColorRandomizer.h"
#include "StreamAnimation.h"
#include "StreamControl.h"
#include <MemoryFree.h>

#define MAX_STRIPS 1
#define MAX_ANIMATIONS 6

#define control Serial

static Adafruit_NeoPixel** strips = new Adafruit_NeoPixel*[MAX_STRIPS];

static uint32_t colors[] = {LEDUtils::red, LEDUtils::orange, LEDUtils::yellow, LEDUtils::green, LEDUtils::blue, LEDUtils::purple};

static Animation** animations = new Animation*[MAX_ANIMATIONS];

static int8_t stripIDs[MAX_STRIPS];

static String temp = "";
static char val;
static String strings[12];

void setup() {

  Serial.begin(9600);
  Serial.println("Free Memory: " + String(freeMemory()));

  strips[0] = new Adafruit_NeoPixel(42, 9);
  stripIDs[0] = 1;

  strips[0]->begin();
  strips[0]->clear();
  strips[0]->show();

  control.println("Setup finished!");
}

void loop() {
  Serial.println("Free Memory: " + String(freeMemory()));

  if(control.available())
  {
    if(control.find('~'))
    {
      temp = control.readStringUntil('~');

      val = LEDUtils::split(strings, temp, ':');

      if(strings[0].equals("CLR"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          LEDUtils::clearSection(*strips[arrayPos], strings[2].toInt(), strings[3].toInt());

          if(strings[4].equals("True"))
          {
            strips[arrayPos]->show();
          }
        }
      }
      else if(strings[0].equals("ALL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          LEDUtils::setAll(*strips[arrayPos], strings[2].toInt(), strings[3].toInt(), strings[4].toInt());
        }
      }
      else if(strings[0].equals("MAT"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint16_t refNum = strings[5].toInt();

            uint32_t colors[val - 6];

            for(uint8_t i = 6; i < val; i++)
            {
              colors[i - 6] = strings[i].toInt();
            }

            animations[findValue] = new Alternate(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 6, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("CRZ"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            boolean fade = strings[5].toInt() ? true : false;
            uint16_t refNum = strings[6].toInt();

            uint32_t colors[val - 7];

            for(uint8_t i = 7; i < val; i++)
            {
              colors[i - 7] = strings[i].toInt();
            }

            animations[findValue] = new ColorRandomizer(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 7, fade, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("TCL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t tripSize = strings[7].toInt();
            uint16_t refNum = strings[8].toInt();

            animations[findValue] = new TripCycling(*strips[arrayPos], refNum, startPixel, stopPixel, tripSize, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("CLI"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t refNum = strings[7].toInt();

            animations[findValue] = new CycleLight(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
      else if(strings[0].equals("COL"))
      {
        int8_t arrayPos = getArrayPosByID(strings[1].toInt());

        if(arrayPos == -1)
        {
          control.print("ERR:Strip ID not found~");
        }
        else
        {
          int8_t findValue = getNextAniPos();

          if(findValue == -1)
          {
            control.print("ERR:Max animations reached~");
          }
          else
          {
            uint16_t startPixel = strings[2].toInt();
            uint16_t stopPixel = strings[3].toInt();
            long updateTime = strings[4].toInt();
            uint32_t color1 = strings[5].toInt();
            uint32_t color2 = strings[6].toInt();
            uint16_t refNum = strings[7].toInt();

            animations[findValue] = new Collision(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
            animations[findValue]->start();
          }
        }
      }
    }
  }

  for(uint16_t i = 0; i < MAX_ANIMATIONS; i++)
  {
    if(animations[i]->getRefNum() != 65535 && animations[i]->isStarted())
    {
      animations[i]->update();
    }
  }

  delay(1);
}

int8_t getArrayPosByID(int8_t id)
{
  for(int8_t i = 0; i < MAX_STRIPS; i++)
  {
    if(stripIDs[i] == id)
    {
      return i;
    }
  }

  return -1;
}

int8_t getNextAniPos()
{
  for(int8_t i = 0; i < MAX_ANIMATIONS; i++)
  {
    if(animations[i]->getRefNum() == 65535)
    {
      return i;
    }
  }

  return -1;
}

```

Note that the includes above are all based on classes I designed to represent the animations, each one has some information in them like the strip to use (passed by reference), the starting pixel, stopping pixel, colors, how long there timers should wait before executing the next animation step, etc. And they are all subclasses of the parent class Animation. I cannot seem to find what is causing the garbling to happen, if I remove references to Serial and just hard-code animations in, everything works fine, and I have around 1KB of SRAM (out of 2K) for other stuff running 6 different animations on one strip of 42 LEDs. At this point I don't make it through the Free Memory println before stuff starts coming up weird and normally the Arduino will just hang and do nothing or keep transmitting the last garbled character over and over as fast as it can. Am I missing something?

# Answer
There was a very major issue with the amount of Strings I was storing in RAM. Moving Strings out of RAM and into PROGMEM using the F() macro has helped significantly. Going at things step by step helped me see where the issue was.
> 0 votes

# Answer
In short:

* Lots of `new`, no `delete`.
* Constant strings like `Serial.print("something")` can be stored in flash memory by Flash Helper `Serial.print(F("something"))`.
* Maybe too wide color spectre. You can save 1Byte per pixel if you use struct with 8b R/G/B. (or you can use even 16b depth colors - but it is little bit harder).
* And maybe, if you were storing some instructions only and prepare pixels into ledstrip directly, you can save a lot. However it takes some time to prepare it, so you have to count with it. Something like fill(color, from, to), gradient(...), move left/right...
* Using Arduino framework is memory and cpu extensive too.

Anyway crashing as you described sounds like stack overflow or memory corruption.
> 4 votes

---
Tags: arduino-uno, serial, led, string, memory-usage
---


# Question
Title: Why have resistor at end of circuit cycle if GND dissipates final energy?
The first challenge on the Arduino Uno manual is to make a closed circuit with a button and LED. The voltage is provided by the 5V pin (non IO), connected by wire to (+) on the bus (breadboard). The wire connects to a resistor, which **makes sense since it resists current running from source**. The button connects to the resistor, if pushed, the button closes the circuit and current passes through LED (making it shine) and through a wire to GND.

OK. The second challenge makes no sense. The resistors are connected not to the 5V, but the GND. WHY? Doesn't current dissipate past at ground?? As if the GND is supplying power!? It's like flipping the anode/diode! Here's the challenge: .What is the logic behind connecting the resistors to GND and WHY DOES IT SUPPLY POWER? I'm not talking about the button, which step two somewhat explains but not why, but the LEDs. Thank you thank you thank you!!

EDIT: Ok, then. I am now being told current flows negative to positive. Fine, then why resistor connected to positive? Also, I was told that GND is there to dissipate the energy flowing from positive because some of that energy was lost. Then, could you explain the circuit and whether flow is perpetual or lost at the end (wherever that is) and if it isn't perpetual in a loop, why have a resistor past the LED when the LED recieved all the volts and the electrical energy it then outputs back on the cycle is reduced by the resistor. Thanks.

Also, I'm changing my question to "Why does resistor on GND ever work on LED" to "Why have resistor at end of circuit cycle if GND dissipates final energy?".

# Answer
Some images may help, other answers so far are quite good. You need to realise the concept that electrons are flowing in a circuit, with series it doesn't matter which order, so in the following schematic, the first 2 are the same and both work in exactly the same way, the 3rd functions the same but obviously uses 2 resistors instead of 1, It is there to help you understand the concept. The resistance of R3+R4 = 1K so the same amount of current flows through D3 the 3rd LED as D1 and D2.

Do you know Ohms law and about voltage drop ?

Also how to calculate resistance in series and parallel ?

There is some fairly simple maths that shows the 3 different legs are all doing the same thing, however it may over complicate things at this stage if it is above your knowledge as you state you are in middle school.
> 1 votes

# Answer
Roman, As I understand your question you have a resistor, an LED and a switch in "series". It makes no difference in which order these are connected. It may help to think like water flowing through a hose, with a tap being a switch - it can be at either end.

"Current" flows through each in turn. As others have mentioned current conventionally is considered to flow from + to - (even though in most, but not all, cases electrons flow from - to +).

In practical circuits it is usually more convenient to select one configuration over another. An Arduino digital pin can be considered as a switch which is either connected to + or -. You could connect a LED (with a current limiting resistor) to either + or -, either is valid it just changes the logic controlling the switch.
> 4 votes

# Answer
To go further with the water analogy as proposed by @Milliways, consider the water system being closed and made of hard pipe (which cannot expand or contract). All of the water (electrical charge) there is, is contained within the closed system. (We'll use a battery instead of a power supply for clarity but it won't make any difference). Think of a simple loop containing a pump & small reservoir (battery), a small turbine or water motor (the LED or most any other electrical load), and a resistor (a constriction somewhere in pipes).

It won't matter where you put the restriction; it will still reduce the flow in the entire loop and therefore, through the turbine, reducing its mechanical output. Even if the restriction is on the return side. Why? Because the same amount of water has to flow past any point in the system, as flows past any other point. If that were not true - the water flowing toward any point != the water flowing away from that point, then there must be either a leak or a water source (loss or gain of water) at that point. Since we believe there is no leak (short circuit to ground) or source of water (battery), then water flowing in must == water flowing out at any point. So wherever you put the restriction (resistor), it limits the flow (current) through the entire loop, and the turbine will do less work.

Update:

> If say, 3V are lost/used in the circuit one way, then 2V isn't enough to power, right?

The difference in voltage at various points in the circuit is like the change in pressure at various points in the hydraulic loop. Energy (which is neither pressure nor voltage) is transferred by the flow of water or electrons from the pump (battery) to the turbine (LED) and the restriction (resistor). But in a closed system, no water (electrons) is/are lost.
> 2 votes

---
Tags: led, resistor
---


# Question
Title: Using an Atmega8 Chip with an Arduino Uno instead of an atmega328
This question is posted here as a reference question (its actually a follows on from comments in my earlier question "How to expand program memory on an arduino?") -( Edgar Bonet suggested this question and who answered 1 below in the comments there).

I think its a useful question to others new to arduino. I have posted an answer too. But you can of course add your answer too. I dont know everything about arduino- still learning. It does not refer to the version of the Uno that uses a surface mount atmega328-but the version with removable atmega328.

1) If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn a bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328)? The atmega8 is of course an older chip than the 328 (and is significantly cheaper) but it still has same pinouts.

2). I am using the 16mhz crystal in my project. So using an Arduino Uno with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino Uno pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator?

3) So hw much memory is left after writing bootlader to atmega8 ?

4) Can I burn the bootloader more than once?

# Answer
1) yes the arduino uno can be used with a blanked at mega8 chip with the NG bootloader burned onto it. You would set the board as NG in the IDE to use the arduino IDE (to upload sketches and so on) with it.

2) A crystal and capacitors is still required -the same values as used for the removed atmega328.

3) The smallest bootloader will leave 7.5kb of program memory left to use on the atmega8.

4) Yes
> 2 votes

---
Tags: arduino-uno
---


title: Help with MPU-6050

text:
# Question
Title: Help with MPU-6050
I have bought MPU-6050 a month ago for a project, I have got a hang I2C protocol and register maps of MPU. I have learnt how to get raw values of accelerometer and gyroscope. What I needed for my project is roll and pitch angles and acceleration in x,y,z axes. I have tried some algorithms as shown below:

First I saw a code which uses only raw accelerometer values to get roll and pitch. Here is a small snippet of that code:

```
x=(AcX)/16384;
y=(AcY)/16384;
z=(AcZ)/16384;
roll = (atan2(y, z)+PI)*57.295779513082320876798154814105;
pitch = (atan2(x , z)+PI)*57.295779513082320876798154814105;

```

As you can see this uses principle of angle between two vectors, the angles were pretty accurate. But the problem with this code is that as the sensor moves in a particular direction without changing the roll or pitch they still seemed to change (The roll and pitch values are dependent on accel values).
Next, I saw about using Complementary Filter my code:

```
#include<Wire.h>
const int  MPU_addr=0x68, dt=20;
float AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
float xa,ya,za,xg,yg,zg;
float gan_x = 0 ,gan_y = 0,aan_x = 0,aan_y = 0, anx = 0, any = 0, gain  =0.95;
int xao = -521 ,yao = 1073 ,zao = 1724 ,xgo = 94 ,ygo =31 ,zgo = 60;                       //offset values
void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1A);
  Wire.write(0b00000110);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}
void loop()
{
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  xa = (AcX-xao)/16384;                                                    //sensitivity adjusting
  ya = (AcY-yao)/16384;
  za = (AcZ-zao)/16384;
  xg = (GyX-xgo)/131;
  yg = (GyY-ygo)/131;
  zg = (GyZ-zgo)/131;
  gan_x = dt * xg + anx;                                                       // integrating
  gan_y = dt * yg + any;
  aan_x = (atan2(ya,za)+PI)*57.295779513082320876798154814105;
  aan_y = (atan2(xa,za)+PI)*57.295779513082320876798154814105;
  anx = (gain) * gan_x + (1-gain) * aan_x;                                     // filtering
  any = (gain) * gan_y + (1-gain) * aan_y;
  //Serial.print(" | GyX = ");
  Serial.print(gan_x);
  Serial.print(" ");
  //Serial.print(" | GyY = ");
  Serial.println(gan_y);
}

```

This code gives good gyroscope values in terms of angular velocity but I want it in degrees is there any way to change those gyro values to degrees(like in first case)?

I saw Jeff Rowberg's library and I can't seem understand all of the code. Can anyone please provide any reference material explaining the functions present in i2cdevlib.h (Ex: mpu.dmpInitialize(), mpu.setDMPEnabled() etc) it would be a lot of help.

I also would like to know if there are any other alternative IMUs (Gyro+accel) other than MPU6050 which are more of an open source than 6050 (in terms of accessing DMP which seems to be main drawback for MPU) and easier to work with.
I am using Arduino Nano.

-Thank you in advance

# Answer
> 3 votes
I finally got this working after one sleepless night

```
#include<Wire.h>
const int MPU = 0x68;
int t = 0,dt = 1;
int AcX,AcY,AcZ,GyX,GyY,GyZ,tmp;
int AcXo,AcYo,AcZo,GyXo,GyYo,GyZo;
float roll = 0,pitch = 0,rollgy = 0,pitchgy = 0,rollac = 0,pitchac = 0,Ax,Ay,Az,Gx,Gy,Gz,gain = 0.95;
void MPUconfig(int Addr,int data)
{
  Wire.beginTransmission(MPU);
  Wire.write(Addr);
  Wire.write(data);
  Wire.endTransmission();
}
void MPUread()
  {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission();
    Wire.requestFrom(MPU,14);  // request a total of 14 registers
    AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    tmp=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    GyX=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    GyY=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    GyZ=Wire.read()<<8|Wire.read();
  }
void offset()
{
  MPUconfig(0x1A,0b00000000);
  int ax = 0, ay = 0,az = 0,gx = 0,gy = 0,gz = 0,i;
MPUread();
MPUread();
ax = AcX;
ay = AcY;
az = AcZ;
gx = GyX;
gy = GyY;
gz = GyZ;
for(i=0;i<1100;i++)
{
    MPUread();
    if(i>100)
    {
      ax = (ax+AcX)/2;
      ay = (ay+AcY)/2;
      az = (az+AcZ)/2;
      gx = (gx+GyX)/2;
      gy = (gy+GyY)/2;
      gz = (gz+GyZ)/2;
    }
    delay(2);
 }
AcXo = ax;
AcYo = ay;
AcZo = 16384-az;
GyXo = gx;
GyYo = gy;
GyZo = gz;
MPUconfig(0x1A,0b00000110);
}
void setup()
{
  Serial.begin(115200);
  Wire.begin();
  MPUconfig(0x1A,0b00000110);
  MPUconfig(0x1B,0b00000000);
  MPUconfig(0x1C,0b00000000);
  MPUconfig(0x6B,0b00000000);
  offset();
}

void loop()
{
  t = millis();
  MPUread();
  Ax = (float)(AcX-AcXo)/16384;
  Ay = (float)(AcY-AcYo)/16384;
  Az = (float)(AcZ-AcZo)/16384;
  Gx = (float)(GyX-GyXo)/131;
  Gy = (float)(GyY-GyYo)/131;
  Gz = (float)(GyZ-GyZo)/131;
  pitchgy = (Gy * ((float) dt/1000)) + pitch;
  rollgy = (Gx * ((float) dt/1000)) + roll;
  pitchac = atan2(Ax,Az) * (float)(180/PI);
  rollac =  atan2(Ay,Az) * (float) (180/PI);
  roll = gain * rollgy + (1-gain)* rollac;
  pitch = gain * pitchgy + (1-gain) * pitchac;
  Serial.print(roll);
  Serial.print(" "); Serial.print(pitch);
  Serial.println(" ");
  dt = millis()-t;
}

```

---
Tags: accelerometer, mpu6050, gyroscope
---


title: Arduino Time Clock Accuracy

text:
# Question
Title: Arduino Time Clock Accuracy
I'm currently trying to create an Arduino time clock by using the PJRC Time library (http://www.pjrc.com/teensy/td\_libs\_Time.html). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time.

However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!

# Answer
> 12 votes
The limitations of accuracy of the library depend on accuracy of the crystal. When they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.

For further information look at the wikipedia article on quartz crystals

The use of a 84MHz crystal versus a 16MHz crystal will not necessarily improve the accuracy of the Arduino clock since the frequency of the crystal is more an indicator of processor speed than accuracy. The accuracy of the Arduino clock is primarily dependent on the accuracy of the crystal oscillator.

EDIT: I am no expert on crystal oscillators so if you see anything wrong here please let me know

# Answer
> 5 votes
Re-visiting an old question... as I found a very informative blog post that sheds new light into it. But let me first provide some context before giving the link.

When assessing the quality of a time base, be it a crystal, a ceramic resonator or a lab-grade frequency standard, there are two notions that should be distinguished:

* **accuracy**: how close is the frequency of the time base to its *nominal* value
* **stability**: how much does that frequency drift over time

Accuracy is important if you want your clock to give correct time “out of the box”. However, if you are willing to spend some time calibrating your clock, then you do not really care because you are going to calibrate out any inaccuracy you measure. jfpoilpret's answer provides an example of a “manual” calibration protocol, which is by necessity quite lengthy. If you can borrow a GPS module with a 1PPS output, the calibration could be done in a few seconds.

Stability is a more serious issue. If the frequency of the time base drifts randomly, this will defeat your calibration efforts. Essentially, the calibration will tell you how fast or slow your clock is running *right now*, but it will not allow you to predict how fast or slow it will run *in the future*.

Here is the promised link: Arduino clock frequency accuracy, by Joris van Rantwijk.

What Joris did is measure the accuracy and stability of an Arduino Pro Mini (clocked off a ceramic resonator) and an old Duemilianove (quartz crystal). From my perspective, the main takeaways are:

* both clocks are *grossly* inaccurate, thus both would need user calibration in order to be used as timepieces
* the quartz crystal of the Duemilianove has decent stability, better than 1.5e-8 at 6 h averaging time
* the stability of the Pro Mini’s ceramic resonator is pathetic, more than *two orders of magnitude* worse than the crystal, which makes it essentially useless as a time piece

Here is his Allan deviation plot, which measures clock instability as a function of observation time:

<sub>(source: jorisvr.nl)</sub>

Although this study has some limitations (only two boards were tested, and the observation time is too short), it is well thought and very informative. I encourage you to read it in whole.

# Answer
> 3 votes
The best way to know the accuracy of the resonator of your board is to measure it yourself.

To do so, you can use the Arduino `millis()` function of your board and write a small sketch that will:

1. enable you to set the beginning time for measuring time drift (eg with a simple push button); you will trigger the button based on an **accurate** time base.
2. then repeatedly call millis() until at least 120h ("arduino hours", that would be around 5 days) have elapsed
3. display a signal when those 120h have elapsed (your sketch should probably "warn" you before the exact time has been reached so you get ready for measure)
4. when the 120h have elapsed, check your reference time based (used in step 1.) and check how much time have elapsed (should be 120h +/- epsilon)
5. once you know the drift of your clock, and provided your board will run in the same environental conditions (temperature mainly) of your measure, you can use it in your sketches to adjust the `millis()` value every hour or so.

Of course, this approach is **far from perfect** as it requires **human intervention** and thus will create additional time drifts during measurements, that's why you need to measure your clock time drifts over a long period.

An improved approach would be to connect a high accuracy RTC clock (the accuracy must be chosen based on the accuracy you need for your application) to your board and adapt the sketch so that it automatically calculates the drift. Once you got the time drift you can do the same as step 5 above in your sketches, and disconnect the RTC clock from your board.

**Important points**:

* measure the time drift on the board that will need clock adjustment later on (if you have several boards, you must measure one drift per board)
* ensure the stability of the environment in which your board will be used

Finally, if you really need high accuracy, then definitely connect an external clock source (e.g. RTC clock, GPS, NTP) to your board and use it as a SyncProvider for the PJRC library.

# Answer
> 2 votes
Your average system clock crystal will be off by several tens ppm (parts per million. They are great for stable and accurate timing of signals, but dramatic for keeping accurate time. Without special provisions the system crystal may be off by several seconds per day.

The solution is to use a proper Real Time Clock, driven by what is commonly known as a 32768Hz watch crystal. These crystals are easily a factor 10 better in accuracy. You can either set up your own oscillator that interrupts the main processor and keep count in your Arduino sketch or you find a RTC breakout board.

Two random examples that pop up in Google with search terms "RTC breakout":

---
Tags: time, arduino-due
---


# Question
Title: Trying to read analog signal with digital pin using outside ADC
Is there a way to route an analog signal from a simple temperature sensor through an ADC, MCP3008, into a digital pin. I have used all the analog pins on my Arduino Mega 2560 and am trying to utilize all the digital I/Os.

Any insights on the matter would be greatly appreciated.

# Answer
The MCP3008 is an SPI device. You connect it to the SPI pins of your Arduino. Then you can read 8 analog channels through it.

It requires 4 pins: MISO, MOSI, SCK and a chip select pin.
> 1 votes

---
Tags: arduino-mega, signal-processing, digital-analog-conversion
---


# Question
Title: Error while installing bootloader ATmega328
I'm trying to install a bootloader on my ATmega328P-PU. I'm trying to install it from Arduino Uno (not original). I can install all sketches. After I click "Burn bootloader" I get the following error:

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

avrdude: Yikes!  Invalid device signature.
avrdude: Expected signature for ATmega328P is 1E 95 0F
 ***failed;
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x3f
avrdude: verification error; content mismatch
Error while burning bootloader.

```

How to fix it?

# Answer
EDIT: First ensure that you have made the hardware correctly (see comment below this post).

If you need different settings for custom avr hardware the following will help:-

The best way to create a custom board definition is to create your own `boards.txt` entry in the Arduino custom hardware folder.

But less effort to learn is to try to temporarily change or add to the Arduino IDE `avr` board definitions.

The board definition (properties) are passed to the tool that burns the bootloader. All board specific properties are provided by the `boards.txt`

Edit the `[ArduinoIDE\Hardware\hardware\arduino\avr\boards.txt` with a text editor and find the Uno section.

It looks like this. Notice the `mcu`, `vid`, `pid` and `uno.bootloader.file=` settings in particular. The bootloader points to a file in `[ArduinoIDE\Hardware\hardware\arduino\avr`

```
uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

```

You can add a new entry like this. The example uses a board prefix of `uno2.` but it can be any simple unique name.

Save the changes to `boards.txt` then restart the Ide:-

```
uno2.name=Arduino ATmega328P-PU

uno2.vid.0=0x2341
uno2.pid.0=0x0043
uno2.vid.1=0x2341
uno2.pid.1=0x0001
uno2.vid.2=0x2A03
uno2.pid.2=0x0043
uno2.vid.3=0x2341
uno2.pid.3=0x0243

uno2.upload.tool=avrdude
uno2.upload.protocol=arduino
uno2.upload.maximum_size=32256
uno2.upload.maximum_data_size=2048
uno2.upload.speed=115200

uno2.bootloader.tool=avrdude
uno2.bootloader.low_fuses=0xFF
uno2.bootloader.high_fuses=0xDE
uno2.bootloader.extended_fuses=0x05
uno2.bootloader.unlock_bits=0x3F
uno2.bootloader.lock_bits=0x0F
uno2.bootloader.file=optiboot/optiboot_atmega328.hex

uno2.build.mcu=atmega328p
uno2.build.f_cpu=16000000L
uno2.build.board=AVR_UNO
uno2.build.core=arduino
uno2.build.variant=standard

```

note: make a copy of the .txt or grab a new one from the zip on arduino.cc if you mess it up.
> 1 votes

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


# Question
Title: Can't connect to my Arduino via W5100 Ethernet shield
I recently bought a W5100 Ethernet shield and I'm trying to run this simple example, which is a little improvement of the basic WebServer sketch provided by Arduino.cc

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

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress DnsServer (192, 168, 1, 6);
IPAddress GateWay (192, 168, 1, 1);
IPAddress SubNetMask(255, 255, 255, 0);
IPAddress ip(192, 168, 1, 20); // IP address, may need to change depending on network
EthernetServer server(80); // create a server at port 80

String HTTP_req; // stores the HTTP request
boolean LED_status = 0; // state of LED, off by default

void setup() {
  Ethernet.begin(mac, ip, DnsServer, GateWay, SubNetMask); // initialize Ethernet device
  server.begin(); // start to listen for clients
  Serial.begin(9600); // for diagnostics
  pinMode(2, OUTPUT); // LED on pin 2
}

void loop() {
  EthernetClient client = server.available(); // try to get client
  if (client) { // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) { // client data available to read
        char c = client.read(); // read 1 byte (character) from client
        HTTP_req += c; // save the HTTP request 1 char at a time
 // last line of client request is blank and ends with \n
 // respond to client only after last line received
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          // send web page
          client.println("<!DOCTYPE html>");
          client.println("<html>");
          client.println("<head>");
          client.println("<title>Arduino LED Control</title>");
          client.println("</head>");
          client.println("<body>");
          client.println("<h1>LED</h1>");
          client.println("<p>Click to switch LED on and off.</p>");
          client.println("<form method=\"get\">");
          ProcessCheckbox(client);
          client.println("</form>");
          client.println("</body>");
          client.println("</html>");
          Serial.print(HTTP_req);
          HTTP_req = ""; // finished with request, empty string
          break;
        }
 // every line of text received from the client ends with \r\n
        if (c == '\n') {
 // last character on line of received text
 // starting new line with next character read
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // a text character was received from client
          currentLineIsBlank = false;
        }
      } // end if (client.available())
    } // end while (client.connected())
    delay(1); // give the web browser time to receive the data
    client.stop(); // close the connection
  } // end if (client)
}

// switch LED and send back HTML for LED checkbox
void ProcessCheckbox(EthernetClient cl) {
  if (HTTP_req.indexOf("LED2=2") > -1) {
    // see if checkbox was clicked
 // the checkbox was clicked, toggle the LED
    if (LED_status) {
      LED_status = 0;
    } else {
      LED_status = 1;
    }
  }

  if (LED_status) { // switch LED on
    digitalWrite(2, HIGH);
    // checkbox is checked
    cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" \
        onclick=\"submit();\" checked>LED2");
  } else { // switch LED off
    digitalWrite(2, LOW);
    // checkbox is unchecked
    cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" \
        onclick=\"submit();\">LED2");
  }
}

```

So I proceed with connecting my shield via a LAN cable to my router (Gateway `192.168.1.1`), but if I ping `192.168.1.20` (my Arduino) it says "Host Unreachable", my router use DHCP which always worked and still works fine, I'm sure that there aren't any MAC address or IP conflict. I googled around a lot but nothing seems to work.

My DNS server is `192.168.1.6` because I'm running PI-Hole (it's an ad blocker) on a Raspberry, and I don't think this is the problem because all devices connected to it are working fine.

Please any help? Do I have to assume that my shield is faulty?

I tried also using DHCP connection in order to get an IP from the router by doing a:

```
Ethernet.begin(mac);

```

But no good as well.

# Answer
*"...Please any help? Do I have to assume that my shield is faulty?..."*

Before trashing the shield, I'd run through a sligtly more comprehensive troubleshooting approach, from the lowest level of the network stack (the physical layer) up to the ICMP/IP layer. Let me expand over this process:

1. **Physical layer**: I bet your router has some LEDs whose purpose is to show *IF* some ethernet device is connected to related physical router port... or not. So, as a very first step, supposing you connect your ethernet shield to PORT-1 of your router, you should check that once you connect the cable and turn on the Arduino.... the "port 1" LED on the router should turn on. If it turns on... let's proceed to next step. Otherwise... let's launch a different question (or expand accordingly your OP);
2. **Ethernet layer**: once the LED is on, we can be sure that the physical layer is OK. So let's go up at Ethernet layer. In order to communicate on an Ethernet network, every device need to have a MAC address. Also, even if not strictly necessarily, we can bet that every ethernet device (including your shield) implement the ARP resolution protocol. This is needed in order, for other ethernet devices, to obtain the MAC address of your shield, in order to include such a MAC address in all the ethernet datagrams to be sent over the network (to communicate with your shield). So, if you configured your shield with MAC `DE:AD:BE:EF:FE:ED` and IP `192.168.1.6` I would:

1. connect my Linux box to your router (*BTW: sorry! I can't help with other operating systems, as I switched to a linux-only notebook lots of years ago!*);
    2. configure my Linux ethernet interface (`eth0`) with an IP like `192.168.1.99`;
    3. run an `arping -I eth0 192.168.1.6` (where `arping` is this tool)

If everything is working correctly, you should receive something like:

```
root@iMac-Chiara:~# arping -I eth0 10.20.20.2
ARPING 10.20.20.2 from 10.20.20.1 eth0
Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.736ms
Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.729ms
Unicast reply from 10.20.20.2 [A4:BA:DB:98:FC:A4]  0.720ms
[...]

```

where you see that my notebook (10.20.20.1) is getting ARP-replyies from 10.20.20.2, who has the `A4:BA:DB:98:FC:A4` MAC address.

If you don't see replyies... we have an Ethernet problem (but not a physical one) and... chances are high that you have a faulty shield (BTW: the message "Host unreachable" you mentioned in your OP, let me think that this is your problem);

Viceversa, if you obtain replyies, than the Ethernet level is OK and problems are located on upper layers. Let's focus on this last particular case

3. **IP layer**: once the physical layer and the ethernet layer are OK, you should be able to properly PING your target (I'm excluding the case where you have some firewall that, somewhere along the path from the two hosts, could "cut" some traffic. I'm also supposing that IP addresses and netmask are properly configured \[from an IP point of view\]). I'm not getting deeper with such a case, as you should be already familiar with PING (BTW: from your POST, it's not clear from *where* you were PINGing your Arduino. Directly from the "router"? or from you PC?)

Having said all the above, let me conclude by saying that several further checks could be putted in place but... it's much better to previously run above checks :-)

Hope this help!
> 2 votes

---
Tags: shields, ethernet, web-server, tcpip
---


# Question
Title: Can you save data to EEPROM using firmata?
I have a few Arduino boards connected to my computer running firmata and I want the computer to be able to differentiate between them even when I unplug them and plug them back into a different USB port in a different sequence. My solution was to save and read a Unique I.D. into each Arduino's EEPROM, but I am not sure how to accomplish this using firmata?

I want to save a few bits of data to the Arduino UNO with EEPROM, but the Arduino has to be running code compatible with firmata. Is this possible?

# Answer
> 2 votes
You have to edit the Firmata source code and add a few lines of code:

1. add the EEPROM library
2. include the library into the Firmata code
3. in the setup() function use the EEPROM library to read the id from the EEPROM

How do you plan to write that data into your Arduino EEPROM? If you want to do that via serial connection than you also need to add that code. I have done something similar in an example for my VoltageReference library, specifically in EEPROMCalibration.ino

**UPDATE**

After a little investigation I understand there is the possibility to exchange generic messages and handle generic commands via Firmata: commands 0x00-0x0F are reserved for customization. On the Arduino side you can use:

```
void storeToEEPROM(int id) {
  ...
}

void readFromEEPROM() {
  char buf[12];
  Firmata.sendString(itoa(the_id, buf, 10));
}

void setup() {
  ...
  Firmata.attach(0x00, storeToEEPROM);
  Firmata.attach(0x01, readFromEEPROM);
  ...
}

```

That will allow you to write and read the id using those two custom commands.

---
Tags: eeprom, firmata
---


# Question
Title: Is EEPROM persisted across program flashes?
If I use `EEPROM.write(someAddr, someValue)` to write a value to an address, how long will that value "stick" to that address before being lost?

If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

# Answer
Only if the `EESAVE` fuse is programmed (it is unprogrammed by default). If not then the EEPROM will be erased when a chip erase command is performed.
> 2 votes

# Answer
> how long will that value "stick" to that address before being lost?

The Atmega328 data retention is guaranteed by Atmel (the manufacturer) for 20 years at 85 degrees Celsius, 100 years at 25 degrees Celsius. Beware cheap Chinese clones usually use counterfeits chips, meaning those values are not going to be guaranteed any more

> If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

While @ignacio answer is more detailed I believe you are interested in plain Arduino IDE programming along with standard Arduino boards, in which case the answer is **yes**, the data is not going to be erased.
> 0 votes

---
Tags: eeprom
---


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

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

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

Any suggestions?

# Answer
> 1 votes
The fix for this issue was to reload the bootloader. I used the SparkFun Caterina bootloader.

---
Tags: arduino-pro-micro
---


title: Detecting mutual contact between balls

text:
# Question
Title: Detecting mutual contact between balls
Is there a simple way to rig two balls in a way that lets you know if they are touching?

For example, here's a bad idea. Put a free-to-move magnet inside of each ball. When the balls get close, the magnets snap together. Use a magnetic sensor within each ball to tell the direction of the magnet. Use an accelerometer to tell the direction of gravity. When the gravity direction differs from the magnet direction, the balls are touching.

I don't need to know the direction of the contact (that would be ideal, but I don't *need* it). It should work over the whole surface. I would like to have more than two balls and be able to tell *which* two are touching. I can make the balls however I want.

(Even very basic advice would be quite helpful. I'm not familiar at all with hardware projects or what kinds of sensors are available or how to combine the available pieces into some desired thing. That includes advice like "this is probably too hard".)

# Answer
### Option 1

Seems you say you can make the balls out of whatever you want, I would suggest the spheres be made of a metal and then you can either suspend them by wire spot welded or soldered onto the balls. Then what you do is you connect all the balls to inputs of an Arduino ( this is if you are doing this with one). Then connect all inputs to pull-up resistors.

Then to read if a ball is touching a neighbour you start with ball `n` and set it as an `output` and use `digitalWrite(n,LOW);` and then poll all the other balls as inputs to see which one reads `LOW/0V` and then record that in an array, you the move onto ball `n+1` and scan the rest of the balls. There is also no need to read the previous ball to `n+1` as if it did not register a touch, then it won't register with the next ball.

Then at the end you reset everything and start at the beginning again. Using the data how you wish at the end.

Below code is just to show, not tested.

```
for(int n =0; n < total_N; n++){
      pinMode(n, OUTPUT);

  for(int i = 0; i < total_inputs; i++){
          if(!(digitalRead(n)))// ball is touching
   {

         myArray[i] = 1;// store a point in the list, replace with a way you want
    }
    else myArray[i] = 0;
}
     pinMode(n, INPUT);
}

```

### Option 2

*(probably to much to go wrong)*

You could use material that will allow IR rays to pass through and make you balls with that. Then in each ball is have a IR transmitter and a IR receiver, making a transceiver basically and then have each ball echo a specific ID and let the other balls pick it up.

To solve the issue that IR travels a good distance you will need to limit the power/voltage/current to the IR transmitter(LED) so that they only work within a certain range.

### Option 3

You could place reed switches or hall effect sensors in each ball, with a magnet. Place a niece of metal behind the sensor so that the magnet is drawn to it. The only issue with this is that either the magnet in each ball will not only affect its neighbour but also itself. So they will need to be spaced and also the right strength of magnet.

### Option 4

A combination of option 2 and 3 would be to surround a IR receiver setup with a piece of metal disk(like a washer) and also a reed switch or hall effect sensor, and then have a ball with a magnet and a IR transmitter by a magnet, so that when the two are pulled together the transmitter and receiver match up in the same view and are able to tell them that they are connected, you would thus have each ball with a set, one to receive placed on one side and another on the opposite side to transmit.
> 2 votes

---
Tags: sensors
---


# Question
Title: Why are my objects losing their member's values?
I have a `Channel` class which on instantiation receives a `_type` via `new Channel("type", ...)`. I can read the type back out via `channelObject->getType()` which returns a string.

This has always worked fine until today. I have no idea what changed but if I `Serial.print(channelObject->getType())` I get a nasty amount of garbage in the terminal:

```
���QQ���� 00@��������'����������������������(�����������b���������������������������������������H���E���������������������������������������������������������������uD��DESC  initializedOoops, no LSM303 detected ... Check your wiring!Ooops, no BMP180 detected ... Check your wiring!Setting IMU ground: Setting front: !! set ground kalman initConnect Powerbooting up...SWATBOT SETUP COMPLETEtype_xelevatoraileronthrottlerudderaux1aux2serial in: DISARMED!E;1
B��LSM303(>.a+a+8L.�S2E/��BMP085.qL3GD20���T �4&�'�%�%�%&
naninfovf�!,�!H�!��!��!Њ!�D�s6/&������?)m((a&l1=#k2���_
X� +�����+����=� ��J�5�.d�6s'���z :����������-/�type_xtype_x    elevatoraileron    throttlerudderaux1aux2�F�OX4Vjx 7���2�?�xr����:~aileronaux1
�:~  elevator
 ~ throttle:):~rudder������=�@��>�̀?��=�=�@��>�����=�=�@��>�f�B��=�i�?�k��BMP085QF��D�C
�#<}D������D]v� ,B����^v�QF����P}D .?P���f�B.s�D2m .?�oIB��P��(=:@���A�A�@9�@ A@�@�?�A0SB0N�>dC9�@ A@�@�?�A ��A��dC��L?��L>s����C�B(��"�  (�  �"��
(�

```

"elevator", "aileron", "throttle", and "rudder" are types for objects that I know exist but why is it coming out like this? I'm also seeing other unrelated parts of my program being spit out too like "Ooops, no LSM303 detected ...". This is all so strange.

If I had to guess, there must be an awry pointer somewhere in my application but I'm having no luck finding it. Worst case I'll rollback my application and retrace my last implementations (a couple days worth of work).

Can anyone give me a clue as to what is going on here?

My broken application is online at: https://github.com/jacksonkr/SwatBotSpine/tree/master

Emphasis on Channel.h:68 which is where all the garbage is coming from.

Related code:

# Answer
> 1 votes
You might be running out of RAM. I suggest you change all lines like this:

```
 Serial.println("SWATBOT SETUP COMPLETE");

```

to use the `F` macro like this:

```
 Serial.println(F("SWATBOT SETUP COMPLETE"));

```

There seem to be a *lot* of places you could change.

---

Also I would not put code (implementation) into the .h files. That belongs in .cpp files. The .h files are for declarations.

---

Inside a class function, using `this->` all the time just makes things look cluttered, eg.

```
StabilityController::StabilityController(RemoteControl* rc, ROSController* ros, IMUController *imu) {
  this->_rc = rc;
  this->_ros = ros;
  this->_imu = imu;

```

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


# Question
Title: Will unnecessary Serial.print() statements slow down my program?
I have lots of `Serial.print()` and `Serial.println()` statements throughout my (rather large) program for debugging when things fail. I've commented out the `Serial.begin()` statement so I don't slow down execution by running a serial port. However, I'd like to leave the `Serial.print()` calls so I only have to uncomment `Serial.begin()` later on.

If there is no Serial port active on the device, are the `Serial.print()` lines still executed at runtime, or does the compiler ignore them? Is there any performance advantage to explicitly commenting out those lines?

# Answer
> 5 votes
No, there is no `USART` wasn't enabled so skip all `print`s. Everything must be done anyways (calls, conversions to strings, writes to `UDR` \- `USART Data Register`). It is just not sent outside by `USART` and it doesn't have to wait for `UDRE` (`USART Data Register Empty` flag) so it might be slightly faster.

You can use similar technique as Loggers - log level variable and `if`s (this can be changed runtime).

Or you can use macros:

```
// comment out this line, if you want to show logs:
#define NDEBUG

#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__)
  #define LOGLN(...) Serial.println(__VA_ARGS__)
#endif

```

And later:

```
LOG(F("Something: 0x"));
LOGLN(variable, HEX);

```

And how it looks after macro substitution? For code:

```
if (...) LOG(F("something")); else LOG(F("something else"));

```

With NDEBUG defined it's expanded to:

```
if (...) ; else ;

```

And without NDEBUG defined it's expanded to:

```
if (...) Serial.print(F("something")); else Serial.print(F("something else"));

```

# Answer
> 1 votes
The compiler cannot know what the situation with the device is at runtime. The function itself must determine that, so the call *will* take place, with arguments and everything. A well-written function would test early on whether there was anything to do, and if not then return early - but that still wastes time.

The norm in programming is to have two versions of the code: one labelled "DEBUG", which has lots of `print()`s, and one labelled "RELEASE", which uses language contructs to ignore them. This is achieved a number of different ways - but Arduino doesn't really support this out of the box.

@KIIV's answer, using `#define`, is one way to do this. The problem with it comes when you have multiple modules, or are using libraries that themselves do their own `print()`s. If you only have your main sketch, then it would work fairly well.

# Answer
> 1 votes
A quick test shows that not doing a Serial.begin makes things run 10 times as fast. For example:

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

void loop ()
  {
  digitalWrite (13, HIGH);
  for (byte i = 0; i < 100; i++)
    Serial.println ("But does it get goat's blood out?");
  digitalWrite (13, LOW);
  delay (500);
  }  // end of loop

```

That took 292 ms to do 100 x of those prints on my Uno. If I comment out the Serial.begin call it takes 29 ms. So, faster but not incredibly fast.

On my page about debugging I have suggested code to turn on or off debugging prints. The basic idea is to have a Trace define that lets you output stuff if debugging is on, like this:

```
#define DEBUG false

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); } while (0)
  #define Trace(x)      Serial.print   (x)
  #define Trace2(x,y)   Serial.print   (x,y)
  #define Traceln(x)    Serial.println (x)
  #define Traceln2(x,y) Serial.println (x,y)
  #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

void setup ()
  {
  beginDebug ();
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (13, HIGH);
  for (byte i = 0; i < 100; i++)
    Traceln ("But does it get goat's blood out?");
  digitalWrite (13, LOW);
  delay (500);
  }  // end of loop

```

Now in this case, with DEBUG defined as `false`, the time taken with pin 13 high is now only 5 µs - a substantial speed-up.

If you define DEBUG to be true, then it is much slower - 290 ms as in the first test.

---

The suggestion made by KIIV will fail if you have `if` statements:

```
#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__);
  #define LOGLN(...) Serial.println(__VA_ARGS__);
#endif

```

For example:

```
if (something)
   LOG ("something is true");

digitalWrite (8, HIGH);

```

Imagine that debugging is off. Now the empty define makes the code look like:

```
if (something)
  digitalWrite (8, HIGH);

```

So you have a side-effect that the code behaves differently if debugging is off.

---

> Semicolon is not part of the macro, so it will be expanded into: `if (something) ;`

See What does the c precompiler do with macros defined as (void)0 \- there are subtle issues with using an empty define compared to void(0).

For example:

```
  Serial.println ("hi there"), LOGLN ("debugging");

```

That fails to compile (with the empty define) if debugging is off. The `void(0)` version does compile. Admittedly it's an edge case, but nevertheless ...

---
Tags: serial, performance
---


# Question
Title: Is my MQ-2 gas sensor analog or digital?
I have this MQ-2 gas sensor for an Arduino Uno:

I found these two articles about how to use it:

But I need to know if the sensor is analog or digital. Also I would like to know what is the blue switch for.

This questions help me a bit:

It says that he use an analog sensor. But as this sensor is not mine I don't want to brake it or burn it.

# Answer
Your sensor is analog. I have the same one. By the way, there is no chip on board, so it cannot form a digital signal ;)
> 1 votes

---
Tags: arduino-uno, sensors
---


title: Question of proper usage for F Macro

text:
# Question
Title: Question of proper usage for F Macro
Here are three use cases. Are all preferred or is the use of the `F()` macro pointless on some?

**1.**

```
Serial.println(F("some string"); // definitely useful here

```

**2.**

```
String str = F("some string");
Serial.println(str);

```

**3.**

```
int num = 5;
String str = F("some string with int ");
str += (String)num;
Serial.println(str);

```

# Answer
Any time String is involved F() becomes pointless. Avoid String like the plague if you value your memory integrity.
> 2 votes

---
Tags: memory-usage
---


title: Arduino only addresses 3 LED at a time

text:
# Question
Title: Arduino only addresses 3 LED at a time
I am running the following sketch on an Arduino Uno using Arduino 1.6.8. Strip is a WS2811 12V.

```
#include <Adafruit_NeoPixel.h>
#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, PIN, NEO_GRB + NEO_KHZ800);

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

void loop (){
   strip.setPixelColor(0, 255, 0, 255);
   strip.show();
}

```

The problem is that the LED’s light in (Green) groups of three and what I want is individual control.

```
strip.setPixelColor(0, 255, 0, 255); Illuminates Pixels 0,1,2
strip.setPixelColor(1, 255, 0, 255); Illuminates Pixels 3,4,5
strip.setPixelColor(2, 255, 0, 255); Illuminates Pixels 6,7,8

```

And so forth.

Although this code uses NeoPixel I get exactly the same issue if I use the equivalent in FastLed.

Any pointers to what I am doing wrong would be appreciated.

# Answer
LED strips with WS2811 and 12V are the ones with one driver and 3 RGB LEDs on it. These are interconnected so you just can't control less than whole group of three.

If you need individual control, you have to get 5V variant with WS2812.
> 3 votes

---
Tags: neopixel
---


# Question
Title: Arduino Software serial not showing the received data
I get the data from a sensor which is in RS485. I am using RS485-RS232 Converter. Then its given to uart usb converter and I get the data in TTL. I am able to receive the data in uart (hyperterminal). I have connected the TX, RX, GND pins to 10, 11, GND pins of Arduino UNO. I want to communicate it with Arduino UNO through SoftSerial and here is the code

```
#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11

SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

void setup() {
    pinMode(rxPin, INPUT);
    pinMode(txPin, OUTPUT);
    mySerial.begin(9600);
    Serial.begin(9600);
}

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

```

But I'm not able to see the data on serial monitor.

# Answer
I had a problem similar to yours recently.

The thing that got me was that the RS232 from the Arduino is reverse. This is because it would usually go through a RS232 IC that produces +12 and -12 signals.

A sensor or RS232 backpack on a LCD cannot deal with the reverse signals.

The SoftwareSerial library has an undocumented feature that will reverse the RS232 output for you.

When you configure your interface do the following:

```
SoftwareSerial mySerial(3, 2, true);

```

The true option instructs the library to reverse the RS232 signals. Hope this helps you out since this post was a long time ago.
> 1 votes

---
Tags: arduino-uno, softwareserial, datalogging
---