# Question
Title: Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?
To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.

Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

# Answer
> 3 votes
Your question should read:

> How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:

```
Vout = 4 * Vin - 10

```

Testing the formula gives the following:

* Vin = 0.0 V ==\> Vout = -10 V
* Vin = 2.5 V ==\> Vout = 0 V
* Vin = 5.0 V ==\> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

simulate this circuit – Schematic created using CircuitLab

How it works:

* OA1 is an op-amp wired in an *inverting* summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
* R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
* The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
* C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

1. Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
2. Fix it in the servo amplifier and tell it to reverse its command signal.
3. Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.

Ref: Inverting Summing Amplifier.

---

**Servo Enable**

simulate this circuit

Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.

Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.

Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).

# Answer
> 2 votes
"transistor" has walked you through what is necessary. Just an additional point of note: if you don't have a +/- power supply, you can easily generate the negative voltage using eg ICL7660 or even using a 555: https://www.ikalogic.com/555-based-voltage-inverter-schematic/

Just because I'm curious, could you add a link to the servo datasheet?

---
Tags: arduino-uno
---


title: Sending number as byte through serial

text:
# Question
Title: Sending number as byte through serial
I'm trying to send data from an Arduino to an Android device.

I saw an online guide for that which provided this code:

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

void loop()
{
  byte msg[64];
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}

```

I tried that example and it is working perfectly!

But when I put `Serial.write("3");` in the setup loop after `Serial.begin(115200);` it appears as question mark on my Android device, I guess that I'm not sending it as a byte, I searched online but without any luck.

# Answer
> 2 votes
Start by changing it to `Serial.write("3", 1);`

Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.

# Answer
> 0 votes
I think this is a timing issue. It is fairly normal for a garbage byte or two to be received shortly after doing a `Serial.begin()` because the transition of "not defined" (or high impedance) output to Serial (which is normally all 1-bits) can cause the receiver to think it got a start bit, and then misinterpret what follows.

Try adding a short delay after `Serial.begin`. You could also try a pull-up resistor on the serial Tx line to ensure it is high prior to `Serial.begin` being called.

Your use of `Serial.available` effectively builds in a delay.

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


# Question
Title: One time execution of a variable incrementation
As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.

Any tips or help will be greatly appreciated!

PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.

```
      void playMan (int ncycles, int mSpeed) {

        switch (selectMel) {
        case 1:
          if (ncycles > 0) {
            tone(12, NOTE_B7, mSpeed);
            delay(100);
            tone(12, NOTE_B5, mSpeed);
            delay(100);
            tone(12, NOTE_B3, mSpeed);
            delay(100);
            tone(12, NOTE_B1, mSpeed);
            delay(100);
            ncycles--;
            break;
          case 2:
            if (millis() % 100 == 0) {
              if (switchVar == 1) {
                ncycles += 5;
                switchVar = 0;
              }
              Serial << ncycles << endl;
            }
            break;
          default:
            break;
          }
        }
      }

```

# Answer
See http://www.gammon.com.au/switches.

Basically you need to detect the transition between the switch not being pressed before, and **now** being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

---

> Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling `millis()` ) and then ignore any further transitions for, say 10 ms.
> 2 votes

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


# Question
Title: IR sensor readings at different voltages
I am currently working on a photo-transistor like this: http://www.ebay.com/itm/10pcs-ITR8307-S18-TR8-Optical-Switches-Reflective-Phototransistor-Output-/381374566327?hash=item58cbb20fb7:g:lgoAAOSwr81UQ7KG

It very nicely allows me to identify colors white, green and black. The problem I am having is that the Arduino is powered with batteries so the readings for those colors change as voltage in the batteries reduces.

I tried to make the reading proportional to the voltage in the system, but this still gives different values, I guess the readings change non-linearly as voltage changes.

I wonder what will be the solution to this problem: Specifically, how to make the reading of an IR sensor the same for the same color at different voltages?

This is the code I am using so far:

```
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
// read the input from the IR sensor on pin A0:
float sensorValue = analogRead(A0);
// read the voltage in the system by connecting pin A1 to Vcc, with the same resistor value used in the IR sensor:
float Vref = analogRead(A1);

// adjust reading value to voltage in system:
float AdjustedReading = sensorValue/Vref;

Serial.println(AdjustedReading);
delay(100);
}

```

# Answer
It sounds to me like your system works, but you have trouble if your voltage drops.

First of all here's 2 tips that might solve your problem.

1. instead of just making 1 reading do 10 and take an average - this reduces noise.
2. the voltage reference is allready based on the voltage that powers the system so with your adjusted reading you try to accomplish something which has already happened an therefore has the opposite effect and actually increase the error.

see http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ for a very good explanation.

3. Add a RC filter to removes random fluctuations in the signal from you photoresistor

see https://electronics.stackexchange.com/questions/17754/where-to-place-a-capacitor-to-smoothen-ir-sensor-reading for a short description and the calculated example.

If however it is correct, and your readings of colors don't follow a linear scale, you would have to deduce that actual curve and apply it in the code - but that might not be easy.

So it would be much more easy to remove that variable by ensuring that the voltage is constant. Most Arduino boards have an 5V onboard voltage regulator that will keep the voltage exactly at 5 Volt when connected to battery via the **power Jack!**

*(USB bypasses this regulator and have a little voltage drop so it is sligthly lower than 5V, and more very prone to fluctations if coming from a AC source affecting your analog read considerably)*

The battery connected onboard voltage regulator however requires a higher input to do the regulation so the battery needs to supply atleast 6.2V or higher, in your case you would have to use a voltage source of less than 6.2V if this is the source of your problems.

*(the voltage regulator on original arduino boards needs voltage of 1.2V higher than the needed output - clones might differ and require upto 2v more than the needed output)*

hope this can help solve the issue

Mikael
> 2 votes

---
Tags: voltage-level, battery, ir
---


# Question
Title: Using an Arduino as the processor for a computer-mouse-like speed detector
I'm looking at making a pretty cheap and easy odometer, eventually for an electric car or similar vehicle.

My idea is to implement a big computer mouse, and track the speed with that: a computer mouse takes photos of the surface it is on, and finds the difference between sequential images in both the X and Y directions.

What I am wanting to do is to attach a downwards-facing camera; something like this, to the bottom of the vehicle, and use an Arduino Nano to do the image processing to achieve a result similar to a computer mouse.

I was wondering whether anyone knows of an libraries/documentation on anything similar, or if anyone has any pointers on reasons why this would not work, or ways it would work.

Thanks all.

# Answer
Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.

If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.

Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to wikipedia, a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.

But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.

Voila; speed! :-)

This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.

Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.
> 1 votes

---
Tags: arduino-nano, c
---


# Question
Title: Adafruit DHT22 Library + Arduino Due not compiling?
i recently purchased a DHT22's and tried to get it to work using Adafruit's DHT library on Github. When i compile it with a Arduino DUE, it gives me the following error:

```
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp: In constructor 'DHT::DHT(uint8_t, uint8_t, uint8_t)':
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp:14:9: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]
   _port = digitalPinToPort(pin);
         ^
Error compiling.

```

It compiles on a Arduino Uno but not on the DUE.

What is the reason for this?

Edit: Below is the example code i use

```
#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

```

# Answer
That library uses direct pin manipulation to make things faster. However the Due is a completely different architecture to the Uno, so direct pin manipulation is done differently.

The library would have to be written specifically to do it in the two different ways and select between them depending on which board is chosen for the compilation. This hasn't been done, and it's unlikely it would ever be done.

This is exactly why `digitalWrite()`, `shiftIn()`, `shiftOut()` et al exists, so that you don't get these kind of problems. By choosing not to use them Adafruit have basically decided that their library will never work on a Due.
> 1 votes

# Answer
There are several Arduino libraries for reading DHT22 and related DHT sensors. The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).

For the Arduino Due use Rob Tillaart's DHTstable library available from his github page where you can download a zip file. Note that his project also has a "DHTlib" library which does not support the Due. There exists yet more DHT libraries which Rob has listed on the DHTLib page on arduino.cc.
> 2 votes

# Answer
The same library works with the Due if you use the older version 1.1.13 from the same Github repo, which is the last version that officially supported the Due.

Here are the changelog entries that show the relevant changes:

> update: 0.1.13 added support for DHT33 and DHT44 - LAST DUE VERSION
>
> update: 0.1.14 replaced digitalRead with faster code (AVR ONLY!!! better support for lower Mhz devices)
> 0 votes

---
Tags: arduino-due, library, compile, adafruit
---


# Question
Title: Velocity from Sensor Data - Best Approach?
I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity.

What is the best approach to get accurate, smooth, and fast data to my control logic?

Would I benefit from combining accelerometer and barometric data? If so, how?

---

Background:

I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.

Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.

I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.

Thanks!

# Answer
> 1 votes
Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).

The first few things to address are in regard to the barometer:

(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data *before* passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.

(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there. (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."

Just one more thing before we get into the filter...

It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.

Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.

One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between \[-1, 1\]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.

Regardless, here's some insight that may be useful:

The Kalman filter is *very* much dependent on how you model your system.

To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):

Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.

We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:

The filter works fairly well.

But what if our model happened to be off - that is, it doesn't reflect what's really happening?

In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.

This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.

There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag", you need to use what is known as an extended Kalman filter - which basically linearizes your data.

Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.

In any case, I hope this helped. Feel free to ask any questions.

(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).

# Answer
> 0 votes
You can use Excel to smooth out data and do graphs if you need to. That's what I use myself. Easiest way is to create a table and type formula to make average from range of numbers, smoother data needs a bigger range of numbers.

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


title: Functions of GSM

text:
# Question
Title: Functions of GSM
I am currently working on an arduino project and wanted to use a GSM module. This is my first time working with a GSM module. So I had a few queries.
What can a GSM module sim900a do with arduino programming?
Also can it do the following:

1. Send sms when motion is detected by a PIR sensor
2. Send sms to only a particular group of cell phones.
3. Respond to a particular kind of sms

# Answer
> 3 votes
> 1. Send sms when motion is detected by a PIR sensor

**Yes**, write a function that does this. Basic support functions in libraries will help you send the sms and detect the PIR. You need to provide the logic.

> 2. Send sms to only a particular group of cell phones.

If the question is if the GSM module supports group send the answer is **no**. You will have to write a function that sends the SMS to each number in the group.

> 3. Respond to a particular kind of sms

**Yes**, again but now you have to write a function that parses incoming messages and does some actions (just as any input parse).

The answer to all these questions is **no** if the function is already available in libraries. The answer is **maybe** if someone has already done something similar.

# Answer
> 2 votes
None of those things you ask are a function of the SIM900A GSM module.

The SIM900A GSM module is capable of sending and receiving text messages (SMS). What you do with those text messages, and what text messages you send to where is entirely down to your Arduino program.

What you are asking is like "Can this car drive from Manchester to Carlisle?" The car can be driven from place to place, but it's *you* that does the driving. So you should be asking "I have a car. Am I capable of driving it from Manchester to Carlisle?"

So yes, the SIM900A GSM module is capable of being used to achieve those three things you ask, but the real question is not can the SIM900A do them, but *can you program the Arduino to get a SIM900A to do them?* And the answer is "Yes, it is perfectly possible if you know how", and we can help you to know how when you start working on the project and come across some stumbling blocks in your programming.

---
Tags: gsm, robotics
---


# Question
Title: Connect Bluetooth remote control with Arduino
For a project I need to connect a **Bluetooth Remote control** with an **Arduino Nano**.

On the Arduino-side I have an HC-05-Bluetooth module. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.

In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:

```
void loop() {
  sensorValue = analogRead( sensorPin );
  cm = 10650.08 * pow( sensorValue, -0.935 ) - 10;
  Serial.println( cm );
  softSerial.println(cm);
  delay( 500 );
}

```

Instead of sending sensor values, I need to connect said remote with the Arduino.

*(Picture shows the basic model of said remote control.)*

The remote control has the Bluetooth class `20258C` which means:

* Major Device Class: Peripheral
* Limited Discoverable Mode
* Audio
* Pointing device
* Remote control

**Remote Control Bluetooth Specifications:**

* BT Device Name: YL-BTM3-xxxxxx
* Supplier ID and Product ID: 0x0A5C / 0x4503
* Class of Device: 0x20258C

My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?

Best regards

# Answer
> 3 votes
This should be a comment, but..

For starters, you'll need to do the pairing from the Arduino with the HC-05 in master mode.

Check this out.

---
Tags: bluetooth, arduino-nano, remote-control
---


# Question
Title: Controlling an LED using a transistor (TL188)
I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.

*(The resistor I used was 150 ohms, and I forgot to change the resistor value in the diagram.)*

The program on the Arduino Uno was the basic `Blink` sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000 ms and turn off for 1000 ms. But when I connected the LED like the diagram below

**For the first 1000 ms delay:**

* LED on pin 13 stayed **on**
* LED connected using the transistor stayed **off**

**For the next 1000 ms delay:**

* LED on pin 13 stayed **partially on (it was dim)**
* LED with the transistor was **on**

I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?

# Answer
You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.

A PNP transistor is somewhat harder to get to grips with than an NPN transistor. Much of it does things backwards.

The operation you see seems to be completely correct when you understand how a PNP works.

With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.

When you have a voltage close to or above the voltage at the emitter the transistor will be off. That means, providing a HIGH to the base will turn it off. A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on. That means providing a LOW to the base will turn it on.

So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off. When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.

"But", you say, "the on-board LED doesn't turn off". That is correct. It just gets dimmer. That is, again, because of how the PNP transistor works. Current (seen from the *conventional sense* \- i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly\*.

---

\*That is a little crudely put, but kind of illustrates what is going on.
> 3 votes

# Answer
It really doesn't matter if you use a PNP or NPN transistor, they are just mirrors of one another. If you have some common anode displays then just start directly with the PNP's.

The flaw I see in your circuit is that you should always use 2 resistors to drive a LED (See schematic). R2 (as you already have) will limit the current to the LED; 220 Ohm you as illustrated is fine.

R1 is needed between the I/O pin and your transistor. This will limit the current through the I/O pin. For what you are attempting a resistor in the range 1K to 2K should do, even if you're switching a few LED's in parallel. If you provide complete details of your setup we can always refine the calculations. One can then take into account the total currents from your displays, the amplification factor of the transistor (hfe) etc.
> 1 votes

---
Tags: arduino-uno, transistor
---


# Question
Title: How to connect an L293D and an MPU6050 to run together?
I'm wondering how to connect the L293D (H-bridge) and an MPU 6050.

I'm using 1 Arduino Uno, 2 DC motors, 1 MPU6050 and an L293D.

When I tried this, I got some sparks/smoke from the breadboard and none of the motors where running. I only used a 9v battery, not 12v.

Here's the L293D:

MPU 6050 wiring: int-digital 2, SDA-A4, SCL-A5, GND-GND, VDD-Vss

L293D wiring: Vss-VDD, Input4-Digital 5, Output4-Motor, Output3-Motor, Input3-Digital 6, Enable2-5V, Enable1-5V, Input1-Digital 9, Output1-motor, Output2-motor, Input2-Digital 10, Vs-12V battery.

# Answer
> 1 votes
I don't really se anything wrong with the wiring, atleast your diagram seems to be in order. only thing I would ad is give the pin 8 a ceramic capacitor to ground

but There is a few possible issues you can check.

1 -the sparks make me think that you had a Loose connection at the spark site on the breadboard, maybe the IC was not properly pushed Down in the breadboard, this happens alot, try Again and make sure the IC is complete inserted.

2 - if this does not work You might have destroyed the first L293 or the breadboard tracks but if you have more than one try to see if a replacement or movement of the old ic does the trick

3 - the motors are to large, and so the current drawn is to high for the L293 to handle and caused thermal shutdown of the L293, a very high current drain will also occur if the motor is stalled. Anyway add some current limiting resistors and see what happends.

4 - if the motor hums without moving then it is because Both the forward and reverse input eg. 1 and 2 is enabled simultaneously.

5 - the code is not appended, so that cannot be verfified, but the MPU 6050 is correctly installed

# Answer
> 1 votes
There a some mistakes with the wiring of the supply voltage (Vss) according to the datasheet (http://www.ti.com/lit/ds/symlink/l293.pdf) of the L293D a those on pin 8 (Vss2) and 16 (Vss1). I think those are not connected because each Vss is for one motor of the driver. So you have to connect 9V (or 12V) to both pins. There is also something wrong with the capacitor (polarity). And your connection of the battery to the breadboard is a bit weird because + of the battery is usally the red not the black wire / marked row on the breadboard.

---
Tags: arduino-uno, sensors, motor, mpu6050, h-bridge
---


# Question
Title: Is this Bluetooth module cool for Arduino?
I am making a basic project that will have 4 or 5 arduino nodes. Each arduino will have a bluetooth module attached. The thing I want is, I want to be able for each one of these arduinos to know the other is present in the room (let's say, 5 meters). For my experience in the cellphone, I don't even have to pair bluetooth devices to know about their presence, as long as they are in visible mode. Since I just need to know their presence, and no exchange of information will ever happen, I probably will never have to pair them right?

For this project I need a bluetooth (BT) module that:

1) Enables me to change the ID of each arduino, so that, even if I use my cellphone to scan for BT devices I will see (Arduino1, Arduino2, etc...) instead of default-factory-names.

2) Enables me to scan around for existing devices every time each X seconds, because I want each arduino to know if the others are in the room.

Will this module do the trick? http://www.ebay.co.uk/itm/Interface-Base-Board-Serial-Transceiver-Bluetooth-Module-For-Arduino-UNO-R3-/111482008102?pt=UK\_BOI\_Electrical\_Components\_Supplies\_ET&hash=item19f4d87226

Later I will probably hang around with batteries so I will want a low power BT module, having the same 2 capabilities mentioned. Will NRF8001 do the trick for me? http://www.nordicsemi.com/eng/Products/Bluetooth-Smart-Bluetooth-low-energy/nRF8001

Thanks!

# Answer
> 1 votes
From skimming that post, I believe that your linked pcb is not a full bluetooth module (note how there is no bluetooth chip or antenna of any kind). This is simply a "base board," which is why it is so cheap1.

You will need something like this that actually has the components you want.

To answer your questions:

1. The bluetooth library for arduino sets the discoverale name to ARDUINOBT by default, but that can be changed in the setup() method.
2. "scan around" is a little ambiguous—AFAIK, bluetooth can only connect to one device at a time, but I'm not sure if that's totally true. You may want to look into using radios instead of BT, as they can communicate more freely with one another, are extremely cheap, and have extensive arduino libraries availible. I'm currently working on a project that uses the nRF24L01, and I'd be happy to answer any questions you have about it.

1: It also has a draw of 6v VCC, which is more than the Uno can output.

# Answer
> 0 votes
The first link is for a **breakout board only** \- it has a **placeholder** for a BT module, similar to the HC Bluetooth models series, but it is n*ot a complete Bluetooth board* (hence the "Interface Base Board" in the product's title). Please do not do that mistake - I did it already :)

For your purposes, it seems that something similar to the cheap HC-05 can satisfy both requirements: You can change the device name, and perform inquiry to scan other Bluetooth devices' MAC address, both using AT commands.

It has low operation voltage (1.8v-3.6v), but it operates as the good-old 2.1 Bluetooth standard, which waste a LOT of energy while running. If power consumption is a prime requirement, you might want to consider the more expensive Bluetooth low energy, such as a breakout board for the chip you suggested (the NRF8001).

# Answer
> 0 votes
Should've been a comment, but...

First of all, your questions 1 and 2: yes, that can be done.

I'd go for a HC-05 just like Omer suggests. And if you want to pair them, it is perfectly possible to pair one master with several slaves. Depending on implementation, a slave can connect to several masters too. The HC-05 can switch between these modes.

You can't do it with a NRF8001, as this is a BLE slave device only, it won't do scanning. Try to find a device that can do both, like BLE mini.

You can't mix BLE and Bluetooth devices for this, it's either or.

---
Tags: rf, bluetooth
---


title: Reading sensor data over MUX

text:
# Question
Title: Reading sensor data over MUX
I will start by saying I am very new to using Arduino. The project I am planning is to create several arrays of sensors (each array will consist of 4 DS18B20 sensors and one temperature/humidity sensor) and using a MUX connected to Arduino I want to read the data from each \[ten\] array. I have found sketches I can modify to do this task in a continuous cycle but I need to be able to display data from an array for an extended time period of several minutes. My Arduino will output to a 3.2" LCD so there is only enough screen space to show data for one array at a time.

# Answer
> 1 votes
The DS18B20 is a 1-Wire device and doesn't require a multiplexer, each device has its own address on the bus and you can connect a lot of them with a single wire. Depending on the humidity sensor you pick you may be able to use the same bus for it as well.

It is harder to find 1-Wire humidity sensors, but you could use a DS2438 Smart Battery Monitor which also includes an ADC to give you values from an analog humidity sensor.

The challenge of designing your project will be setting up an easy to understand display and controlling how/when it changes.

---
Tags: temperature-sensor, multiplexer
---


# Question
Title: No Battery Microcontroller Operation - (Motion, heat, induction etc)
I am using an ATtiny85 to sleep for a long period of time, collect some data, send it over radio, and go back to sleep, after disabling everything possible. The ATtiny is currently powered by a coin cell. I can get quite some time off that coin cell, but it's simply not enough, and the coin cell cannot be changed once the board is deployed. Peak current draw is around 10-15 mA.

My aim here is to find an alternative power source for my board. Some good news is that the boards are never more than one or two feet from a receiver, so rf-like power transmission may be possible. Some other options may be motion or heat (it's a wearable device). The amount of power could be pretty small, as I only need it at peak periods, so I could just charge up a supercapacitor for a while and drain it when power is needed after the Attiny wakes up for less than a second.

The ideal situation would be to have a means of power transmission or generation that provides enough current to continuously power the microcontroller without the need for sleep, but I recognize that this is probably not feasible. However, due to the limited range it might be. Another concern is radiation to the wearer.

If anyone has any experience in this kind of power transmission or generation or just any ideas I would love to hear it. Thanks!

# Answer
10mA is quite a lot for a coin cell. And of course the duration is really low.

As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.

In my opinion and according to my experience you have two possibilities:

1. use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver
2. use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.
> 1 votes

# Answer
This question seems to be aligned to your other question about nrf24l01+ transceiver. The charge pump is a good idea, but if this is still for the nrf24l01+ project i would not recommend it because it would cause ripples in the supplied power and RF noise which is really not something you want together with the nrf24l01+.

if the unit is to be strapped on the wrist or ankles a concept like the one in a shake/faraday flashligt might be implemented, but that would be a diy custom job. and probably require size, even though they can fit a similiar contraption into a wristwatch.

But anyway I'm not sure if you are aware, but the nrf24l01+ has a function called enhanced shockburst which is designed for very low current consumption according to the datasheet it only requires 1% or 0.12ma at normal transmitting mode! this comes at the cost of transmitting power ofcourse but your receiver is only a few feet away so that is most likely not an issue.

https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss\_Preliminary\_Product\_Specification\_v1\_0.pdf page 14

I'm pretty sure you already have optimised your current consumption, but one setting you might have missed is the atTiny clockspeed which can be lowered to 1mHz instead of 8mHz this will lower the current to run the processor to 20 of the normal.

if these are not implemented already, then they might give you the needed battery life.
> 0 votes

# Answer
I just helped a friend install a Fitbit "Zip" model. In the process of doing that I noticed it is powered by a CR2025 (3V lithium button) battery.

Their ads claim it runs "up to 6 months" on this battery. It communicates wirelessly (ie. Bluetooth) as well as having an LCD screen. It also takes measurements.

Thus, what you are trying to achieve sounds technically possible, as someone has done it.

---

> I can get a few weeks depending upon usage, and I need a few months.

So to solve your problem it would help to know what your existing current consumption is.

I have a project about an ATtiny85 torch locator. That does not do radio transmission but **does** flash an LED. I calculate the battery should last 3 years, and at this stage (almost a year after I made it) it is still working on the same battery.

You may get some ideas from that link.

I calculated (and confirmed by measurement) that in idle mode it uses 4.4 µA. You should be getting a similar figure during your sleep periods.
> 0 votes

---
Tags: power, attiny, sleep
---


# Question
Title: Sensor for very low temperature (liquid nitrogen)
I'm looking for a way to measure temperatures in range of 40 to -200 °C (100 to −320 °F). The usual solution DS18B20 works only down to -55 °C (-67 °F).

Any ideas?

*p.s.* Precision of 2 °C would be good enough.

# Answer
> 2 votes
You probably want a K-type thermocouple (the most common type).

They have a range of around -200°C to +1350°C (depending on probe).

Alternatively a Resistive Temperature Device (RTD) can be used, since these have a typical range of around -240°C to 650°C with higher accuracy.

This might be of help to you: http://digital.ni.com/public.nsf/allkb/C50FA55B3B2F85D9862572D00083350E

# Answer
> 1 votes
I did a search on "cryogenic temperature sensors" and found these from Lake Shore Cyrotronics – the price is shocking. It appears that you can use silicon diodes as cryogenic temperature sensors, so you might be able to use less expensive parts if you don't need a ton of accuracy.

---
Tags: temperature-sensor
---


title: Counting minutes in arduino

text:
# Question
Title: Counting minutes in arduino
I have a dipswitch of 4 steps to get a binary number that will turn out to decimal from 0 to 15, So I need to get that number and make it the ammount of minutes to make something and also be aware of some input while the time runs out.

So I was thinking of having a variable being equal to millis() and then dividing it by 60,000 which is a minute in millis and If I get an integer that must mean a minute has passed, the problem is that I don't know how to check if the result is an integer or a float.

any advice?

# Answer
Your method is completely wrong.

You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis(). When the difference between them is greater than or equal to `60000 * 15` then 15 minutes have passed.

Look at *BlinkWithoutDelay* in the Examples menu in the IDE - it showcases the technique for you.
> 1 votes

# Answer
To my understanding you want to make some sort of device that will count X min. To get X you configure the 4 dip switches to get the time (0000 - 1111 or 0 - 15). The easiest way is to configure 4 pins to INPUT\_PULLUP then you wire your switch to those pins and to ground. If the pin is grounded (switch in the on state) it will register a 0 and if the pin is NOT grounded (switch in the off state) it will register a 1.

note: if all switch are "off" you will get a max value of 15 based on my example.

```
long startTime;
void setup(){
    pinMode(7, INPUT_PULLUP); //8bit
    pinMode(6, INPUT_PULLUP); //4bit
    pinMode(5, INPUT_PULLUP); //2bit
    pinMode(4, INPUT_PULLUP); //1bit

    startTime = millis();
}

void loop(){
    long inputTime = 0;

    if(digitalRead(7))
        inputTime += 8;

    if(digitalRead(6))
        inputTime += 4;

    if(digitalRead(5))
        inputTime += 2;

    if(digitalRead(4))
        inputTime += 1;

    inputTime = 60000*inputTime;

    if(millis() - startTime <= inputTime){
        //X min has passed -- Do something here if you like

        startTime = millis(); //reset the timer
    }else{
        //Time not yet reached -- Do something here if you like
    }
}

```
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Is it possible to simulate PWM using delay() function?
I was thinking about if it is possible to **simulate** PWM (AKA pulse width modulation).
Is it possible to reach the speed of the PWM using the delay() function ?.
Note : I am talking about the pins which does not support PWM, Arduino uno Pin 13 for example.

# Answer
It is possible to create a PWM signal from a non-PWM digital pin although you would not want to use delay, but timer interrupts for accuracy and finite timing. PWM intervals are typically measured in (μs\[microseconds\] vs ms\[milliseconds\]).

The standard Arduino servo library does this: Servo.
> 3 votes

# Answer
It would be possible to do it. Would it be a smart thing to do ?

I do not think so. Micro-controllers (not just Atmel's) have dedicated hardware modules to manage the signals for PWM. What happens when you use AnalogWrite is the compiler/interpreter/whatever uses these informations to modify the appropriate registers so the toggling is not managed by the code.

If you use the delay() functions, you are simply letting clock cycles pass by until the time you set is passed which is a lot less efficient. Plus, you would probably not get the same PWM frequency.
> 1 votes

# Answer
What you are talking about is more appropriately called Bit-Banging. Check out this link. It even has an example of what you are trying to do. @Jason is correct that it causes a number of issues. The link above will also run you through the draw backs of this method which I will summarize.

* Jittery due to interrupts (Interrupts can be disabled)
* The Processor cannot do anything else and keep the output working
* Frequency and Duty Cycle are difficult to determine
> 1 votes

# Answer
I think it depends on what you want to use it for. I compared using PWM and bit banging to run a small DC motor. PWM produced an audible whine that I found very irritating. Using the delay function removed that (a delay on/off cycle of 10 milliseconds). I also found that it was relatively easy to control not only the ratio of on/off (PWM) but also the length of the cycle. This was useful for starting the motor with a slightly higher "push" to get it moving. (I'm sure that this could be done using PWM too) With respect to performance of the engine, I didn't find much actual difference.

The key issue with a DC motor is that while the digitalWrite() is LOW, the inertia of the motor carries the rotation on and so the effect of the delay is smoothed. In addition the RPM of the motor wasn't critical for my application.

However, if one was running a LED then using delay() might be visibly discernable and cause discomfort (and possibly seizures?). For this, I'd definitely use PWM.

regards Mark
> 0 votes

---
Tags: pwm
---


title: How to integrate ESP8266

text:
# Question
Title: How to integrate ESP8266
Just, to make sure how it works:

* I will connect the module to Arduino
* it will create AP to which I can connect and send commands via HTTP

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID (the PC will just communicate over regular network)? Is it possible to communicate bidirectional somehow?

# Answer
> So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

If you set the ESP8266 in AP you can connect to it with every wifi capable device.

You can control an ESP8266 with just an Arduino, but you I would not recommend using your Arduino as the power supply. If I remember correctly the mega's VCC pins are rated for 200mA which may or may not be enough for your ESP8266 I'm not sure, but I would recommend using another power supply for the ESP8266.

> Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID

Yes that is possible.

> Is it possible to communicate bidirectional somehow?

I am not exactly sure what you want, but it is possible to communicate in both directions. Assuming you know the local IP address of your ESP8266, you could for example send an HTTP request to it using any browser to which the ESP8266 can reply with anything.

Your ESP8266 can also send data to your computer, but it would require some program on your computer listening for incoming connections. Also possible, but more difficult.

At last I would like to tell you that driving an ESP8266 with an Arduino is like driving a Ferrari with the engine from a tuk tuk. It will move, but you will never use all of it's features. I don't know which version of the ESP8266 you have, but there are versions out there that can be programmed via USB just as your Arduino and you can just use the Arduino IDE and all of it's features like the Arduino language.
> 2 votes

# Answer
Just wanted to second what @larzz11 says in the last para. If you don't need the ADC's, running Arduino code on the device is definitely the simplest/easiest way to use the device. The AT command firmware is challenging to get working in a stable fashion.

Also just to re-affirm the power requirements of the ESP8266 is higher than the 3v3 supply on the Arduino—you'll need a step-down converter from a sufficiently powerful 5v supply, or separate power supply, to get it working consistently.

Bidirectional comms are definitely doable, but the limited SRAM on Arduino make string parsing a real challenge, and even handling relatively small responses/requests can hit up against the available SRAM.

One of the nice things about using Arduino on the ESP8266 is that the ESP8266 has 8 times the amount of SRAM, making that more feasible also.
> 0 votes

---
Tags: arduino-mega, esp8266
---


# Question
Title: Controlling a DC motor with an external power source
I'm trying to use an Arduino to release a **single drop** of water using a solenoid valve. This article describes how to create this circuit with a Raspberry Pi using a DC powered solenoid that opens and closes very quickly and they use this for photographing water drops. Exactly what I need, if I could only get it to work with the starter kit items first.

The design for the solenoid circuit from that site looks like:

I don't have a solenoid yet, but I've been experimenting with the cheap motor that comes with the Arduino and a 9 V battery. I've burned out several transistors in my attempts to get this working. My schematic looks like:

Relays won't work. They are too slow. Also, I need to use an external battery. I can't use the power from the Arduino because I will eventually be moving up to a 12 V battery and the Arduino won't be able to handle that.

# Answer
Seeing as you want to use a 12V battery, you should try an external motor controller. You would essentially connect the Arduino to the controller, then the external battery and motor to the controller. Dimension Engineering makes several high quality motor controllers that are compatible with Arduino and can handle the voltage (like this controller). The site also includes Arduino libraries, documentation, and all the specifications on every product. I have used several of their products with my Arduino Uno and have had no problems.
> 5 votes

# Answer
I can think of a couple of things that you might consider.

The motor looks like a good surrogate for the solenoid.

If you're burning out transistors, look at the following 3 most probable causes:

a) Voltage spike when you cut the current to the coil (motor or solenoid). If the fly-back diode is still intact, this should not be your case.

b) Current spike exceeding Icmax. This is the maximum current your BJT can sustain without damage. An inductor like your solenoid or motor will reach in DC a maximum value dictated by Ohm's law. So measure the motor's resistance with a multimeter and calculate the Imax. It should be Imax = (VDC - Vcesat)/Rcoil, where Vcesat is the saturation voltage of your BJT, somewhere around 0.3V. Measuring the current of the motor connected to the battery also works if you measure it while you block the rotor. Check that your transistor can handle the current. Small signal transistors usually are rated at around 150mA, so this might be too little for your coil. So maybe you would need to buy/build a Darlington transistor that will have the amplification factor and current capacity to handle the load.

c) If a and b are OK, then maybe the transistor is overheating? Your fingers will tell you :-)

Once this works with the motor, you might need to recalculate to accommodate the (eventual) higher current of the solenoid.
> 2 votes

# Answer
You will also need a ceramic capacitor connecting the wires of the motor. also the diode should be at least 1amp and the transistor have the specs to take the loadd.
> 0 votes

---
Tags: power, motor, battery, transistor
---


title: Load Arduino flash code from SD card

text:
# Question
Title: Load Arduino flash code from SD card
I have an Arduino Uno. It doesn't have a lot of memory space, which is a bit of a nuisance. I was wondering: Is it possible to load a text file from an SD card and compile it on the Arduino into code that the Arduino can use. I don't really care if it is slow or uses 99% of the memory space just to load on the code. If it is possible would this work: use bootup code to load a piece of code to Arduino, dispose of bootup code so there is more code, do what ever that code does, dispose of that code, load new code.

# Answer
> 5 votes
See topic #16812, “Load sketch code from SD Card”, in forum.arduino.cc, which explains how to replace the ordinary Arduino bootloader with one that can load programs from an SD card.

Also see Bootdrive loads Arduino sketches from SD card at dangerousprototypes.com, which gives different code to do the same thing. It also mentions BootDrive for Arduino from baldwisdom.com.

Note, the program code that these loaders install into flash is already compiled, as opposed to being original C source code. If you want to load source-level code into the Arduino, look for an interpreter / interpretive language to run on the Arduino.

# Answer
> 1 votes
The flash memory is only designed to be reloaded 10,000 times. While that might seem a lot, if you are planning a system where, every day you load some part of code into flash, and then some other part, etc. you will use up those 10,000 writes fairly quickly.

> I don't really care if it is slow or uses 99% of the memory space just to load on the code.

Well, you **will** care because if 99% of the memory space is the loader, you will only have 1% for the code, which defeats the purpose.

> It doesn't have a lot of memory space, which is a bit of a nuisance.

I suggest a larger processor such as the Atmega1284 (128k of flash), Atmega2560 (256k of flash) or the Atmega644P (64k of flash).

All but the Atmega2560 come in DIP versions of the chips, if that helps.

---
Tags: arduino-uno
---


title: Watchdog approach

text:
# Question
Title: Watchdog approach
I'm developing up a project that is designed to run 24/7 (an energy monitor) logging via wifi.

Due to a variety of considerations I've ended up with a design that links an Arduino Nano with an ESP8266-01.

I was considering designing in a watchdog, but had the thought that each of these MCUs could act as the watchdog for the other. My hypothesis is that the likelihood of both going down simultaneously is relatively low, and as both need to communicate with each other regularly, they will know when the other unit has become non-responsive, and they would also be able to initiate a hardware (rather than software) reset on the other device.

Is this a valid/workable approach? Or is there something else I need to consider that would warrant an external watchdog(s)?

EDIT: as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply), so this isn't expected to be an issue.

# Answer
> 2 votes
I had a similar project a while back, including the desire for the watchdog.

> My hypothesis is that the likelihood of both going down simultaneously is relatively low ...

Here's the problem. If it is solar powered (or even just battery powered) then the likelihood is quite high that they will both get insufficient power at much the same time (ie. low voltage).

One thing I noticed was that if voltage slowly drops (as it does when the sun goes down, and the battery discharges) then the processor can enter a brown-out situation where it basically just goes dead, without resetting.

Now you **can** set brown-out detection in the fuses, but the reference voltage generator, needed to make it work, itself increases the power consumption. So you get the situation where the brownout detection drains the battery, causing a brown-out situation, where without brownout detection it might have lasted all night.

---

Anyway, the net effect was that the design on the linked page wasn't as reliable as I hoped.

To make this answer more complete, here is my watchdog processor schematic:

And this was the code for it:

```
// Reset solar panel watchdog
// Author: Nick Gammon
// Date: 22 March 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

 After reset waits for TIME_TO_WAIT minutes, then brings D0 (pin 5) high for long
 enough to activate a MOSFET and reset the other board.

 Fuses: Low: E2 High: DD

 (Brownout at 2.7V)

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte MOSFET = 0;          // pin 5
unsigned long counter = 0;

const float TIME_TO_WAIT = 30; // minutes
const unsigned long SLEEPS_TO_WAIT = TIME_TO_WAIT * 60.0 / 8.0;  // 8 second sleeps

// watchdog interrupt
ISR (WDT_vect)
  {
   wdt_disable();  // disable watchdog
  }  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (MOSFET, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  }  // end of setup

void loop ()
  {
  counter++;

  if (counter >= SLEEPS_TO_WAIT)
    {
    digitalWrite (MOSFET, HIGH);
    delayMicroseconds (10000);
    digitalWrite (MOSFET, LOW);
    // our job here is done
    sleep_enable ();       // ready to sleep
    sleep_cpu ();          // sleep
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  noInterrupts ();       // timed sequence coming up
  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP3) | bit (WDP0);    // set WDIE, and 8 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep

```

The design intention here was that the watchdog processor would reset overnight (when the solar panel lost power and the supercapacitor eventually discharged) and in the morning it would power up, wait 30 minutes (for the sun to rise and the voltage to become stable) and then unconditionally reset the other processor from whatever state it was in.

---

> as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply)

Yes, well I also live in a country with 240V power. Today during 41°C heat the power failed a number of times for very short intervals. Various computers reset or behaved strangely. Like with a low voltage battery, a brown-out, or brief failure, of the mains power could simultaneously strike all your devices, including the watchdog device.

# Answer
> 2 votes
As a watchdog mechanism to protect against software lockup type issues then using one processor to detect issues and reset the other is an economical idea. However, I would completely agree with Nick that if you want protection from hardware issues like brown outs or slow rise time of the power supply then both micros could share the same vulnerabilities that a dedicated watchdog device would be able to address. How significant this is depends on your power arrangements.

The other case to consider is now much does the software of one device interact with and depend on that of the other device such that it is conceivable that one device locking up in some way could impact the other defeating the watchdog functionality.

Personally I've seen too many situations where an internal micro watchdog failed to detect and recover an issue so would always go for an external device in any professional product. Even there I would advise the use of a devices which requires the watchdog to be kicked within a time window rather than just within a maximum time period - otherwise if things contrive to go wrong in such a way that the watchdog is permanently getting kicked it will not recover the situation. \[I saw the micro pin responsible for kicking a simple external watchdog accidentally reconfigured by runaway code as a timer output once.\]

I suspect that if you are thinking that your product needs a watchdog then it is worth doing properly with an external one.

---
Tags: arduino-nano, esp8266, reset
---


# Question
Title: Problems with Windows 8.1 install of Arduino IDE
I have replaced my Arduino, thinking it would solve the problem, but I still get it. Whenever I try to upload code, I get the error messages programmer is not responding and not in sync. Then I heard Arduino had drivers required. But my Windows 8.1 didn't recognize Arduino Uno. It was put in the other devices area as an unknown device in the device manager. The update driver button is greyed out. I get the message:

> The drivers for this device are not installed (code 28). There are no compatible drivers for this device. To find a driver for this device, click update driver.

That's the greyed out button… When I look at driver details, it says 'No driver files are required or have been loaded for this device.' For the not in sync/programmer not responding error, I've tried restarting the board before uploading, restarting whilst uploading, you say it, I've done it. How can I fix this so I can finally follow my dream to be an engineer/programmer?

# Answer
Getting started with a new toolchain can be quite a challenge…

I'm not a Windows guy, but it looks like there **are** drivers that need to be installed to get things working with the Arduino. I'm guessing that what is going on here is that Windows is looking locally for drivers and not finding them (or any indication that drivers are needed). I think the button was grayed out because it couldn't help – not because help wasn't needed.

Here are a few sources that I found by searching on:

> arduino driver windows 8.1

1. \[SOLVED\] Arduino drivers for Windows 8.1 64bit
2. Windows 8.1 (64bit) USB-serial driver for Arduino?
3. Installing the Arduino IDE – Windows 8.1 & 10
4. Install Arduino Drivers on Windows 8

While we're at it, it is worth mentioning that "out of sync" error message from avrdude are very common. A bit of searching here will find you some good resources on solving them as well – deal with the drivers first, then see if errors persist.
> 1 votes

---
Tags: arduino-uno, windows
---


title: Using / calibrating pH sensor module

text:
# Question
Title: Using / calibrating pH sensor module
I've bought this sensor module board to link to an Arduino nano: http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326

I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so.

So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment).

Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea.

Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :)

**Update 09-11-2015**

Got feedback from the seller. She sent me the following ZIP: http://1drv.ms/1MSk1DX. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible.

The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:

```
 avgValue = 0;
 for (int i=2;i<8;i++)       // take the average value of 6 center sample
   avgValue+=buf[i];

 float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
 phValue=3.5*phValue+Offset;

```

Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from?

Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.

Schematics can be found in the ZIP file by the way.

**Update 11-11-2015**

Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using

```
buf[i]=1024 - analogRead(SensorPin);

```

Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results:

```
pH 7.0 reference --> 6.27
set offset to: 0.73
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.86

```

So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:

```
pH 7.0 reference --> 8.70
set offset to: -1.70
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.70

```

The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though.

To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right.

**Another update**

Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: http://1drv.ms/1lkAO6e. Next question is how to convert this into a suitable formula?

**Update 18-11-2015**

Working on @slash-dev's solution, here's what I did:

I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:

```
int rawValue = analogRead(SensorPin);
int buf[10];                //buffer for read analog

for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
{
   buf[i] = rawValue;
   delay(10);
}

// sorting left out to reduce the sample length

int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
   avgValue += (buf[i] - CENTER);

```

In this stage I'm printing the raw value of course.

The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.

Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good.

Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.

Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot?

When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one.

So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus.

Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere.

**Next update: :)**

So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.

So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :)

**USB power vs linked?** Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

# Answer
> 3 votes
The schematic only shows one trim pot (R23), and it does, as you suspect, set a level for the LED to illuminate. More of a GOOD/BAD indicator, and is available on pin `DO`.

The other trim pot is not on the schematic. Is it marked on the board? R6, R7, R8 or R9 maybe? It probably controls the gain on `p_AOUT`.

`t_AOUT` is an analog temperature voltage, and appears to measure the temperature of the board.

**Edit - official but totally bogus:** According to my secret source, you are supposed to put the probe in the pH 7.0 reference solution and, with `Offset` defined to be 0.0, run the program and display the calculated pH value. You may need to decrease the trim pot gain to get smaller (the smallest?) numbers. Now take that displayed value and modify the `Offset` constant in the sketch to be 7.0 minus the displayed value. If the displayed value is 8.1,

```
#define Offset (-1.1)

```

Build and upload the modified sketch. This time, put the probe in your pH 4.0 reference solution and adjust the gain pot until the displayed value is as close to 4.0 as you can get. This will calibrate it for mostly acidic solutions.

---

# Edit 1: Iterate?

It's not clear, but I also wondered if this procedure is supposed to be iterated. Go back to 7 and make sure that adjusting the gain didn't change `Offset`. Then test the pH 4 solution again; the gain pot may require a small(er) change. If it seems to be diverging, um, don't do that. ;) I think it would diverge only if the probe had an inverted response, which would probably mean it's bad.

If you are measuring basic solutions, do the same procedure with reference solutions of pH 7.0 (of course) and a basic reference solution.

Voilà!

NB: For the 7.0 test, you could short the probe pins together. It really should look like a short circuit when pH == 7.0. If switching to using the real probe in the pH 7.0 solution gives wildly different readings, the probe *may* be bad. If you're able to calibrate it, it *may* be "good enough".

---

# Edit 2: Fix the formulas in the provided sketch.

The schematic shows a non-inverting op amp with `PH+` on the input, and `p_AOUT` on the output. The (adjustable?) gain is

```
R9/R8 + 1 = 10k/10k + 1 = 2

```

The slope of an ideal probe response is -59mV/pH. You were experimentally getting a negative slope, which agrees with the schematic. I believe it was correct to "invert" the `analogRead` value by subtracting it from 1024. There is no way that the provided code could have worked with a positive slope of 3.5.

The reference voltage provided to the the `PH-` pin is half the zener diode voltage... which is unidentified. It could be the very-common 5.1V part, which is essentially forcing `PH-` to be at

```
5.1V/((R6+R7)/R6) = 5.1V/2 = 2.55V

```

I say probably, because you usually want the plus or minus probe voltage swing to have as much room as possible. This would imply (an ideal) `analogRead` of pH 7.0 to be

```
2.55V/5.0V * 1024 = 522

```

This is the "center" of the probe swing about pH 7.0.

### Step 1: Determine the reference voltage

At pH 7.0, print out the raw `analogRead` return value, before inverting it. (The pot wiper should be at it's limit. Which way, I don't know. Changing the gain pot shouldn't change the `analogRead` very much at the low-gain end. If it does change it, turn it to the other extreme.)

As stated before, you can run the pH 7.0 test by shorting the BNC connector pin to the shield or by using your reference solution. I recommend shorting for now, to eliminate any possible interference from the probe. It will absolutely determine the offset, but only if the gain is as small as possible. You have to start here. Once you know the center reading, you can change the code to display the voltage:

```
#define CENTER 522
int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
  avgValue += (buf[i] - CENTER);
float voltage = (((float)avgValue) / 6.0) * (5.0 / 1024.0);

```

Print this out. You'd better get something close to 0.0... don't make me come over there. :)

### Step 2: Set the gain pot.

This is determining the slope, but you need to maximize the swing for the most extreme pH you want to read, say 4.0. Using the 4.0 reference solution, adjust the gain pot so that the displayed voltage is close to +2.5V, say +2.25V to make sure it's not pegged at 1024. (Let's see, slope is negative, 4.0 is \< 7.0, so voltage should increase...) With that reading, you can calculate the pH/V:

```
-3pH/2.25V  =  -1.33 pH/V

```

### Step 3: Calculate and print pH

Modify the original computation to use the pH/V slope:

```
float phValue = voltage * (-1.33) + 7.0;

```

This is not even close to `phValue = 3.5*voltage + Offset`. -\_- I have found several source now that echo my original answer. Totally wrong, and wrong to the point of misleading. I do think these steps will do it. It sounds good in my head, anyway. :D

---

# Edit 3: "Next question is how to convert this into a suitable formula?"

Ok, if you don't want to fix the formula in the code, you can fit a linear or quadratic curve to your data. Linear is actually recommended as "good enough", and that is effectively the change suggested in **Edit 2**. If we just use your data points, though, this would be the linear approximation:

```
float adjustedPh = phValue * 1.627 - 2.499;

```

...and the quadratic approximation:

```
float adjustedPh = (-0.01796 * phValue + 1.8056) * phValue - 2.94;

```

# Answer
> 2 votes
> **USB power vs linked**

Just to add my 2 cents on your latest update about the USB or 5V from the PI.

You say you connect it to the VIN:

> as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage \> 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.

I recommend you connect your ***power from the PI to the arduino's VCC*** as this is a regulated 5v and doesn't need to be regulated again.

# Answer
> 1 votes
I don't know if this is a complete answer, but I can't comment yet.

The analogRead function in Arduino which is used by your sensor reads values from 0 - 5V. It divides the values between 0 and 5V in 1024 steps. So it returns a value between 0 and 1023. That is why it is multiplied by 5. It is easier to understand if the calculation is done in reverse order. Example:

analogRead returns 512, so that is on 1024 / 512 = 0,5th part of its range. Multiply that by 5.0 to get the actual voltage. 0.5 * 5.0 = 2.5. It is then divided by 6 to get the average.

I would also change the order of the calculation. The comments say that it calculates the average, but it doesn't it just adds the values. It does divide it by 6 eventually so that does not cause the error, but for readability it is generally good practice to let your code do what the comments say.

# Answer
> 0 votes
As a first approach, I'd collect a number of measurements from each of as many knowns as you can find or make, and plot them for a visual clue to the linearity or not (probably not) of the sensor's output vs. pH. You could try to eyeball-fit a curve to the data; interpolate linearly between sample points if you have enough of them; or run a least-squares approximation fit. The key is you'll need enough data - knowns - to make whatever approach you use give results accurate enough for your intended use. (Obviously this will be different if you just need to know if something is acidic or basic, or you're monitoring tropical fish tanks, etc.)

Update: If your pH meter is good enough for the fish, and if your sensor is reliably repeatable and sensitive enough, why not check your meter against the two standards, then calibrate the sensor to your meter? Once you're happy with the result, lock down the screws with a dab of nail polish (it's not very tamper-proof but it will be tamper-evident). A pH 10.0 standard won't be very useful to you; at that extreme you'll already know the pH is out and you probably won't care about the exact value. You need your precision between the fish-tolerable limits, close to the pH goal. In fact, if you trust your meter, you don't even need the standards. In that case you need only make up a few samples as you described, covering the pH range of interest, and use them to calibrate your sensor to the meter.

# Answer
> 0 votes
I can't ask a question but make sure you're giving it enough power for the heating element, its not much but you never know try a separate power source if you are not.

Now you mentioned the nano, are you using a 3.3v nano or 5V nano? (the regulator would have a 33 or 50 on it after a letter or two) if 3.3V and assuming by example code they give the analog output is 5V you'll need a level shifter of sorts to map to 3.3V, then change the calculations to use 3.3 instead of 5 value. if that's not the case and it's not power or connections then it may be broke or the probe etc.... there's a few variables.

# Answer
> -1 votes
> **USB power vs linked**

Read it and use current Vcc instead of 5.0 in your code.

I have the same sensor and have the same problem. I'll be glad if you share full working code in this thread.

---
Tags: sensors, c++, arduino-nano
---


title: Xbee for Arduino Uno

text:
# Question
Title: Xbee for Arduino Uno
I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. (XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))

Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?

# Answer
> 3 votes
What you have there is an XBee *module*. It is designed to plug into an XBee *shield* which then plugs into the Arduino.

So you need to buy more.

That's the bad news. The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.

Numerous people make the shields, such as:

Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going. If you want to talk to your computer there is a device called the XBee Explorer which plugs into the PC to allow you to communicate with an XBee module.

---
Tags: arduino-uno, hardware, communication, xbee
---