# Question
Title: What is the best way to unit test my code without controller?
I want to unit test my Arduino code. Ideally, I want to execute and test my code without uploading it to the board. What tools or libraries can help me with this?

There is an Arduino emulator in development which could be useful, but it doesn't yet seem to be ready for use.

# Answer
> 10 votes
You can easily simulate your Arduino code using the famous Proteus ISIS.
You just will have to search for the specific Arduino simulation library for Proteus.

*Here you a small **tutorial** of how to make this thing done:*

**First**, identify the path the Arduino IDE generates the hex file to?
for example if you are using the official IDE you will find the hex file location in the "arduino IDE path/lib/preferences.txt"
Or if you are using Arduino ERW which I recommended the most on windows! So you can simply open the output folder by "Sketch \> Copy HEX file as path".

**Second**, download the Arduino library from Here. Then copy `ARDUINO.LIB` and `ARDUINO.IDX` to folder "library" in the install directory Proteus.

**Third**, open ISIS and you should be able to find the component.

Please find this image of the worksheet after finishing the above steps, and simulation works just fine!

And as a head start for you, please find this small memo I prepared for the **Arduino Uno Pins Layout**:

```
0-14: I/O
A0-A5: Analog

We can use analog as digital:
=============================
Pinout:
00: Rx      | Can't be used as I/O if I wrote in the code Serial.begin
01: TX      |
02: Interrupt
03: Interrupt & PWM
04:
05: PWM
06: PWM
07:
08:
09: PWM
10: PWM & SPI
11: PWM & SPI
12: SPI
13: SPI
A0:
A1:
A2:
A3:
A4: TWI
A5: TWI

```

# Answer
> 10 votes
I always try to isolate the hardware logic from the rest of the domain logic.

Classes (or whatever) from domain logic can be programmed in c++ (with the known arduino restrictions like exceptions or std lib) and can be tested with gtest. When these classes are tested, simply instance from arduino program excluding the main with tests.

If your project is pure hardware this solution will not help you very much, but if you have your own algorithms, protocols...etc, test them with Google test will save you hours of on board testing and memory problems with unexpected results and your software will gain in quality.

# Answer
> 4 votes
Have you looked at the AVR simulator that's part of Atmel Studio? Considering Atmel designed the processor, the simulation may very well be running the HDL that was used to produce the MCU itself.

I suspect if you're doing something involved enough to be using unit-testing, you should probably stop thinking of your device as an "Arduino", but rather "An ATmega MCU on a PCB". There are **much** more information and tools available about ATmega CPUs in general then Arduinos.

---
Tags: programming, testing
---


title: Modbus Protocol Compile Error

text:
# Question
Title: Modbus Protocol Compile Error
I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:

```
#include <SimpleModbusSlave.h>
#define  LED 9
enum
{

  ADC_VAL,
  PWM_VAL,
  HOLDING_REGS_SIZE // leave this one
};

unsigned int holdingRegs[HOLDING_REGS_SIZE];
void setup()
{
  modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
}

```

I am getting Error has.

```
SimpleModbusSlaveArduino.cpp: In function 'void setup()':
SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

```

I have made changes in the lib as in forum. but I found no value read by my software.

Master sending below request on read mode. But not receiving anything.

```
12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
12:31:02.953: Read Holding Register(s), Repeat Loop
12:31:02.953: Device Address: 01h, Register: 0000h
12:31:02.953: |-> Read Register: 0000h
12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

```

CHANGES MADE IN AS IN FORUM MENTIONED

# Answer
Not sure where you got the library from, but if it's from this github repo, you're using it wrong.

The function prototype for `modbus_configure` is:

```
void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

```

The example file shows how to use it correctly

```
modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);

```
> 4 votes

# Answer
In your first example the error is that SERIAL\_8N2 is not declared. maybe you are using an old Arduino IDE? try latest 1.0.x or 1.5.x

in the second case TOTAL\_REGS\_SIZE is a pointer to int, while the function expect a char. Without code is hard to tell what is wrong and how, but in your first code it should be

```
modbus_configure(115200, 1, 2, HOLDING_REGS_SIZE);

```

also because you are not passing a reference to the array, you have to pass a pointer pointing the current element in the update function

```
modbus_update(holdingRegs[i]);
i++

```
> 1 votes

---
Tags: arduino-uno, programming, arduino-mega, networking
---


# Question
Title: How to measure total energy usage of an arduino board
I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.

**Question:**

How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?

Thanks a lot.

**To clear up some things**

No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.

Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.

I would like to know the entire energy consumed, not just the pump.

# Answer
In order to calculate the amount of energy you have to calculate the power first.

The relation is

Energy = (Power * Time of usage)

How to calculate the power?

The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project. The main thing you have here is the pump and how much does it consume current. Usually, you will have on the "plate" of the pump the current withdrawal of it.

Say it consumes 2 Amps. If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.

If there are any other major/important components in your project just calculate the current withdrawal from them.

Now add up all the currents and say you ended up with 2 Amps.

If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage. WHY? Because: P(power) = V(voltage) * I(current)

If not, just find the power of each component. Add up all the powers of all you components.

Now you will only have to calculate the energy.

E(Energy) = Power * time

Time here refers to how long is your system working? Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).

Say your power ended up with 3kW *kilo Watt* You've run the system for 2 hours every day Energy = 3 * 2 = 6 kWh

If you've kept this for a full month. Energy save in a month = 180kWh.

Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!
> 3 votes

# Answer
There are some chip that measure current flow (like ACS714). Just be sure to buy a chip that will not fry under your load, and mount it in serie with the pump. That chip will bring an analog (but there a re "smarter" chip witch use i2c or spi) signal to arduino, using the formula on the datasheet you can find out real (well, as always there are small error) current flow.

You should already know the voltage of the pump, but you can easily read it with a similar chip or even a voltage divider, just pay attention if you are using PWM as if it will fake your reading)

Now, as already pointed out by Adel Bibi, you can multiply the voltage of the pump with the current value readed (find power), multiply with the time elapsed from the last measure and sum up with precedent measure (integral of the power by time)

you can do the same on the wind/solar panel, just invert the sign of the current (as you are Producing and not Consuming power) and voilà!
> 2 votes

# Answer
With the accumulator in the system, current draw will increase as that is topped off. The accumulator provides sufficient pressure to drive the system. As system pressure draws down, the pump turns on to bring up the accumulator, with maximum draw nearing cut-off pressure. Taking the total run time of the pump in question (@DLJ) you may chop this up into discrete chunks and measure the draw over those periods, plot that out. I like that greenwall, and I want one. -- Aloha nui loa, MKK edit -- As an aside, even a 12V pump driving the smallest 1 liter accumulator to 250 kPa, will draw up to 3A for a few moments, given the size of your system. What motor shield are you using?
> 0 votes

---
Tags: programming, sensors
---


# Question
Title: Change Options for the AVR Programmer via Arduino IDE
I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

> avrdude -p attiny13 -P /dev/cu.usbmodemfa131 -c stk500v2 -F -B20 -U flash:w:programm.hex

It took a while to figure out that I had to slow the baud rate via the -B20 switch. If I try to upload via the arduino 1.0.5 IDE avrdude is executed as follows.

> /Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny13 -cstk500v1 -P/dev/tty.usbmodemfa131 -Uflash:w:/var/folders/9t/5jldfq752fs1x74\_rhn2plz80000gn/T/build7680201613426497544.tmp/attinytest.cpp.hex:i

My question is, how can I change the preferences such that I have control over the avrdude parameters? Say I want to add a -B20 switch and change stk500v1 to stk500v2.

# Answer
> 3 votes
**Short answer**: I'm afraid you can't do it with Arduino IDE 1.0.5.

**Long answer**:

First of all, be aware that `-B20` does not specify the baud rate but the bitclock period (in us); this is specific to `stk500v2` programmer.

Normally, enabling your programmer should only be a matter of adding it to the list of programmers known by Arduino IDE; that list can be found in `hardware/arduino/programmers.txt`. You would then append the following lines at the end of this file:

```
strangeprogrammer.name=Somehow Strange Programmer
strangeprogrammer.communication=serial
strangeprogrammer.protocol=stk500v2
strangeprogrammer.force=true
strangeprogrammer.speed=?????

```

However, the problem here is that Arduino IDE does not seem to be able to use flag `-B` (bitclock period) but only flag `-b` (baud rate) which value is set to whatever you will put to `strangeprogrammer.speed`.

At least that's what I could find out by inspecting Arduino IDE source code: `AvrdudeUploader.java` never adds that flag to the `avrdude` command-line :-(

That means your options are:

1. Rebuild the Arduino IDE 1.0 on your own after modifying `AvrdudeUploader.java` to support `-B` flag; code should be quite easy (about 2 more lines of Java code).
2. Switch to Arduino IDE 1.5 and follow Federico's answer :-)
3. Use another IDE, something that deserves the **IDE** name. I use Eclipse with this Arduino plugin and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:

---
Tags: avrdude, avr, programmer
---


title: Arduino Lego Robot

text:
# Question
Title: Arduino Lego Robot
I'm currently developing a Lego Robot, the mindstorm series to be specific. I want to replace the lego NXT brick with an arduino, maybe an intel galileo in the future. How do I establish connections from the arduino with the lego sensors? Also, I would like some input on any cool features that I can add to this robot. This robot is to be seen as a human companion. Thanks in advance.

An example of a sensor i would like to use is here : http://www.hitechnic.com/cgi-bin/commerce.cgi?preadd=action&key=NIS1070

How do I interface this with an arduino?

# Answer
Doing a quick search on google you can find a couple of shields designed for that purpose:

Second one is allows less motor connections but it's cheaper and has a book written by the designers
> 2 votes

---
Tags: arduino-uno, robotics
---


# Question
Title: Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600
This is a follow on question from How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?

I did manage recompile optiboot bootloader to work at 57600 bps and uploaded it to a couple of ATmega328-PUs. I just changed the `BAUD_RATE` to `57600L` in Makefile and recompiled it.

They worked just fine with my Arduino Single Sided Serial (Severino) and a couple of custom standalone Arduino boards with FTDI-like header.

However, I couldn't program the same MCUs using my Arduino Uno R3. When I try to upload a sketch, avrdude just sits there waiting for a response that doesn't come. The output I got is something like this:

```
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Ricardo\arduino-1.0.5\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv:
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

```

Would that have anything to do with the 2nd MCU that acts as the USB driver on the Uno - the ATmega16U2? Do I have to patch it, too?

So, my questions are:

**1. Why my recompiled optiboot didn't work with my Arduino Uno R3?**

**2. What can I do to check what's wrong with the upload process using my new bootloader?**

# Answer
Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see source-code here) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.

It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

> Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.
> 1 votes

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


# Question
Title: Can I get a Datetime object from a unix timestamp?
Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example `Wed Apr 02 17:15:06 2014`.

I have:

1. A unix timestamp: `1396451852`.
2. An offset from my hour zone, `+1` hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.

# Answer
The seconds since (UNIX) epoch relies on a database.

> New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

* Reduce the timezone database to the timezone you are actually interested in;
* Don't forget about daylight savings time for you specific timezone;
* The leap years are well known too and reasonably easy to program;
* The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

## Conclusion

* So can you convert epoch to a time/date format? Yes.
* Will it be accurate? It'll drift away over time (months or years)

## Advise

If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?
> 2 votes

# Answer
The Arduino Time Library looks like it can do it. Or have a look at the strftime() function from unix and unix-oid environments. There is source to strftime() here. It's pretty large but you can probably cut it down considerably to just the format parts you need.
> 1 votes

---
Tags: programming, time
---


# Question
Title: Modifying serial message for Adafruit NFC/RFID card
Using an Uno configured with an Adafruit RFID-NFC shield to send the UID values to a desktop game I am building.

Works fine. However, in addition to just the UID, I need to send 1 additional value, lets call it 'game choice'. This can be one of 3 values. This is just the relevant code. Can any experts suggest how I might modify the following to send this additional value?

```
/**************************************************************************/
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

#define IRQ   (2)
#define RESET (3)  // Not connected by default on the NFC Shield

Adafruit_NFCShield_I2C nfc(IRQ, RESET);

void setup(void) {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("init");
}
void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
  int nfcDEC;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {

   nfc.PrintHex(uid, uidLength );
}
}

```

# Answer
had to simply modify PrintHex in Adafruit\_NFCShield\_I2C.h

to accept an additional argument
> 1 votes

---
Tags: arduino-uno
---


title: How do I use Arduino and node.js?

text:
# Question
Title: How do I use Arduino and node.js?
I am new to Arduino, however I have experience in web development, lately I have been using, meteor js and the mean stack for different projects. However, I am open to trying any language for development.

What I am trying to do is build a simple application to control the LED on the Arduino over the web.

I am working with another person, and the Arduino will be behind a firewall so I am not sure how to access it via the internet. I do have access to an Arduino Uun that I can use for testing at home which does have linio connected via bridge, which I don't quite understand what that does.

I've also heard of this, but would like to stay away from third party builds as much as possible if I can do it myself.

Whats the common way to do this with an Arduino behind a firewall? How do I do this with a Arduino Yun? Is it easier with a Yun?

# Answer
> 9 votes
I am working on similar project that uses internet to communicate with external device (mobile). I am reading data from sensors and passing them over the web with web sockets. I am using Arduino Yun for this project and Spacebrew (for web sockets communication). It's very interesting approach but quite a challenge in some cases. You will probably run into asynchronous/synchronous problem, which in my case lead me to running some Python scripts on Yun triggered from Processing code. I am currently running Spacebrew server on my VPN, so I can connect my Yun left at home and use my iphone from everywhere to get the readings.

It's also worth mentioning Yun comes with pre-installed Temboo library, which is great starting point for web communication. The configuration is really easy and quick. You will also find official documentation very handy and easy to understand. It's really great starting point for experimenting with web-like applications integrated with Arduino Yun.

### Spacebrew

* http://docs.spacebrew.cc/

Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive spaces. Or, in other words, a simple way to connect interactive things to one another. Every element you hook up to the system can subscribe to, and publish data feeds.
* http://github.com/Spacebrew/pySpacebrew

This repo contains the Spacebrew Library for Python along with documentation and example apps.
* http://github.com/julioterra/yunSpacebrew

The Spacebrew Yun library features two main components - a set of python scripts that run on the linino, and a library that runs on the atmel chip. You find there information how to install both of these components so that you can connect to Spacebrew from an Arduino sketch.

### Temboo

Yun has also build in Temboo library, it's a great way to start experimenting, once you prove the concept you can start narrowing your environment and moving away if you don't want to use 3rd parties software.

* http://www.temboo.com/arduino

The Temboo Library makes it easy to connect to over 100 web-based resources and services with Processing. Currently you can find libraries for Android, Arduino, iOS, Java, Node.js, PHP, Processing, Python, REST API, Ruby, Twyla

### Node.js

You can also run node.js on the Yun itself, here's good article and some packages ready to install:

### What is Bridge library for Arduino Yun?

You also asked about Bridge library. As you know Yun has two processors on board, one is running your Processing code, the other one has Linux on it (Linino). Bridge basically simplifies communication between them so they can "talk" to eachother, more information here:

* http://arduino.cc/en/Reference/YunBridgeLibrary

(Taken from arduino.cc documentation:)

The Arduino Yún has two processors on board. One is an ATmega32U4 like on the Arduino Leonardo. The other is an Atheros 9331, running Linux and the OpenWRT wireless stack, which enables the board to connect to WiFi and Ethernet networks. It is possible to call programs or custom scripts on the Linux system through the Arduino to connect with various internet services.

The Bridge library simplifies communication between the ATmega32U4 and the AR9331. It inherits from Stream, and many of the methods should be familiar from Serial and other derivatives of Stream.

Bridge commands from the 32U4 are interpreted by Python on the AR9331. Its role is to execute programs on the GNU/Linux side when asked by Arduino, provide a shared storage space for sharing data like sensor readings between the Arduino and the Internet, and receiving commands from the Internet and passing them directly to the Arduino.

Bridge allows communication in both directions, acting as an interface to the the Linino command line.

### Where to start?

I would start with Temboo if I were you, it's a great learning curve and quite simple step to start. You will also learn and understand how the board works and how you can communicate with "external world". Once you have proof of concept, start experimenting with different libraries and improving the approach. Perhaps you will find Spacebrew more handy later or even discover different solutions.

# Answer
> 1 votes
first of all you need to have clear what you need to do. Arduino UNO is just a microcontroller with a serial (over USB) connection. To make your arduino accessible from the internet, it need to be connected with the internet, or to have something that act like a bridge. You can use an ethernet shield, a wifi shiled, or a YUN witch is an arduino UNO + a micro linux with has ethernet and wifi (programmable in phyton, or the chip can command the linux sending command to bash shell using the special bridge library) You can even connect arduin on the pc by usb and create a bridge program, or, if your firewall/router is a unlocked linux/similar, you can use it.

How many option, and we event startint to decide how o talk with it. As you want to use node.sj, you can use socket or get/post. Using socket is faster, lighter, and can create a pull connection, and js wil be a requisite. With get/post you don't even need js, pure html form will do.

then, after you decided witch sistem you like (arduino as http server or plain socket) you can open the corresponding port on the firewall/nat. but is just the last part

---
Tags: arduino-yun, web-server
---


# Question
Title: Extend battery life with a power-controlling microcontroller?
**This article** describes a method to extend the battery life: use a low-power controller to switch on the Arduino only when needed. The author states that this method uses considerably less power than using Arduino's sleep mode.

**Are there downsides to this approach? Which variant should I build?**(The TPS61240 variant seems to use something from Circuits@Home that's not available anymore.) **I'd appreciate schematics or links to detailed instructions.**

Background: I'm building a sensor device that's in an environment with no mains power supply. The sensor should wake up eg. hourly, read eg. a temperature sensor, possibly send an SMS and then go back to sleep.

# Answer
Switching off power to the board only makes sense if you're using a full Arduino. Once you strip the Arduino down to the bare MCU and decoupling capacitors (or start with a basic breakout board instead), disabling unused peripherals and sleeping the CPU has much more of an effect since you no longer need to supply power to an external monitor chip.

Naturally this may involve creating your own board for the MCU. Fortunately Atmel has the basics of that covered.
> 4 votes

---
Tags: battery
---


# Question
Title: Measuring resistance conceptually and in code?
How would I measure resistance over a certain length? In this case the resistance is variable.

What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.

I'm not sure if this would work, or how to implement it in code.

I've seen this forum post, but it's not making much sense to me.

How can I measure resistance?

# Answer
you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).

Then what you need is a know resistence resitor, so you can set up a voltage divider and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)
> 3 votes

---
Tags: current
---


# Question
Title: Client or WiFiClient wrapper for adafruit CC3000 wifi
I have a CC3000 wifi module from adafruit that is working OK. Now, I am trying to use it together with an external service, which code requires me to pass a Client (from Arduino SDK) reference, but the Adafruit\_CC3000\_Client does not inherit from Client nor WifiClient.

I am looking for an appropiate wrapper, but unable to find one. Does anyone know about such wrapper?

# Answer
> 5 votes
As I didn't get any answer, and further search for an existing solution failed, I decided to roll my own. The class header is very straightforward, I decided to go for single inheritance and composition of Adafruit\_CC3000\_Client:

```
class CC3000Client: public WiFiClient {
public:
    CC3000Client(Adafruit_CC3000& cc, Stream& stream=Serial);
    virtual ~CC3000Client();

    virtual int connect(IPAddress ip, uint16_t port);
    virtual int connect(const char *host, uint16_t port);
    virtual uint8_t connected();
    virtual int available();
    virtual void stop();
    virtual void flush();
    virtual int peek();
    virtual int read();
    virtual size_t write(uint8_t v);
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual int read(uint8_t *buf, size_t size);
    virtual operator bool();

private:
    Adafruit_CC3000& cc3000;
    Adafruit_CC3000_Client client;
    bool peeked;
    int peeked_byte;
    Stream& stream;
};

```

The implementation is a bit tricky (or I didn't manage to find a better way), as the Adafruit client does not have peek() functionality, so this wrapper class have to implement it.

```
CC3000Client::CC3000Client(Adafruit_CC3000& cc, Stream& stre) :
        cc3000(cc), peeked(false), stream(stre), peeked_byte(0) {
}
CC3000Client::~CC3000Client() {
}

int CC3000Client::connect(IPAddress ip, uint16_t port) {
    client = cc3000.connectTCP((uint32_t) ip, port);
    peeked = false;
    if (client.connected())
        return 1;
    return 0;
}
int CC3000Client::connect(const char *host, uint16_t port) {
    uint32_t ip = 0;
    if (!cc3000.getHostByName((char*) host, &ip)) {
        stream.println(F("Couldn't resolve!"));
        return 0;
    }
    client = cc3000.connectTCP(ip, port);
    peeked = false;
    if (client.connected()) {
        return 1;
    }
    return 0;
}
uint8_t CC3000Client::connected() {
    return (uint8_t) client.connected();
}
int CC3000Client::available() {
    if(peeked)
        return 1;
    return (int) client.available();
}
void CC3000Client::stop() {
    peeked = false;
    flush();
    while (client.connected()){
        client.close();
        delay(10);
    }
}
void CC3000Client::flush() {
    peeked = false;
    while (connected() && available())
        read();
}
int CC3000Client::peek() {
    if (!peeked) {
        if (available()) {
            peeked_byte = read();
            peeked = true;
        } else
            return -1;
    }
    return peeked_byte;

}
int CC3000Client::read() {
    if (peeked) {
        peeked = false;
        return peeked_byte;
    }
    return (int) client.read();
}
size_t CC3000Client::write(uint8_t v) {
    return (size_t) client.write(v);
}
size_t CC3000Client::write(const uint8_t *buf, size_t size) {
    return client.write(buf, size);
}
int CC3000Client::read(uint8_t *buf, size_t size) {
    if(peeked){
        buf[0]=peeked_byte;
        peeked=false;
        return client.read(buf+1, size-1);
    }
    return client.read(buf, size);
}
CC3000Client::operator bool() {
    stream.println("Error, bool() not implemented");
    return true;
}

```

Both files are available here, if you are using biicode all you have to do in your code is to put an include like the following and run "bii find", that will also retrieve and install the cc3000 library:

```
#include "diego/ardunet/cc3000client.h"

```

I have used and tested it with a simple http\_get call (also here) and with the temboo service, and it has worked OK for sending emails from a Gmail account from an Arduino Mega2560 connected to the CC3000. This temboo service uses via the SDK Client interface most methods of this wrapper, but the bool() operator and the CC3000Client::write(const uint8\_t \*buf, size\_t size) method.

---
Tags: wifi
---


title: Pass variable in a URL

text:
# Question
Title: Pass variable in a URL
I am working on code where I am able to manually enter the value in the URL to let the PHP code save it in the database, but I'm unsure how to do it with a variable in a loop running. This is the URL:

```
student.cs.hioa.no/~s180343/updatedb.php?verdi=25

```

Code:

```
void setup() {
  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);
  Serial.println("Ready");

  // run various example processes

}

void loop() {
   runCurl();
   delay(10000);
}

void runCurl() {
  // Launch "curl" command and get Arduino ascii art logo from the network
  // curl is command line program for transferring data using different internet protocols
  Process p;        // Create a process and call it "p"
  p.begin("curl");  // Process that launch the "curl" command
  p.addParameter("student.cs.hioa.no/~s180343/updatedb.php?verdi=25"); // Add the URL parameter to "curl"
  p.run();      // Run the process and wait for its termination

  // A process output can be read with the stream methods
  while (p.available()>0) {
    char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
}

```

# Answer
> 2 votes
You can pass in a variable into a function. Something like this:

```
void runCurl(int verdi) {
    ...
    String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
    myUrl += verdi;
    p.addParameter(myUrl);
    ...
}

```

You call the function like this, now:

```
runCurl(1);
runCurl(2);
runCurl(someVar);

```

and so on. Since it's already in your main `loop()` function, you just need to set pass in a different number based on whatever it is you're trying to do.

# Answer
> 0 votes
first of all, you declare your `buffer` as a string of 50 characters, but

```
student.cs.hioa.no/~s180343/updatedb.php?verdi=

```

is already 48, and you start your value at 1200 and increments over that, so basically

```
sprintf (buffer, "student.cs.hioa.no/~s180343/updatedb.php?verdi=%d", val)

```

will create a buffer of 53 characters (52 characters + `\0`).

Secondly, it's always a better idea to give the *full* URL to a program such as curl, as it might work but may give unexpected results as well if you do not provide the protocol… `curl` could legally assume you want `ftp` or `gopher` to access that address!

```
http://student.cs.hioa.no/~s180343/updatedb.php?verdi=%d

```

Third, here's how you setup and use your `val` variable:

```
int val=1200;
sprintf (…, "…", val);
val++;

```

so once you've reached `32767` your int is overflowing, getting back to `-32,768`.

Oh, and by the way, it is good practice on a Q&A site such as Stack Overflow to actually *ask* a question and say what your problem is. All my hints here are insights based on reading your flawed code.

HTH

# Answer
> 0 votes
Alright. I'm assuming you mean that you need the last part of the url varied from, say 1 to 100. Like Java, Processing, and, by extension, Arduino, allow you to add an integer to a String to get a String. I haven't tested this out, but it should work:

```
#include <Process.h>
#define MIN 0
#define MAX 100

int i;

void setup() {
  i = MIN;

  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);
  Serial.println("Ready");

  // run various example processes

}

void loop() {
   if (i<=MAX) {
     runCurl();
     i = i+1;
   }
   delay(10000);
}

void runCurl() {
  // Launch "curl" command and get Arduino ascii art logo from the network
  // curl is command line program for transferring data using different internet protocols
  Process p;        // Create a process and call it "p"
  p.begin("curl");  // Process that launch the "curl" command
  String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
  p.addParameter(myUrl+i); // Add the URL parameter to "curl"
  p.run();      // Run the process and wait for its termination

  // A process output can be read with the stream methods
  while (p.available()>0) {
    char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
}

```

---
Tags: programming, arduino-yun, variables
---


# Question
Title: How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?
I am starting a personal project of home automation and I have a raspberry pi and an arduino Uno board.

I want communicate raspberry pi and my arduino where my raspberry should be able to write and read signals to and from arduino.

The distance between them I think its going to be something around 10 to 15 meters.

What do I need for it? what kind of wires or other components I'll need to achieve my goal? I repeat: I do not want to communicate raspberry pi and arduino wirelessly.

Thanks!

# Answer
> 9 votes
for length such as this, you should be using protocols that are designed for length, such as:

* UART,
* CAN,
* Ethernet

for UART, you can't of course use a direct connection between the two boards, you need to upgrade the connection and wiring to either rs232 or rs485, using a driver between the arduino pins and the cable.

Though, the simplest solution would be to plug the Arduino on the Raspberry Pi using a lengthy USB cable (or more likely 3 five meters cable), which should work fine as long as you only do serial communication. The USB 2.0 limitation of 5 meters are for "hi-speed" connections, which is not our concern for simple serial data communication.

HTH

---
Tags: serial, uart
---


# Question
Title: Can anyone explain how to use MPL sensor with Arduino MEGA?
I am trying to connect a MPL3115A2 Altitude/Pressure/Temp Sensor Breakout which I bought from Hobbytronics to my Arduino Mega. What I had in mind was (Breakout -\> Arduino):

`3.3V -> 3.3 V` `GND -> GND` `SDA -> A4` `SCL -> A5`

The information which I've found so far is very conflicting and I'm not sure whether or not I should be using pull-up or in-line resistors, and if so, what value?

The code which the product page links to also differs, with one stating that the Wire library is unsafe to use with a 3.3V rated sensor due to the internal pull-ups, but the other code uses the Wire library?

If anyone could advise me on how best to use this sensor without frying it, it would be much appreciated!

# Answer
> 3 votes
Since the device is 3.3V and the Arduino is 5V, you *will* need a I2C level converter such as the TCA9517. Simply supply the Mega side with 5V and the device side with 3.3V and attach 4.7kohm pull-ups to 5V on the Mega side, and it will convert both SDA and SCL for you. You won't need pull-ups on the device side since it includes pull-ups on the board.

For I1 and I2 (push-pull outputs) you can use either normal level converters or you can use a SN74LVC2G07 along with the pull-ups found on the Mega inputs.

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


# Question
Title: How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?
My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found this shield for Arduino and this library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.

# Answer
this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.

zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.

That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)

zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun. The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield
> 2 votes

# Answer
**This project is very simple.** As I understand it, this is your setup:

```
+–––––––––––––––––––––––––––––––––––––––––+
|                                         |
|  Arduino 1-––––––––––-PS4 Controller    |
|  |                 (W. Shield attached) |
|  |USB                                   |
|  |                                      |
|  Computer                               |
|  |                                      |
|  |[Wireless]                            |
|  |                                      |
|  Arduino 2                              |
|                                         |
+–––––––––––––––––––––––––––––––––––––––––+

```

*Made with ASCIIFlow*

If you have a very small range (I'd say 10-20 feet max), I recommend using Bluetooth. The HC 06 Bluetooth module looks like a good choice. There's also a less powerful HC05 if I remember correctly. I had one once but accidentally destroyed it before I could connect with a bad soldering job :). The one linked on Amazon luckily comes with a "backplane" already soldered so you just need to attach 5V, GND, and the TX/RX pins to the Arduino, accordingly. Then, you can select the BT module (wherever it appears on your OS; search online for this) and then you can connect to it and add the password 1234. After that, it should function like a normal COM port.

You would connect this to the HC06 to Arduino 2, and wirelessly the HC06 to the computer. The computer would then be connected to Arduino 1, who would receive the PS4 signals, with the shield. You would use Processing to receive the PS4 signals and to send data to the second Arduino board. I'm not an expert on Processing, but I found this serial library.

I ***do not*** recommend using Xbee because one Arduino needs to talk to the computer and the other at the same time. That's not practical with the way it's set up on most boards. The OP would need another UART connection, even so the Xbee and the USB to UART chip use the same pins on all standard boards.
> 1 votes

---
Tags: library
---


title: Controlling LED from web server

text:
# Question
Title: Controlling LED from web server
I have a LED attached to my Arduino wifi shield that I want to control from my PHP web server. In terms of communication, should I

1. Make my Arduino a web server and then communicate with PHP web server via HTTP
2. Make my Arduino a web client and receive commands from my PHP web service. I would parse the JSON response

Also my other question is should I communicate with JSON between my PHP web server or is there a better way to send commands to my LED light?

# Answer
> 4 votes
There's no need for either PHP or JSON. Simply detect when one of two URLs (say, `/led/on` and `/led/off`) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.

# Answer
> 4 votes
The REST protocol is ideal for this and there's a nice Sketch already written, called RESTduino on Github: https://github.com/jjg/RESTduino

Basically (and loosely) REST treats a URL as a command. Quoting from the RESTduino doc's:

"To turn on the LED attached to pin #9 (currently case sensitive!):

```
http://192.168.1.177/9/HIGH

```

This will set the pin to the HIGH state and the LED should light. Next try this:

```
 http://192.168.1.177/100

```

This will use PWM to illuminate the LED at around 50% brightness (valid PWM values are 0-255)."

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


# Question
Title: Pressure transducer / sensor (0.5 - 4.5V) innacurate analog pin readings
I have a relatively cheap 0-15psi pressure transducer. It has 3 pins - ground 5V and signal. The signal outputs a voltage of 0.5V to 4.5V based on pressure from 0psi to 15psi. I can verify it does respond to significant pressure increases so it works at least to a point.

The issue is that the reading from arduino can differ by over 50% when at ambient atmospheric pressure (resting on a table). It should be significantly more accurate if the sensor data are to be trusted. The code is basic:

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

void measurePressure(){
  int rawReading = analogRead(A0);   // Range : 0..1024
  //float rawVoltage = (rawReading * (4.5 / 1023.0)) + 0.5;

  Serial.print("Raw reading: ");
  Serial.println(rawReading);

}

void loop() {
  measurePressure();
  delay(1000);
}

```

The output variations are not entirely random, it seems that the reading goes down and up in intervals of roughly 5-15 seconds. Below is a sample output:

```
Raw reading: 61
Raw reading: 67
Raw reading: 70
Raw reading: 73
Raw reading: 74
Raw reading: 78
Raw reading: 75
Raw reading: 82
Raw reading: 85
Raw reading: 90
Raw reading: 89
Raw reading: 97
Raw reading: 103
Raw reading: 119
Raw reading: 146
Raw reading: 165
Raw reading: 171
Raw reading: 168
Raw reading: 163
Raw reading: 150
Raw reading: 143
Raw reading: 118
Raw reading: 88
Raw reading: 70
Raw reading: 62
Raw reading: 64
Raw reading: 72
Raw reading: 78
Raw reading: 80
Raw reading: 82
Raw reading: 88
Raw reading: 92
Raw reading: 102
Raw reading: 134
Raw reading: 160
Raw reading: 170
Raw reading: 172
Raw reading: 166
Raw reading: 158
Raw reading: 149
Raw reading: 132
Raw reading: 100
Raw reading: 73
Raw reading: 63
Raw reading: 61
Raw reading: 71
Raw reading: 77
Raw reading: 79
Raw reading: 84
Raw reading: 90
Raw reading: 90
Raw reading: 99
Raw reading: 134
Raw reading: 161
Raw reading: 170
Raw reading: 166
Raw reading: 161
Raw reading: 151
Raw reading: 133
Raw reading: 103
Raw reading: 81
Raw reading: 68
Raw reading: 63
Raw reading: 63
Raw reading: 71
Raw reading: 73
Raw reading: 81
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 98
Raw reading: 128
Raw reading: 161
Raw reading: 171
Raw reading: 166
Raw reading: 159
Raw reading: 145
Raw reading: 120
Raw reading: 85
Raw reading: 67
Raw reading: 57
Raw reading: 63
Raw reading: 72
Raw reading: 75
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 97
Raw reading: 130
Raw reading: 164
Raw reading: 172
Raw reading: 163
Raw reading: 155
Raw reading: 135
Raw reading: 101
Raw reading: 69
Raw reading: 60
Raw reading: 62
Raw reading: 72
Raw reading: 78

```

I tried adding 4.7k pull down resistor with no change but that was just a blind try. I have a multimeter connected as well and the reading seems to be more stable ranging from about 0.495V to 0.535V (variations do not seem to match arduino output).

What could be causing the issue?

# Answer
> I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Reinstatement of incorrect edits by Annonomus Person (AP: Please do not edit answers in such a way that you entirely change their meaning. In the current discussion "the board" is meaningless. We are trying to distinguish between symptoms seen in two different 'boards', an Arduino Uno, and an Arduino Micro.)

Looks to me like the problem is with the Arduino Micro's 5V supply then.

If you are powering the Micro from an external supply (not USB), then 4.6V on the Micro's "5V" output would indicate that the 5V regulator is not operating within its expected range.

If you *are* powering from USB, then the regulator is not in play. The 4.6V would indicate a problem with the USB's 5V supply.

Likely possibilities:, either the upstream supply is inadequate, or the micros and whatever is attached to it is drawing too much current.

I suspect that the transducer output is fluctuating in a way that's too rapid to be seen by your meter, but which is sampled by the Arduino Micro, giving your varying result numbers.

Either the "4.6V" is inadequate to run the transducer, causing erratic transducer output, or the 4.6V itself is fluctuating, with similar results at the trans output.

And you might also check the ground between micro and transducer -- are you sure that's wired correctly?
> 2 votes

---
Tags: sensors, arduino-pro-micro
---


# Question
Title: How precise can I get Arduino using rotary encoders?
Stepper motors are often pricey for a large motor. However, with a powerful, standard DC motor and a rotary encoder, you can "simulate" a stepper motor. **How accurate are rotary encoders with Arduino just with a basic loop and not much other code?** Is it going to "miss a pulse" and not record enough rotation often? How can I handle this with much more code? Is there a better way to do this? Would interrupts help? Is there some sort of circuit that would help with this problem?

Note: It will probably not exceed 4 rotations a second... *(That may be a lot but if you're doing a lead screw type mechanism that would only be 24 inches a minute if there is 10 rotations per inch of linear motion.)*

# Answer
> 11 votes
Interrupts are what you would use in this situation.

The rates that you have mentioned are slow enough where you *probably* would be able to count it inside of a loop, however this is not recommended, as a typical loop will take many clock cycles to complete, and depending on the number of instuctiuons per loop, you may miss some counts.

Interrupts are made for this purpose, as they can be triggered at any time, regardless of the state of the loop.

There is a function named `attachInterrupt()` which will take three arguments.

1. Interrupt Pin
2. Interrupt Service Routine
3. Mode

Below is an example for counting an interrupt

```
volatile int myCounter = 0;

void setup(){
    attachInterrupt(0, count, RISING);
}

void count(){
    myCounter++;
}

```

The Modes are as follows:

> LOW, CHANGE, RISING, FALLING

More information about using interrupts can be found here.

Depending on the encoder you use, you will need to tailor the code your needs, and do some more calculations to determine your position, but this should be a good starting point.

**Edit** Here is some example code from Arduino Sandbox for using a rotary encoder.

# Answer
> 3 votes
Adding some references to already-written libraries and examples, to enable comparison between different approaches, and experiences with speed versus susceptibility to missing steps.

Reading rotary encoders: http://playground.arduino.cc/Main/RotaryEncoders

Quadrature Encoder too Fast for Arduino (with Solution): http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino/

Teensy Encoder library: https://www.pjrc.com/teensy/td\_libs\_Encoder.html

Reading rotary encoder on Arduino: http://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino/

---
Tags: interrupt, rotary-encoder
---


title: Calibrate Watchdog Timer

text:
# Question
Title: Calibrate Watchdog Timer
Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every *hour*!

# Answer
> 4 votes
Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.

With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 \[DIP\] or 7/8 \[TQFP\]) by setting ASSR\[6:5\] to 0b01 and changing the CKSEL\[3:0\] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.

If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).

---
Tags: timers
---


title: Creating a wireless remote

text:
# Question
Title: Creating a wireless remote
I am trying to create a wireless remote control to control a servo motor via Bluetooth. What all do I need to establish this? I did some research and found the following:

Tinyduino

Bluetooth low energy shield

Would these be enough (in addition to the servo motor) to establish my needs? Any advice on how I would go about coding this? I can research on the specifics but hints on functions to use would be greatly appreciated. Thanks!

I need to be able to control the system wirelessly (may it be Bluetooth or whatever) through a remote control. This remote control could be a push button system or an app on the phone. I do not have this designed yet. I do not know how to make iPhone apps so the best solution for me would be a simple push button on/off switch that can wirelessly tell the servo motor to either turn 90º clockwise or counterclockwise.

The RFDuino suggestion is very helpful, thank you for that. Can anyone recommend a push-button switch (small) that can wirelessly transmit the signal to the servo motor on the device? I hope this clears things up. Thanks!

# Answer
I would also check out RFDuino.

Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.

The RFduino runs Arduino code and can do everything an Arduino can.
> 1 votes

---
Tags: bluetooth, remote-control
---


# Question
Title: Mic input and Speaker output using arduino
I am trying to make a small project. Firstly, I want to record voice using a small microphone(electret) for the time button is pressed and on releasing the button, the speaker of my laptop should output the recorded voice or a speaker attached to the arduino should output.

**Note: I don't want to use any shield to do so. Simply Arduino**

# Answer
Microphone input is easy (ADC). Speaker output is easy (PWM). Both have many, many examples strewn across the Internet.

What happens in between is *not*, and will require external components. You will need at the very least somewhere to store the samples between record and playback. Investigate SPI SRAM large enough to store all the required samples at your chosen sample rate (8 kS/s should be high enough for human speech).
> 3 votes

---
Tags: interrupt
---


# Question
Title: It is possible to program Linino to send HTTP requests and then use the returned values in sketch?
I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.

In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.

If it is possible, how to do that?

# Answer
Take a look at Bridge example or TemperatureWebPanel example: you see you can receive kind of "commands" and react "doing things".

Then take a look at HTTP Client example, where you delegate an HTTP call to the linux side.

Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.

A short test can be done by cutting and pasting the examples above.
> 1 votes

---
Tags: programming, library, sketch, arduino-yun, web
---


title: Accessing Arduino Yun from Internet

text:
# Question
Title: Accessing Arduino Yun from Internet
I am trying to access my Arduino Yun from the internet, and it's not quite working. I have correctly port forwarded the port 5555 from the router to the Yun (verified I am able to access my many other NAT'd resources).

I can access the Yun from my internal network.

In the Arduino sketch I have this (among many other things). Mainly taken from example sketches.

```
#include <Bridge.h>
#include <HttpClient.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer server;

void setup {
   // Listen for incoming connections on port 5555
   server.noListenOnLocalhost();
   server.begin();
}

```

Is `server.noListenOnLocalhost();` the right one to use to access from the outside world?

# Answer
> 2 votes
Well, I'm not familiar with the Yun, but the first thing that stands out is the missing

```
Bridge.begin();

```

line apparently needed to initialize the Bridge library that you use.

And you do have something like

```
YunClient client = server.accept();

```

and "more" in the main loop (or a function where applicable) of your code, right ?

And yes, `noListenOnLocalhost()` is the correct function for serving external clients.

---
Tags: arduino-yun
---


# Question
Title: Why am I getting "fatal error: SoftwareSerial.h: No such file or directory"
I downloaded the Adafruit\_GPS library from Adafruit and I'm trying to compile the example code (due\_parsing) but I can't seem to get past this silly error:

```
In file included from due_parsing.ino:15:

/Users/haddad/Documents/Arduino/libraries/Adafruit_GPS/Adafruit_GPS.h:24: fatal error: SoftwareSerial.h: No such file or directory
compilation terminated.

```

This is the location in the example Arduino Sketch where `SoftwareSerial.h` is mentioned:

```
#ifdef __AVR__
  #include <SoftwareSerial.h>
#endif

```

I noticed it's around an `ifdef` guard, so shouldn't it not even matter that I don't have this library?

I went into the .h and .cpp files and commented out the where it called `SoftwareSerial.h`, but I'm still getting that above error.

Does anybody know how to fix this? I am using Arduino IDE v1.5.5

---

Update:

I didn't put the library in the library direct on my mac but I'm now getting tons of errors, all the errors are with `SoftwareSerial.cpp`. Is anybody else having similar issues when you go to compile?

# Answer
According to your comment:

> after commenting out those ifdef guards, it worked

I would say that is a bug in the **Adafruit\_GPS** library.

As a matter of fact, the **DUE** is not using the **AVR** architecture (it uses **ARM**), that explains why `#ifdef __AVR__` in `Adafruit_GPS.h` never passes; but then something else should be done specifically for the DUE (missing `#else` or `#elif`).

After checking on *github*, there is an issue open for that; unfortunately, as of April 2014, it has not moved for 10 months.

Your best guess would be to go there and try to "reactivate" this issue.
> 3 votes

# Answer
So I went into the interface file (.h) and removed all references to AVR and then went into (.cpp) and removed all references to AVR there as well. It now seems to be working, although sometimes it says "Not supported Architecture ARM" during compilation...very weird
> 0 votes

# Answer
this is a "bug" in the arduino IDE pre-compilation process. If you turn on the compiling verbositi in thge precerences menu, you will see that arduino has copied all file (with a rater "stupid" code that just look for include) into a temp folder (wiring lib are not copied, but the below still aplly). Until here, ugly but still fine.

Then, it will -force- compilation of every "included" file, one by one, the facto bypassing the #ifdef.. and this is why you get that problem.

Solution is to heavy change the ide so it will force compilation only in the main, and let the compiler include and compile needed libraries.

I still have no idea why every file is forced, but a change like this is really heavy and break-old-code prone..

Newest IDE to bypass this problem (and also some other problem, like depeency) use a "config" file that will tell the IDE if use the AVR or ARM or x86 library, probabily this file is missing and the ide see te lib as only AVR by default.

Double check if it is really usable on DUE
> 0 votes

---
Tags: arduino-due, softwareserial
---


# Question
Title: Use an Arduino as a user interface for the computer
I wanted to use either Arduino Mega or Uno as a form of an interface between me and the computer. I want to apply it to the following scenario; if I press a button on a circuit board I want it to trigger an action on my computer, like scroll down.

How can I achieve this? How would the code look like and what programs would I need to translate from Arduino to Windows?

# Answer
> 3 votes
For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

* Use the (USB) serial data interface, and have software on the host computer which accepts commands over that. Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)
* On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard. That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.
* The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" *approximation* of a low-speed USB interface *in software* on arbitrary I/O pins with some external matching/protection componenets. A USB keyboard is a common demo application of that.

# Answer
> 2 votes
Arduino Yun, Leonardo, Esplora and Due have the ability to appear as a native Mouse and/or Keyboard to a connected computer by use of the Mouse and Keyboard libraries.

Here's an example of how you would use SWITCH3 on the Esplora to active PAGE UP on your keyboard.

```
if (!Esplora.readButton(SWITCH_3)) {
  Keyboard.press(KEY_PAGE_UP)
  delay(100);
  Keyboard.releaseAll();
  }

```

Here's an example of using the Esplora to control the Keyboard and Mouse to control the Flight Simulator option of Google Earth.

If you want to use the Uno it's more difficult but it can be done by sending data from the Uno to a Python program running on the PC. The Python program uses the pywin library to control windows.

Here's a fully worked out Instructable on how to do it.

# Answer
> 1 votes
You can do that easily with a few of the Arduino boards that have built-in USB communications support.

You find that feature on Leonardo, Micro, Esplora and Due boards. You also find that on some Arduino compatible boards like the Adafruit Flora.

Simply plug the Arduino USB port to your computer and the Arduino will behave like a keyboard. Then you can program your sketch to perform what you want with your buttons. Check the Arduino mouse and keyboard library.

---
Tags: serial, linux
---


# Question
Title: How can Arduino control with a servo with only one wire?
I was playing with getting my servos to be on dedicated power, separate form the Arduino entirely, but obviously controlled by the Arduino. I originally had the ground of the Arduino joined with the `-` of the battery, but to my surprise my Arduino continued to control the servos when I remove the ground wire entirely from the Arduino.

I was under the impression that all electricity must form a complete circuit, and be a closed loop. But my Arduino can obviously send a signal to a component that has no return path to itself.

I feel like I'm missing something fundamental about a electricity. So my question is:

**Why does this work?**

# Answer
The return signal is probably the other wire's servo. This only works when the control pulses to both servos are not in sync. Pull one signal wire off the breadboard and both servos will stop working.

You need to interconnect grounds or you will get strange effects sooner or later.
> 5 votes

---
Tags: electricity
---


# Question
Title: How do I use two ultrasonic sensors to control a 5 V motor?
I've hooked up two ultrasonic sensors to my breadboard and I also got a 5 V motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.

I want the motor to run at let's say 100 once I start it up:

* The first sensor should be used to slowly slow down the motor when an object is placed in front of it
* The second sensor should be used to slowly speed up the motor when an object is placed in front of it

I do not want the speed to return to 100 once the object is removed. It should remain at the same speed according to which sensor was used.

Tell me if I have to clarify anything in the comments.

Code

```
int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 20) {  // Distance from sensor
    analogWrite (motorPin, 50);
  } else {
    int duration, distance;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (1000);
    digitalWrite (trigPin2, LOW);
    duration = pulseIn (echoPin2, HIGH);
    distance = (duration/2) / 29.1;
    if (distance > 20) {  // Distance from sensor
      analogWrite (motorPin, 150);
    }
    if  (distance > 20) {  // Distance from sensor
      Serial.println("Out of range");
    } else {
      Serial.print(distance);
     Serial.println(" cm");
    }
    delay(500);
  }
}

```

# Answer
This is *very* simple using the **`map()` instruction.** Here's the code you would use (feel free to modify values:

```
int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);

```

So if both sensors gave equal values, they would offset each other. To make it still work if an object is removed, you could just use the last `distance`/`distance_2` value and update the other.

---

One issue with this approach is, if the line of transformation of the object is *not* perpendicular to the line of the pings, the value will go:

> 10 → 11 → 12 → 13 → 14 → 15 → 16 → 17 → 18 → 19 → 20 → \[Out of range\]

**I've added some pretty animations to show you what I mean:**

Perpendicular:

Collinear:

---

As I understand, this is what you want:

```
int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;
int postdist = 112;
int postdist2 = 112;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  //First Read
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  int ltol = postdist - 5;
  int htol = postdist + 5;
  if (distance > 20 || !(distance > ltol && distance < htol)) {  // Distance from sensor
    Serial.println("Out of range");
    distance = postdist;
  }
  //Second Read
  int duration2, distance2;
  digitalWrite (trigPin2, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin2, LOW);
  duration2 = pulseIn (echoPin2, HIGH);
  distance2 = (duration2/2) / 29.1;
  int ltol2 = postdist2 - 5;
  int htol2 = postdist2 + 5;
  if (distance2 > 20 || !(distance2 > ltol2 && distance2 < htol2)) {  // Distance from sensor
    Serial.println("Out of range");
    distance2 = postdist2;
  }
  //Math:
  Serial.print("Distances-1: ");
  Serial.print(distance);
  Serial.print(" cm 2: ");
  Serial.print("Distances-1: ");
  Serial.print(distance2);
  Serial.println(" cm");
  postdist = distance;
  postdist2 = distance2;
  int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);
  if(speed < 60) {speed = 60;} //Modify 60 to meet your needs for minimum threshold
  analogWrite (motorPin, speed);
  Serial.print("Motor Speed: ");
  Serial.println(speed);
  delay(500);
}

```

**Changelog:** forgot to edit `postdist`/`postdist2` at end of cycle, added minimum threshold, prevent very small changes in voltage to keep voltage stable and prevent noise.
> 1 votes

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


# Question
Title: Replicate a Waveform Exactly with An Arduino Uno
So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions? Here is the code:

```
 //3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19
char incomingByte = 0;

int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void timing()
{
  //Serial.println("This is a 0ms Event");
 // if(Serial.available() > 0)
 // {
    incomingByte = Serial.read();
    Serial.print("I received");
    Serial.println(incomingByte);

     pinMode(10, OUTPUT);
     digitalWrite(10, HIGH);
     delayMicroseconds(16000);
      digitalWrite(10, LOW);
      delayMicroseconds(2000);
      digitalWrite(10, HIGH);
 }
//}

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

for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}
pinMode(3,INPUT);
attachInterrupt(1,timing,RISING);

//Begins Serial
Serial.begin(115200);
}

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

```

Here's the waveform I'm trying to duplicate:

# Answer
If you're looking to speed your code up I would recommend not using `digitalWrite` or `Serial`. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using port manipulation.

Example of turning a pin on or off with a preprocessor macro using port manipulation

```
#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

```

Using port manipulation in your code:

```
#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

void timing()
{
    //incomingByte = Serial.read(); // If needed uncomment, but it's slow
    //Serial.println(incomingByte); // If needed uncomment, but it's slow

     // Set pinMode in setup()
     DIGITAL_WRITE_10_HIGH();
     delayMicroseconds(16000);
     DIGITAL_WRITE_10_LOW();
     delayMicroseconds(2000);
     DIGITAL_WRITE_10_HIGH();
 }

```
> 1 votes

# Answer
This code is wrong in many ways.

first of all, `timing()` is execute inside an interrupt, this mean that while it is running, all other interrupt and timer stop (delayMicroseconds works because it does not rely on timer, but on know instruction execution time). That mean you have to keep the interrupt funzion faster as possible, or bad things may and will happen. (microseconds still work because it is based on know instruction duration in loop)

For example, Serial is interrupt driven; this may cause a race condition that will freeze the code.

As far as i can understand pin 3 may be a button (in that case you need to apply some antibounce code, just look at the signal create by pressing a button with your oscilloscope to see what happen), so you can just make a digitalRead every loop, if true do your code. So you will keep `timing()` out of interrupt.

`pinMode()` only needs to be set once, in `setup()`. Also, `digitalRead()` is really slow: operating directly on the register is a lot faster! see port manipulation

but in your case i would delete all precendent code and do some math to use an ad-hoc PWM, so you will be almost code free and because it will be almost all done by hardware, precision and possible granularity will increase, see secret of arduino PWM
> 0 votes

---
Tags: c++, c, timing
---


# Question
Title: It is possible to run an entire script on the Linux side? If so, how, what and where to do that?
I am new to using Arduino Yun and I would like to know if it is possible to run an entire script on the Linux side. In my case the script should execute a HTTP request to a remote server, parse the subsequent HTTP response and return some value that then can be used in the Arduino sketch.

If it is possible, what I have to do? For example, how should I write and run script files? what programming language should I use? where I should put those script files on the Linux side?

# Answer
> 0 votes
Arduino Yun ships with python pre installed. You can copy python scripts from your pc to the yun with `scp` (or WinSCP or `putty`, if you're on windows). Once copied, just run it using Process from your sketch. As they are scripts, program name is `python` and the path to your script is its first argument (you can do that in a different way, but that would require some linux magic, which I suggest to postpone if you're new to it).

Other pre installed options include lua and bash. Other languages such as ruby, erlang and php are available as optional packages.

---
Tags: programming, sketch, arduino-yun, web
---


title: Calibrating Accelerometer Sensor

text:
# Question
Title: Calibrating Accelerometer Sensor
I'm working with an Adafruit LSM303DLHC Accelerometer Sensor hooked up to an Arduino. I've downloaded the appropriate libraries to make it work and uploaded the example sketch "accelsensor.pde". I then placed my sensor at rest on a flat surface and obtained the following acceleration vector values on average, in units of meters per second:

```
X: -0.24  Y: -0.71  Z: 10.47

```

At rest, each of these three values fluctuate approximately +-0.04 on average.

As I see it, the values are off a bit. At rest, the X and Y components should hover closer to 0m/s^2 while the Z component should be closer to 9.8m/s^2.

What is the best way to compensate for this biased measurement? Should I simply add back the average observed bias? Or is there a more robust method to calibrate the sensor values?

# Answer
> 1 votes
there are varius calculation.

At the end of the day, if take a point in every position (under no acceleration), you should end up with a sphere, or matematically speacking, wthe lenght of the vector should be equal to gravity, so `sqrt(x*x+y*y+z*z) = G` or, to do less computing `x*x+y*y+z*z = G*G` (same apply for magnetometer, but using local magnetic force, or gyroscope, using a know-speed rotation like a LP player)

To create that spere you have to take many point, and find a multiplicator (or function) for each axes. That is particualary important when one axes has differnet precision of others, you are `linearizing` the axis output, and then `normalizig` its value relative to others axes.

Once you have corrected the vector lenght to have a spere, you should look at the offset of the sphere; if its `center` point is not on the `origin` point 0,0,0 then the differece between `center` and `origin` is the correction you talk about. This is offset correction.

Also many (well, all) sensor are affected on their temperature; many claim to be "thermocompensated", that means this difference is less evident due to some some sort of hardware and/or software filtering.

# Answer
> 1 votes
To get rid of the fluctuation, you could always try a moving average. It isn't hard to modify the `Smoothing` example (under `File->Examples->1. Analog->Smoothing`) to accept accelerometer values.

As for the slight offset in the X & Y values, that is probably because your sensor isn't sitting perfectly flat.

---
Tags: sensors
---


# Question
Title: TCP communication between Arduino client and server
I'm currently trying to build an Arduino robot controlled via a wifi connection. I have an Arduino Mega running as a client and it successfully connects to the server on LAN via the Adafruit cc3000 wifi board. However instead of grabbing the contents of the JSON file and printing it to serial, I'm just getting a 100 continue response. While this means I'm doing something right, I don't know what to do next in order to grab the data I need. Do I need to get the 100 message then respond with the GET request, or is there a way that I can GET the data straight away?

Thank you all in advance. Here is the Arduino code I have so far:

```
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <stdlib.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ 3  // MUST be an interrupt pin!
#define ADAFRUIT_CC3000_VBAT 5 // Apparently these can be any two pins
#define ADAFRUIT_CC3000_CS 10  // But I wouldn't change these...
// Use hardware SPI for the remaining pins (On a Mega 2560, SCK = 52, MISO = 50, and MOSI = 51)
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

#define WLAN_SSID "VM540258-2G"
#define WLAN_PASS "XXXXXXXX"
#define WLAN_SECURITY WLAN_SEC_WPA2

String readString = String(100); //string for fetching data from address
uint32_t ip = 3232235523; // This translates into the ip address we need
                          // 323223552X; 192.168.0.X

void setup(){
  Serial.begin(115200); //Can also work at 9600

  //Initialise CC3000 module
  Serial.println(F("\nInitializing CC3000..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }
  //Connect to the Wireless Access Point
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP()) { //Obtain IP addeess
    delay(100);
  }

  while (! displayConnectionDetails())
  {
    delay(1000);
  }
}

void loop(){
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  if (client.connected()) {
    client.println("GET /project-test/state.json HTTP/1.0"); //Make a request for state.json
    client.println(""); //Mandatory blank line?
    if (client.available()){
      char c = client.read();
      Serial.print(c);
      //read char by char HTTP request
      if (readString.length() < 100) {
       //store characters to string
       readString += c;
      }
    }
  }
  //Once we have obtained the data, disconnect from the server
  client.close();
  Serial.println(readString);
  delay(1000);
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

```

The initial JSON file I'm using contains the following:

```
{"speed_left":null,"speed_right":null,"direction_left":null,"direction_right":null}

```

And the serial output I get when I run the Sketch:

```
Initializing CC3000...
Started AP/SSID scan

Connecting to VM540258-2G...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.0.7
Netmask: 255.255.255.0
Gateway: 192.168.0.1
DHCPsrv: 192.168.0.1
DNSserv: 192.168.0.1

Connect to 192.168.0.3:80
100

Connect to 192.168.0.3:80
100

```

ad infinitum

# Answer
you are missing the `HOST` header in the request, so the server tell you to `100 CONTINUE` you request. Also yes, the final empty row IS mandatory

for example, to ask `www.example.com/index.html`

```
GET /index.html HTTP/1.1
Host: www.example.com

```
> 1 votes

# Answer
I'm going to guess that it's a problem with your server not expecting an HTTP/1.0 request. I note the following from RFC 1945 about the response codes:

> 9.1 Informational 1xx
>
> This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. HTTP/1.0 does not define any 1xx status codes and they are not a valid response to a HTTP/1.0 request. However, they may be useful for experimental applications which are outside the scope of this specification.

I'd recommend changing your request to be HTTP/1.1 compliant (with a Host: header as suggested by @lesto)
> 0 votes

# Answer
Okay, I have a better answer, again done without testing.

If I look at the BNF for an HTTP-message from the RFC, it indicates that the message body is terminated by a blank line.

So, you actually need 2 CRLFs (i.e. 2 blank lines). The first one separates the headers from the body of the HTTP request. You don't actually have a message body (which is fine, it is optional). But, you'll need another CRLF to terminate the (blank) body.

Since you only sent one blank line, the server is sending you the continue status codes, prompting you to finish sending your message (i.e. the message body).

So, try adding another client.println("");
> 0 votes

---
Tags: arduino-mega, tcpip
---


title: Ethernet shield programming

text:
# Question
Title: Ethernet shield programming
This is first time programming with Ethernet shield . I want to test the web server application with my Arduino. I have an Arduino Uno, Ethernet shield, and a potentiometer. Below code being uploaded.

Question are:

* Currently I am using LAN connection to configure. How to configure it? Is internet required for below application?
* How do I check the output?
* Is there any software where i can make customized tags?
* I have values coming from the serial port to be monitored on webserver. Can someone share how to monitor it?

Ethernet shield

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

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

// 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(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

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

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
      client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

```

# Answer
> 3 votes
You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.

The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.

To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.

---
Tags: arduino-uno, ethernet, networking, web-server
---


title: Faster GPS update rate for parser

text:
# Question
Title: Faster GPS update rate for parser
I really hope somebody can help me.

I need help making my code receive updates faster to the parser...I need the received GPS coordinates (Latitude and Longitude) to update 5 or more times a second, currently it locks when stationary. Can somebody help?

code:

```
#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
//SoftwareSerial ss(4, 3);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);
//double getCurrentLatitude();
//double getCurrentLongitude();

//double cLatitude = 0.0;
//double cLongitude = 0.0;
//
//double getCurrentLatitude(){
//  return cLatitude;
//}
//
//double getCurrentLongitude(){
//  return cLongitude;
//}

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

//  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
//  Serial.println();
//  Serial.println("Sats HDOP Latitude      Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
//  Serial.println("          (deg)         (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
//  Serial.println("------------------------------------------------------------------------------------------------------------------------------------------");

  Serial1.begin(9600);
}

void loop()
{
  double flat, flon = 0.0000000000000;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  //static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

//  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
//  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
//  gps.f_get_position(&cLatitude,&cLongitude, &age);

  //print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
  //print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

  float lati = (float)flat;
  float longi = (float)flon;

  Serial.print("     ");
  Serial.print(lati, 8);
  Serial.print(" ");
  Serial.print(longi, 8);
  smartdelay(0);
  //cLatitude = flat;
  //cLongitude = flon;
//  print_float(getCurrentLatitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
//  print_float(getCurrentLongitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

//  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
//  print_date(gps);
//  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
//  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
//  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
//  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
//  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
//  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
//  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
//
//  gps.stats(&chars, &sentences, &failed);
//  print_int(chars, 0xFFFFFFFF, 6);
//  print_int(sentences, 0xFFFFFFFF, 10);
//  print_int(failed, 0xFFFFFFFF, 9);

  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (Serial1.available())
      gps.encode(Serial1.read());
  } while (millis() - start < ms);
}

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

/*
    If data is invalid, print out *******
    otherwise print out buffer
*/
static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

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

```

# Answer
I assume you're using TinyGPS which I sourced from https://github.com/mikalhart/TinyGPS

I've recently done a similar thing - just trying to get the gps to work and give me as much data as possible.

The code I used to do this is here:

```
#include "TinyGPS.h"

#define GPS_BAUD 115200
#define PC_BAUD 115200

TinyGPS gps;

int led1 = 13;

long lat, lon;

unsigned long fix_age, time, date, speed, course;

unsigned long chars;
unsigned short sentences, failed_checksum;

void setup()
{
  pinMode(led1, OUTPUT);
  Serial1.begin(GPS_BAUD);
  Serial.begin(PC_BAUD);
  Serial1.println("");
  Serial1.println("Initializing");
  Serial1.println("");
  digitalWrite(led1, HIGH);
  delay(2000);
  digitalWrite(led1, LOW);
  delay(500);
}

void loop()
{
  while(Serial1.available()){
    if(gps.encode(Serial1.read())){
      digitalWrite(led1, HIGH);
      gps.get_position(&lat, &lon, &fix_age);
      gps.get_datetime(&date, &time);
      Serial1.println("");
      Serial1.println("Lat: " + String(lat));
      Serial1.println("Lon: " + String(lon));
      delay(3000);
      gps.stats(&chars, &sentences, &failed_checksum);
      Serial1.println("Chars: " + String(chars));
      Serial1.println("Sents: " + String(sentences));
      delay(1000);
      Serial1.println("Fails: " + String(failed_checksum));
      Serial1.println("");
      delay(1000);
    }
    Serial1.print(".");
  }
}

```

I was using an Arduino Mega 2560, but I think you have the same Serial ports on your Due. I connected the TX pin of my GPS ( can't remember the model but I think it was a 10Hz version of this: https://www.sparkfun.com/products/9891 ) to Serial1's RX and I used a small serial 2 row LCD display to output which was connected to Serial1's TX, hence I was using serial1 for both transmitting and receiving. If you remove the delays from the code above the data is read and then written back as fast as possible and while I never measured how many fixes I was seeing per second I'm fairly sure there were at least 5.

The code you want is probably something like this:

```
#include "TinyGPS.h"

#define GPS_BAUD 115200
#define PC_BAUD 115200

TinyGPS gps;

int led1 = 13;

long lat, lon;

unsigned long fix_age, time, date, speed, course;

unsigned long chars;
unsigned short sentences, failed_checksum;

void setup()
{
  pinMode(led1, OUTPUT);
  Serial1.begin(GPS_BAUD);
  Serial.begin(PC_BAUD);
  Serial1.println("");
  Serial1.println("Initializing");
  Serial1.println("");
  digitalWrite(led1, HIGH);
  delay(2000);
  digitalWrite(led1, LOW);
  delay(500);
}

void loop()
{
  while(Serial1.available()){
    if(gps.encode(Serial1.read())){
      digitalWrite(led1, HIGH);
      gps.get_position(&lat, &lon, &fix_age);
      gps.get_datetime(&date, &time);
      Serial.print("    ");
      Serial.print(lat);
      Serial.print(" ");
      Serial.print(long);
    }
  }
}

```

As commented by @connor-wolf above you will probably need to change the baud-rate of your communications up because otherwise you the limit of the amount of information you can send/receive per second is probably too low. The baud rate must also match the baud rate of your GPS device. Some GPS devices have an adjustable baud rate.

---

A quick google turned up an average NMEA sentence length of 60 bytes and if I recall correctly you may have 2 or 3 sentences to each fix? (I think the extra sentences contain extra info like satellite counts, and stuff). So assume you need 180 bytes per fix and you want at least 5 fixes per second that would be 900 bytes. In baud that is 900x8 = 7200. So assuming my estimations above are accurate or overestimated then you have enough bandwidth.

I'm not sure however if the Micro transmits/receives over serial while running the other instructions in your code - I would assume not to be safe but it's worth some research. Therefore you have to account for the time the micro spends transmitting and interpreting the data as time in the second that it can't spend receiving the data. Therefore I would suggest that doubling or even tripling the data rate would be a good idea. (as you can see from my example I just set it to as high as the GPS would go.)

Anyway. I hope all that helps.

P.S please forgive if I've used the wrong terminology for fixes/sentences or whatever
> 2 votes

---
Tags: arduino-due, tinygps
---


title: strange behaviour of dtostrf()

text:
# Question
Title: strange behaviour of dtostrf()
I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.

This is what I have:

```
char ang[3], lat[9];
dtostrf(GPS.angle, 3, 0, ang);
dtostrf(GPS.latitude, 9,5, lat);

Serial.println(lat);
Serial.println(ang);
Serial.println("-------");

```

I would expect the following in the serial monitor:

```
5111.60160
267
-------

```

But instead, I'm getting this:

```
5111.60160
2675111.60160
-------

```

So it looks like the `ang` holds both the angle and the latitude....

Why is this happening? And how can I solve this?

My goal is to make one big string, comma separated, from the data stored in `GPS`

# Answer
Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

> char ang\[3+1\], lat\[10+1\];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.
> 4 votes

---
Tags: programming, sketch
---


title: Arduino Mega's 4 Serial Ports?

text:
# Question
Title: Arduino Mega's 4 Serial Ports?
I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

# Answer
> 1 votes
No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.

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