title: Arduino serial monitor first message

text:
# Question
Title: Arduino serial monitor first message
I'm connect arduino to my PC through serial monitor. Very common situation:

```
Serial.begin(9600);
delay(100);
Serial.print("Hello, World!");

```

But I always get an `¤ello, World!`. How can I get the first symbol straight? I've tried on both unix & windows, mega & uno. I've also tried `println`, but with no happiness

# Answer
See the following article:

http://www.arduino.cc/en/Main/ArduinoBoardNano

See the section at the bottom called:

Automatic (Software) Reset

Basically, one has to delay for 1 second (at least) after initializing the serial port before you can read data. It seems that the Arduino makes an assumption that after the serial port is initialized, what may happen next is a request to load a program. As such, it looks for a period of time (I guess up to a second) for a string of magic characters that indicate a program load. If it doesn't find those, then it starts to behave as you would expect ... but only after it times out looking for a program load.
> 1 votes

# Answer
I'd have to be pretty quick to connect my serial monitor to see immediate terminal output from my program, if that output uses the same USB I used to load the program. You can test this by resetting the Arduino so it will repeat the output and see if you get a clear message this time. So I leave a couple of seconds' delay in the code to let the slow human catch up. Most of my devices announce their name and code-version on the serial I/O and flash a quick "I'm here" on the LED (if I chose to attach one) when they first wake up:

```
const char IdString[] = "Hello.cpp: $Revision: 1.3 $";

void setup(void)
{
   Serial.begin(57600);            // open serial port

   // Identify to the terminal
   delay(2000);
   Serial.println(IdString);       // hello (terminal)

   // Init LED pin
   pinMode(LED_PIN, OUTPUT);
   digitalWrite(LED_PIN, LOW);

   nblink(4);                      // hello (LED)
   ...

```
> 0 votes

# Answer
This is more a wild guess than a real answer... Assuming your terminal is using a character set more or less like ISO-8859-1 or Windows-1252, then you are receiving 0xA4 when you expect 0x48. My guess is that the very first start bit got lost somehow.

Here are the serial port waveforms corresponding to the expected and received bytes. ‘S’ and ‘T’ are the start bit and stop bit respectively. The data bits are sent least-significant first. The idle state is HIGH:

• ‘H’ = 0x48 = 0b01001000

```
────┐               ┌───┐       ┌───┐   ┌──────
    │ S   0   0   0 │ 1 │ 0   0 │ 1 │ 0 │ T
    └───────────────┘   └───────┘   └───┘

```

• ‘¤’ = 0xA4 = 0b10100100

```
────┐           ┌───┐       ┌───┐   ┌──────────
    │ S   0   0 │ 1 │ 0   0 │ 1 │ 0 │ 1   T
    └───────────┘   └───────┘   └───┘

```

You can see that, if you remove the start bit from the first waveform, you get exactly the second one. I do not know what may be the cause of this though.
> 0 votes

---
Tags: serial
---


# Question
Title: Analog INPUT_PULLUP for resistive sensors?
Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between *Ax* and *GND*. Software is the same, except declaring *Ax* as INPUT\_PULLUP instead of INPUT.

# Answer
> 1 votes
> Can you use the internal pull-up on an ADC pin?

Yes.

> Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.

Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the `DIDR0` and `DIDR1` registers appropriately.

---
Tags: analogread, photoresistor
---


# Question
Title: Programmed 5 Volt output to power a relay
I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.

Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives? Thanks.

# Answer
> 1 votes
Your concern for the output capability of the pin should be its current sourcing or sinking capability, not its voltage. Arduino pins typically have a limit of 40ma per pin and a total maximum of 200ma. This is for the Atmega328p (you didn't say which Arduino you're using. You'll need to drive motors or relays or anything else with a substantial current requirement with a driver circuit powered independently of the Arduino itself. That can be with a shield made for the purpose or a circuit you design and build into your project. Motors and relays in particular need snubber diodes to protect the driving circuits from inductive "kickback" or spikes generated in their coils.

---
Tags: voltage-level
---


# Question
Title: Assembling a float from an array of bytes
I would like to convert an array of bytes, received from serial, to a float.

Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function

```
public static byte [] float2Bytes(float value)
    {
        return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
    }

```

When bytes arrive, they are stored in an array and the assembled.

```
hiBytew1 = bufferBytes[9];
//Serial.println(hiBytew1);
loBytew1 = bufferBytes[10];
//Serial.println(loBytew1);
hiBytew2 = bufferBytes[11];
//Serial.println(hiBytew2);
loBytew2 = bufferBytes[12];
//Serial.println(loBytew2);
float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

```

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

# Answer
> 3 votes
Just cast the pointer.

```
float conAck = *((float*)(bufferBytes + 9));

```

---
Tags: serial, arduino-mega, float
---


title: Reading tiny voltage changes

text:
# Question
Title: Reading tiny voltage changes
I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.

But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).

Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?

Thank you,

Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659 Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

# Answer
> 3 votes
You could try using `analogReference(INTERNAL);`, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.

# Answer
> 1 votes
It is reasonable to use `analogReference(INTERNAL);`, as suggested by Alexander M, to set the range of the ADC to 1.1 V.

Another alternative is to use two resistors to make a voltage divider, to make an external reference of 1 V (min.) at the AREF pin, and then use `analogReference(EXTERNAL);`, but the Arduino's supply voltage is likely to be noisier than the internal reference.

Regarding tiggun's suggestion about grounding the V- pin, it isn't clear to me that the mpx12DP will function correctly with V- and ground connected together.

In any case, you can use two or three of the op amps in the four-op-amp LM324 package to make a differential amplifier or an instrumentation amplifier. See figures 38 and 39 on page 20 of the LMx24 datasheet mentioned in the question. Figure 38 shows a differential amplifier; you could, for example, replace R3 with a 50KΩ resistor and R4 with a 1MΩ resistor to get a voltage scaleup of about 21, via the formula shown: Vₒ = (1 + R4/R3)·(V₂-V₁). Alternately, you can use a small variable resistor as in figure 39 to make a variable-gain instrumentation amplifier.

# Answer
> 0 votes
Your sensor has differential output, with a voltage difference between the Vout+ and Vout- being the measurement. The span of this difference is 0 to 55mV. The reason the sensor is wired this way is to reduce noise. To amplify this type of output you would need a differential output amplifier which is more complicated than a single op amp.

However, you can also just wire the Vout- from the sensor to ground, and then use the sensor as a single-ended output from 0 to 55mV (noise might be a problem). If you do this, you can then amplify Vout+ with your LM324 op-amp as described on page 13 of the LM324 datasheet with a non-inverting amplifier. By setting the ratio of R2/R1 to 60, you would get up to 55mV\*80 = 4.4V which is pretty good.

The op amp needs some voltage headroom, so if you are using 5V supply for it, don't set the amplified voltage max to 5V.

edit: I don't think you need much headroom and 4.4V will give you better resolution than 3.3V

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


# Question
Title: Why the bootloader burn on ATmega328 rather than Atmega16U2 in Arduino Uno
I have been researching about the reason why we have a second MCU in arduino UNO for a while now. finally i understood that its been use as USB to serial converter. the question that really bug me now, why is the boot-loader is burn on the main ATmega328 not Atmega16U2 ?

# Answer
> 2 votes
The purpose of the bootloader is to get the firmware through the serial port and burn it into the flash. The 16U2 has no access to the 328's flash. The job has to be done in the 328 itself.

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


title: What is GND on board?

text:
# Question
Title: What is GND on board?
I've looked in several places, and so far can not understand to want to be the GND who is on the board.

There is this documented anywhere?

# Answer
It is the 0V reference for everything else, as well as the power supply return.

"Ground (electricity)" on Wikipedia
> 2 votes

---
Tags: pins
---


# Question
Title: How to use an external clock with the Due timer?
I want to use an external clock signal as an interrupt for the Due timer. How do I do that? I could not find any info on this on the net.

# Answer
Everything you need to know is in the SAM3X datasheet:

http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A\_Datasheet.pdf

However, as Atmel's datasheets are some of the most cryptic ones around, you'll need to spend quite some time deciphering it.

There's an entire section just on the timers. It tells you all about how they work, however, relating that to which registers you need to set to get it to do that is not clear (as is normal for Atmel) since the registers are listed elsewhere in that section with no real relationship between them.
> 1 votes

---
Tags: arduino-due
---


# Question
Title: Handle reading timing in Python using pySerial
I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every **5 seconds**.

From Arduino I could do,

```
Serial.println(value);
delay(5000); // should I wait here?

```

Inside Python script I could do,

```
import serial
import time

arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?

while True and arduino.isOpen():

    try:
        value = arduino.readline().strip()
        print value

        time.sleep(5) # should I wait here?

    except KeyboardInterrupt:
        print "\nClosing..."
        arduino.close()

```

EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer. I've found out that to solve that I should add `arduino.flushInput()` just after opening the port.

# Answer
The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.

## Arduino `delay`s

You don't need to deal with the timing delay in python if the Arduino is `delay`ing. According to the documentation `readline` will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.

Note that `readline` will block your program from doing anything else while it waits. As such, It is pretty useful to explore python `threading` when you are writing a program which collects data over a serial stream unless the program is *only* collecting data.

## Python `sleep`s

If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each `loop`, and for the python script to only read the data every 5 seconds. In this case you could have python `sleep` and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using `sleep` by using a `timer` object to periodically call a function that `open`s the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream.
> 3 votes

---
Tags: python
---


title: Sketch Upload to LinkIt ONE Timeout

text:
# Question
Title: Sketch Upload to LinkIt ONE Timeout
I've just bought a new LinkIt ONE IoT prototyping board, and I'm having trouble getting started with it.

I'm working on a mac. I've installed the LinkIt ONE SDK onto my Arduino IDE as specified in the instructions here: http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd

When I go to upload my first sketch to my board, the sketch compiles and goes through uploading, but before it uploads, it stops uploading and the Arduino IDE perpetually tells me "Uploading...". When I look at the console below, it's telling me this:

```
[txd] AT

[txd] AT

[medrv]: Time out call back

[error] time out
[medrv]: Kill timer, event is AT_TIMEOUT

```

I've read some forums about an issue similar to this on the MediaTek website, but they don't help with the issue on the Mac. The ability to use LinkIt ONE on a Mac is new only this month, so I believe if we come up with a fix for this issue, it will help lots of people in the future who have this similar problem.

# Answer
*Disclaimer: I do not have access to one of these devices to test this on.*

Section 3.4.1 of LinkIt's developer's guide (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The `[txd]` report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

> If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:
>
> 1. Extract the content of the zip file available in LinkIt ONE SDK software’s **Driver** folder (see 2.3.2, “Installing LinkIt ONE SDK”) named `MacOS_USB_COM_Driver_BM_xxx.xx.x.zip`.
> 2. Run the installation package (`BMCDCACM_Driver_v115.05.0.mpkg`) and click **Next** to install it.
> 3. Wait until driver installation has finished, then restart your Mac.
>
> BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.
> 1 votes

---
Tags: bluetooth, arduino-ide, wifi, gps
---


# Question
Title: Malloc with Objects in Arduino libraries
My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:

C++ & the AVR

I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:

```
class Container
{
std::vector<otherObjectType> otherObjects;
};

```

which obviously does not work in the arduino without the C++ standard library.

My next choice would be to create a dynamic array using new, ie

```
otherObjects = new otherObjectType[3]
{
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    }
};

```

But this does not work as well, since new is not supported...

finally I could try to use malloc as laid out here, but that also wont work without new.

I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.

# Answer
> 1 votes
`new` actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.

Both of these work for me:

```
namespace{ //namespace to deal with .ino preprocessor bug
    class foo{
    public:
        int bar;
        foo(int a){
            bar = a;
        }
    };
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};

//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);

```

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.

Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.

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


# Question
Title: Flash a .hex to an ATtiny45 with Arduino
I'm trying to upload a hex file to an ATtiny45 with an Arduino. I uploaded the Arduino ISP sketch to my board. I connected the ATtiny as shown below:

Then I go to CMD and type:

```
avrdude -c avrisp -p t45 -b 19200 -P COM6 -U flash:w:main.hex:i

```

And it gives me this error:

```
Please define PAGEL and BS2 signals for ATtiny45!

```

I double checked the connections and i tried to uplad a bootloader with Arduino IDE as written in this article: Programming Hex-code on an Attiny85 with the Arduino. I can uplad sketches with ArduinoIDE with no error.

# Answer
Googling the error gives this tutorial. Towards the bottom of the page they say

> You’ll probably get the following message, but don’t worry, the upload should have worked anyway:
>
> *avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85*

So it seems this can be ignored and the part has been programmed!
> 2 votes

---
Tags: flash, attiny, sketch
---


# Question
Title: How can I run multiple programs on an Arduino?
I'm trying to get students to experiment with Arduino. However, due to a lack of boards, two teams of students will collaborate on each board. They will push their own code (independent from each other) and use half the pins.

The "hardware" part isn't really a concern: students will push their sketches on a server that uploads them on the board, or something like that.

What I'm worried about is the software part. **How can I allow two sketches to run on the same board**, and **allow the user to upload sketches without resetting the board**?

---

As of my understanding, using the flash memory isn't an option, because the board must be reset before it can be written.

My first idea was to compile the students' C code into custom-made "assembly", and then push the assembly code to the board, which stores it into RAM and interprets it. However, my biggest problem would be implementing functions, I don't really have a clue of how I could do that. While common C functions could just be encoded in a fashion like `FUNC printf STRING %s VAR a` for `printf("%s", a)`, I don't know how to encode user-defined functions. Besides, I don't even think the RAM is sufficient for running the client, storing two small programs, and running them.

Then, I thought about running the C code on the computer, but replacing `digitalWrite` with appropriate signals to the board. However, I'm worried about the performance of this, mostly when dealing with "high" speeds - say, using a custom-made library to print text on a LCD driver.

# Answer
In addition to the other answers, I have a few ideas:

1.) Instead of doing variable prefixes, have them wrap all of their code inside a namespace! Please note that you can't wrap "setup" or "loop" in that namespace. Example

```
setup() {
  if(conditionIsTrue) {
    aGroup::setup();
  } else {
    bGroup::setup();
  }
}

loop() {
  if(conditionIsTrue) {
    aGroup::loop();
  } else {
    bGroup::loop();
  }
}

namespace aGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

namespace bGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

```

2.)

Please note you'll have issues with a student tries to access an analog pin and doesn't prefix it with `A`. For example, if I wanted analog pin 5, I should do `analogRead(A5);`, ***not*** `analogRead(5);`. That could cause some major issues.
> 4 votes

# Answer
A little late, but I used a potentiometer as a switch to determine which "sketch" to run; in this case swapping LEDs on/off. I assume it can be applied to this instance, the students just have to share/divide pins and declare variables together at the top with comments. (I'm new at this, but I think a shift register (75HC595) could be used if you run out of pins). Thoughts?

EDIT: Potentiometers give a value of 0-1023. I split that up into 2, 3, and 4 separate sketches with no problems. You just have to change the IF/ELSEIFs to reflect how many sketches you want to run (512 for 2, 341 for 3, ~256 for 4, etc).

```
int sensorPin = 0;
int sensorValue = 0;
int ledPin1 = 4;
int ledPin2 = 8;

void setup() {

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {

  sensorValue = analogRead(sensorPin);

  if (sensorValue < 512)
{
    digitalWrite(ledPin1,HIGH);
    digitalWrite(ledPin2,LOW);
}

  else
{
    digitalWrite(ledPin2,HIGH);
    digitalWrite(ledPin1,LOW);
}
}

```
> 3 votes

# Answer
> How can I allow two sketches to run on the same board, and allow the user to upload sketches without resetting the board?

This is "easily" dealt with as long as you can enforce certain minimum disciplines.

Students must only use assigned pins.

Identifiers (functions, variables ...) defined by a group must always be unique to that group. This can be as simple as eg always starting with a group specific symbol or eg one group NEVER using a z in names and the other ALWAYS using Z etc. Annoying but easy.

Loop() contains calls to two non-terminating functions eg Group1() and Group2() All code for Group1 is in Group1() and ....

One digital pin is assigned for Giulio's use.
When GiuliosPin is low the system executes Group1() - and never exits it until restarted.
When GiuliosPin is high the system executes Group2() - and never exits it until restarted.

I uses a system very close to the Group1() / Group2() selection for my own purposes to allow multiple sketches to be compiled at once - but I use a constant which is set as I compile to choose which to run. My concern is the ability to test multiple code fragments.

---

Added:

After reading Mac's similar answer I see I missed mentioning Setup().
Code from both users can be merged into the same Setup() as the identifiers are unique.
Or the Setup() function for each Group can be carried out inside their unique Groupx() function with a "run once" function at the start of their code. This is a matter of programming discipline and not in any way hard per se.
> 2 votes

# Answer
There is no native multitasking on an Arduino. A few solutions have been suggested above, all of which depend on cooperative multitasking - each half has to play fair.

An alternative may be this:

Buy some AtTiny chips - e.g. AtTiny 24a; they are about $2-3 each. Buy some VeroBoard. Solder the AtTiny on to the board, so each verboard strip has 2 pins on it (not the other way, where each veroboard strip has half of the pins on it). Solder on some pins, cut the track between the pairs of pins, and cut the board to size. You should be able to get a working board, with 12 usable pins per board, and you'll be paying less than $5 per board in your local currency. Buy a USBISP, and hook up the pins, whenever you need to program them - I suggest using the FreeTronics programmer, like this one here: http://www.jaycar.com.au/productView.asp?ID=XC4237 \- you can solder 2 pins for the "slow clock" option - you'll need this. Optionally, you could make an adapter board which plugs into all of the relevant pins in one go, to program it. You should only need one of these. To figure out which wires to connect where, compare the top diagram on http://www.dz863.com/datasheet-8310956563-ATTINY24A-SSU\_8-bit-Microcontroller-With-2k-4k-Bytes-In-system-Programmable-Flash/ with https://www.olimex.com/Products/AVR/Programmers/AVR-ICSP/resources/AVR-ICSP.gif

You can power them with AA batteries or an external power supply - you could easily make one power supply that runs many boards. Check out the spec sheet for the voltage required - it varies, depending on the clock speed (default clock speed as described is 1 MHz, google "avr fuses" for how to set them to e.g. 8 MHz at no extra cost).
> 2 votes

# Answer
There is a solution. It requires some programming discipline from your students, but it is feasible.

1) Make sure each group uses different variable and function naming conventions (one starts all variable and functions with `a_` and the other group with `b_`). These functions will be written in separate include files.

2) In the `setup()` and in the `loop()` functions, you will call either `a_setup()` or `b_setup()`, and either `a_loop()` or `b_loop()`. Each of the group setup and loop functions will call their functions and use their variables as the groups want to, but they are not allowed to call variables/functions from the other group. Other resources can also be allocated by you in advance for each team.

3) During the `setup()` function, start by reading a specific input that you will either connect to GND or to 5V. Use the result of this reading to execute either one version of the software, or the other.

This is not elegant, but it gets two program into each Arduino.
> 0 votes

---
Tags: system-design, networking
---


title: 0-1 V input to 0-5 V Output

text:
# Question
Title: 0-1 V input to 0-5 V Output
We have an instrument that has analog output of 0-1 volts and we need to convert this to 0-5 volts. What is the best op amp to use for this and how should the resistors be set up? Any help would be greatly appreciated.

Thanks,

Paul

# Answer
> 5 votes
Since you used Arduino tag..., you don't need an opamp. Instead you can select ADC reference voltage on your arduino to 1.1V. This way you don't need any additional parts and you get the whole precision range.

```
analogReference(INTERNAL1V1);

```

http://www.arduino.cc/en/Reference/AnalogReference

---
Tags: analogread, hardware, analog-sampling, op-amp
---


# Question
Title: reversing DC motor rotation using TWO limit Switches Problem !! need help
I'd like to write a code for reversing DC motor rotation direction as follows:

1. Start the motor rotation clockwise (CW).
2. When reach Limit Switch (CW) → motor will stop for 5 sec.
3. after 5 sec. of stopping → the motor will rotate in counter clockwise direction(CCW).
4. When reach Limit Switch (CCW) → motor will stop for 5 sec.

and repeat point 1, 2, 3 and 4...

Actually I wrote a code for reversing the motor direction using **two** limit switches and it is working good. But when I added delay the motor did not stop using the limit Switches and continue to rotate... If any one can help... Here is my code for reversing the direction with out delay 5 sec. My limit SWs are connected on Normal Open.

```
int sw1, sw2, sw3;
const int LM1 = 0;
const int LM2 = 1;
const int LM3 = 6;
const int CW = 10;
const int CCW = 9;
const int Buzzer = 7;

void setup() {
  pinMode(LM1, INPUT);
  pinMode(LM2, INPUT);
  pinMode(LM3, INPUT);
  pinMode(CW, OUTPUT);
  pinMode(CCW, OUTPUT);
}

void loop(){
  sw3 = digitalRead(LM3);
  sw1 = digitalRead(LM1);
  sw2 = digitalRead(LM2);

  if (sw1 == LOW && sw2 == HIGH) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite(CCW, LOW);

      sw2 = digitalRead(LM2);
    } while (sw2 == HIGH);
  }
  else if (sw1 == HIGH && sw2 == LOW) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, LOW);// change the direction of rotation (UP Movement)
      digitalWrite(CCW, HIGH);

      sw1= digitalRead(LM1);
    } while (sw1 == HIGH);
  }
}

```

# Answer
Normally you use state machine for this kind of programming: you have a `state` variable that remembers what you are doing, and depending on the current state you decide what to do next. Below is an example with two states. I have embedded a few assumptions about the wiring of your motor and your switches, which may be wrong, so you have to check the code.

```
void loop() {
    static enum {MOVING_CW, MOVING_CCW} state;

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            delay(5000);
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            delay(5000);
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}

```

This will start in the `MOVING_CW` state, but you have to actually start the movement in `setup()`. It has the drawback of having long delay()s in the loop, which is undesirable if you have other tasks to perform. These delays can be removed by “remembering” that you are waiting as two extra states:

```
void loop() {
    static enum {MOVING_CW, MOVING_CCW, STOPPED_CW, STOPPED_CCW} state;
    static unsigned long time_stopped;
    unsigned long now = millis();

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            state = STOPPED_CW;
            time_stopped = now;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            state = STOPPED_CCW;
            time_stopped = now;
        }
        break;
    case STOPPED_CW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case STOPPED_CCW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}

```
> 2 votes

# Answer
Maybe the code with the 5 second delay is more usefull. Because you are telling us the code you now deliver is supposed to work?

Probably using delay(5000) will work?
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to connect a card reader (extracted from printer) to arduino uno
I'v got this USB/SD card/CompactFlash reader from an old DELL AIO 926 printer, it's a double sided PCB board and that's all i know about it. I tried to google it but couldn't find anything relevent, how can i tell what voltage it takes and what each wire does and how to interface it with arduino?

It seems to me that it has two sets of 4 wires (red/orange - black - yellow - white) and an extra blue wire, i'm guessing that the black is for GND, red/orange for VCC, yellow/white for SDA/XDA I2C serial bus data transfer, but no clue what the blue wire does, i could've tested this with arduino but i don't want to risk frying the board by using a wrong voltage. any help would be greately appreciated. thanks.

# Answer
I can pretty much categorically say you won't get it working.

I have a similar board here with the same SMSC (now owned by Microchip) chip on it.

The interface is USB plus some other signals. I have managed to identify the USB portion of the interface on mine, but not the other signals.

The SMSC chip has the option of using an external ROM chip to store its program, and Dell love to do that. So, it has a custom firmware which means it doesn't get recognized by my computer without Dell's specific drivers installed. So it's useless.

There's a very very slim chance you may get it working with a USB Host Shield, but unlikely - and at the end of the day, what's the point? It's just an SD card reader. Wire an SD card socket direct to the Arduino and save yourself both the headaches of trying to work it out and also the massive pointless expense in buying the hardware you'll need to do the interfacing.
> 1 votes

---
Tags: arduino-uno, usb, sd-card
---


title: Change input reference to 1 - 5 V

text:
# Question
Title: Change input reference to 1 - 5 V
I am using a sensor which delivers a 4 to 20 mA output. Converting this with a 250 Ohm resistor to ground I convert this to a 1 - 5 V output.

My question how can I change the 0V reference, so I can use the full spectrum I found a way to change the 5V reference (analogReference()). Is it possible to change the 0V reference of a input to 1V?

Any other solution to my problem is welcome as well! (As long as it doesn't involve I2C or anything which lowers my looptime drastically)

# Answer
The ADC is ground-referenced, and there's no way to change that. The question is if that's necessary. The ADC has a 10-bit resolution, that's good for 1024 different levels between 0 and 5 V. If you convert the 4-20mA with a 250 Ω resistor to a 1-5 V range you still can discriminate between more than 800 different values.

If that's not enough you can use a differential amplifier to subtract 1 V:

By choosing R3 = 1.25 R1 you convert the 0-4 V range to a 0-5 V range.
> 6 votes

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


# Question
Title: What is the difference between Accelerometer, Gyro, and Magnetometer Sensor?
I'm starting in the arduino world and I'm building an autonomous smart vehicle.

So, after some weeks building and adjusting the vehicle, I got to a point in this project that I want to log it's movements. Talking with a friend, he showed me an Gyro/Accel sensor and I really think that it would be an awesome upgrade to my vehicle

After reading some articles, I'm failing to understand the difference between an **Accelerometer Sensor**, a **Gyro Sensor** and a **Magnetometer Sensor**

So what is the main difference between those sensors?

# Answer
The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving.

The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.

The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.

Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.

The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.

Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.

Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.
> 5 votes

# Answer
The main difference is the way they operate and what they sense. In other words, they are all very very different things. Yet they can all measure motion in some way.

* An accelerometer senses both the gravitational pull of the earth and the inertia / momentum of the motion of the device
* A magnetometer senses the earth's magnetic field to get a compass heading.
* A gyroscope senses *changes* in twist and angle.

They can all give information about motion and attitude, but each has both benefits and drawbacks compared to the others. Some drift more than others, some are slower or lower resolution, etc.

So generally all three are used together to get the benefits of them all and, to some extent, negate the drawbacks of them.

For instance, a gyroscope isn't good at measuring inertia, but it is good at measuring changes in angles. But those changes in angles drift over time and you lose accuracy. A magnetometer is good at giving you an exact angle, but it takes longer to get an accurate result, and it's not good at fine changes in angle. So a magnetometer is used to correct the drift of the gyroscope, and an accelerometer is used to measure inertia.

So to sum up:

* Accelerometer for changes in speed
* Gyroscope for changes in angle
* Magnetometer to correct the gyroscope
> 4 votes

---
Tags: sensors, accelerometer, gyroscope, magnetometer
---


title: micro arduino and w5100

text:
# Question
Title: micro arduino and w5100
I would like to ask if it is possible and how to connect the following module http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH\_DefaultDomain\_0&hash=item3aab3dbff6

to the arduino micro

I found some pin layouts but only for Leonardo or Ethernet shield, Uno etc.

Also I've choosen this model because it can be programmed directly in arduino using Sockets API

# Answer
> 2 votes
While it would have been nice to see your research rather then having to spend some time finding this information myself, I did find this http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/ from what I can see this should be compatible to any arduino as long as it has 3 volt pin and 4 i/o pins. While the arduino micro doesn't have a 3v3 pin, as far as I know, that shouldn't be an issue as long as you can drop the voltage from the 5 volt pin, this module should work for you.

---
Tags: arduino-uno, ethernet, arduino-micro
---


# Question
Title: Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno
I've researched how to attach multiple buttons to a single analog input using a resistor network. Instructables has a good lesson on this: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/?ALLSTEPS

My requirement is that I need to attach an interrupt to buttons (ie the analog input) before reading the analog value, so that all the buttons can act as a trigger.

This works for voltages in the higher range, but not in the lower range (the trigger input waits for a RISING edge).

Can any one suggest a circuit that steps a \>0V+ to +5V input to a +5V output so that any button push would trigger the input?

Otherwise, does anyone have other suggestions on how to use triggers for each button?

# Answer
Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.

Connect the analog network to both the analog input and D6.

If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have *not* connected the voltage then configure the comparator to use the internal bandgap reference (`ACSR |= _BV(ACBG)`).

Enable the comparator interrupt and capture on a rising edge (`ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)`).

Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (`DIDR1 |= _BV(AIN0D)`, `DIDR1 |= _BV(AIN1D)`).

Write an ISR that does what you want on comparator trigger (`ISR(ANALOG_COMP_vect) { ... }`).

Now go back and read all that ***three more times*** until you understand it. As always, see the ATmega328P datasheet for details.
> 6 votes

# Answer
Considering the fact that from a *functional point of view*, you just want **to have more digital inputs, I would propose to use a `Parallel-In Serial-Out Expander`**, (e.g. `CD4021B` or `74HC165`).

This IC (i.e. `74HC165`) has 8 digital inputs, that can be 'shifted' and send to your Arduino using just 2 wires. Arduino has a built-in function for this (i.e. `shiftIn`) to read the input and to convert it to a byte.

If 8 inputs is not enough, then you can chain multiple IC to create 16, 24 ... digital inputs.

There is an official tutorial for the CD4021B.

I don't know if this is a requirement, but if you want to register **multiple key-presses at the same time**, then this is a really good strategy.
> 2 votes

# Answer
I really do not know your level of experience, so please, ignore this if not applicable; Most cases of a push button will not need an interrupt. It is a human pushing the button and so precise timing is no where close to needing an interrupt. You would only need an interrupt if you wanted to actually interrupt some looping code. And since timing (of a human by definition) is not that great, simply checking for a button press in your looping code will always be good enough. That being said, the common resistor networks you have read about will work adequately.

```
psuedo code;
void loop()
{
  int btn = analogRead(pin);
  if (btn > pin1Level)
  {
    if (btn > pin5level) DoPin5();
    else if (btn > pin3level) DoPin3();
    else DoPin1();
  }
  doOtherStuff();
}

```
> 0 votes

---
Tags: pins, interrupt, voltage-level, button
---


# Question
Title: If I have a group of Arduinos connected via I2C, can one Arduino cause the rest to freeze?
I have a group of four Arduino boards connected via I2C. One is the master, which sends and receives values from all of the others. I noticed that the Master will stop executing its loop if power is removed from one of the other Arduino boards.

Can one Arduino in a I2C group cause the rest to freeze? Is there a way to prevent this?

I am using one of the Arduino boards to connect to a server via network shield and I don't want the other Arduino boards to be effected if the networked Arduino freezes.

# Answer
There are a number of places in the standard Wire library where the code goes into a tight loop waiting for an interrupt to occur. If that is missed for some reason, it will loop indefinitely.

By removing power from one of your devices you may be introducing electrical conditions that prevent the I2C messages from being transmitted properly (possibly just noise). Alternatively the device may parasitically power up from the SDA/SCL data and then behave in unpredictable ways. It is probably unwise to do this.

There is an alternative I2C master library at http://dsscircuits.com/articles/arduino-i2c-master-library which does not hang (I believe it times out instead).
> 1 votes

# Answer
I can say from personal experience, I had a similar event. I had a logic analyzer hooked up and was using it. I got the code working the way I wanted. A day later when I tried it the code failed. Turned to be because I had not powered up the logic analyzer and it was still hooked up. If I unhooked it or powered it on everything worked fine. This was on an Netduino BTW, but it leads me to believe (not being an electronics person per se) that yes it very possible if some unexpected load is on the I2C bus.
> 0 votes

---
Tags: i2c, networking
---


# Question
Title: Fried two Arduino Nano's but works when powered
It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.

When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...

I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.

I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!

Does anyone know why it's doing this? What did I see smoking? Is it repairable?

# Answer
Judging by your list of observations:

* Cannot power through USB
* Can power from external source
* Can program through USB

it is most likely that the power feed from the USB to the +5V rail has been interrupted. There is only one component in that link - the diode D1 (an MBR0520). That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that. A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.

The diode is on the underside of the Micro and close examination may show a small crack in the surface of it. That is if it's still there. I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).
> 1 votes

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: I am having an issue reading a HIGH LOW signal from a pressure switch
I'm trying to read either high or low from a pressure switch, I do have a pulldown resistor attached but even if I plug in a wire with nothing on it i get a false high. I've changed pins, tried adding `INPUT_PULLUP` to the program but it it reads false.

The code i'm using is:

```
const int mainPump = 2;
const int prePump = 3;
const int idleValve = 4;
const int chemTankLow = 5;
const int chemTankHigh = 6;
int pressure = 8; //7 originally removed const
const int chemValve = A7;
const int mem2 = A6;
const int mem3 = A5;
const int mem4 = A4;
const int mem5 = A3;
int tankLow = 0;
int tankHigh = 0;
int pressureFault = 0;
int lpe = 0;
int maxlpe = 2;
unsigned long timer[10]; //number of timers needed
byte timerState[10]; //store timers
int goNoGo = 0;
int readVoltage = 0;
int var = 0;

void setup() {

  pinMode(idleValve, OUTPUT);
  pinMode(prePump, OUTPUT);
  pinMode(mainPump, OUTPUT);
  digitalWrite(mainPump, HIGH);
  pinMode(pressure, INPUT);   //removed _PULLUP after input
  pinMode(chemTankLow, INPUT);
  pinMode(chemTankHigh, INPUT);
  pinMode(chemValve, OUTPUT);
  pinMode(mem2, OUTPUT);
  pinMode(mem3, OUTPUT);
  pinMode(mem4, OUTPUT);
  pinMode(mem5, OUTPUT);

  digitalWrite(mem2, HIGH);
  digitalWrite(mem3, HIGH);
  digitalWrite(mem4, HIGH);
  digitalWrite(mem5, HIGH);
  digitalWrite(chemValve, HIGH);
  digitalWrite(idleValve, HIGH);
  digitalWrite(prePump, HIGH);
  digitalWrite(prePump, HIGH);
  digitalWrite(idleValve, HIGH);
}
void loop()
{

       tankLow = digitalRead(5);
   tankHigh = digitalRead(6);

  if (tankLow == LOW && tankHigh == LOW){ //start day tank refill
   digitalWrite(A7, LOW);
  }
  if (tankLow == HIGH && tankHigh == HIGH){
    digitalWrite(A7, HIGH);
  }
  static int state = 1; // initial state is 1, the "idle" state.
  static unsigned long ts;

  switch (state)
  {
    case 1:
    ts = millis();

  if (delayMilliSeconds(1, 6000)){//600000

  digitalWrite(prePump, LOW);

  goNoGo = digitalRead(mainPump);
  if (goNoGo == LOW) {

    digitalWrite(idleValve, HIGH);
  }
    else {
      digitalWrite(idleValve, LOW);
          digitalWrite(mem2, LOW);
    digitalWrite(mem3, LOW);
    digitalWrite(mem4, LOW);
    digitalWrite(mem5, LOW);
    }

        readVoltage= digitalRead(idleValve);
    if(readVoltage==LOW){

    delay(4000); // wait time motors to stablize
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (4.83 / 1023.0);

    if (voltage >= 2.00)
    {
      state = 2;
    }

    else {
      delay(56000); //on time for test
    //  if (delayMilliSeconds(2, 51994)){
    digitalWrite(mem2, HIGH);
    digitalWrite(mem3, HIGH);
    digitalWrite(mem4, HIGH);
    digitalWrite(mem5, HIGH);

     digitalWrite(idleValve, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(mainPump, HIGH);
    }
    }

}
//} for if timer
break;

    case 2:
       ts = millis();
      digitalWrite(mainPump, LOW);
      digitalWrite(idleValve, HIGH);
       digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);
        delay(20000);
        state = 3;

        break;

        case 3:

      digitalWrite(mainPump, LOW);
      digitalWrite(idleValve, HIGH);
       digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);

      pressureFault = digitalRead(pressure);
  if (pressureFault == HIGH){

    state = 4;
  }
   if (millis() - ts > 3600000){
    state = 5;
  }

   break;

   case 4:
   digitalWrite(mainPump, HIGH);
   digitalWrite(prePump, LOW);
   digitalWrite(idleValve, LOW);
      digitalWrite(mem2, LOW);
    digitalWrite(mem3, LOW);
    digitalWrite(mem4, LOW);
    digitalWrite(mem5, LOW);
    delay(3000);
    digitalWrite(mainPump, HIGH);
   digitalWrite(prePump, HIGH);
   digitalWrite(idleValve, HIGH);
      digitalWrite(mem2, HIGH);
    digitalWrite(mem3, HIGH);
    digitalWrite(mem4, HIGH);
    digitalWrite(mem5, HIGH);
    delay(600); //60000
    state = 1;

    break;

    case 5:
    ts = millis();
        digitalWrite(idleValve,LOW);
        digitalWrite(prePump,LOW);
         digitalWrite(mainPump, HIGH);
           delay(60000); //60000 for standard
           digitalWrite(mem2, LOW);
           delay(60000);
           digitalWrite(mem2, HIGH);
           digitalWrite(mem3, LOW);
           delay(60000);
           digitalWrite(mem3, HIGH);
           digitalWrite(mem4, LOW);
           delay(60000);
           digitalWrite(mem4, HIGH);
           digitalWrite(mem5, LOW);
           delay(60000);
           digitalWrite(mem5, HIGH);

           delay(1000);   // leave this time
         digitalWrite(idleValve, HIGH);
         digitalWrite(mainPump, LOW);
       state = 2;
         break;
         default:

         state = 1;

         break;

  } //switch
} //loop

int delayMilliSeconds(int timerNumber,unsigned long delaytime){
  unsigned long timeTaken;
  if (timerState[timerNumber]==0){    //If the timer has been reset (which means timer (state ==0) then save millis() to the same number timer,
    timer[timerNumber]=millis();
    timerState[timerNumber]=1;      //now we want mark this timer "not reset" so that next time through it doesn't get changed.
  }
  if (millis()> timer[timerNumber]){
    timeTaken=millis()+1-timer[timerNumber];    //here we see how much time has passed
  }
  else{
    timeTaken=millis()+2+(4294967295-timer[timerNumber]);    //if the timer rolled over (more than 48 days passed)then this line accounts for that
  }
  if (timeTaken>=delaytime) {          //here we make it easy to wrap the code we want to time in an "IF" statement, if not then it isn't and so doesn't get run.
     timerState[timerNumber]=0;  //once enough time has passed the timer is marked reset.
     return 1;                          //if enough time has passed the "IF" statement is true
  }
  else {                               //if enough time has not passed then the "if" statement will not be true.
    return 0;
  }

}

```

As for wiring it is as basic as it gets 3.3v pin off the arduino to a pressure switch and then back to the arduino . but i'm not even making it to the switch before i have an issue literally plug in a 3ft wire not connected to anything and it goes to case 4 I've tried setting the code up to go to case 4 if it detects a LOW but hasn't changed my issue.

# Answer
As a hint. Start by removing the stuff you added an just try to detect a grounding of your input pin (I'm assuming digitalRead(pressure) is the standard read the digital value of a pin and not some funky function you've written)

Use some code like this to test your hard ware

```
int    pressure;

void setup()
{
    Serial.begin(9600);  //Start a serial monitor to see the results
    pressure = 4;  // Assumes your pressure input is pin 4
                   // change if need be
    pinMode(pressure,INPUT_PULLUP);  //Sets put to input with pullup
    digitalWrite(pressure,HIGH);      //Activates pullup
}

void loop()
{
     if (digitalRead(pressure))
     {
          Serial.println("Pin is High");
     }
     else
     {
          Serial.println("Pin is low");
     }
     delay(1000);
  }

```

Now compile, upload and activate the serial monitor. Every second you will get the read of the pin on the monitor. See if grounding the pin is detected. If not, you may have popped the port.

BTW. 3 ft of wire will need some filtering and protection. That will pick up a lot of noise.

Cheers
> 1 votes

---
Tags: programming, sensors
---


# Question
Title: is any windows application available for accelerometer based computer mouse
I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

# Answer
...................................... ......................................
> 0 votes

---
Tags: arduino-uno, accelerometer
---


# Question
Title: is any windows application available for accelerometer based computer mouse
I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

# Answer
try "remotemouse.exe" its a open source application you can modify the codes according to your requirement
> 1 votes

---
Tags: accelerometer
---


# Question
Title: Android <-> HC-05 <-> Arduino communication issue
My project involves Android (Samsung Galaxy 2) to Arduino (Uno) communication via HC-05.

HC-05 is connected to Arduino on pins 10,11 using SoftwareSerial lib.

I got this setup running for a while and was satisfied by the outcome - my bi-directional communication worked fine.

**Issue:**

I made a change to the communication protocol and now messages sent from Android to Arduino get corrupted. It happens under particular circumstances - when Arduino writes (streams) packets of data to Android and, at the same time, monitors the input from Android for a particular message which signals the end of communication. This message, when read from SoftwareSerial buffer, gets corrupted. This corruption is not consistent - it corrupts the packet in (seemingly) random way.

I've already run many tests and am pretty sure that this message is not corrupted on the Android side.

**Questions:**

1. Is there anything about HC-05 or SoftwareSerial lib which prevents simultaneous bi-directional communication?
2. Can it be that input/output buffers interfere in some way?
3. How can I achieve reliable communication using the aforementioned HW and comm scheme?

P.S. I got pretty much code and am not sure what parts of it might be relevant to this issue. Will provide relevant parts per your request.

Thx

# Answer
> 3 votes
As mentioned by @alex.forencich, SoftwareSerial is not designed to support simultaneous bi-directional communication.

I found a link to AltSoftSerial library on Arduino site, and this lib seems to work properly in my setup.

To convert from SoftwareSerial to AltSoftSerial you need to change the pins that HC-05 is connected to (on Arduino Uno these are pins 8,9), and to make this minor change in the code:

```
//#include <SoftwareSerial.h>
//SoftwareSerial swSerial(10, 11);

#include <AltSoftSerial.h>
AltSoftSerial swSerial;

```

# Answer
> 1 votes
Another option is to use a separate chip to send and receive. An Attiny87 (picking a random example) has a UART and an SPI interface - it could receive the data via UART, send via SPI to the Arduino; then receive the data from the Arduino and send it via UART. Since the whole chain now has hardware support, you're going to have reliable communications. The data could be buffered on the AtTiny, and raise a signal to the Arduino to say when data is ready.

ATTiny chips are cut-down versions of the ATMega chips used on Arduinos, and they can be programmed over ISP. They can be had for a few dollars.

Yes, this is a lot of extra work.

# Answer
> 0 votes
Software serial ports are a hack and this is the result - random corruption, missed bytes, etc. The reason is that very precise timing is needed for both receive and transmit and it is very difficult to achieve this with the CPU, especially if you want to simultaneously receive and transmit. The problem is that the CPU has to either read the pin or update the pin at exactly the right moment, and the CPU can't do more than one thing at the same time. You can use interrupts, but it is still possible for the TX and the RX to conflict, and there is nothing you can do about it.

The solution is to either never run RX and TX at the same time, use a different serial protocol where this is not an issue (e.g. I2C), or use a hardware serial port. I would suggest using an Atmel XMEGA microcontroller - you can get these with 6 or more independent hardware serial ports.

# Answer
> 0 votes
An alternative to software serial is to use hardware serial.

You can use hardware serial (i.e. supported in hardware by the chip) using pins 0 & 1. You will NOT! be able to do serial communications (e.g. programming your arduino) at the same time - I always make sure I have EITHER usb OR bluetooth serial connected at any given time. USB for power is ok.

# Answer
> -1 votes
Hey thought I'd pitch in. I was having quite a few issues in trying to control an led using hc 05 from an android phone. I was using SoftwareSerial. It didn't work. The board is an arduino mega 2560. Finally, I got it. SoftwareSerial turns digital pins to tx and rx com pins. Make sure to use digital pins on the board to communicate when your using SoftwareSerial. Hope it helps...

---
Tags: bluetooth, android
---


# Question
Title: Serial communication not working between two Arduinos unless connected to computer
I have a robot with an Arduino Mega that gets data from a bluetooth module and sends it to an Arduino Leonardo to activate some functions. It all works amazing but only if the boards are connected to my computer. As soon as I disconnect them and power them from their own batteries, the serial communications seems to stop working. When I connect it to the PC again the communication between the Arduinos begins working.

Does anyone know why this is happening?

The Mega is powered by a 9V battery and the Leonardo by 4x AA (6V). On the Mega I use TX/RX(2) for communication with the BT module and TX/RX(3) for communication to the Leonardo.

# Answer
> 2 votes
Voltage, Electrical Potential, Potential Difference, Electric Tension - whatever you refer to it as - is the always measured *between two points*.

Generally of course we mean two points within one circuit, and most of the time we mean between something and the circuit's 0-Volt rail; it's implied whenever somebody quotes a voltage, unless they specifiy otherwise.

We always refer to the 0-Volt rail as 'ground', no doubt stemming from the term 'earth', which is literally a connnection into the ground itself. In the case of a battery powered circuit, the 0-volt rail is only 0 Volts *referenced to the rest of the circuit*. In such a circumstance, the circuit's ground is said to be **floating** when referenced to another circuit. Thus, two circuits with independent power supplies and no interconnection cannot be compared to one another in sense of voltage.

This typically doesn't matter, but when you need to interconnect independently-powered circuits you run into a problem. As both grounds are floating, any other voltage on each circuit is referenced to said floating voltage, and therefore is also floating. This makes wired communication between them impossible.

Unless you create a voltage reference between the two.

Simply connect the ground rails of each together; the cicruits are then referenced to one another at 0 Volts. It doesn't have to be the ground rails that are connected - any two points connected together will allow you to reference any point on board A to board B and get a correct potential difference. However, it's pretty useless doing that except in some odd situations.

---
Tags: serial, arduino-mega, arduino-leonardo
---


# Question
Title: Sketches not uploading to Micro from Ubuntu 14.04
I recently bought an Arduino Micro to see what all the fuss was about and I figured I'd use it with Ubuntu on an older Dell Latitude. I was able to install all of the files using some tutorials but I have this problem uploading sketches. After plugging in the board, the green top LED is consistently flashing so it seems to be working, but when I try to upload a sketch I get the following error

```
Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

```

Any ideas how to fix this? I tried pressing reset during the send as some forums have suggested but it doesnt seem to be working.

# Answer
I have a Micro and Ubuntu 14.04. I have successfully uploaded sketches to the Micro using IDE 1.0.6. Thus that combination should work.

I suggest you get the sketch compiling OK. Then hold down the Reset button on the Micro, start an upload with your other hand, and release Reset when it says "Uploading".

---

Try typing

`lsusb | grep Arduino`

I found with a sketch uploaded which opens the Serial port:

`Bus 003 Device 087: ID 2341:8037 Arduino SA`

If you hit Reset and wait a second, then do the lsusb again you see a different device:

`Bus 003 Device 086: ID 2341:0036 Arduino SA`

That one (the 0036 one) is the one it will upload to. You might get 0037 rather than 0036 because I reflashed the bootloader to be the Leonardo one, but the concept is the same.
> 2 votes

# Answer
The only way I have been able to fix this is revert back to Ubuntu 12.04.

There is something about 14.04 that does not play nice with the Micro.

I've tried running avrdude on the command line as well with no luck. The Arduino IDE code jumps through some hoops to detect the proper USB port, so timing is probably critical. I don't know the secret sauce for 14.04 though. The micro is tricky since USB is disconnected and reconnected during programming.

If anybody has better luck with this please update.
> 0 votes

---
Tags: uploading, ubuntu
---


# Question
Title: ESP8266 wifi module sending data via jQuery
Hey all I have the ESP8266 module and I have already set it up and it's working good. However, when I run this HTML page code here:

```
<html>
    <head>
        <title>ESP8266 LED Control</title>
    </head>
    <body>
    <button id="6894" class="led">Toggle Pin 13</button> <!-- button for pin 13 -->

    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(".led").click(function(){
                var p = $(this).attr('id'); // get id value (i.e. pin13, pin12, or pin11)

                $.get("http://192.168.9.60:80/", {pin:p}); // execute get request
            });
        });
    </script>
    </body>
</html>

```

I have to send the number 6894 instead of 13 because for some reason its not sending out the correct number. If i send 13 then what it receive is 114. When i send 6894 i receive 689.

My arduino code is this:

```
*/
//====================================================================================
//                                [The SSDI of the current wifi router]
//                                |              [The password of the current wifi router]
//                                |              |
//                                V              V
String SSIDandPW    = "AT+CWJAP=\"xxxxxxwifi\",\"xxxxxx123\"\r\n";

//                                      [The STATIC IP of the wifi module]
//                                      |                [The main IP of the router]
//                                      |                |              [The default submask]
//                                      |                |              |
//                                      V                V              V
String eIPrIPmask   = "AT+CIPSTA_DEF=\"192.168.9.60\",\"192.168.9.1\",\"255.255.255.0\"\r\n";
const int ledDimmer = 5;         // Used to dim the LED strip (digital Pin 3)

SoftwareSerial esp8266(9,10);    // Pin D10 to=> TX on ESP8266 | Pin D9 to=> RX on ESP8266
//================================= End define WiFi Module =================================
//==========================================================================================

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

  pinMode(13, OUTPUT); //Just for a wifi demo from html page

  //================================ Start Setup WiFi Module =================================
  //==========================================================================================
  esp8266.begin(19200);
  sendData("AT+RST\r\n",                    2000, true); // Reset module
  sendData("AT+CWMODE=1\r\n",               2000, true); // Configure as access point
  sendData(SSIDandPW,                       5000, true); // Pass of current wifi
  sendData("AT+CIPMUX=1\r\n",               2000, true); // Configure for multiple connections
  sendData("AT+UART_DEF=19200,8,1,0,0\r\n", 2000, true); // Set baud of COM
  sendData(eIPrIPmask,                      2000, true); // Default network mask IP
  sendData("AT+CIPSERVER=1,80\r\n",         2000, true); // Turn on server on port 80
  sendData("AT+GMR\r\n",                    2000, true); // Get firmware version
  sendData("AT+CIFSR\r\n",                  2000, true); // Get ip address
  Serial.print("Server is now running!");
  //================================ End Setup WiFi Module ===================================
  //==========================================================================================
}

void loop() {
  //=========================================== Start Loop WiFi Module ===========================================
  //==============================================================================================================
  if(esp8266.available()) {                               // check if the esp is sending a message
    if(esp8266.find("+IPD,")) {
      delay(500);
      int connectionId = esp8266.read() - 48;             // subtract 48 because the read() function returns

      esp8266.find("pin=");                               // advance cursor to "pin="
      int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
      retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
      retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")
      String closeCommand = "AT+CIPCLOSE=";               // make close command
      Serial.print("returned: ");
      Serial.print(retunedNum);
      Serial.print("----------");
      closeCommand += connectionId;                       // append connection id
      closeCommand += "\r\n";
      sendData(closeCommand,                250, true);   // close connection
      //digitalWrite(retunedNum, !digitalRead(retunedNum));   // toggle pin
      if (retunedNum == 6894) {
        Serial.print("OFF");
        digitalWrite(ledDimmer, LOW);
      } else if (retunedNum == 6904) {
        Serial.print("ON");
        digitalWrite(ledDimmer, HIGH);
      } else if (retunedNum == 689) {
        digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);              // wait for a second
        digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);              // wait for a second
      }
    }
  }
  //============================================ End Loop WiFi Module ============================================
  //==============================================================================================================
}

//                     [The data/command to send]
//                     |                  [The time to wait for a response]
//                     |                  |                [Print to Serial window (true = yes | false = no)]
//                     |                  |                |
//                     V                  V                V
String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  long int time   = millis();

  esp8266.print(command);          // send the read character to the esp8266

  while((time + timeout) > millis()) {
    while(esp8266.available()) {
                                   // The esp has data so display its output to the serial window
        char c = esp8266.read();   // read the next character.
        response += c;
    }
  }

  if (debug) { Serial.print('Returned: ' + response); }
  return response;
}

```

And the console output is this:

```
14880AT+RST

OK
14880
"qXÑ{ÂB!É
1Â±þ)ÒBÙa
+ò“H!a5)�#)ÒÂia%YakN‘ J!ÐCÊ!�
÷þˆ2ô
ready
14880AT+CWJAP="xxxxxxwifi","xxxxxx123"

OK
14880AT+CIPMUX=1

OK
14880AT+UART_DEF=19200,8,1,0,0

OK
14880AT+CIPSTA_DEF="192.168.9.60","192.168.9.1","255.255.255.0"

OK
14880AT+CIPSERVER=1,80

OK
14880AT+GMR

AT version:0.22.0.0(Mar 20 2015 10:04:26)
SDK version:1.0.0
compile time:Mar 20 2015 11:00:56

OK
14880AT+CIFSR

+CIFSR:STAIP,"192.168.9.60"
+CIFSR:STAMAC,"18:fe:34:9b:4e:68"

OK
Server is now running!

returned: 689----------148804 HTTP/1.1
Host: 192.168.9.60
Connection: AT+CIPCLOSE=0

0,CLOSED

OK

```

What I really am wanting to do is have a way to send a 10 charater string to the arduino instead of the limited 3 numbers above. I just am not sure what i need to add/modify in order to make it see letters/numbers and only the first 10 that i send.

Any help would be great!

# Answer
> 3 votes
```
  int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
  retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
  retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")

```

Your code always expects the pin number to have 3 digits.

In case of 13, it takes a space character as the last digit.
It reads charachters '1', '3' and ' '. Their ASCII codes are 49, 51 and 32. With this, the calculated number is

```
(49 - 48) * 100 + (51 - 48) * 10 + (32 - 48) = 114.

```

With 6894, it just uses the first three digits and ignores the last.

For 1 or 2 digit long number you could just pad it with '0' character i.g. "013".

If you want to read an arbitrary string, you should replace the above code with this code:

```
String retunedStr = "";
for(;;) {
    char c = esp8266.read();
    if (c == ' ')
        break;
    retunedStr += c;
}

```

And obviously replace

```
Serial.print(retunedNum);

```

with

```
Serial.print(retunedStr);

```

With this, you should only use letters (A-Z, a-z), numbers (0-9), dash (-) and an underscore (\_) for the string.
If you use other characters, you could have problems with the URL character encoding.

---
Tags: arduino-ide, wifi, arduino-nano, esp8266
---


# Question
Title: Binary reader with arduino blinking 8 leds
I´m trying to insert a binary raw sequence (01010100, 01101000, 01100001) into Arduino. I would like to make 8-led group blink in a loop, showing with light each 8-group binary sequence when: 0=light off and 1=light on.

It´s possible to do this operation with Arduino-uno ?

# Answer
You just prepend the number in binary with B e.g. B01100100 which is 100 in decimal

```
byte sequence[] = {
    B10000000,
    B01000000,
    B00100000,
    B00010000,
    B00001000,
    B00000100,
    B00000010,
    B00000001
}

```

And to check the n-th bit from the right in a number you do

```
boolean bit_set = number & (1 << (n - 1)) != 0;

```
> 1 votes

---
Tags: arduino-uno, led
---


title: Parsing Int over Serial Slow

text:
# Question
Title: Parsing Int over Serial Slow
I am trying to communicate between my PC and Arduino Mega 2560 using this serial library. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:

```
if(Serial.available() > 0){
  resultString = Serial.readStringUntil('\n');
  if(resultString.equals("r")){
    countEnc0 = 0;
    countEnc1 = 0;
    countEnc2 = 0;
  }else{
    int counter = 0;
    int lastIndex = 0;
    for (int i = 0; i < resultString.length(); i++) {
      // Loop through each character and check if it's a comma
      if (resultString.substring(i, i+1) == ",") {
        // Grab the piece from the last index up to the current position and store it
        write[counter] = resultString.substring(lastIndex, i).toInt();
        // Update the last position and add 1, so it starts from the next character
        lastIndex = i + 1;
        // Increase the position in the array that we store into
        counter++;
      }
      // If we're at the end of the string (no more commas to stop us)
      if (i == resultString.length() - 1) {
        // Grab the last part of the string from the lastIndex to the end
        write[counter] = resultString.substring(lastIndex, i+1).toInt();
      }
    }
    analogWrite(8, write[0]);
    analogWrite(9, write[1]);
    analogWrite(10, write[2]);
  }
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
}

```

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char\*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.

# Answer
First off, I would recommend `strtok` or even `getline` to parse comma delimited strings.

Secondly, I'm pretty sure no PWM is responsive enough for 1000 updates per second. But for other purposes this data rate might be needed.

To do this, build a custom cache that does the following:

1. Reads 1000 characters per go, if available, or less.
2. Parses on the go. From this set up callbacks to you PWM class, so that you can set PWM values while parsing.

Why this? I am not convinced that the sluggishness is due to the `for` parsing data. More likely, it's because you are processing every instruction as you get it.

1000 serial reads with 6 length `for` loops over strings (your case) will be significantly slower than 1 serial read and a 6k length `for` loop.
> 1 votes

# Answer
The String class is slow. I would get rid of that first. I am confused about whether you are sending or receiving, or both, as your code seems to parse and then send. See this test code here:

```
int countEnc0 = 123;
int countEnc1 = 456;
int countEnc2 = 789;

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

  unsigned long start = micros ();
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
  Serial.flush ();

  Serial.print ("Time taken = ");
  Serial.print (micros () - start);
  Serial.println (" uS");
  }  // end of setup

void loop () { }

```

That replicates the time taken for that one line which echoes the three figures. My results were:

`Time taken = 1632 uS`

OK, yours will be faster at the faster baud rate, but only 4 times as fast.

So, 240 times that and allowing for the faster baud rate gives:

```
1632 * 240 / 4 = 97920 µS

```

That's a fair bit of that second gone (a tenth), without even parsing anything.
> 1 votes

# Answer
If your bottleneck is really in the parsing (and you should confirm this before you spend any effort to optimize it), eliminate the parsing.

I usually recommend sending ASCII strings on serial channels to make debugging simpler, and I'd still suggest you get everything working this way first, even if you can't make the sample rate you need.

Once you're convinced your system works except for its speed, you can replace the ASCII communication with raw binary. A simple protocol would suffice: 3 or 6 bytes (do you need `int16_t`s?) of data and a 1 byte checksum downstream, and an ACK / NAK byte upstream to trigger a resend if needed, will probably be more than sufficient.

The receiver would only have to confirm the checksum and process the already ready-to-go binary sample values.
> 0 votes

---
Tags: serial, c++
---


# Question
Title: Common wireless gadget with rotary encoder to connect with Arduino
I'm looking for a common "wireless gadget" with a rotary encoder that can be accessed by an Arduino. Background: I need a portable rotary encoder to create a simple way to control model railway locomotives. The only one I have found so far is a wireless mouse where the scroll wheel can be easily used as rotary encoder.

But they usually are using USB on the PC side which is not that easy to handle by Arduino. Does anybody knows about other common "wireless gadgets"?

# Answer
That sounds like a candidate for building your own. It shouldn't be too hard.

There's plenty of low-cost Arduino-compatible wireless modules available. My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.

Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice. Write the sketch.

Add another nRF24L01 to your main Arduino to receive whatever you send.

Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel. I'm sure you could think of other things you could do with that wireless channel :)
> 1 votes

# Answer
In addition to @Majenko,

If your device is going to talk to a PC/Laptop (or cellphone!), then HC05 or HC06 bluetooth serial module may be a better fit. You will still need to write software to receive the data, but you won't need another Arduino at the other end.
> 0 votes

---
Tags: wireless
---


# Question
Title: how does an 8-bit AVR do 10-bit analog read?
I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for `analogRead()`. https://www.arduino.cc/en/Reference/AnalogRead

I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno, yields a resolution between readings of: 5 volts / 1024 units or, .0049.

My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?

Shouldn't the analog read be 2^8 or 256?

# Answer
> 4 votes
It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC. The CPU register size doesn't dictate what it can communicate with, either internally or externally. The only thing it dictates is how big a number it can cope with at any one time. Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.

---
Tags: arduino-uno, analogread
---


# Question
Title: How does the reset button work on the Arduino?
I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.

I have been using this board for many weeks with no problem and just now I have been getting this error:

```
avrdude: stk500_getsync()

```

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

# Answer
The reset button does pretty much the same as unplugging the board and plugging it back in. It restarts your program from the beginning.

The same thing happens when you program the board - the USB interface presses the reset button for you. That then enters the bootloader for a second or two so it can try and program it.

When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in. If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

* If you have anything else plugged into the Arduino then unplug it.
* Try powering the Arduino from different power supplies.
* If you have another Arduino or an AVR programmer try re-flashing the bootloader.
> 10 votes

---
Tags: arduino-uno, avrdude, reset
---


# Question
Title: How to store values inside an empty array and get the average integer? [UPDATED QUESTION]
Goodafternoon,

I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.

After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?

I came up with the following:

```
const int micPin = A0;
int soundArray[10];

void setup() {

  Serial.begin(9600);
  pinMode(micPin, INPUT);

}

void loop() {

  int micValue = analogRead(micPin);
  Serial.println(micValue, DEC);
  //delay(400);

  for (int i = 0; i > 10; i++) {
    soundArray[i] = micValue;
    Serial.println(soundArray[i]);
  }
  delay(1000);
  Serial.println("End of for loop");

}

```

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.

This is not what I want. I want to get different numbers in the array of that moment.

Hope someone can help me out. Thanks in advance.

# Answer
The error message is correct. You did not define the size of the array. You have 3 choices:

1. Declare it with a constant length

int foo\[10\];
2. Declare it and initalize it

int foo\[\] = {0,1,2,3,4,5,6,7,8,9};
3. Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)

int *foo; int size = 10; foo = (int*)malloc(size * sizeof(int)); free(foo);

As reference: http://www.arduino.cc/en/pmwiki.php?n=Reference/Array
> 1 votes

# Answer
There are three main sorts of "average" used normally in Maths:

* Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
* Mode: This is the "most common" value in a set of values. For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
* Median: This is the middle value of a set of values. If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.

By your comments it sounds like "mode" is what you are after - the most common number in your set of values.

It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.

I have an Average library that can do it for you. The main part of the `mode()` function of that library looks like this:

```
most = _store[0];
mostcount = 1;
for(pos = 0; pos < _count; pos++) {
    current = _store[pos];
    currentcount = 0;
    for(inner = pos + 1; inner < _count; inner++) {
        if(_store[inner] == current) {
            currentcount++;
        }
    }
    if(currentcount > mostcount) {
        most = current;
        mostcount = currentcount;
    }
    // If we have less array slices left than the current
    // maximum count, then there is no room left to find
    // a bigger count.  We have finished early and we can
    // go home.
    if(_count - pos < mostcount) {
        break;
    }
}
return most;

```

Basically two loops, one inside the other. The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at). If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value. Move on to the next number.

To use the Average library it's quite simple:

```
const int micPin = A0;

// We want to be able to store 10 int values here.
Average <int>sounds(10);

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

void loop() {
    // Push 10 values into the Average buffer.  Any old values will drop
    // off the bottom.
    for (int i = 0; i < 10; i++) {
        sounds.push(analogRead(micPin));
    }
    Serial.print("Mode value is: ");
    Serial.println(sounds.mode());
    delay(1000);
}

```
> 1 votes

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


# Question
Title: Strange phenomenon when declaring double
**Consider this question closed, found my answer through the answers I had**

I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity. The curve should look like this:

Is someone able to check what is wrong with my code?

```
float array[30];

struct Formula {
  int LoopTime = 1000;
  int AccelerationLoops = 11;
  float VelocityLoop = 0;
  float VelocityFactor = 0;
  int TotalLoops = 0;
  float DeltaPosition = 0;
  int Setpoint = 0;
  int Iteration = -1;
  float EndOne = 1.25;
}Formula;

float SetPosition = 1404;
float Position = 0;
float Velocity = 36;

void setup() {
  Serial.begin(115200);
  for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    ProgFormula();
    Serial.println(Formula.Iteration);
    if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
  }
  for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    //Serial.println(array[Formula.Iteration]);
  }
}

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

}

void ProgFormula(){
  if(Formula.Iteration == -1) {
    Formula.DeltaPosition = SetPosition - Position;
    Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
    Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
    Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
    Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
  }
  else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
    Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
  }
  else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
    Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
  }
  else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
    Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
  }
  else {
    Formula.Setpoint = Formula.Setpoint;
  }
}

```

# Answer
> 0 votes
OK, this may not be a proper answer. I'm just having a hard time reading your code, and I cannot understand why you make it so complicated. If you know the acceleration profile, computing the position profile is just a matter of integrating twice. Here is an example, not for Arduino but for a PC. It should not be very different on an Arduino, you just wouldn't use `printf()`:

```
/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
    float x = 0, v = 0;

    for (int t = 0; t <= max; t++) {
        v += acceleration(t);
        x += v;
        printf("%d\t%f\n", t, x);
    }
}

/* Your particular acceleration profile. */
float VttgJ(int t)
{
    if (t <  7) return t;
    if (t < 13) return 12 - t;
    if (t < 40) return 0;
    if (t < 46) return 39 - t;
    else        return t - 51;
}

int main(void)
{
    compute_profile(VttgJ, 50);
    return 0;
}

```

---
Tags: arduino-uno
---


# Question
Title: Counter using Ultrasonic Sensor (self.arduino)
I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment. Any help would be appreciated!

example of what i want the Serial Monitor to write: Count:0 Count:1 Count:2 ....

What it is currently doing: Count:0 Count:0 Count:0

```
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm, count;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

    // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
// count = 1;

 if (inches > 5)
{
  Serial.print("Count: ");
  Serial.print(count);
  Serial.print('\n');
  delay(1000);
        count++;

}

}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}

```

# Answer
> 2 votes
Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

**Global**

```
long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

```

**Static**

```
void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

```

Both will do the same job, but the `static` form is preferred since it is always better to keep a variable's scope as narrow as possible. It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.

---
Tags: sensors
---


# Question
Title: how can I change the setting for number of upload retries in the IDE?
I run into this problem when I mess something up, and it's pretty annoying to wait for 10 not in sync timeouts before I can try some different method.

```
...
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85

```

How can I set the number of "attempts" to say 2 instead of 10? Or how can I safely interrupt the upload process in the IDE?

# Answer
The code is not in the arduino ide but in the tool chain (.exe) that it runs.

Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.

The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.
> 1 votes

---
Tags: arduino-ide, avrdude
---


# Question
Title: BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic
So I'm trying to hook up this BLE breakout board to an Arduino Uno. SparkFun has a hookup guide which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.

I have hooked up the board to my Uno with the following pinouts:

```
GRN -> Reset
RXI -> RX (tried with TX as well)
TXI -> TX (tried with RX as well)
VIN -> Tried 5V and 3.3V
CTS -> GND
BLK -> (No Connection)

```

I use their example code they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.

Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

# Answer
So I found out what I was doing wrong, and want to smack myself for it -.-

The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.

Hope this ends up helping someone out.
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, pins, ftdi
---


# Question
Title: Arduino ATmega328P works but board (Uno R3) seems broken
This is the first time I'm using my Arduino. It's an Arduino UNO R3. I have two boards. One works, but the other doesn't. I changed the ATmega328P from the broken one to the good one and it works, so I can confirm that the controller works. The issue seems to be in the board.

When I plug the board it doesn't come up either in Mac or in Windows. The LED blinks and the output pins have voltage, but it seems that it's only getting electricity from the computer, it's like the data channels don't respond. The other board works perfectly both on Windows and Mac.

I checked the logs on the Mac and nothing changes when I plug the board. It's like I'm not plugging anything.

Is there a way to reset the board only? Maybe a component was badly soldered in the factory. I can't use the warranty because I got the board last year and never used it until now.

# Answer
> 2 votes
The R3 uses an ATmega16u2 in place of the FTDI. It is possible that it is not loaded, busted crystal, or it has no local power to it. It is a small SMT.

You could use your good Arduino setup as ICSP programmer to talk to the ICSP of the 16u2 to see it is alive. And if so then program it.

# Answer
> 1 votes
I have a sketch, that runs on a Uno, that detects chip signatures on other boards. You can use that to verify if the other board is good.

http://www.gammon.com.au/forum/?id=11633

You just need six jumper cables, like this:

From your description it sounds more like the Atmega16U2 is not working, that is the USB interface chip, the small chip near the USB socket. You can use the same sketch and a similar interface to check that as well.

That should at least show that the chip(s) are alive and giving valid signatures.

You could use About this Mac -\> System Information to see if the problem Uno is listed as some sort of USB device.

---
Tags: arduino-uno
---