# Question
Title: Classes and objects: how many and which file types do I actually need to use them?
I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.

So I have seen that you can have the following ways (not exhaustive list) to organize code:

1. A single .ino file;
2. Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
3. An .ino file with an included .h and .cpp file in the same folder;
4. Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

* Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
* **\[preferred approach\]** Including a .cpp file where a class is declared, but *without* using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

# Answer
## How the IDE organizes things

First thing, this is how the IDE organizes your "sketch":

* The main `.ino` file is the one of the same name as the folder it is in. So, for `foobar.ino` in `foobar` folder - the main file is foobar.ino.
* Any other `.ino` files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
* This concatenated file becomes a `.cpp` file (eg. `foobar.cpp`) - it is placed in a temporary compilation folder.
* The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
* The main file is scanned for `#include <libraryname>` directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
* Any `.c`, `.cpp` or `.asm` files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
* Any `.h` files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
* The compiler adds into the build process standard files (like `main.cpp`)
* The build process then compiles all the above files into object files.
* If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you `strcpy` etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

---

## Avoiding the pre-processor quirks

The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other `.ino` files). Then make another tab (a `.cpp` file) and put your stuff into it like this:

```
#include <Arduino.h>

// put your sketch here ...

void setup ()
  {

  }  // end of setup

void loop ()
  {

  }  // end of loop

```

Note that you need to include `Arduino.h`. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

---

## Avoiding the setup/main paradigm

You don't have to run with the setup/loop concept. For example, your .cpp file can be:

```
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

```

---

## Force library inclusion

If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main `.ino` file:

```
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

```

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

---

## Naming issues

* Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.
* Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

---

> Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:

```
class foo {
  public:
};

foo bar;

void setup () { }
void loop () { }

```

However you are probably best off to follow normal practice: Put your declarations in `.h` files and your definitions (implementations) in `.cpp` (or `.c`) files.

### Why "probably"?

As my example shows you *can* put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).

If this class is then used in multiple other files in your project this is where the separate `.h` and `.cpp` files come into play.

* The `.h` file *declares* the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.
* The `.cpp` file *defines* (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.
* The `.h` file is what gets included into other files. The `.cpp` file is compiled once by the IDE to implement the class functions.

### Libraries

If you follow this paradigm, then you are ready to move the entire class (the `.h` and `.cpp` files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. `myLibrary`) and put the `.h` and `.cpp` files into it (eg. `myLibrary.h` and `myLibrary.cpp`) and then put this folder inside your `libraries` folder in the folder where your sketches are kept (the sketchbook folder).

Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

---

A bit more detail here.
> 34 votes

# Answer
My advice is to stick to the typical C++ way of doing things: separate interface and implementation into .h and .cpp files for each class.

There are a few catches:

* you need at least one .ino file - I use a symlink to the .cpp file where I instantiate the classes.
* you must provide the callbacks that the Arduino environment expects (setu, loop, etc.)
* in some cases you will be surprised by the non-standard weird things that differentiate the Arduino IDE from a normal one, like automatic inclusion of certain libraries, but not others.

Or, you could ditch the Arduino IDE and try with Eclipse. As i mentioned, some of the things that are supposed to help beginners, tend to come in the way of more experienced developers.
> 6 votes

# Answer
I'm posting an answer just for completeness, after finding out and testing a way of declaring *and* implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.

Blinker.ino

```
#include <TurnSignals.cpp>

TurnSignals turnSignals(2, 4, 8);

void setup() { }

void loop() {
  turnSignals.run();
}

```

TurnSignals.cpp

```
#include "Arduino.h"

class TurnSignals
{
    int
        _left,
        _right,
        _buzzer;

    const int
        amberPeriod = 300,

        beepInFrequency = 600,
        beepOutFrequency = 500,
        beepDuration = 20;

    boolean
        lightsOn = false;

    public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
    {
        _left = leftPin;
        _right = rightPin;
        _buzzer = buzzerPin;

        pinMode(_left, OUTPUT);
        pinMode(_right, OUTPUT);
        pinMode(_buzzer, OUTPUT);
    }

    public : void run()
    {
        blinkAll();
    }

    void blinkAll()
    {
        static long lastMillis = 0;
        long currentMillis = millis();
        long elapsed = currentMillis - lastMillis;
        if (elapsed > amberPeriod) {
            if (lightsOn)
                turnLightsOff();
            else
                turnLightsOn();
            lastMillis = currentMillis;
        }
    }

    void turnLightsOn()
    {
        tone(_buzzer, beepInFrequency, beepDuration);
        digitalWrite(_left, HIGH);
        digitalWrite(_right, HIGH);
        lightsOn = true;
    }

    void turnLightsOff()
    {
        tone(_buzzer, beepOutFrequency, beepDuration);
        digitalWrite(_left, LOW);
        digitalWrite(_right, LOW);
        lightsOn = false;
    }
};

```
> 6 votes

---
Tags: programming, c++, class
---


title: How to writte simple string compare?

text:
# Question
Title: How to writte simple string compare?
I new to Arduino and I'm attempting to writte a simple string compare code like this:

```
void loop()
{
  distance(cm);
  delay(200);
}

void distance(char[3] unit)
{
  if (unit[] == "cm")
    Serial.println("cm");
}

```

Could somebody please advise me how to writte it correctly? Thanks in advance!

# Answer
> 0 votes
```
if (strcmp (unit,"cm") == 0) {

    // matches cm

}

```

For syntax like this the intellisense in products such as Atmel Studio or Visual Studio can really help. Whilst you still need to understand what you might be looking for the intellisense makes all the available Arduino functions visible from the code. If you install the Arduino plugin then there will be an Arduino reference explorer in both ide's which explains everything.

---
Tags: string
---


title: Hall Effect Sensor for POV Project

text:
# Question
Title: Hall Effect Sensor for POV Project
I'm making a POV project and need to count the RPM of the DC Motor.

I purchased a Hall Effect Sensor and it seems to work perfectly at slow speeds, however once the motor speeds up, the sensor doesn't pick up the magnet at all.

The datasheet for the sensor is at: http://cdn.shopify.com/s/files/1/0045/8932/files/AH180.pdf?100744

This is one of my first projects and I'm not sure what I should be looking for on the datasheet.

The sensor came as part of this product: http://www.freetronics.com.au/pages/hall-effect-magnetic-and-proximity-sensor-module-quickstart-guide#.VZ0Zs\_meDGc

There doesn't seem to be a problem with the code:

```
int pin = 13;
volatile int state = LOW;
volatile int tcnt = 0;

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, CHANGE);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(pin, state);
  Serial.println(tcnt);

}

void blink()
{
  tcnt = tcnt + 1;
  state = !state;
}

```

Thanks!

# Answer
From the datasheet of the hall effect sensor, the thing is only checking for 125usec in every 125msec - so if your magnet whizzes by in \<100msec it will miss it.

Obviously you haven't stated the speed your magnet passes your sensor, but as it's only active 0.1% of the time, this seems the likely reason to miss.

Can you put it nearer the shaft/axle ?
> 1 votes

---
Tags: sensors
---


# Question
Title: Is it possible to see a graphical view of digital and analog pin values?
Using Visual Studio for my Arduino project I am struggling to know the states of various pins during operation.

I do use the Visual Micro debugger but I don't want to have to set a watch for every pin.

How can this be done easily?

# Answer
Visual Micro provides this for you if you have the debug module enabled. It also optionally shows analog, memory and i2c. Read more about Arduino debug and the digital pin viewer
> 0 votes

# Answer
The Arduino Dashboard project sounds promising but quite likely it loops through the I/O pins periodically and uploads the results to your PC. I'm guessing you want live monitoring (as opposed to snapshots) while your own program (not the Dashboard sketch) is running. In that case, you'd need to isolate the relevant parts of the Dashboard sketch and integrate them with your code, and unless your are looking for fairly low frequency signal changes, have a timer interrupt function that runs the Dashboard frequently, which will have an impact on your own code. If the signals are fairly low frequency you might get away with putting a call to Dashboard in your `loop()` function instead of running it from a timer interrupt. If you're looking for program bugs that are changing your outputs, once per `loop()` may be fairly useless. A timer-interrupt would be necessary, and might have to analyze the stack and output the names or addresses of functions that had run recently. At that point you'd be on your way to implementing a debuggerand may want to consider an in-circuit emulator or a bus analyzer to capture the event. Or get smarter about isolating the code responsible for the event until you have a manageable, printf-debuggable code segment.
> 0 votes

---
Tags: arduino-mega
---


title: How do I debug on-chip with Arduino?

text:
# Question
Title: How do I debug on-chip with Arduino?
Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?

# Answer
> 6 votes
The Arduino Uno uses the Atmel Atmega328p microcontroller, which only has one debug option, DebugWire. There are a few tools that can work with it, but the least expensive and most commonly available is the AVR Dragon.

You can use AVR Studio 6 for this. You can use the `.elf` file file produced during the Arduino build process directly, but setting up the debugger is a little easier if you port the Arduino program to the AVR Studio. It's not difficult, but there are a lot of little pieces to deal with. There are guides online to help you through this.

# Answer
> 1 votes
This might not be right for you, but the Visual Micro plugin for Atmel Studio and Visual Studio has a USB debugger which only uses Arduino code.

In the background the debugger uses Serial which might affect some time-sensitive applications.

---
Tags: ide, emulation, debugging
---


# Question
Title: I2C TinyWireS SEND: How to convert unsigned long to uint8_t array?
How do you convert an unsigned long to a `uint8_t` array? I am interested in sending an unsigned long integer from an ATTiny85 to an Arduino Uno via I2C. The issue is with `TinyWireS.Send()` which can only send a var of type `uint8_t`. I believe the solution would be to use `TinyWireS.Send()` in an array?

# Answer
> 1 votes
This might not be politically correct code, but it is pretty simple to just cast a pointer to uint8\_t like this:

```
long data = 5;
uint8_t *rx = (uint8_t*) &data;

```

You can still use array subscripts even though its a pointer, and you can pass it to a function like an array. Just don't go past `rx[3]`.

Alternately, you could also make a union like this:

```
union{ long data; uint8_t bytes[4]; } convert;
convert.data = 5;

```

And then use `convert.bytes` as your array to send.

# Answer
> 0 votes
I do exactly this with an ATtiny You have 32 bit long that needs to be broken up into 4 8-bit chunks. You need to some simple bit shifting to accomplish this.

```
volatile unsigned long Data1;//this is the data you are sending
volatile byte SendCount;
volatile uint8_t sendByte;

void requestEvent()
{

  SendCount++; //increment this
  switch (SendCount)
  {
    case 1:
      Data1 = GetMyData();
      //Data1 = 55555;
      sendByte = Data1 & 0xFF;
      break;
    case 2:
      sendByte = Data1 >> 8;
      break;
    case 3:
      sendByte = Data1 >> 16;
      break;
    case 4:
      sendByte = Data1 >> 24;
      SendCount=0;
      break;
  }

  TinyWireS.send(sendByte);
}

```

You need to initialize `SendCount = 0;` in your Setup method.

You will need to recompose the 4 bits back into a 32 bit long on the Master device too.

---
Tags: i2c
---


# Question
Title: RC servo misbehave using arduino and MPU6050
I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050. I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.

```
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);

pitch_angle = (ypr[1] * 180 / M_PI) + 90;
roll_angle = (ypr[2] * 180 / M_PI) + 90;

Serial.print(pitch_angle);
Serial.print("\t");
Serial.println(roll_angle);

pitchServo.write((int)(pitch_angle));
rollServo.write((int)(roll_angle));

```

Without servo being connected everything works well. But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.

```
100 95
ypr 12.21   10.51   5.49
100 95
ypr 12.23   10.31   5.48
100 95
ypr 12.25   10.15   5.45
100 95
ypr 12.27   10.02   5.45
100 95
ypr -13.31  30.81   55.76
120 145
ypr 20.53   -21.36  -52.59
68  37
ypr 64.96   35.38   10.25
125 100

```

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.

**EDIT:** Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base. Wiring is very simple:

Any idea? Thanks

# Answer
> 1 votes
At the end two pull-up resistors and one capacitor solved the problem.

I followed instruction here:

http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/

Now it works well.. Thank you all.

# Answer
> 0 votes
So a couple of ideas.

1) you need to be real careful with the MPU and overflows. You do not show all your code, but you must check for overflows, and ignore the data if one has occurred. I see in your print a stray negative value, that tells me you are not skipping bad data.

2) I dont know how 'tight' your loop is. You need to service the MPU a lot. In fact the sample you used, uses an interrupt to do so. I think the default update rate is about 100 times per second. That may be too fast to make large changes in servo positions. You will need to think about moving slower from point A to B if the difference is more than the servo can handle at that speed.

3) You are adding 90. With the numbers you have shown that is probably ok, but in your final code you need to be careful you do not exceed a servos range, 0 to 180. the map() function is probably something you will want to use, instead of just adding 90.

4) My guess is that since it works for a second or 2, it is indeed over flowing data, and then goes to heck. Especially since you do not skip errors.

5) it takes the 6050 30 seconds or so to settle - so you will see large gyro drift (including PitchRollYaw) until it does. Probably not what your code is expecting.

---
Tags: servo, gyroscope
---


# Question
Title: Using Arduino To Control Boot Sequence of PC
I want to know if it is possible to use an arduino to tell a pc which os to boot to. I know It is possible to turn on the pc by wiring it to the motherboard pins with the power switch, and I know the arduino I have (http://www.amazon.com/SainSmart-ATmega328P-Development-Compatible-Arduino/dp/B00E5WJSHK/ref=sr\_1\_1?ie=UTF8&qid=1436368217&sr=8-1&keywords=sainsmart+uno+r3) can act as a mouse or keyboard. Can that be done before the pc has booted however?

# Answer
So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.

The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.

A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a serial console. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.
> 2 votes

---
Tags: keyboard
---


# Question
Title: Arduino UNO with LMT86LP temperature sensor
I am trying to use the Arduino Uno with the LMT86LP temperature sensor, but I am getting strange output voltages from the sensor.

I have the pins (from left to right, flat side facing forward) as VDD, OUT, and GND. VDD is connected to 5V, GND to GND, and Vout to A0 (analog pin 0). The readings from the Arduino are consistently around 360 mV but should be somewhere around 1800 mV as I measured the output of the sensor using a multimeter and got a constant 1.8 V.

Right now the code is very simple. I am just doing `analogRead()` and printing to the Serial Monitor.

# Answer
> 1 votes
The result from `analogRead()` is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.

1.8V/5V⋅1024=368.64

---
Tags: arduino-uno, temperature-sensor
---


title: PWM-FILTERS -DAC

text:
# Question
Title: PWM-FILTERS -DAC
I want to implement a digital controller C(z) on an Arduino Uno (transfer function in the z domain) in order to control a plant

```
G(s) = 3750/[(s+10)(s+30)(s+100)].

```

I have implemented G(s) with electronics (op-amps, capacitors and resistances). I want to realize C(z) on the Arduino Uno. The input to the Arduino is the error signal `(reference − output of G)` and the output of C(z) is the input of G(s). Finally, I will have a closed loop system with negative unit feedback. The reference input is a unit step signal (1 volt).

My problem is: how can I use PWM and filters in place of a DAC?

# Answer
> 1 votes
If you want to use PWM in place of a DAC, the normal thing to do is to use some kind of analog low-pass filter. However, many people skip the filter when the signal is meant for some system that inherently acts as a low-pass. Example: dimming an LED, where the human eye is the filter.

In your case, since your plant looks like a third order low-pass filter with cuts at 1.6, 4.8 and 16 Hz, you can probably skip the filter. If you output on pins 5 or 6, the PWM frequency will be around 980 Hz (exactly: fCPU/16384). At that frequency, your plant gain relative to DC will be

G(j2π × 980 Hz) / G(0) ≈ 1.3 × 10−7 j

Probably low enough to not be an issue.

---
Tags: pwm, digital-analog-conversion
---


# Question
Title: Write to file in SD card in wave shield V3
I just started tinkering with Arduino. I'm curious to know though, is it possible to read and write to a file stored in the SD card in the Wave shield v3 by Elechouse? I'm able to play files stored in said SD card, but I don't know how I'd go about writing some logs. I'm using an Arduino Mega.

Thanks in advance.

# Answer
No, you cannot. The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card. The only control you have is IO pins that emulate pressing the buttons on an MP3 player.
> 1 votes

---
Tags: arduino-mega, shields, sd-card, audio
---


# Question
Title: XBee on Arduino Fio - how to read the status of a local digital XBee output pin?
I am using a Fio to control a set of relays. The unit uses an XBee (series 1 Pro) in transparent mode to receive commands over serial UART and everything works fine. The XBee is also configured for digital Input/Output Line Passing and the XBee on the Fio "mirrors" on an output pin the input state on a remote XBee and also this works fine.

How can I interrogate from the Fio the state of the output pin (e.g. D0) of the local (receiving) XBee? Is there an AT command that I could send via `Serial.println("ATxx")` that would trigger the XBee to send back over UART the status of the pin (high or low)?

# Answer
> 1 votes
You cannot read the state of output pins via an AT command, you can only read the state of input pins using the ATIS command.

See: http://ftp1.digi.com/support/documentation/90000982\_S.pdf

---
Tags: xbee
---


# Question
Title: Use Arduino to detect low battery state and shut it down
I wanted to know if it is possible to monitor a battery that is driving the Arduino and check its voltage. When the voltage drops below a certain level (i.E below 3.0V) it should shutdown and disconnect itself from the battery by using a relay or something. When the battery is full enough again it should power up again. Is that possible without any external sensors just by using the Arduino's inputs?

# Answer
It is not entirely beyond possible, in fact quite possible in theory.

I think the saying 'in theory, theory and reality are the same, but in reality they are not' is appropriate here.

So to monitor voltage, a simple voltage divider circuit can be used, and the Arduino can monitor that, and release a relay controlling the power line. The same relay could be wired to also reconnect when voltage reaches a threshold. I think the circuit actually requires 2 (or more) relays, and technically is it a kind of sensor, but since you indicated a relay was ok, it could work. So given those requirements, do you really need someone to draw it out, or were you just curious?

Simple battery monitoring from http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html
> 1 votes

# Answer
Have a look here http://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/ It is for bare metal Atmel chip, but applicable to Arduino as well probably. Step one in getting longer battery life is to move to a bare metal Atmel chip, choose ATMEGA or ATTINY depending on how many pins you need. Also see my answer here What are (or how do I use) the power saving options of the Arduino to extend battery life?
> 1 votes

# Answer
I'm assuming Arduino is powered directly by the battery, and not via a voltage regulator. In that case you van measure VCC by first measuring the internal 1.1v voltage reference (in relation to Vcc). Since the internal 1.1v is constant and VCC will lower over time, the reading (0-1023) will increase.

See this article: http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/
> 1 votes

---
Tags: power, voltage-level, battery
---


# Question
Title: Choose the correct solar panel and battery for solar use
I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.

Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.

# Answer
> 3 votes
I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.

## Battery

For the battery there are a few different ways to figure this out:

1. The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
2. You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
3. A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.

## Solar Panel

For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.

So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.

---
Tags: sensors, power, arduino-nano, battery, solar
---


# Question
Title: Arduino WiFi shield working intermittently, "WiFi Shield not present"
I am trying to use the official arduino wifi shield, It works occasionally, but most of the time (when running the WiFi web server example code, or my derivitave program, it outputs `WiFi shield not present` on the terminal. I have tried updating the firmware several times, but it has not fixed the problem. Is the wifi shield always this unreliable? What can I do to fix it?

# Answer
> 1 votes
Be sure the shield is not shorting out on the metal USB socket on the Arduino board. I don't know if this is still an issue but I've seen many Arduino boards with black electric tape on the top of the USB socket to insulate it from shorting out the shield.

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


title: How to use C Libraries for Arduino code

text:
# Question
Title: How to use C Libraries for Arduino code
I have a code in Visual studio that I want to implement in Arduino. But there is a problem. Many libraries usable in Visual Studio aren't usable in the Arduino IDE. How can I use them in my Arduino code? To be precise, the libraries I want to use are

```
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>

```

I know I have `<iostream>` available in Arduino. `<math.h>` is also available I think along with the `<string>` library. The main problem is to how to use `#include<queue>` and its functions such as `priority_queue()` and other functions of iosteam like `.pop()`? Any help would be highly appreciated.

# Answer
> 4 votes
Some of the libraries you mention (iomanip, iostream, queue, string) are part of the STL - Standard Template Library. Whilst it does not ship with the IDE download, you can install it yourself. See The Standard Template Library (STL) for AVR with C++ streams \- a port to the Arduino by Andy Brown.

I have some implementation notes here.

Be aware that a lot of Arduinos don't have much RAM, so you need to use libraries like this with caution.

Library download: AVR standard template library, version 1.1.1 \- 197.29 kB

---
Tags: c++, c, ide
---


title: Controlling DC motor speed?

text:
# Question
Title: Controlling DC motor speed?
I'm trying to control a DC motor through L293D motor controller

```
const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

void setup(){

  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);

  digitalWrite(enablePin, LOW);
  digitalWrite(controlPin2, LOW);

Serial.begin(9600);
Serial.println("Ready");
}

void loop(){
if (Serial.available() > 0) {
    int inByte = Serial.read();

    switch (inByte) {
    case '0':
  digitalWrite(enablePin, LOW);
   digitalWrite(controlPin2, LOW);
 Serial.println("OFF");
      break;
    case '1':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 50);
    Serial.println("CW slow");
      break;
          case '2':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 100);
    Serial.println("CW slow +");
      break;
          case '3':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 150);
    Serial.println("CW medium");
      break;
          case '4':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 200);
    Serial.println("CW fast");
      break;
          case '5':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 250);
    Serial.println("CW fast +");
      break;
    case '6':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 50);
    Serial.println("CCW slow");
      break;
      case '7':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 100);
        Serial.println("CCW slow +");
      break;
      case '8':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 150);
        Serial.println("CCW medium");
      break;
       case '9':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 250);
        Serial.println("CCW fast");
      break;
}
}
}

```

It is working well except 1 to 5 are reversed:

* 1 should be the minimum speed
* 5 should be the maximum.

But it is back to front:

* 5 is the minimum speed
* 1 is the maximum speed

Any ideas?

# Answer
So first thing, you should try to be more disciplined with your code formatting and the question...

FYI: it's best to use #define as it doesn't use memory for storing pin numbers... It's like Find and Replace in a text editor, this:

```
const int controlPin2 = 4; // connected to pin 2 on the H-bridge
const int enablePin = 3;   // connected to pin 1 on the H-bridge

```

Becomes this:

```
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

```

So this is the tidied up code, you can see the problem is a lot more approachable when the code is indented consistently, and good use of spaces and new lines is used...

```
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '5':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}

```

So your actual problem is that you need to reverse cases 1, 2, 3, 4, 5 to be 5, 4, 3, 2, 1...

There are two solutions:

1. **Inelegant**: would be to simply change the case numbers, they don't have to be in-order.
2. **Elegant**: copy and paste the code in each of the 5 cases about.

The result of option 2 is as follows, please feel free to confirm this is working?

```
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '5':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Industry Standard for Single-Board Computers?
Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor? I'm trying to sell management on using Arduino, but they are stuck on the question "what if Arduino goes out of business", and if I could answer "we can just switch over to using brand X because it's the same size and has the same connectors", my life would be much easier.

# Answer
> 1 votes
* Whether or not the Arduino company goes out of business isn't all that relevant. For one thing, there are now two competing companies vying for the Arduino trademark - arduino.cc and arduino.org.
* The Arduino has such a ground-swell of popularity that clone boards are widely available on eBay and from other suppliers. While people are willing to buy them, someone will sell them.
* The design is open-source, which makes it a safer choice than other designs who keep their design proprietary. For one thing, it guarantees that someone will make compatible boards, even if Arduino(s) fold.
* The "heart" of the Arduino is (in most cases anyway) a chip from Atmel - so you really should ask if Atmel will go out of business. Probably not, but in any case, an alternative supplier might just as easily go out of business.
* I wouldn't be building an "Arduino board" into a production system anyway - too much chance that wires would fall out of the prototyping sockets. However the prototyping board is good for learning about their capabilities, and testing your code.

> Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor?

I'm not aware of any industry-standard form factor. The Uno design has caused a *lot* of people to make "shields" that fit onto that form factor, so that is probably the closest you would get to an industry standard.

# Answer
> 0 votes
If you need a real computer, there are nowadays various options based on the Intel NUC concept. The Gigabyte variant, for example. It also has GPIOS accessible through a normal pinheader, in case you need them. And, being x86, there is virtualyl no risk of loosing the supplier.

---
Tags: hardware
---


# Question
Title: HC-SR04 quits pinging when distance < 0 || distance < MAXDISTANCE
so here is the issue. I have a mega 1280, a handful of neopixels and a HC-SR04. I am using the New Ping library (tried both 1.5 and 1.6). I am trying to make a device that will tell my mom when she has pulled into the garage enough so she don't get hit by the garage door AND doesn't run into the wall. I wrote a bunch of code to handle the lights and what colors to do when and this part works perfectly. My issue is with the sensor. It works great except for 2 specific conditions.

1. if you are too close. I normally either cover one of the 2 sonic sensor part or just barley touch then with a piece of cardboard (or anything for that matter
2. If you go outside the scope of the max distance

when either of this are met, the ping sensor stops clicking and it just returns all 0's for the output. I am including the code less the part for the lights because even if i remove that part of the code, it still fails on those 2 conditions.

```
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
#include <NewPing.h>
#define TRIGGER_PIN  52
#define ECHO_PIN     53
#define MAX_DISTANCE 120
#define PIN 6
#define LEDNUM 8

int codeFact = (MAX_DISTANCE / (LEDNUM * 3));
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDNUM, PIN, NEO_RGB +     NEO_KHZ800);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  strip.begin();
    strip.show();
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 0, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 0, 0));
      strip.show();
      delay(50);
    }

Serial.begin(115200);
}

void loop()
{
 delay(2000);
  int uS = sonar.ping();
  int dis = uS / US_ROUNDTRIP_CM;
  Serial.println(dis);
  /*
  Light code normally goes here
  */
}

```

# Answer
The HC-SR04's range is 2cm to 300 cm, if you exceed this range or come below this range, which is exactly what you are doing, the utrasonic sensor will not receive any echo and hence there will be no data on the output. If you bring it too close and since both the transmitter and receiver located close to each other, the receiver will not receive any ultrasonic. Put a function that checks if the ultrasonic comes down to 2-3. If it becomes true beep a buzzer that tells you that you are too close. Don't let it reach 0.
> 1 votes

---
Tags: arduino-mega, sensors
---


title: How to read pH value

text:
# Question
Title: How to read pH value
I am trying to read the pH value from a analog pH meter, SEN-01454. From the source code I found, voltage maps to pH value. This is the code:

```
pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();

```

But then the value is not correct. So how do i actually do it.

The example code from Wiki page for product.

# Answer
> 1 votes
This is SOME of the code. We are missing the `avergearray()` function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..

From another source, I got this:

```
/*
# This sample codes is for testing the pH meter V1.0.
 # Editor : YouYou
 # Date   : 2013.10.12
 # Ver    : 0.1
 # Product: pH meter
 # SKU    : SEN0161
*/

#define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
unsigned long int avgValue;  //Store the average value of the sensor feedback
float b;
int buf[10],temp;

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");    //Test the serial monitor
}
void loop()
{
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(10);
  }
  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  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;                      //convert the millivolt into pH value
  Serial.print("    pH:");
  Serial.print(phValue,2);
  Serial.println(" ");
  digitalWrite(13, HIGH);
  delay(800);
  digitalWrite(13, LOW);

}

```

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?

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


title: Change arduino.local server address

text:
# Question
Title: Change arduino.local server address
I have a Yun and I'm trying to change the URL I type in to access the Web UI.

I've successfully changed its hostname in `/etc/config/system`, which now lets me SSH in using the new name. However:

* Going to newname.local doesn't work (no response at all).
* Going to arduino.local pulls up the green page 'Wait a moment or click here...', after which no page is rendered.

How can I access my Yun by typing in newname.local in my browser?

# Answer
That should be working fine.

I just logged into my Yún and changed its name by editing that file. I then restarted `avahi-daemon` since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).

Browsing to the new name worked fine.

```
matt@dell:~$ ssh root@arduino.local
root@Arduino:~# vi /etc/config/system
(edit the config file)
root@Arduino:~# hostname skybridge
(manually changing the hostname so I don't have to reboot)
root@skybridge:~# /etc/init.d/avahi-daemon restart
(restart the avahi daemon)

```

Browsing to `skybridge.local` now shows me the Arduino login as it should.

As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.

There are a number of caches involved in the system, any of which may be getting in the way. It could be that the browser has cached incorrect or out of date information about the FQDN (*fully qualified domain name*) for the name you have given your Yún, in which case just closing and re-opening your browser may help. It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.

Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the `avahi-browse` and `avahi-resolve` commands. OS X has similar tools, but I don't know off hand what the commands are:

```
matt@dell:~$ avahi-browse _arduino._tcp
+  wlan0 IPv4 skybridge                                     _arduino._tcp        local
^CGot SIGINT, quitting.
matt@dell:~$ avahi-resolve -n skybridge.local
skybridge.local 192.168.0.252

```
> 0 votes

---
Tags: arduino-yun
---


# Question
Title: How do I upload sketch (and parameters) through a user interface
I'm pretty new to Arduino and I'm developing my first real-world project.

I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.

What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:

1. How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?
2. When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

# Answer
> How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?

Yes, you have to use avrdude. The simplest way is just to bundle avrdude.exe and the avrdude.conf file with your program and call it, along with its required parameters, with `system()` or some similar (eg `execv()`) method (or whatever Windows has decided to provide instead of those standard functions - who knows what goes through the minds of Windows developers...).

> When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

When you upload a new sketch you are writing to PROGMEM. That's really the only time you can do it. Yes, there are ways you can write pages of data to PROGMEM, and that's exactly what the bootloader does when you upload a sketch, but manipulating individual variables in PROGMEM is not possible without major brain surgery being done in your sketch. To store these kind of tweakable parameters you would normally use the EEPROM.

It can also be good to use external storage for some of these things to - either an SD card (overkill) or an external SPI or I2C EEPROM or Flash chip. This keeps all the data completely separate from your sketch so you can never overwrite that data when you upload a new sketch.

It is, of course, up to your sketch to provide some kind of interface to tweak the settings, whether stored in internal EEPROM or an external EEPROM chip. Creating some kind of serial protocol which your C++ program can interface with will be essential. Only while your sketch is running will you be able to change those variables. If you don't want to allow end users access to that interface then one method could be to have a separate sketch which is a "calibration and configuration" sketch which your program uploads in order to adjust the settings. Once you have finished it then re-uploads the original (or new) sketch to allow normal operation again.
> 2 votes

# Answer
1) Why not just

```
system("avrdude ...");

```

That's more or less what the Arduino IDE does.

2) If you really want to embed the data in the executable, see Embedding Blobs in Binaries. You would need to re-link and re-upload the program each time you change that data. You won't need the Arduino IDE, as it's only job is basically to call avr-g++ and avrdude. You *can* use the IDE if you find it's CLI easier than those of the standard tools.

If you put the data in EPPROM instead, the avrdude can upload it without re-uploading the program.
> 3 votes

# Answer
The avrdude/upload part has been fairly well covered by the other answers, but what has not been mentioned yet is that it is fairy trivial to modify program memory contents by modifying the hex file to be uploaded.

Basically, you just write hex-encoded bytes in the correct place in the file, and then update the checksum at the end of each line you modify. It can help if you put a readily recognizable placeholder sequence in the desired location in your source code, which you can look for in the hex file as an extra verification you are making your substitutions in the correct place. This is fairly straightforward string processing and unsigned byte math which you can accomplish in the language of your choice. There are also tools which can convert between hex files and binary images, and probably tools or libraries which can fix the checksums for you.

Do pay attention to the license terms of avrdude and any other non-original code or tools you distribute.
> 1 votes

---
Tags: c++, uploading, progmem
---


# Question
Title: xbee communication not established between arduino
I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX\>TX TX\>RX and 5V GND)

http://continentalee.com.sg/xbee-adapter My xbee adapter

I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.

Code is here

```
char msg = ' '; //contains the message from arduino sender
const int led = 13; //led at pin 13

void setup() {
Serial.begin(9600);//Remember that the baud must be the same on both arduinos
pinMode(led,OUTPUT);
}
void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

```

The problem comes.

When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.

however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

Thank you for your help in advance.

# Answer
> 0 votes
Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.

Not sure if this will help ...

> Arduino is connected to PC USB... RX\>TX TX\>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

> however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU

You could try this for better diagnostics

```
    void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

      Serial.print("data arrived from xctu: ");
      Serial.print(msg);
      Serial.println();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

```

---
Tags: arduino-mega, xbee, wireless
---


title: Arduino bluetooth module as a server

text:
# Question
Title: Arduino bluetooth module as a server
I was looking around becouse I need to simulate a OBDII device. I think about to use Arduino for that. I was reading some tutorials how to use bluetooth module but I didn't find any tutorial when Arduino is a server. Alway Android app is a server. Is there way to put SP server in Arduino and Android as a client? And do I need special shield/module for that? If you could gave me some links to tutorials or code would be grate. Interesting for me would be also possibility to send data form computer by USB to Arduino then Arduino push it forward to Android. - but that is not must have, first possibility is more importand for me.

# Answer
There are two types of bluetooth devices for Arduino. Some are "slave" only and some are both "master or slave".

There is little difference in price so you should buy one that is master or slave.

This page (HC-05) describes one that appears to be commonly used but there are many and I do not have a recommendation. Some devices are in the form of small boards which connect to the pins on the Arduino (normally serial tx/rx) and some are shields that plug onto an Arduino. The article also shows the connection.

This appears to be an ODBII bluetooth arduino forum thread that uses bluetooth and ODBII. Video

By default Android is in bluetooth master mode. This article appears to show the Android programming required to enable a bluetooth slave.
> 2 votes

---
Tags: serial, arduino-mega, bluetooth, android
---


title: Standalone Atmega 2560 ISP program

text:
# Question
Title: Standalone Atmega 2560 ISP program
First I need to say, I'm a complete electrics newbie, so I need your help.

I have got a standalone Atmega 2560, which I want to program. I connected MISO, MOSI, SCK, RESET, 5V and GND to an Arduino Uno. In addition a 16MHZ oscillator is connected to XTAL1 and XTAL2 plus I pull all VINs of the Atmega with a 100nF to GND. Plus I connected a separate VIN and GND to the 2560.

I programmed the Arduino Uno as an "Arduino as ISP". Afterwards I connected the 2560 as mentioned above, changed the board to "Mega 2560" and tried to upload a sketch through the Arduino and I get the error message: avrdude: stk500v2\_getsync(): timeout communicating with programmer

Is there something I missed?

Cheers jb

# Answer
> 0 votes
I have a sketch that programs bootloaders. A side-effect of that sketch is it fixes up the "divide clock by 8" fuse.

It looks like the wiring will be the same, but cross-check on that page (scroll down to the part about programming the Mega2560).

Once a bootloader is installed you could use it, if you get an FTDI cable, or simply go back to using the ArduinoISP now that the fuse is fixed.

---
Tags: avrdude, isp
---


# Question
Title: Writing MIDI Notes More Quickly to a Shift Register with Arduino
I'm working on an Arduino code which will interpret a given MIDI note message and output the corresponding note number to a string of LEDs as a binary integer. I have adapted it from existing code found on the site Notes & Volts which features a similar circuit designed to trigger an LED every time a key is pressed.

My circuit takes this further by telling the user exactly *which* note is being pressed. The note value byte is information is passed to a 74HC595 shift register which displays the note as a binary via a line of LEDs.

In a loose sense the code I have adapted "works". When a key is pressed a series of LEDs light up corresponding to the MIDI note designated to that key. The issue is that this only happens sporadically. Many times a key press won’t be followed by any LEDs but other times it will. Even quick, successive presses tend to result in only a handful of "read" notes.

Why does this happen? To my intuition it would seem that the Arduino is "missing" notes, that is, spending so many clock cycles writing bits to the shift register that it falls out of sync with incoming bytes from the keyboard. Notes & Volts describes almost this exact situation in one of their instructional videos (relevant part at around 6:57). The author cautions against including too many time consuming processes in the code but doesn't mention how many is *too* many. I can only assume that a ShiftOut command takes a good deal longer than a digitalWrite and that this explains why the example code works but my adaptation does not. Given this information, how long exactly does ShiftOut take and what could be done to speed up my program?

```
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;  //The pins I am using

void note_On(byte channel, byte pitch, byte velocity) {  //Runs when note is pressed

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, pitch);
  digitalWrite(latchPin, HIGH);  //Write 'pitch' to 74HC595. Standard fare
}

void note_Off(byte channel, byte pitch, byte velocity){ //Writes '0' when note is off (all LEDs off)
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, 0x00);
  digitalWrite(latchPin, HIGH);
}
void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  MIDI.begin(MIDI_CHANNEL_OMNI);
  MIDI.setHandleNoteOn(note_On);
  MIDI.setHandleNoteOff(note_Off);
}

  void loop() {
  MIDI.read();  //This function which must be re-run in quick succession
}

```

### UPDATE

@CL @Nick I wrote a code comparing the execution time difference between shiftOut and digitalWrite. While I am not perfectly confident in all of the numbers (1K digitalWrites takes a full 44mS??) one result did not surprise me - shiftOut is slower. By my numbers it is 3.75 times slower. That said, I welcome critiques on my methodology and I will address them as soon as I can. In the meantime I will make a point to research Arduino SPI and welcome any other alternatives to shiftOut.

```
int latchPin = 8;       //Declaration of serial register pins
int clockPin = 12;
int dataPin = 11;

int led = 13;          //On-board LED

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  Serial.begin(9600);

  pinMode(led, OUTPUT);

}

void loop() {

  unsigned long startTime = millis();    //Writes to SR 1K times.
  for(int i = 0; i < 1000; i++){       //Prints difference between
    digitalWrite(latchPin, LOW);       //start and end times.
    shiftOut(dataPin, clockPin, MSBFIRST, 0xFF);
    digitalWrite(latchPin, HIGH);
  }

  Serial.print("\nsO:");
  Serial.print(millis() - startTime);

  delay(1000);

  startTime = millis();
  for(int i = 0; i < 8000; i++){    //Performs digitalWrite 8K times
    digitalWrite(led, HIGH);
  }

  Serial.print("\t\tdW:");          //
  Serial.print(millis() - startTime);

  delay(1000);
}

```

**UPDATE** While working on a similar issue I discovered that a dramatic change to my code seems to perfectly clear up the issue. I'd still like to know why this particular example does not, however, so I'll keep poking around until I get somewhere.

# Answer
> 3 votes
`shiftOut` is slow, yes. It is basically "bit banging" a synchronous serial interface, which is a bit daft really when the Arduino has a hardware synchronous serial interface built in that can operate at much higher speeds.

That built in synchronous serial interface is called **SPI**. I suggest you switch to SPI instead of shiftOut.

Also you should check what codes the MIDI keyboard is actually sending out. I had a similar experience to you recently, but as far as I can tell it's down to the keyboard, not my software. I built a system which reads in MIDI NoteOn codes through a serial port and plays a sample of a bass guitar at the right pitch. The system worked perfectly when wired to the computer through a USB MIDI adapter, but as soon as I connected it to a keyboard (I don't have one, so I only had the one chance to test it recently with a real keyboard) it would only react to a key pressed after a long delay. Almost as if the keyboard only sends a NoteOn if there is nothing happening for a while, and sends something else at other times. I need to examine the keyboard's output data in more detail to see exactly what is being sent and why.

You might like to manually examine the MIDI codes being sent by the keyboard to be sure that it is actually sending a NoteOn when you think it should be and not something else (it'd be very interesting to see the results of your experiments too).

# Answer
> 1 votes
I can't believe it is the shiftOut that is the issue. There is more going on here than meets the eye. I wrote a MIDI decoder a while back. That reads from MIDI and outputs to serial. That would be a **lot** slower than doing one shiftOut. It runs perfectly, not just with you sitting there tapping notes, but with the synth generating its inbuilt music. See video of it in action.

Either the library is doing something weird, or your 74HC595 is wired strangely. Do you have current-limiting resistors for each LED? Please show your wiring.

Also add a Serial print to display when your `note_On` and `note_Off` are called, and with what values. In my test I was able to connect MIDI up to Software Serial (pins D2 and D3 in my case) which was fine for receiving MIDI.

---
Tags: shift-register
---


# Question
Title: Arduino UNO capacitive sensor not working
This is a visualization of my Arduino connections:

I wish to read the data using the Capacitive sensor Library. iv'e tried the following code but variables `total1`, `total2`, `total3` always have the value `0` and i don't know what is wrong.

**My code:**

```
// Import the CapacitiveSensor Library.
#include <CapacitiveSensor.h>

// Name the pin as led.
#define speaker 11

// Set the Send Pin & Receive Pin.
CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);        // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
  cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example

  // Arduino start communicate with computer.
  Serial.begin(9600);
}

void loop()
{
  // Set a timer.
  long start = millis();

  // Set the sensitivity of the sensors.
  long total1 =  cs_2_3.capacitiveSensor(60);
  long total2 =  cs_2_4.capacitiveSensor(60);
  long total3 =  cs_2_5.capacitiveSensor(60);
 /* long total4 =  cs_2_6.capacitiveSensor(60);
  long total5 =  cs_2_7.capacitiveSensor(60);
  long total6 =  cs_2_8.capacitiveSensor(60);
  long total7 =  cs_2_9.capacitiveSensor(60);*/

  Serial.print(millis() - start);        // check on performance in milliseconds
  Serial.print("\t");                    // tab character for debug windown spacing

  Serial.print(total1);                  // print sensor output 1
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total2);                  // print sensor output 2
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print(total3);                  // print sensor output 3
  Serial.print("\t");                    // Leave some space before print the next output
  Serial.print("\n");
}

```

# Answer
As found on the Capacitative Sensor Library page (emphasis added):

> * **Use a 1 megohm resistor (or less maybe) for absolute touch to activate.**
> * With a 10 megohm resistor the sensor will start to respond 4-6 inches away.
> * With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size). Common resistor sizes usually end at 10 megohm so you may have to solder four 10 megohm resistors end to end.
> * **One tradeoff with larger resistors is that the sensor's increased sensitivity means that it is slower. Also if the sensor is exposed metal, it is possible that the send pin will never be able to force a change in the receive (sensor) pin, and the sensor will timeout.**
> * Also experiment with small capacitors (100 pF - .01 uF) to ground, on the sense pin. They improve stability of the sensor.

The two emboldened points suggest that for a touch-piano, it would likely be advantageous to use a lower value resistor such as 1MΩ. Because the sensitivity increases as the resistor value increases, you want to use the *lowest possible* resistor value to reduce jitter & interference among your signal wires.

---

Also, later on the page:
> The grounding of the Arduino board is very important in capacitive sensing. The board needs to have some connection to ground, even if this is not a low-impedance path such as a wire attached to a water pipe.

Ensure the Arduino is not run from a battery or unplugged laptop. For capacitative sensing to work, a stable ground connection is needed (via a DC plugpack or USB wall-wart is fine).

As a general note, try testing with only one capacitative connection first, then when that works, re-add the others.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Does restarting Yún configuration mess up Arduino or its SD card?
I noticed something odd recently - a Yún, that was working previously, wouldn't connect.

After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot `ls /mnt/sd/` or `sda1`. It just sits there, requiring Ctrl+C, and gives no output.

Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?

# Answer
> 2 votes
It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.

---
Tags: arduino-yun, sd-card, linux
---


# Question
Title: Arduino screws up trivial program involving enum
Behold this insanity:

```
enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

```

I'm pretty good at C++, so I'm fairly sure that should compile. However I get this error:

```
sketch_jan21b.ino:3:13: error: variable or field 'TellMe' declared void
sketch_jan21b.ino:3:13: error: 'WhatArduinoIs' was not declared in this scope
Error compiling.

```

I've encountered the Arduino "IDE"'s propensity for insane and totally unrobust modification of programs before. Specifically when you `#include` libraries Arduino only magically adds the relevant C++ files if the `#include` is in your main sketch. `#include <LiquidCrystal.h>` in another C++ file? Link errors.

I suspect in this case it is Arduino magically trying to add function declarations to the start of the file so their order doesn't matter. I.e. it turns the file into this:

```
void TellMe(WhatArduinoIs pls);

enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

```

That obviously doesn't work. How can I tell Arduino to leave my damn program alone?

# Answer
> 6 votes
You can workaround the issue by putting your `enum` and function into a namespace. You can even take advantage of C++ unnamed namespaces if you like:

```
namespace
{
  enum WhatArduinoIs {
    Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
  };

  void TellMe(WhatArduinoIs pls) { }
}

void setup() { }
void loop() { }

```

It's annoying (as are many things in the Arduino IDE), but it seems to work.

If you're more experienced with programming then you might want to consider using a 3rd party IDE with an Arduino plugin, such as Eclipse. The Arduino IDE is really only designed for beginners.

# Answer
> 4 votes
You seem to be correct about what the arduino IDE is doing to your sketch.

Arduino will not preprocess any .h or .cpp files, so you could use a second file. you could also break the IDE's function locating regex with a dummy `throw()` statement like this:

```
void TellMe(WhatArduinoIs pls) throw() { }

```

The dummy throw allows it to compile for me on 1.5.8

# Answer
> 1 votes
**All** you need is a function prototype. I have a detailed explanation at Classes and objects: how many and which file types I actually need to use them?

So, this compiles:

```
enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls);  // prototype
void TellMe(WhatArduinoIs pls)
  {
  }
void setup() { }
void loop() { }

```

Off-site reference: How to avoid the quirks of the IDE sketch file pre-preprocessing

---
Tags: ide
---


# Question
Title: Using an Arduino as an LED controller for an arcade stick
I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.
What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin. For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.
Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain.

And my current code:

```
int buttonlisten = 22;
int led = 53;
int val = 0;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(buttonlisten, INPUT);
}

void loop() {
  val = digitalRead(buttonlisten);
  digitalWrite(led, val);
}

```

Thanks!

# Answer
> 0 votes
I think the idea of putting the arduino between the button and ground is the problem here — `1P` appears to be the input for the controller button, and you can't expect to take an 'input' from the button on *both pins at once*.

Try connecting one lead of the button back to its ground, and the other to `1P` (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as `INPUT_PULLUP`.

This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share `GND`) when the button is pressed.

---
Tags: programming, arduino-mega, pull-up
---


title: Embedded-c, schedule a function?

text:
# Question
Title: Embedded-c, schedule a function?
Simple question, of course if you do this

```
FunctionA();
Delay(1000);
FunctionB();
FunctionC();

```

it will call A, then wait a second, then call B, then call C.

How does one do this? ...

```
FunctionA();
.. Invoke FunctionX one second from now ..
FunctionB();
FunctionC();

```

So, I want it to do A, then without stopping continue to B and then C. Later (one second later) it will do X.

Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!

# Answer
> Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:

```
// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015

typedef void (*GeneralFunction) (); // function pointer type

GeneralFunction wantedFunction = NULL;  // function to call
unsigned long functionTimerStarted;     // when the timer started
unsigned long delayPeriod;              // how long to wait (ms)

void functionA ()
  {
  Serial.println ("Function A");
  }  // end of functionA

void functionB ()
  {
  Serial.println ("Function B");
  }  // end of functionB

void functionC ()
  {
  Serial.println ("Function C");
  }  // end of functionC

void functionX ()
  {
  Serial.println ("Function X");
  }  // end of functionX

void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
  {
  wantedFunction = f;
  functionTimerStarted = millis ();
  delayPeriod = when;
  }  // end of scheduleFunction

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

  functionA ();  // call this now
  scheduleFunction (functionX, 2000);  // call this later
  functionB ();  // call this now
  functionC ();  // call this now

  }  // end of setup

void loop ()
  {
  // see if time to call the delayed function
  if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
    {
    wantedFunction ();
    wantedFunction = NULL;  // don't call it again
    }  // end of if time up

  // do other wanted stuff here

  }  // end of loop

```

This uses:

* A function pointer to remember which function to call in the future.
* A global variable to remember when you wanted this timing interval to start.
* A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:

```
  scheduleFunction (functionX, 2000);  // call this later

```

Then in loop() we see if the time is up, and then call the function.

This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.

You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.

For more information about function pointers, see Function pointers / function callbacks / function variables.
> 1 votes

---
Tags: threads
---


title: Get JSON data from Arduino with AJAX

text:
# Question
Title: Get JSON data from Arduino with AJAX
I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call. At the moment I have the following code on Arduino:

> ```
> #include <SPI.h>
> #include <Ethernet.h>
>
> byte mac[] = {
>   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
> };
> IPAddress ip(192, 168, 1, 177);
>
> EthernetServer server(80);
>
> void setup() {
>   Serial.begin(9600);
>   while (!Serial) {
>     ;
>   }
>
>   Ethernet.begin(mac, ip);
>   server.begin();
>   Serial.print("server is at ");
>   Serial.println(Ethernet.localIP());
> }
>
>
> void loop() {
>   float temperatureIndoor;
>   float temperatureOutdoor;
>   EthernetClient client = server.available();
>   if (client) {
>     Serial.println("new client");
>     boolean currentLineIsBlank = true;
>     while (client.connected()) {
>       if (client.available()) {
>         char c = client.read();
>         Serial.write(c);
>         if (c == '\n' && currentLineIsBlank) {
>           client.println("HTTP/1.1 200 OK");
>           client.println("Content-Type: application/json;charset=utf-8");
>           client.println("Server: Arduino");
>           client.println("Connnection: close");
>           client.println();
>
>           temperatureIndoor = 22.77;
>           temperatureOutdoor = 15.55;
>           client.print("{\"0\":{\"TemperaturaInterior\":\"");
>           client.print(temperatureIndoor);
>           client.print("\",\"TemperaturaExterior\":\"");
>           client.print(temperatureOutdoor);
>
>           client.print("\"}}");
>           client.println();
>           break;
>         }
>
>       }
>     }
>     delay(1);
>     client.stop();
>     Serial.println("client disconnected");
>   }
> }
>
> ```

I'm trying to get values with the following ajax call:

```
    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
            data: { tag: 'getData'},
            dataType: 'json',
                  async: false,
                  success: function (data) {

$('#TemperaturaInterior').val(data.TemperaturaInterior).show();
$('#TemperaturaExterior').val(data.TemperaturaExterior).show();

                            }
                        });

```

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino: {"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values. Any idea? Thanks

NOTE:

This what I get when ask to arduino to give me the values:

# Answer
This is more of a Stack Overflow question, but I'll help you a bit. The problem has nothing to do with your Arduino per-say. It has more to do with your PHP/Ajax.

Your code is suited for a completely local setup, but pulls from a remote site, which violates some security protocols build into your browser and jQuery. You need to change your code to this:

```
$.ajax({
    url: 'http://192.168.1.177/',
    type: 'post',
    data: { tag: 'getData'},
    dataType: 'jsonp',
    async: false,
    success: function (data) {
        $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
        $('#TemperaturaExterior').val(data.TemperaturaExterior).show();
        }
    });
(may need slight modifications since you didn't include all PHP/html code)

```

For more information, see the jQuery documentation, particularly look at data types and what it says about cross-domain json vs jsonp.

Here is a relevant SO question.
> 1 votes

# Answer
Ouch man you are getting burned by CORS. This stack overflow box isn't big enough for me to explain how much of a pain CORS is and how much trouble it will cause you. That being said there is a really good recourse that will help explain how to get this working with a couple of http headers http://enable-cors.org/. Good luck
> 0 votes

---
Tags: arduino-uno
---


title: Converting float to String

text:
# Question
Title: Converting float to String
How can I convert a `float` value into a `String` object without implementing any library?

I'd like to avoid using `char` array.

# Answer
> 3 votes
If you want to do it manually, rather than using the standard tools (`dtostrf()` for example) then you need to think mathematically.

A floating point number is made up of two distinct parts - the *integer* part and the *decimal* part.

For instance the number `123.4567` is made up of the integer part 123 and the decimal part 4567. Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output. In this case, though, it isn't.

So what to do? Simple: keep dividing the number by 10 until it is just one digit. But *be sure to count the number of times you divide by 10*. So the example above would end up as 1.234567 with a divide count of 2. This is the same as the scientific representation, 1.234567×10².

So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number. So you end up with "1" and 0.234567 and a count of 2.

Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1. Grab the integer portion and add it to your string, then remove it from your number.

Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.

You now just keep repeating the same process again and again until the *absolute* value of the count equals the number of decimal places you want to print.

For negative numbers you should start by placing a "-" in your string, then taking the *absolute* value of the number (the number as a positive).

Or you just use the standard library function `dtostrf()`.

---
Tags: arduino-ide, c, variables
---


title: Reading a photoresistor

text:
# Question
Title: Reading a photoresistor
I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)

I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit?

I could not find my optocoupler in fritzing. This is it: http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref\_=oh\_aui\_detailpage\_o07\_s00

This is my plan.

The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.

I based my circuit on this:

But I don't know if it will do the same thing.

# Answer
Based on the revised information given above I present a different answer. Use the opto-coupler as shown here:

Your kettle LED will be in series with the optocoupler (note the polarity, not reversed like in your question).

If the LED is on the transistor in the PC817 will conduct and the Arduino pin will be LOW. If the LED is off the transistor will not conduct and the Arduino pin will be HIGH.

Note: The Arduino pin will be the reverse of the kettle LED.

I'm leaving the other answer there because I think it is a reasonable answer to the question of "detect a voltage".
> 1 votes

# Answer
Wouldn't this be simpler?

*Note: amended answer increases R1 to 10 k.*

The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.

I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.

This gives:

* For an input voltage of 5 V -\> 2.3 V on the Arduino input
* For an input voltage of 10 V -\> 2.6 V on the Arduino input
* For an input voltage of 20 V -\> 2.9 V on the Arduino input
* For an input voltage of 30 V -\> 3.1 V on the Arduino input

This is all within spec for the Arduino.

Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.

```
3.3 * 0.6 = 1.98

```

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.
> 5 votes

---
Tags: voltage-level, analogread, photoresistor, voltage-protection, digital-in
---


# Question
Title: Arduino webserver: faster alternative to "indexof" for parsing GET requests?
I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:

```
String readString;
EthernetClient client = server.available();
if (client) {
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();

    if (readString.length() < 20) {
      readString += c;
    }
    ...
    ...
      if (readString.indexOf("?a1o") >0){
        mySwitch.send(a1o, 24);
      }
      if (readString.indexOf("?a1c") >0){
        mySwitch.send(a1c, 24);
      }

```

The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: http://192.168.0.180.

-Is there a command faster than "indexOf" that I could be using?

-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.

Thanks!

# Answer
> 8 votes
Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.

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

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

// Our IP address
IPAddress ip(10,0,0,241);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup()
  {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) { } // wait for serial port to connect.

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("Server is at "));
  Serial.println(Ethernet.localIP());
  }  // end of setup

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;

// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
  {
  // find where the parameters start
  const char * paramsPos = strchr (data, '?');
  if (paramsPos == NULL)
    return;  // no parameters
  // find the trailing space
  const char * spacePos = strchr (paramsPos, ' ');
  if (spacePos == NULL)
    return;  // no space found
  // work out how long the parameters are
  int paramLength = spacePos - paramsPos - 1;
  // see if too long
  if (paramLength >= MAX_PARAM)
    return;  // too long for us
  // copy parameters into a buffer
  char param [MAX_PARAM];
  memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
  param [paramLength] = 0;  // null terminator

  // do things depending on argument (GET parameters)

  if (strcmp (param, "foo") == 0)
    Serial.println (F("Activating foo"));
  else if (strcmp (param, "bar") == 0)
    Serial.println (F("Activating bar"));

  }  // end of processGet

// here to process incoming serial data after a terminator received
void processData (const char * data)
  {
  Serial.println (data);
  if (strlen (data) < 4)
    return;

  if (memcmp (data, "GET ", 4) == 0)
    processGet (&data [4]);
  }  // end of processData

bool processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
    {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;
    }  // end of switch
  return false;    // don't have a blank line yet
  } // end of processIncomingByte

void loop()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
    {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done)
      {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
      }  // end of while client connected

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/html"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(F("<!DOCTYPE HTML>"));
    client.println(F("<html>"));
    client.println(F("<head>"));
    client.println(F("<title>Test page</title>"));
    client.println(F("</head>"));
    client.println(F("<body>"));
    client.println(F("<h1>My web page</h1>"));
    client.println(F("<p>Requested actions performed"));
    client.println(F("</body>"));
    client.println(F("</html>"));

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop

```

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).

`processIncomingByte` is called for each byte from the client. Once an entire line is assembled it calls `processData`. If that finds a "GET " line it calls `processGet`. That looks for the parameters on the GET line. The GET line looks like this:

```
GET /?bar HTTP/1.1

```

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with `strchr`.

Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.

---
Tags: web-server
---