title: Sending LCD commands to a slave micro

text:
# Question
Title: Sending LCD commands to a slave micro
I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.

My plan was to make functions that used existing code such as lcd.print("This or that"); to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.

Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd\_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example: lcd\_print("any string of any length"); lcd\_print(a\_2d\_array \[x\] \[y\]); lcd\_print(this\_byte); lcd\_print(this\_integer);

Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:

lcd.print();

Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

# Answer
> 1 votes
Just inherit `Print` class and implement `virtual size_t write(uint8_t);` and you can use all kinds of print/println that Print implements. See Print Class @arduino.cc.

It implements these methods for you:

```
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

```

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.

And for std::ostream like approach I like this (works with anything inherited from Print class):

```
template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

void loop() {
  float variableA = 221.23;
  String variableB = "Some string";
  Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
}

```

Then you can implement some commands interface.

---
Tags: serial, lcd, communication
---


# Question
Title: Faster and lighter approximate timing code without using timer
I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower. I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:

```
boolean onOff=1; // arduino led state. My task here is LED blinking.
byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
//Code will be executed every "loopCounter" iteration of loop().
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
      if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
        loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
        digitalWrite(13, onOff= !onOff); // the task itself.
        }
}

```

It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing. It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done. So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms\*1000 == 1 sec. So you need it to be done every 1000 iterations.

1. So, is that really can save some ram and cpu time?
2. Is comparing with zero is faster for arduino than comparing with not zero?
3. Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?
4. Any side-effects of using my pattern? I can only think of very unaccurate timing and delays more than you think if your sketch done smth more than usual, because of button push for example or some sensor changed value.

Thank you!

# Answer
> 3 votes
Personally I wouldn't be putting too much effort into optimizing away your timers. `millis()` is pretty fast - the work needed to calculate the result is done in the background *anyway* (by interrupts). I tried some test code:

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

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  start = micros ();
  volatile unsigned long now;
  for (byte i = 0; i < 100; i++)
    now = millis ();
  finish = micros ();

  Serial.print ("Time taken to do millis: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {

  }  // end of loop

```

Results:

```
Time taken to do digitalWrites: 520
Time taken to do millis: 188

```

You can see that the `digitalWrite()` (which you weren't worried about) takes 5.2 µs, whereas calling `millis()` (which you *were* worried about) takes 1.88 µs.

---

> Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.

---
Tags: code-optimization, millis
---


title: Gas Sensor Library for Proteus

text:
# Question
Title: Gas Sensor Library for Proteus
Does any one know how to use Gas Sensor module in Proteus. I wanna use Gas Sensor but I am unable to find it in Proteus. So, does anyone know any way of adding Gas Sensor Library for Proteus software. Thanks in advance.

# Answer
I have found the Gas Sensor Library for Proteus, so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.

Thanks.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Servomotor losing its connection right after being connected to Arduino
I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.

```
#include <Servo.h>

#define SERVO 6 // Porta Digital 6 PWM

Servo s; // Variável Servo
int pos; // Posição Servo

void setup ()
{
  s.attach(SERVO);
  Serial.begin(9600);
  s.write(0); // Inicia motor posição zero
}

void loop()
{
  for(pos = 0; pos < 90; pos++)
  {
    s.write(pos);
  delay(15);
  }
delay(1000);
  for(pos = 90; pos >= 0; pos--)
  {
    s.write(pos);
    delay(15);
  }
}

```

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

# Answer
Your code is correct. Check the following:

* Arduino works from 5V, but most servos need 6V.
* Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
* Check that grounds of both power supply for Arduino and power supply for servo are connected together.
> 1 votes

---
Tags: arduino-uno, motor, servo
---


# Question
Title: Distance sensor - Not working on fabric surface
I am using ultrasonic HC-SO04, not giving reading on fabric. I lost many hours on testing my obstacle avoidance robot car in front of my sofa, every time it hits hard but works fine on other hard surfaces. Is there any other distance sensor which can detect soft objects like fabric from long or short distance?

Also looking any other accurate long distance cheap sensor which can work easily with Arduino. Please let me know. Thanks

# Answer
> 2 votes
There are three types of commercially viable sensors for small scale projects:

1. **Ultrasonic sensors(HC-SO04 and similar):** These sensors use ultrasound much like a submarine uses its sonar to locate things by sending out a sound wave(trigger pin) and then measuring the time it takes for the sound wave to bounce back by reading the echo.There are two problems with this sensor. It needs a pretty solid object to bounce sound of thus walls are good but cloth absorbs the sound wave and the echo never bounces back. The second is you can encounter ghost echos when the sound wave strikes a corner and creates a echo for an object that is not really there. These sensors typically have a range of around 250cm to 600cm however some sensors can sense up to 7 meters away. Thus while it has good range it can not reliably detect all things and you might have false positives on it as well.
2. **IR(Infrared) Sensors:** These work like the ultrasonic ones but with light instead of sound. The sensor sends out a pulse/beam of IR light and measures the time it takes to reflect the light pulse/beam. This sensor is much faster than the ultrasonic ones but they have a much smaller range than ultrasonic sensors with a normal range of about 1.5 meters. While they work on most obstacles some might be missed due to the ability of some materials to absorb the IR light pulse thus there is no echo to measure.
3. **LIDAR(Laser Range Sensors):** There are various models of these but the principle is the same as the IR sensor. These can have massive range but they also come in at a massive prices. You can find cheaper ones around I saw a model for $80 that has a 40 meter range.

# Answer
> 0 votes
If you are using HC-SR04 then I would suggest you to first check it out on simulation. I use Proteus software for simulation purposes and you should download the Ultrasonic Sensor Library for Proteus, using this library you can easily simulate your Ultrasonic sensor in Proteus and can design your code. It will save you from hardware testing.

---
Tags: arduino-uno
---


# Question
Title: The most effective way to format numbers on Arduino
I made a big search about how to Format Numbers with the Arduino. I want to **format unsigned Longs into a String** in this format: "*23,854,972*".

The most of the snippets I found work **only with the standard C / C++ Libraries**. They **dont work on the Arduino** until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is **fast**.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is **more effective** in the sense of speed.

Incoming Number: 23854972 Arduino Program Output: 23,854,972

# Answer
> 4 votes
Here is my try at it: The usual way to write a number in decimal is to get the digits from right to left with a loop that looks something like

```
digit = '0' + val % 10;
val /= 10;

```

The following function does exactly this, with the addition of adding commas at the correct positions:

```
/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}

```

Note that the string is right adjusted in the buffer, and the unused characters are not touched. This means you can get a right adjusted string by:

* pre-filling the string with spaces (for padding)
* calling the function above
* using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no padding.

Here is a simple test program:

```
unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i < COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}

```

# Answer
> 4 votes
> The most effective way to format numbers on Arduino

If "effective way" is minimum effort you could hack the avr-libc source code for ltoa and do something like below:

```
char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
{
  int c;

  if (val >= radix)
    s = ultos_recursive(val / radix, s, radix, pos+1);
  c = val % radix;
  c += (c < 10 ? '0' : 'a' - 10);
  *s++ = c;
  if (pos % 3 == 0) *s++ = ',';
  return s;
}

char *ltos(long val, char *s, int radix)
{
  if (radix < 2 || radix > 36) {
    s[0] = 0;
  } else {
    char *p = s;
    if (radix == 10 && val < 0) {
      val = -val;
      *p++ = '-';
    }
    p = ultos_recursive(val, p, radix, 0) - 1;
    *p = 0;
  }
  return s;
}

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

  char buf[32];
  Serial.println(ltos(12345678, buf, 10));
  Serial.println(ltos(-12345678, buf, 10));
}

void loop()
{
}

```

Gives the output:

```
12,345,678
-12,345,678

```

Cheers!

PS: Please see the table driven, non-recursive, number conversion in Cosa (source and benchmark) for a lean and faster implementation.

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


title: Wiring LED strips in parallel & ground

text:
# Question
Title: Wiring LED strips in parallel & ground
Schematic:

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.

My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):

1) How should I wire the LED strips?

My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:

1a) How should I join the thinner wires to the thick wire coming from the power supply?

1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)

I also am unsure about the ground.

2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?

Sub-question: 2a) Does the wire coming from transistor to ground need to be thick?

I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.

I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

# Answer
> 0 votes
It's all a question of *losses*.

Wire is basically a resistor. The thinner and longer the wire the higher the resistance. Current flowing through a resistor causes a voltage drop across the resistor.

Long thin wires with large amounts of current through them will basically mean you get less than your 12V at the LED strips. The question has to be: how much less a voltage is tolerable?

Each strip takes 1.2A. Take for example 24AWG wire. That has a resistance of 0.0842Ω per meter. With 1.2A flowing through a meter of that you get 0.10104V dropped across the wire. That turns your 12V into 11.9V.

Conversely, a meter of 14AWG wire has a resistance of 0.00829Ω - so you would lose 0.009948V over that length.

Now you want two strips - which is double the current, and thus double the voltage drop. On 14AWG you would lose about 0.02V over a meter. Not really enough to worry about. But you can't connect 14AWG to the LED strips. You can connect thinner wire (say 24AWG as above) to them. But that looses too much voltage. Well - *over a meter it loses too much voltage*. But what about over, say, 10cm? That's a 10th the length of before, and so a 10th the voltage loss: 0.01V.

So what is to stop you having a short length of thin wire connected to the LED strips, which then connects to a longer length of thick wire? Answer: absolutely nothing.

And how do you join them together? Well, I find the best way is with solder. Insert the thin wire (stripped) into the end of the fat wire (stripped) and twist them together (axially) then flood the joint with solder.

# Answer
> 0 votes
I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge. Look at this Example on Ebay and you can see what i mean.

I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.

As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.

Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.

There is a bit of learning required first, once you have researched the above you will have you exact answers.

---
Tags: power, wires, rgb-led
---


# Question
Title: DMX dimmer appears to receive data from Arduino but connected lights do not respond
I'm trying to control a DMX dimmer (eurolite ES-12 IEC DMX Switchback) through an Arduino Mega. In an earlier test, we were able to make one RGB DMX light run through the color spectrum. Now, a technician has installed this ES-12 dimmer pack with 12 1-channel DMX lights attached to it. The dimmer has some kind of built-in testing program and all the lights work.

The documentation on the dimmer is very sparse regarding the programming side of things. The dimmer is set to mode `d---` and when the Arduino is running its program, a little green light flickers next to the `d---`, apparently responding to the signals it's receiving, like so: `d---.` Unfortunately, that the only light that responds.

I've tried using the DMXSimple library (the DMX is connected to pin 3), but even the example code (after correcting the brightness-- to ++) does not get any response -- none at all, not even the little green light. The only thing the little green light responds to is an analogWrite() on pin 3.

I'm guessing it's an addressing issue, but I don't know enough to fix it. As I understand it, the dimmer is seen as the controller and is sent a LOW on channel 0 as the Start Code (SC): http://www.dmx512-online.com/packt.html. The first light on the dimmer will then be channel 1, the second light channel 2, etc. (since, the technician tells me, they are 1-channel lights). Is this correct? Or is the dimmer its own universe that should be addressed in some other way?

# Answer
The light technician, Toby Peperkamp, came with the solution. I'm not sure exactly where he found the information, but apparently the protocol for non-RGB DMX lights requires that the lights be switched on to maximum (255) at the beginning of the connection. So I added that to the setUp() and all the lights started to respond.
> 0 votes

---
Tags: arduino-mega, programming
---


title: No power_usi_disable() on Arduino Uno

text:
# Question
Title: No power_usi_disable() on Arduino Uno
we have an error after compiling the code in arduinouno that is displayed as
error: 'power\_usi\_disable' was not declared in this scope in Board: "Arduino/Genuino Uno".how to rectify this error. please reply us fast

# Answer
The Arduino Uno does not have a USI peripheral. Thus, you cannot disable the power of the (non-existent) USI, and there is no `power_usi_disable()` function.

Solution: remove the call to `power_usi_disable()` from your code.

**Update**: To answer your *new* question in the comment, `WDTCR` is the Watchdog Timer Control Register on some AVR chips. On the Uno it is called `WDTCSR`, because it is a control and status register.

Looks to me like you have downloaded from somewhere a program you do not understand. That program was written for an ATtiny chip and you are trying to compile it as-is for an Arduino Uno, which is based on an (incompatible) ATmega328P. That's not the way to do it: you have to understand the program and rewrite all the ATtiny specific stuff to fit the Uno.
> 3 votes

---
Tags: arduino-uno, compile
---


title: Wifly Library that works with RN171

text:
# Question
Title: Wifly Library that works with RN171
Does anyone know of a library that works with the WiFly-RN171? I've tried all that I could find (WiFly, WiFlyHQ and WiFlySerial) but none of them work.

WiFly and WiFlySerial both hang on WiFly.begin().

WiFlyHQ fails to enter command mode and hence proceeds no further.

I'm using the WiFly-RN171 with an Arduino Uno and Communication Shield (XBee, Bluetooth, RFID) - XBee Shield as seen below.

Has anybody gotten this configuration to work?

# Answer
> 0 votes
I have the same configuration and it works (Arduino UNO rev3) I used WiFlyHQ library. Just be carefull with the serial.

```
Serial.begin(9600);
...
if (!wifly.begin(&Serial, NULL)) {
   ...

```

Upload with serial select then put it on USB and then open the monitor.

---
Tags: arduino-uno, wifi, shields
---


# Question
Title: "avrdude: stk500_recv(): programmer is not responding" when uploading sketch
When I try to upload any sketch to my arduino uno r3, the code compiles, the board resets and the RX light blinks 3 or 4 times.I have nothing from the TX light.

The uploading progress bar in the IDE stucks at it's end for a period and then gives me "avrdude: stk500\_recv(): programmer is not responding" 10 times.

I've done the loopback test and it works well so, what should i do ?

thanks for help.

# Answer
> 0 votes
> yes, it has worked before. ... uncorrect bootloader or something,,...

Does the last program you successfully uploaded write anything to the serial port? If you just run the Arduino (no upload attempt) with the Arduino IDE's serial terminal open, can you see that output? It's pretty hard to damage the boot-loader without actually writing a new, bad one to the chip.

If the current program seems to running but not writing to serial when it should, a likely cause of upload failure is the code in 16U2 processor (or the chip itself) that handles the USB to serial conversion; it's the square 32-pin chip between the 16 MHz crystal and USB connector. Its firmware can be re-loaded - search here for how to do that. If the chip itself is damaged it is probably not worth attempting a repair.

Update: Is the +5v pin on the power header (left edge of the board, if the USB connector is pointing up) reading 5v? You'd expect the output pins to read 0v, 5v, or be noisy if they are floating. A steady 1v sounds strange. At this point it would be worth trying this board on another computer, and another board on your computer, and see which one fails.

---
Tags: arduino-uno
---


# Question
Title: How to use Serial Monitor without Arduino board?
I want to use Arduino(atmega8) on breadboard using USBASP programmer and want to use Serial Monitor without using any Arduino board as ISP programmer. My questions: 1. Is such thing possible? 2. How do I do that?

# Answer
> 1 votes
> How to use Serial Monitor without Arduino board?

Yes that is possible. Connect to the RX/TX pins on the breadboard chip. Remember these are 5V. You will need an Serial-USB or RS232 adapter to connect your development machine. Please see this blog post for some inspiration.

Cheers!

---
Tags: serial
---


# Question
Title: How do I know if bootloader flash was successful?
I just bought a raw Atmega328p microcontroller. I am attempting to flash it with the Arduino bootloader.

The process seemed relatively straightforward as I had just followed the posted tutorial (https://www.arduino.cc/en/Tutorial/ArduinoISP).

Everything seemed to go fine and I even got a message after the second attempt with a message of 'Burning Bootloader Done'. I am targeting the device as if it were an Arduino Pro Mini.

I then moved onto program the chip with an Arduino sketch via the FTDI programmer. However, the sketch upload fails. It says that it is out of sync. I verify that everything is wired up correctly, yet it still fails. I then remove power to the Atmega328p chip (just to see if I get a different error) yet I still get the out of sync error.

This has me questioning whether or not the bootloader was even flashed in the first place. So how do I know if the bootloader actually was successful? A couple things to note:

* When I power on the Atmega328p, the PB6 output starts blinking immediately. I would assume that if there were a bootloader, there would be a moment of pause until the regular program starts. Should I expect to see a pause if the bootloader is on the chip?
* If the bootloader is on the chip, should I even expect to see the Atemga328ps default heartbeat?
* When I flash the chip with the bootloader, it says that it could take up to a minute to finish. However, it only takes 6 seconds until it states 'Bootloader Finished Burning'. This seems like it's happening too fast.

If we determine that the problem is due to something else (i.e. not the bootloader), I will begin a new discussion. However, right now I'm just curious how I know if the bootloader is actually on the device.

# Answer
See my page about burning bootloaders.

The sketch there has a "verify" option so you can check if the bootloader was burned.

See my post What happens when code is uploaded using the bootloader?.

With Optiboot installed you expect to see three flashes:

As for your other problems, see Have I bricked my Arduino Uno? Problems with uploading to board.

You may well not have set the fuses correctly.
> 1 votes

---
Tags: arduino-uno, bootloader, arduino-pro-mini
---


# Question
Title: Why does the current drop through a multiplexer?
I am trying to control 64 leds through a number of 8:1 analog multiplexers. The input is from pin 11 on the Arduino which is giving 40mA (maximum) and it is pulsed at 38kHz. Then I use other pins to select one of 64 leds to control. For testing, I am just trying one of those leds. The problem is that the current across the led is just 2mA, which means it is very dim. Using a multimeter, the current after the first multiplexer seems to be 4mA and after the second just 2mA. How can I get the current to increase? Thanks in advance!

# Answer
Analog multiplexers are not a good design choice for switching digital signals.

You should instead choose a digital solution. Maybe the 74HC138 would be a better choice? That's a 3-to-8 decoder with 3 enable inputs.

You could use 9 of them to reduce pin usage on the Arduino, or 8 of them if you have pins to spare.

One of the enables on the first-stage can be a "mater enable" - or tie one of the enables of all 8 of the second-stage together for a "master enable". Another enable to all the 8 second-stage muxes can be the PWM signal. The third is driven by the Arduino or the first stage as a MUX selector.

Something like this arrangement:

Note that the outputs are *active low*, so you would connect the anode of your LEDs to +5V and the cathode, through a suitable resistor, to the output.

Another option would be to use a set of shift registers that have an *output enable* pin. Drive that pin with the PWM signal and you can have any combination of LEDs enabled at once.
> 1 votes

---
Tags: led, multiplexer
---


# Question
Title: How much time does the Arduino need to call a Function or to read a Variable?
How much **time** does an Arduino Uno or Mega need **to only call a function**. And how does the time change if this function is inside a Class, for example inside a Library?

The same thing for a variable. How much time does a micro-controller need **to read a declared variable**?

How to determine this values? Is there a mathematic formula? Can we predetermine this type of delays and other similar micro-controller related delays?

# Answer
> 8 votes
It is hard to give a general answer, as it depends on the specifics of your code and on how the compiler compiles it:

> How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

* the caller puts the arguments on some predefined CPU registers, unless they are already there from a previous operation (the compiler tries to optimize the code so that this happens whenever possible)
* the caller issues the `call` instruction to do the actual function call
* the callee pushes some CPU registers into the stack in order to use them without clobbering the caller's data
* the callee does its job
* the callee pops the previously pushed registers
* the callee issues the `ret` (meaning return) instruction
* the caller finds the return value in some CPU registers

On the Uno, the `call` and `ret` instructions cost 4 CPU cycles each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs) each. `push` and `pop` are 2 cycles each, and you need one such pair for every 8-bit register you need to save.

> And how does the time change if this function is inside a Class, for example inside a Library?

The only difference is that a class method receives an extra hidden parameter called `this`. Except if it's a virtual method, which is more expensive because it involves some pointer dereferencing.

> How much time does a micro-controller need to read a declared variable?

“Reading” generally means transferring the contents of the variable to some CPU registers. Local variable are usually allocated to CPU registers in the first place, so there is no need to read them. Global (and local static) variables are stored in RAM, and reading them takes 2 cycles per byte (e.g. 4 cycles for a 16-bit `int`).

> How to determine this values?

Disassemble the code generated by the compiler. Then look up the instructions in the instruction set manual: it documents the number of clock cycles needed by each instruction.

# Answer
> 4 votes
> How much time does an Arduino Uno or Mega need to only call a function.

Why do you want to know? This sounds like an X-Y problem.

It will vary, depending on a lot of things.

* The number of arguments, because the more arguments the more work involved. Plus if an argument involves copying it might invoke a copy constructor.
* Whether or not the compiler in-lines the function. If it is in-lined (copied into the other function) then there is less work, for example the compiler doesn't need to generate `call` and `ret` instructions.
* What the function does. The more things a function does, the more registers the compiler may have to `push` and then `pop` afterwards to save the state of registers which had useful information in them, outside the called function.
* The size of the arguments. Longer arguments take longer to copy onto the stack, or put into registers. For example, `long` arguments will take longer than `char` arguments.

---

> How much time does a micro-controller need to read a declared variable?

Again, it varies. It depends on the variable size, and whether or not it is already in a register. If the variable happens to be in a register at the time, you could argue it takes zero time to read it.

---

> How to determine this values?

The sensible thing to do is to time some test code. Here's an example from another thread:

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

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {
  }  // end of loop

```

In the middle of the code there I time doing digitalWrite 100 times. By dividing the resulting output by 100, I can work out how long each digitalWrite takes.

---

You don't normally need to know how long, exactly, it takes to read variables, and call functions. Either your code works at an acceptable speed, or it doesn't.

Trying to answer this question on test code may give meaningless results. For example, in my test code the compiler may have in-lined the digitalWrite call. But if I use digitalWrite in many places it will no longer in-line it, which means the timing figures are now incorrect.

---

> The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

If that was what you wanted to know, it would have been better to ask that exact question. That saves us waffling on about copy constructors and so on.

I tested with the code below, which calls `micros()` and saves the results to a variable `foo`. I made it volatile so that the compiler wouldn't be tempted to optimize away the saving altogether (because it isn't used anywhere else).

```
void setup ()
  {
  pinMode (13, OUTPUT);
  PORTB = 0;
  }  // end of setup

volatile unsigned long foo;

void loop ()
  {
  PINB = bit (PB5);   // toggle D13
  foo = micros ();
  PINB = bit (PB5);   // toggle D13
  }  // end of loop

```

I measured 3.380 µs on my oscilloscope for the time when D13 is high. That would be 54 clock cycles. A couple (only) would be the time taken to toggle D13. Thus you can probably reckon `micros()` in general as taking 3.38 µs.

Changing it to call `millis()` instead, it only takes 1.760 µs (28 clock cycles). This is probably because all `millis()` does is return a variable which has already been calculated (in the timer ISR).

Test done on an Arduino Uno running at 16 MHz.

---
Tags: time
---


# Question
Title: Can i supply the AREF pin with an Analog pin from the same board?
I guess its a dumb question but couldnt find anything about it online. I know its possible to supply the AREF pin with 3.3 V to increase the ADC resolution.

For the project i am working on the analog voltage i will be reading will be between 0 and 2.2 and the increased resolution is a must.

I know i can use another board that has a 12 bit resolution but i really would like to make do with Uno. So i wonder if i can set an analog pin to output 2.3 V and feed it to the Aref pin.

If thats not possible please let me know why, so i can increase my knowledge

# Answer
> 3 votes
With an input voltage between 0 and 2.2 V, you can use a 2:1 voltage divider to cut the voltage in half. In your code, use `analogReference(INTERNAL)` to set the analog reference voltage to 1.1 V. The 1.1 V internal reference voltage is created by a bandgap circuit so is reasonably accurate.

To make the voltage divider, put two equal resistors (eg 10KΩ each) in series; connect one end of the series to your input voltage, the other end to ground, and the mid-point to an analog input pin.

# Answer
> 0 votes
The output voltage of the "analog outputs" (which are actually PWM) are dependent on supply voltage and so are not a good choice where precision is required. Consider using either an integrated voltage reference (e.g. TL431) or a constant-current source feeding a zener diode instead.

---
Tags: arduino-uno, analogwrite, analogreadresolution, analogreference
---


title: Arduino MPU6050 Control 2 Servo

text:
# Question
Title: Arduino MPU6050 Control 2 Servo
I'm new to gyroscope and accelerometer and am working on my project to control servo with Arduino Uno R3 based on the reading from InvenSense MPU6050 6DOF gyroscope and accelerometer. I've found the a same sheet of code from different websites.

Website 1\_http://www.projehocam.com/wp-content/uploads/mpu6050-2-servo.txt

Website 2\_http://www.instructables.com/files/orig/FLY/GZAL/IDIN48PC/FLYGZALIDIN48PC.ino

And from this part of the code, I couldn't understand the servo.write part...

```
    #ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        Serial.print("ypr\t");
        Serial.print(ypr[0] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[1] * 180/M_PI);
        myservoY.write(int(ypr[1] * -180/M_PI)+90);   // Rotation around Y
        Serial.print("\t");
        Serial.println(ypr[2] * 180/M_PI);
        myservoX.write(int(ypr[2] * 180/M_PI)+90);   // Rotation around X
    #endif

```

Why is the operation (int(ypr\[1\] * -180/M\_PI)+90) ??

# Answer
> 0 votes
`ypr` contains the Yaw, Pitch and Roll. It is provided in radians.

Servo.write takes degrees.

Multiplying radians by 180/PI converts it to degrees. Adding 90 centralises it around the 90 degree point (half way) of the servo.

---
Tags: arduino-uno, servo, mpu6050
---


# Question
Title: externally powering the Arduino questions
I have several questions on externally powering the Arduino Uno

* I have a 7.2V power source that is 6 rechargeable AA batteries together, 1.2V and 1300mA each. If i use a 4.70 and 1.5 ohm resistors together to give 1.16 amps, can I power the arduino with this?

+ Can I power a servo off the Arduino 5V rail If i place a 470uF or more capacitor alongside it?
    + Will anything heat or blow up or am I just being paranoid like always?

# Answer
I am guessing that you are thinking of dividing down the battery voltage from 7.2V down to 7.2\*(4.7)/(4.7+1.5) = 5.5V. This is generally a bad idea for a few reasons.

1. The battery voltage will not be a constant 7.2V. When they are fully charged it could be even higher. As they discharge they could drop significantly and your Arduino POR (power-on-reset) circuit would potentially shut the board down before the batteries are fully discharged
2. The batterys' internal resistance would probably drop the output voltage considerably once the resistors try to draw 1A of current. It might even collapse the voltage to some unusable value.
3. Even if the battery internal resistance is very low and even if the Arduino is not drawing much power (or even off) you will always be drawing ~1A of current from the batteries. This will rapidly drain your batteries and will also heat them up from their internal resistance. Not to mention your external resistors better be able to handle \> 5W or so. Conclusion: lots of unnecessary heat and power loss.

To answer your other question, assuming the servo is low power and the Arduino power supply is up, you could power it from the Arduino 5V supply (not your batteries).

If you need to use batteries to power an Arduino, I would highly recommend a power regulator to produce a stable output voltage to power your Arduino.
> 3 votes

# Answer
This question has been answered on electronics.stackexchange, e.g. How to provide separate voltages from a common power source

Daniel V has explained the main issues.

The 'killer' for most people is the resistors are always across the battery, and so they alone will take over 1A from the battery pack continuously, and hence run it flat in just over an hour. Further, they need to dissipate over 5W of heat, so they aren't that cheap either.

A NiMh rechargeable battery will have a voltage of about 1.4V when it's fully charged, dropping to under 1V before it is exhausted. So that would mean the resistor network needs to output 5V or less with an input voltage from 6x1.4V=8.2V down to under 6x1V=6V.

So the resistor ratio would need to handle 8.2V in and produce 5V out, and then 6V in would produce 3.66V. My reading of the ATmega sec is it might struggle to run at 16MHz at that 3.66V input voltage.

You might try to make a resistor-based voltage divider more efficient by increasing the total resistance.

However, as explained on the electronics.stackexchange, the load presented by the ATmega on an Arduino varies dynamically, from microsecond to microsecond, so it is very hard to choose resistors which would maintain the voltage within a reasonable operating range, while the current passing through the Arduino varies so much.

An Arduino has an on-board voltage regulator.

However, the typical 5V regulator on generic Arduino's have a drop-out voltage of 2V, i.e. the input voltage needs to be 7V or more. That means most of that battery pack capacity will provide less than 7V, so the voltage will start to drop.

You *might* be lucky and the on-board regulator will 'track' the input voltage down. That means it will fail below 5V as its input drops below 7V. You would need to test your Arduino; there is no guarantee that the regulator on the board does this. Further, it might struggle to run at 16MHz as the voltage approaches 4V.

So, if this is just a one-off hobby project, it might be reasonable to try that. However, if other people are going to use it, it might be too risky.

The ATmega can be run with anything between 5V and 1.8V if the clock is slow enough. Also you'd need to either modify the electronics, or change the bootloader of the Arduino to ensure it runs at a much lower clock frequency. So it is possible to run at a lower voltage than 5V, by changing the bootloader, but it seems like a strange exercise. Then a resistor divider (which wastes a lot of energy), or the on-board regulator could be used.

Instead, look at a Low-Drop-Out (LDO) voltage regulator. There are parts which will regulate anything from 8.4V down to 6V, or less, down to 5V. An Arduino alone uses well under 100mA, it is the electronics it is driving which uses the majority of an Arduino's specified 500mA.

So you look for a voltage regulator, which will take 9V in (as a safety margin) with a drop-out voltage of 0.7V (lots at this spec), 5V out, and 250mA or better. Most electronics distributors have a product selector which will help you find this, and you may find small ready-made modules which do exactly this (but not an LM111xx).

You don't post a link to the servo you're using.

Low-cost servo's typically take a lot of current as they move. I've measured some using a proper bench power-supply unit (bench PSU). They typically take well over 1A for periods long enough for me to see it happen. So the power supply would likely need to supply more than 1A for short periods, i.e. 10's of milliseconds. You will need quite a substantial capacitor to handle that.

Depending on the servo, you might be better to use 4xNiMh to power the servo directly, without any intermediate regulation, and a more modest capacitor. The ground (-) of that power supply needs to be connected to the GND of the Arduino so that the servo signal from the Arduino will drive the servo correctly.

In that case, you might use a low-cost (ebay) DC-DC step up (boost) switching regulator to provide the 5V to the Arduino. Their are lots available which are intended to power USB devices at 5V.
> 2 votes

# Answer
Your typical Arduino has a built-in 5V regulator. Just plug the batteries into the barrel jack - that is what it is for.

If you don't have a barrel jack on your Arduino (it's one of the little ones?) then you will need a *voltage regulator*. For battery usage you want a switching "buck" regulator.

You can find them cheaply enough under the name "UBEC" (Universal Battery Elimination Circuit) and are used for model aircraft etc.
> 1 votes

# Answer
You can connect the batteries fine into Vin or the barrel jack, however you will run into the issue that your battery voltage will sag. This will vary on what chemistry batteries you are using, NiMh voltage discharge sits on a bit of a plateau around 1.2V typically, alkaline has more of a gentle curve downwards and then drops off quite sharply around or below 1V.

The reason this is an issue is highlighted on the Arduino Uno page itself:

> Input Voltage (recommended) 7-12V
>
> Input Voltage (limit) 6-20V

and

> The board can operate on an external supply from 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

The issue here is the dropout of the onboard regulator.

The solution is to use your own external regulator and connect it to the 5VDC pin.

You can use:

1. An external swithcmode DC-DC converter, you would be ideally after a buck boost. DC-DC converters are available from ICs for a full ground up DIY design to available on board modules and daughterboards and fully assembled circuits. Regarding the other answer a BEC or UBEC may not be suitable as typically they are buck converters and have higher minimum output voltages than that required by the OP, some however with careful selection may be alright to use.

Adafruit off the shelf buck-boost module: https://www.adafruit.com/products/2190

2. An external linear LDO regulator, ideally with as low dropout as possible. You will need to pick this part to suit your input voltage range, this may be difficult as extremely low dropout parts are typically low current and not suitable if wanting to drive a servo. Something like a REG103 for example may work, depending on the dropout an LDO linear regulator may work down to around 5.2~5.3VDC minimum, which should be okay for most of the capacity of the batteries.
3. A premade shield, some may work for you, some to give you an idea of what is required.

DC-DC converter for battery shield: https://www.wayneandlayne.com/projects/battery-booster-shield/

Adafruit has a lithium battery shield such as does Sparkfun (not enough rep for more links)

Itead has a AAA battery shield also.

Options here will depend on your design ability and assembly skills as to if you can DIY or need off the shelf.

Your servo will be fine connected to the external regulator as long as the option you use is rated to supply enough current.
> 0 votes

---
Tags: arduino-uno, power
---


# Question
Title: How to serially communicate arduino uno to PIC18f4550?
I am new in PIC programming

my question is, how can i communicate arduino UNO with PIC18f4550. i am using THIS programmer board for PIC controller and it has a builtin RS232 serial interface.

Can any body tell me how to communicate between them. I want to communicate in such a way that only Rx & Tx pins and the power pins of arduino will be used.

# Answer
> 1 votes
yeah you can quite easily do the Serial communication between Arduino and PIC Microcontroller. You need to connect the below pins:

* Arduino TX will be connected to PIC RX.
* Arduino RX will be connected to PIC TX.
* GND of Arduino must be connected to GND of PIC.

Next thing you need to remember is to have same baud rate for both Arduino and PIC. Now you should check these two posts:

First one is explaining the Serial Communication of Arduino while the second one is Serial Communication of PIC Microcontroller. You should also read What is Serial Port? to get more idea about Serial communication.

I hope they will help you out. If you still got into some issues then let me know.

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


# Question
Title: Measuring The Distance Using GPS programmed with Arduino
Who among here have tried measuring the before and after distance traveled using gps? I'm going to use the code from TinyGPS library's distance\_between command without constant value of latitude and longitude,

like this:

```
static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002

```

I want to see that the first GPS latitude and longitude results is used as reference point.

How will I apply it on my code so that I could be able to get the distance I traveled? Please help me.

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
 /*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
 */
 static const int RXPin = 4, TXPin = 3;
 static const uint32_t GPSBaud = 4800;

  // The TinyGPS++ object
TinyGPSPlus gps;

 // The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
 Serial.begin(115200);
 ss.begin(GPSBaud);

     Serial.println(F("FullExample.ino"));
     Serial.println(F("An extensive example of many interesting     TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. "));                    Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars     Sentences Checksum"));
     Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
           Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ?        TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
   (unsigned long)TinyGPSPlus::distanceBetween(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON) / 1000;
     printInt(distanceKmToLondon, gps.location.isValid(), 9);

     double courseToLondon =
    TinyGPSPlus::courseTo(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON);

   printFloat(courseToLondon, gps.location.isValid(), 7, 2);

   const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

   printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

   printInt(gps.charsProcessed(), true, 6);
   printInt(gps.sentencesWithFix(), true, 10);
   printInt(gps.failedChecksum(), true, 9);
   Serial.println();

   smartDelay(1000);

   if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
   }

  // This custom version of delay() ensures that the gps object
  // is being "fed".
  static void smartDelay(unsigned long ms)
  {
  unsigned long start = millis();
  do
  {
   while (ss.available())
    gps.encode(ss.read());
    } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
     {
   if (!valid)
   {
    while (len-- > 1)
    Serial.print('*');
    Serial.print(' ');
    }
    else
    {
   Serial.print(val, prec);
   int vi = abs((int)val);
   int flen = prec + (val < 0.0 ? 2 : 1); // . and -
   flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
   for (int i=flen; i<len; ++i)
   Serial.print(' ');
   }
   smartDelay(0);
  }

 static void printInt(unsigned long val, bool valid, int len)
 {
  char sz[32] = "*****************";
  if (valid)
  sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
   sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
  }

  static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
  {
  if (!d.isValid())
   {
   Serial.print(F("********** "));
   }
   else
   {
   char sz[32];
   sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
   Serial.print(sz);
    }

    if (!t.isValid())
    {
    Serial.print(F("******** "));
    }
    else
    {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
    }

    printInt(d.age(), d.isValid(), 5);
    smartDelay(0);
    }

    static void printStr(const char *str, int len)
    {
    int slen = strlen(str);
    for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
    smartDelay(0);
    }

```

# Answer
This is where those dreaded maths classes come in.

You know - the ones where no one paid attention because you thought "Where in the real world would I ever want to know this stuff?" Well, right here is were you would want to know this stuff.

The distance between two points on a 2D plane (i.e., a map) can be looked at as two vertices of a right-angled triangle.

Going from Start to Finish you travel X degrees across the globe and Y degrees up or down it. So you can calculate the number of degrees between the two points with simple pythagoras' theorem:

In C it's quite easy to do those calculations. You can find X and Y by subtracting the two longitudes and scaling it for the logitudinal circumference of the Earth where you are. You can do the latitudes in a similar way:

```
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0

```

24901 is the circumference of the Earth at the equator, and 24860 is the circumference of the Earth going through both poles. Both are in miles, so the result will also be in miles. The numbers are different for the two directions because the Earth is not a perfect sphere. It is somewhat flattened at the poles, and is called an *oblate sphere*.

It doesn't matter which one you subtract from which since, when you square them, they will become positive anyway:

```
float X2 = X * X;
float Y2 = Y * Y;

```

Then you can get the square root:

```
float Distance = sqrt(X2 + Y2);

```

So now you know how to calculate it without relying on some function in some library. It only takes a couple of lines of C code and you don't have to then know just how to use this unknown function provided by a library, and the theory will stand you in good stead for future similar projects.

Oh, and the code in full, in case you want it:

```
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0
float X2 = X * X;
float Y2 = Y * Y;
float Distance = sqrt(X2 + Y2);

```
> 1 votes

# Answer
I have been always frustrated from the missing double (64bit) type in Arduino world and hence the problem with properly calculating GPS distance, bearing and destination point.

The following library uses Float64 & Math64 libs and also adds some fast and very fast implementations of trigonometric functions and fast and regular versions of GPS GPS distance, bearing and destination point.

Feel free to use it - and any help in improving it is welcome !

https://github.com/vtomanov/Gps64
> 0 votes

---
Tags: arduino-uno, tinygps
---


# Question
Title: Which Barcode Scanner to be used with arduino in India
I know this question is not so releavant as it does not include any research, but I am in search of a barcode scanner that i can easily interface with arduino and get output from it but unfortunately the Scanner models which are listed from the people doing the same stuff are not easily available in India. So if anyone knows which barcode scanner would best suit the requirement please suggest. Availabilty in **Indian** market would be much appreciated :)

# Answer
Most barcode scanners behave just like a regular keyboard.

Try getting one with a PS2 port. You can pretty easily interface a PS2 keyboard to an Arduino. There are already libraries for it.
> 2 votes

---
Tags: arduino-uno
---


title: What if I just connect 5V DC to my UTP?

text:
# Question
Title: What if I just connect 5V DC to my UTP?
Here is the image of Ethernet shield near RJ45 socket:

These small boxes are probably SMD capacitors which may mean, that internal board is glavanically disconnected from the UTP line.

Is this true?

If this is true, then what will happen, if I pass `5V` `DC` current just into my UTP? Won't I be able to wire appropriate conductors just into Arduino power input? Won't I be able to power Arduino this way?

The question is about not using premade PoE splitter. I have an injector, which injects `5V` into line.

**UPDATE**

I found my injector put power to lines 4,5 and GND to 7,8. Can I take this power on Arduino side?

# Answer
> 1 votes
Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)

Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)

Or you can use external PoE injector and extractor:

For 100Mb networks are two unused communication pairs used as power lines:

---
Tags: arduino-uno, power, ethernet
---


# Question
Title: Controlling 12v DC LED strips using Arduino UNO
I have 2 LED strips with 6 LEDs on each. They use a 12V power supply.

My question, how can I use them like regular LEDs using Arduino UNO? Without any MOSFETS or transistors if possible.

And can I use PWM?

# Answer
> 3 votes
It's not safe for the MCU without transistors or so.

You can use some kind of LED driver (for example TLC5940 with on chip PWM) or ULN2003 as 8 channel low side switch (instead of 8 transistors, PWM is possible if you do it programmatically) or many others.

With single transistor it looks like:

Where R\_1 can be about 1K and transistor can be any NPN that could handle led current.

---
Tags: arduino-uno, led, pins, pwm
---


# Question
Title: Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power?
I am using an Arduino Mega 2560 board. I have tried connecting a 115 Ω resistor from 5V to Reset, and 10 µf capacitor form reset to GND (to disable autoreset), and the variables still seem to reset themselves when I unplug and replug-in the Arduino. Any way to stop this from happening?

Basically I am making a device that is sensitive to time, and must run for about 2 months, but if it is unplugged, it can't lose its place in time and reset the whole program.

I think one alternative would be for me to have it actually write how long it has been running into a `.txt` file on the microSD card and then verify that in the start-up...

Any ideas?

# Answer
Save the variables you need to EEPROM.
> 5 votes

# Answer
Arduino Mega board has RESET-EN "jumper". If you cut the trace, it won't reset MCU by DTR from USB-to-Serial chip. If you have to upload new sketch, you'll have to short it by piece of metal.

There is also possibility to use `.noinit` section for storing variables, so if you don't loose power, it won't get overwritten by automatic init. However, bootloader could be messing with that memory too. So it might not help without erasing this bootloader and using ISP(SPI) interface to program it.

Or you can use for example RTC (if you already have one) and it's battery backed RAM.
> 1 votes

# Answer
If you can't give the MCU enough warning of a power-down to save its critical variables, you'll have to keep it alive with batteries, sleeping if necessary, until the power comes back.

Tying Reset high won't help. The chip resets at power-up - that's built in. In fact, a power-up reset and a grounded-Reset-pin reset behave a bit differently - see the datasheet. Even if it didn't reset on power-up, the RAM needs power to maintain its contents, so it loses them when it drops.
> 1 votes

# Answer
Take power from UPS (uninterruptable power supply).
> 0 votes

---
Tags: arduino-mega, power, time, reset
---


# Question
Title: Absolute noob looking for troubleshooting help
My 10-year-old son went to a "Robotics Camp" and came home with a non-functional Arduino robot. I figured it shouldn't be too much trouble to get it working. He swears he had it operating at the camp, but our best efforts notwithstanding, we were unable to reproduce his successes at home to any degree at all. Currently we seem to have an ungainly, $400 paperweight.

I'm a .Net web-developer by day, but I'm completely uninitiated when it comes to Arduino. I did enough research to learn how to upload a basic sketch- the "Blink" sketch- to our board an verify that the board is functional. Upon uploading the Blink sketch we got a flashing red LED. I was able to go into the sketch and modify the the variable values and see the results in the duration of the LED flash after uploading the sketch again. So I'm confident that we have a good connection to the PC and a functioning Arduino board.

But beyond that I'm stumped. When I attempt to upload the program that my son brought home, the robot does nothing. I can see a red LED blink a few times on the Arduino, but other that that, nothing happens.

Here's some photos of our setup:

Here's the sketch that my son brought home:

```
/***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 16 servos, one after the other

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These displays use I2C to communicate, 2 pins are required to
  interface. For Arduino UNOs, thats SCL -> Analog 5, SDA -> Analog 4

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <QueueList.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN  300//150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  400//600 // this is the 'maximum' pulse length count (out of 4096)

uint16_t servoMins[] = {160, 200, 500, 150, 150, 150, 0};
uint16_t servoMaxs[] = {600, 600, 700, 600, 600, 600, 0};
uint16_t servoHomes[] = {380, 400, 300, 340, 375, 375, 0};

enum GroupType {WithPrevious, NewGroup};

#define PAUSE_COMMAND 6
#define NUM_TRANSITIONS (PAUSE_COMMAND+1)

unsigned long currentTime;

class transition
{
  private:
    unsigned long startTime;
    unsigned long totalTime;
    uint16_t pulseLenStart;
    uint16_t pulseLenEnd;
    uint16_t currentPulseLen;
    int id;
    bool transitioning;

  public:
    void init(int id, uint16_t current)
    {
      this->id = id;
      currentPulseLen = current;
      totalTime = 0;
      startTime = 0;
      pulseLenStart = current;
      pulseLenEnd = current;
      transitioning = false;

    }

    uint16_t calculate(unsigned long currentTime)
    {
      float t = 1.0f;
      if (totalTime > 1e-3f)
        t = (currentTime - startTime) / (float)totalTime;
      t = (t > 1.0f) ? 1.0f : t;
      currentPulseLen = (uint16_t)(((float)pulseLenEnd - (float)pulseLenStart) * t + pulseLenStart);
/*      if (transitioning)
      {
        Serial.println("transitioning");
        Serial.println(id);
        Serial.println(t);
        Serial.println(currentTime);
        Serial.println(startTime);
        Serial.println(totalTime);
        Serial.println(pulseLenStart);
        Serial.println(pulseLenEnd);
        Serial.println(currentPulseLen);
      }
*/
      if (t >= 1.0f)
        transitioning = false;
      return currentPulseLen;
    }

    void createTransition (uint16_t pulseLen, unsigned long time)
    {
/*      Serial.println("create Transition:");
      Serial.println(id);
      Serial.println(pulseLen);
      Serial.println(time);
*/
      pulseLenStart = currentPulseLen;
      pulseLenEnd = pulseLen;
      totalTime = time;
      startTime = currentTime;
      transitioning = true;
    }

    bool isTransitioning()
    {
      return transitioning;
    }
};

transition transitions[NUM_TRANSITIONS];

struct Command
{
  uint16_t pulseLen;
  unsigned long totalTime;
  int commandType;
  GroupType groupType;

  void execute()
  {
    transitions[commandType].createTransition(pulseLen, totalTime);
  }
};
QueueList<Command> commandQueue;

void program ();
void restoreHomePositions (double seconds);

void setup()
{
  pwm.begin();

  Serial.begin(9600);
  Serial.println("Hello world");

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  for (int servoNum =0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    //pwm.setPWM(servoNum, 0, servoHomes[servoNum]);
    transitions[servoNum].init(servoNum, servoHomes[servoNum]);
  }

  restoreHomePositions (0);
  program();
  restoreHomePositions (.75);

  yield();
}

void processCommandQueue();

void loop()
{
  currentTime = millis();

  processCommandQueue();

  for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    if (transitions[servoNum].isTransitioning())
    {
      uint16_t pulselen = transitions[servoNum].calculate(currentTime);
      if (servoNum != PAUSE_COMMAND)
      {
        pwm.setPWM(servoNum, 0, pulselen);
        Serial.println("setPWM");
        Serial.println(servoNum);
        Serial.println(pulselen);
      }
    }
  }
}

bool isTransitioning()
{
  for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    if (transitions[servoNum].isTransitioning())
      return true;
  }
  return false;
}

int frame = 0;
void processCommandQueue()
{
  if (!commandQueue.isEmpty())
  {
    Serial.println("Frame");
    Serial.println(frame);
    frame++;
  }
  if (!commandQueue.isEmpty() && !isTransitioning())
  {
    do
    {
      Command top = commandQueue.pop();
      top.execute();
    }
    while (!commandQueue.isEmpty() && commandQueue.peek().groupType == WithPrevious);
  }
}

void move (int commandType, uint16_t pulseLen, double seconds, GroupType groupType = NewGroup)
{
  Command command;
  command.groupType = groupType;
  command.commandType = commandType;
  command.pulseLen = pulseLen;
  command.totalTime = (unsigned long)(seconds * 1000);
  Serial.println("Command:");
  Serial.println(groupType == NewGroup ? "NewGroup" : "WithPrevious");
  Serial.println(commandType);
  Serial.println(pulseLen);
  Serial.println(command.totalTime);
  commandQueue.push (command);
}

void rotateWrist (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[5], servoMaxs[5]);
  move (5, pulseLen, seconds, groupType);
}

void bendWrist (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[4], servoMaxs[4]);
  move (4, pulseLen, seconds, groupType);
}

void rotateForeArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[3], servoMaxs[3]);
  move (3, pulseLen, seconds, groupType);
}

void bendForeArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[2], servoMaxs[2]);
  move (2, pulseLen, seconds, groupType);
}

void bendUpperArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[1], servoMaxs[1]);
  move (1, pulseLen, seconds, groupType);
}

void rotateRobot (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[0], servoMaxs[0]);
  move (0, pulseLen, seconds, groupType);
}

void pause (double seconds)
{
  move (PAUSE_COMMAND, 0, seconds, NewGroup);
}

void restoreHomePositions (double seconds)
{
  rotateRobot (0, seconds, NewGroup);
  bendUpperArm (0, seconds, WithPrevious);
  bendForeArm (0, seconds, WithPrevious);
  rotateForeArm (0, seconds, WithPrevious);
  bendWrist (0, seconds, WithPrevious);
  rotateWrist (0, seconds, WithPrevious);

}

//This is where the program goes!

void program ()
{
    //Available commands
  /*rotateWrist (where, seconds, groupType)
  bendWrist (where, seconds, groupType)
  rotateForeArm (where, seconds, groupType)
  bendForeArm (where, seconds, groupType)
  bendUpperArm (where, seconds, groupType)
  rotateRobot (where, seconds, groupType)
  pause (seconds)*/

  //example 1 -- rotates the wrist servo 100% over 2 seconds,
  //starting a new transition group.
  rotateWrist (100, 2);
  //example 2 -- bends the upper arm and the forearm at the same time
  //moving both 45% over 1.5 seconds.
  bendUpperArm (45, 1.5);
  bendForeArm (45, 1.5, WithPrevious);
  bendForeArm(45, 1.7, WithPrevious);

}

  //To start a new group, the groupType should be either NewGroup or left blank
  //Any call after that set to WithPrevious will start the transition at the
  //same time as the first transition in the group.
  //As soon as a new call is made with a NewGroup groupType, a new transition group is m
// End of your program

```

# Answer
I'm not familiar with the breadboard in your images. You didn't mention if you're familiar with how to use a breadboard and from what I can see I'm not even sure why its being used. It looks to me like you could just connect the jumper wires directly to the pins on the Arduino.

Was the Arduino ever unplugged from the breadboard after it was known to work properly?

Due to the angle of the photo it is hard to see which pins the wires are connected to. Can you identify which Arduino pins the six wires are connected to?
> 1 votes

# Answer
Please consider the following to assist in your understanding of the Arduino and of the servo operation. I recently "instructed" a summer camp of teens to construct the MeArm robot arm, using inexpensive servos and an Arduino.

The servos you have will operate without the servo driver, enabling you to isolate the problem. Consider to connect the signal wire for each servo to an assigned pin on the Arduino and test each servo with the built-in Sweep sketch. Your off-board power for the servos should share the ground with the Arduino, while the +V would connect to the power lead for the breadboard and hence to the servos.

Pins 6, 9, 10, 11 are PWM capable and you can modify in the Sweep sketch to operate each one independently as a way of testing the base "kit."

The code for Sweep is simplistic, while the servo driver has a good bit of "middle-man" calculations to accomplish more refined control.

Example from the summer camp:

\[in setup\] claw.attach(9); inout.attach(10); updown.attach(11); rightleft.attach(6);

\[in loop\] \- the following was placed in a for-loop: claw.write(pos);

... and more code including delays and limits to pos to prevent servo chatter/slam.

This will likely show you that your servos are working (or not) and enable a better understanding of the basics, while perhaps increasing your chances of understanding the more complex and flexible servo board library of code.
> 1 votes

---
Tags: arduino-nano, adafruit, robotics, wires
---


# Question
Title: Uploading .hex to ATTiny13 using Arduino
I would like to upload a .hex to ATTiny13V (or '13A) using Arduino Uno R3. I think I know everything to do, but ATTiny13 ISP support and Arduino IDE is a bit search-and-find, and I have some grey-areas in my understanding of how this all works together.

I got here by:

-Finding an Instructable that did something I liked, and there's a ATTiny13V used, a .hex to upload, and C source if I want to modify the source. Right now I do not need to modify the source, the available .hex is fine.

-I then looked for a way to have AVR programing from OS X. This seems a little problem, many AVR programmer hardware work great under Windows but seem to have mixed results under OS X. I saw Arduino could be used for this under OS X.

-I looked on local craigslist for Arduino, someone was selling a Uno R3 with some extras for a great price, and here we are. And now I have a lot more projects I wish to complete!

I am using Arduino 1.6.10 (from the .cc not the .org).

I read on stackexchange and other places that smeezekitty's core13 works for the ATTiny13. elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/

That's great, but: If I am not using any of the Arduino-specific commands, I don't think I need the bootloader, correct? I think it is not really a bootloader but builds support for some of the Arduino-specific higher-level commands used by sketch files.

Do I even need the ATTiny13 core files if I hook the pins up properly between the '13 on a breadboard and the Arduino (as per here: https://create.arduino.cc/projecthub/arjun/programming-attiny85-with-arduino-uno-afb829 ).

I really do not understand what the Arduino IDE/bootloader is doing for me as an abstraction layer. Do I need the bootloader if I'm not using any of the higher-level Arduino-specific commands on the chip? HOw about the core files for ATTinyanything vs specifically ATTiny13?

The hex file and C source I will be using are here: http://www.instructables.com/id/Programmable-LED/ My nextstep will be to modify the source. The C source looks like it references some AVR-specific header files. I see that the ArduinoIDE uses avrdude so maybe things will compile anyway?

I feel like I'm close but not 100% in my understanding of what I need to do, with the tools I have on hand.

Thanks for your help- I am not above a step-by-step.

Main question 1: I have a .hex file, an Arduino and IDE 1.6.10, OS X, and breadboard and useful components. What do I need to do to put the hex on this ATTiny13?

Main question 2: Jumping-off points for taking the C source I linked, tweaking it a bit, building a hex, and uploading that. I am not against moving it to a sketch if I have to, but it would be good for me to learn how this works before I mode to the IDE.

I have a small software background, am comfortable taking that C source and making changes and compiling (assuming I can find the needed .h files), but this is my first time working with any multiprocessors.

# Answer
> 1 votes
Your computer cannot talk directly to the ATtiny. You need some piece of interfacing hardware between them. This is called an ICSP (or ISP) programmer. You also need software to drive the programmer, typically avrdude.

If you do not have a programmer, you can buy one (I had success with some very cheap USBASPs), or you can program an Arduino Uno to behave like an ISP programmer. You do this by uploading into the Arduino a program called ArduinoISP, like explained in the tutorial Using an Arduino as an AVR ISP (In-System Programmer). You will typically use the Arduino IDE and the Arduino core for the Uno to compile and load ArduinoISP into your Uno. Once this is done, you can use the Arduino as a programmer and burn your .hex into your ATtiny.

If you want to compile your own programs for the ATtiny, you will need the avr-gcc compiler and the avr-libc. These are bundled with the Arduino IDE, so you already have them. You will need an Arduino core for the ATtiny *only* if you want to use the Arduino APIs and libraries. Otherwise you can write plain C programs with noting else than the avr-libc and avr-gcc.

**Edit**: To compile a plain C program, you can type something like this:

```
avr-gcc -mmcu=attiny13a -DF_CPU=1200000 -Os -Wall -Wextra flickled.c -o flickled.elf
avr-objcopy -O ihex flickled.elf flickled.hex

```

This assumes your source file is called `flickled.c` and your ATtiny runs at 1.2 MHz.

---
Tags: avr, attiny13
---


# Question
Title: Pneumatic cylinders with sensors with Arduino Uno
I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended). I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!

```
// Constants for pneumatic valves
   const int dvere = 2;
   const int davkovani = 3;
   const int lisovani = 4;
   const int vyhazovani = 5;
// ----------------------------------------
// Constants for sensors
   const int vyhazovaniZasunute = 6;
   const int vyhazovaniVysunute = 7;
   const int lisovaniVysunute = 8;
   const int lisovaniZasunute = 9;
   const int dvereZasunute = 10;
   const int dvereVysunute = 11;
   const int davkovaniVysunute = 12;
   const int davkovaniZasunute = 13;

void setup() {
  // Pneumatic cylinders set as output
  pinMode(dvere, OUTPUT);
  pinMode(davkovani, OUTPUT);
  pinMode(lisovani, OUTPUT);
  pinMode(vyhazovani, OUTPUT);

  // Sensors set as input
  pinMode(vyhazovaniZasunute, INPUT);
  pinMode(vyhazovaniVysunute, INPUT);
  pinMode(lisovaniVysunute, INPUT);
  pinMode(lisovaniZasunute, INPUT);
  pinMode(dvereZasunute, INPUT);
  pinMode(dvereVysunute, INPUT);
  pinMode(davkovaniVysunute, INPUT);
  pinMode(davkovaniZasunute, INPUT);

  // Set pneumatic cylinders as they are retracted
  digitalWrite(dvere, HIGH);
  digitalWrite(davkovani, HIGH);
  digitalWrite(lisovani, HIGH);
  digitalWrite(vyhazovani, HIGH);
}

void loop() {

  if(digitalRead(dvereZasunute) == HIGH)
  {
      digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
      delay(3000);
      digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
  {
      digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
  {
      digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
  }

  // sensors - HIGH - light on, LOW - light off,
  // pneumatic cylinders - HIGH - retracted, LOW - extended.
}

```

# Answer
```
void loop() {

...

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

...
}

```

If the condition is met, then `davkovani` is going to be LOW 99.999% of the time. It will only briefly go HIGH, as there is no delay there. The loop will iterate and set it LOW again. So it may seem to be "not working" whereas the problem is that it "works" very briefly.
> 1 votes

# Answer
Your code's variable names must be meaningful. You mention "2 magnetic sensors (when the pneumatic cylinder is retracted and extended)"-I guess it is solenoid valve. I hope I don't guess wrongly. This help us to understand your code. Otherwise, do you have any procedure diagram-it is like square and prismatic shape to illustrate your programing and its sequence.
> 0 votes

# Answer
Hi~ The synchronized method is below. The function millis() you can refer Arduino.org. It is a function to show you current time. Here I use it to create a time interval to run synchronization.

Declaration the variables are below:

```
/* Declaration time interval variables for synchronizing pneumaticValve1 and pneumaticValve2. The interval is 1000ms.  */
long perviousTimepneumaticValve1 = 0;
long perviousTimepneumaticValve2 = 0;
long previousTimeLocal = 0;
long interval = 1000;

```

The loop() function is below:

```
void loop() {
checkPneumaticValve1();
checkPneumaticValve2();
}

void checkPneumaticValve1() {
  if (millis()-previousTimeLocal>interval) {
    printPneumaticValve1();
    previousTimeLocal=millis();
   }
 }

void printPneumaticValve1() {
     //Here write your code for PneumaticValve1
   }

void checkPneumaticValve2() {
   if (millis() - previousTimeLocal > interval) {
     printPneumaticValve2();
     previousTimeLocal=millis();
   }
  }

void printPneumaticValve2() {
  //Here write your code for PneumaticValve2
  }

```
> 0 votes

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


# Question
Title: How to insert a power button on Arduino Nano
I've an Arduino Nano to which a Micro Servo 9g is connected. The Arduino board and consequently the servo are powered by a USB powerbank connected to the board with a USB mini cable.

My question is: Is there a way to insert a power switch so I can turn on/off the board without plug/unplug the USB (that now is the way I use) ? I was thinking to cut the USB cable and work with the positive of it but if someone has an alternative or any tips I'd really appreciate it. Thanks!

EDIT: If is needed I could make a wiring diagram.

# Answer
Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.

Another alternative would be to put the microcontroler in sleep mode and have it use very little power.
> 1 votes

# Answer
As Gerben said, you can buy a cable with a switch built in.
> 0 votes

---
Tags: power, arduino-nano
---


title: EthernetUdp2 does not name a type

text:
# Question
Title: EthernetUdp2 does not name a type
I'm using arduino Ethernet shield 2 form arduino.org and the arduino IDE 1.7.10 also from arduino.org the code is :

```
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUdp2 udp;
void setup() {
  // put your setup code here, to run once:

}

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

}

```

and it is giving the following Error :

```
Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

```

after Enabling Show verbose output I got :

```
Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

Build options changed, rebuilding all

Using library Ethernet2 in folder: C:\Program Files\ArduinoOrg\libraries\Ethernet2

Using library SPI in folder: C:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI

C:\Program Files\ArduinoOrg/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\cores\arduino -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\variants\standard -IC:\Program Files\ArduinoOrg\libraries\Ethernet2\src -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp -o C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp.o

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

```

any Help please

These libraries came with the IDE and were not added by me and all the includes were added automatically after using Sketch --\> Import Library --\> Ethernet2

# Answer
The error you see, `'EthernetUdp2' does not name a type`, means exactly that - there is no type `EthernetUdp2` defined.

If you look at the source of EthernetUdp2.h, you'll see that the class declaration is `EthernetUDP`. See:

```
class EthernetUDP : public UDP {
    private:
        // Private members...
    public:
        EthernetUDP();  // Constructor

      // Public members...

};

```

`class EthernetUDP : public UDP` defines a class called `EthernetUDP` that inherets from the base class `UDP`. The constructor is what gets called when you instantiate a new object of type `EthernetUDP`.

Replace the line `EthernetUdp2 udp;` in your code with `EthernetUDP udp;` and it should work because the types will match. For reference:

```
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUDP udp; // <---- This works

void setup() {
  // put your setup code here, to run once:

}

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

}

```
> 1 votes

# Answer
As it was answered above by Cheirbriados, the library is `EthernetUdp.h` not `EthernetUdp2.h`. I'll post you an example code, but you can also analyze it by yourself, by going on tab Examples of the Arduino IDE and choosing Ethernet -\> UDPSendReceiveString:

```
#include <SPI.h>         // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  //buffer to hold incoming packet,
char  ReplyBuffer[] = "acknowledged";       // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

```
> -1 votes

---
Tags: ethernet
---


title: Minimal Arduino using ATmega32U4

text:
# Question
Title: Minimal Arduino using ATmega32U4
I am a newbie and I would like to build my own minimalistic ATmega32U4 based arduino compatible board. Can anyone please tell me which parts resistors/capacitors (and maybe one status led) I need to connect it over usb to my computer? Thanks in advance.

# Answer
Several Arduinos and Arduino-compatible boards use the ATmega32U4. Many of them have published open-source plans that show exactly what components are used and how they are connected. They may not be the absolute minimal number of components, but it seems clear that you don't need *more* components than a known-working board:

* 1 ATmega32u4
* 1 16 MHz crystal
* 2 22pF ceramic caps (for crystal)
* 1 uF decoupling cap
* 1 pushbutton
* 1 10 KOhm pull-up resistor (for pushbutton)
* 1 LED
* 1 220 Ohm resistor (for LED)
* 1 USB socket
* 2 22 Ohm resistors (between USB socket and ATmega32u4)

Alas, there are two unnecessarily difficult hurdles between newbies and getting a new ATmega32u4 device connected over USB to a computer:

* The ATmega32u4 and nearly every other device that communicates over USB is only available in SMT packages with pins at 0.8 mm pitch or even closer together. Most people find packages with pins at 2.54 mm pitch easier to handle and plug into a breadboard.
* Installing a bootloader into any new processor chip is often tricky.

As Russel already pointed out, you can save a lot of time by starting out with an Arduino or Arduino-compatible board that already has the chip soldered on and the bootloader programmed in, bypassing the above unnecessarily difficult hurdles.

A few Arduinos and Arduino-compatibles (with links to schematics, etc.) that use the ATmega32u4:
> 4 votes

# Answer
Building your own may be worthwhile from a learning point of view, but makes minimal sense otherwise. You can buy Arduino clones (legal) from China for under $US5 each - good enough quality, assembled, working.
You cannot build one for that.

A DIY minimalist Arduino requires a running processor - see datasheet for the processor of choice as Ignacio says.Probably decoupling capacitors and maybe one or two resistors and maybe 1 or 2 small capacitors. If you cannot derive the needed information from a datasheet you do not know enough to sensibly do it by yourself. There are many on-web ~= minimalist implementations to copy.

If you want onboard USB you'd usually use a USB-serial converter but this can be done by "bit bashing" if you truly want a minimalist implementation\>

BUT - just buy one and use the large amount of time gained to learn related things of more immediate use.
> 2 votes

---
Tags: atmega32u4
---


title: Help with usbasp pinout

text:
# Question
Title: Help with usbasp pinout
I am having trouble figuring out the pinout of my 6 - pin USBasp Chinese clone that I got off eBay. **BEFORE YOU TELL ME TO LOOK AT THE PINOUT DIAGRAMS,** I can tell you that my version of the usbasp has no way of telling which way is up and which ways is down. Images:

# Answer
Look at the following pinout diagram (from telecnatron.com):

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header. The header shell will have a triangle marking pin 1. Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell). Each socket on the cable also will have a triangle marking pin 1.
> 2 votes

---
Tags: usbasp
---


# Question
Title: How to purge incoming Xbee packets from the buffer?
I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.

My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:

```
void burnSerial(void) {
  while (xbee.readPacket(20)) {
    xbee.getResponse().getRx16Response(rx16);
  } //read all available responses
    // only do this when not in a constant stream of responses or it may hang.

  while (Serial.available()) { Serial.read(); }
  //burn whatever may be in serial buffer
}

```

But this doesn't work. The next time I call `xbee.readPacket()`, I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?

# Answer
It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets *until* you find the confirmation and *then* you return from the function or do whatever else you want to do. There is no need for a separate `burnSerial()` function, nor should you blindly discard data. So basically, the sequence of operations should be:

* Send the command
* Read packets until you find the 'confirmation' identification marker
* Return or exit

This assumes that your transmitter only sends confirmation *after* it has halted the stream.
> 1 votes

---
Tags: xbee
---


# Question
Title: digitalPin giving lower voltage than Vcc
I am using an ATTINY88 for a project that requires to turn on an LED. Right now I am using pin PA1(ADC7/PCINT25). I noted, however, that when the pin is ON, I get about half the voltage that is connected to Vcc. I checked the voltage in other pins and they are close to Vcc. Will anyone know, what could be the reason for this?

I figure this pin has an internal resistor enable, but I am not certain.

# Answer
> 2 votes
You should connect the AVCC pin to VCC. From the datasheet (emphasis mine):

> AVCC is the supply voltage pin for the A/D converter **and a selection of I/O pins**. This pin should be externally connected to VCC **even if the ADC is not used**. \[...\]
>
> The following pins receive their supply voltage from AVCC: PC7, PC\[5:0\] and (in 32-lead pack- ages) **PA\[1:0\]**. All other I/O pins take their supply voltage from VCC.

---
Tags: voltage-level, attiny, resistor
---


# Question
Title: Strobe Frequency Calculation, how its done?
I'm using the Arduino sketch for LED stroboscope found here: http://mehax.blogspot.co.uk/2011/02/arduino-stroboscope.html.

Also below, I've inserted the loop part where this calculations are made:

```
void loop() {
// this while is a workaround for timer limitations using micros vs millis
sensorValue = analogRead(analogInPin);   //take potentiometer reading
hold = sensorValue*55 + 400;             //add some time to scale and for code execution
microsCurrent = micros();                // collect current time
if (microsCurrent > microsPrev + hold){  //set up timing loop
frequency = 1000000/(microsCurrent - microsPrev);
microsPrev = microsPrev + hold;            //set up millis for delay stuff

//set all 6 LEDs high (they were already plugged in)
digitalWrite(3,HIGH);
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
delayMicroseconds(.02*hold);  //leave LEDs on long enough to see

//set all LEDs low
digitalWrite(3,LOW);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);

if(millis() > millisSerial + 200){
  millisSerial=millis();    //reset timer
  holdFrequency = 1000000/hold;
  //do some math to find values
  rpm = frequency * 60;

```

I want to use this code in my project, but I don't really understand how this code calculates the stobing frequency.

So, I have following questions:

1. Why "hold" variable is calculated in the given way?
2. Why "microsCurrent", "microsPrev" and all other timings are executed?
3. How "frequency is calculated"?
4. What is "hold frequency" variable?

Sorry, I'm very new to Arduino and don't know much coding. Will appreciate very much your help!

# Answer
> Why "hold" variable is calculated in the given way?

`hold` stores the intended delay between the strobe pulses, i.e. the stroboscope period. It is computed as an affine function of the potentiometer cursor position because... well, that's the simplest way to make it user-adjustable. 400 µs is the shortest period that (according to the program author) one may reasonably want to set.

> Why "microsCurrent", "microsPrev" and all other timings are executed?

See the Blink Without Delay Arduino tutorial.

> How "frequency is calculated"?

From the code:

```
frequency = 1000000/(microsCurrent - microsPrev);

```

The frequency is the inverse of the period. The period is the time elapsed between this strobe and the previous one. The numerator is a conversion factor to get the frequency in hertz from a period in microseconds.

> What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period), disregarding the timing jitter that makes the actual instantaneous frequency slightly different.
> 1 votes

---
Tags: programming, c++, led, sketch, frequency
---