# Question
Title: Is parity check hardware only or can I read it? ( Arduino Mega )
Maybe a simple question, but I can't seem to find it.

Parity check is simple error detection.

But is in done in hardware on the arduino and is the data discarded before i can read it from software?

The reason I ask this quote from Thomas

> 1 Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).

From http://www.thomasknauf.de/rap/seatalk1.htm#Dat which might have confused me. So I guess this is not an option ... after the feedback from users.

So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.

But after more seaching I found this GitHub repo: https://github.com/rob42/FreeboardPLC\_v1\_2 which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7

Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.

# Answer
> 3 votes
This came up a while back on the Arduino Forum \- talking about Asynchronous SeaTalk.

I made a modified version of HardwareSerial which can be downloaded from http://gammon.com.au/Arduino/HardwareSerial9bit.zip

Changes are:

* The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.
* There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.
* There is a new function `Serial.write9bit ()`. This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.
* The read function, which already returns an int, now will return the 9th bit where required.

---

Example code:

```
void setup ()
{
 Serial.begin (115200);  // debugging prints
 Serial1.begin (115200, true);  // 9 bit mode
 Serial2.begin (115200, true);  // 9 bit mode
 Serial.println ("--- starting ---");
}  // end of setup

int i;

void loop ()
{

 Serial1.write9bit (i++);  // send another byte

 // display incoming on Serial2
 if (Serial2.available ())
   Serial.println ((int) Serial2.read (), HEX);

 // check if we have sent all possible characters
 if (i >= 0x200)
   {
   delay (100);
   while (Serial2.available ())
     Serial.println ((int) Serial2.read (), HEX);
   delay (5000);
   i = 0;
   }  // end of sent 512 bytes
}  // end of loop

```

---

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.

Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

* HardwareSerial.cpp
* HardwareSerial.h

... and replace them with the ones in the download.

---

Note that this is for version **1.0.1** of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.

The actual changes are here: http://gammon.com.au/Arduino/hardwareSerial\_diffs.txt

You could use those to guide your implementation on more recent versions, if the file download does not work "as is".

# Answer
> 2 votes
AVR devices with a hardware USART have a real 9-bit mode; there is no need to "fake" it.

But to answer your question, it is done in hardware; the appropriate USART Parity Error bit is set and while the datasheet is vague about it, it is implied that the data is stored in the receive buffer.

---
Tags: serial
---


# Question
Title: ws2812b NeoPixel - how to address it? How Arduino knows the correct order of LEDS on the stripe?
How to get a One-Wire address of a given WS2812B pixel? I bought several of these, and I cannot make them light. On the other hand, when I connect the addressable LED strip made of these diodes, I have no problem controlling it.

Here is my set-up:

I tried many programs, e.g. AdaFruit\_NeoPixel -\> simple, setting number of LEDS to 1, but no effect. No blinks, nothing - as if the diodes were dead.

If every One-Wire device is identifiable by 64 bit ID, how does the Arduino know the correct "order" of the LEDS on the ribbon? How to tell the Arduino the new sequence of the LEDS on the strip that would result if I replace one (broken) LED with another?

# Answer
> 4 votes
The WS2811/2812/2812B is not a 1-Wire device but is in fact a timing-based shift register with 3 LEDs (external in the case of the WS2811) connected to it.

As long as valid bit pulses are sent to the input of one of these devices it will shift the data through it and subsequently out of its data output. Connecting this output to the input of another device will shift data into that device as well, with the latest data sent being transmitted towards the furthest device in the chain.

Provided 24 bits per device are sent before the latch signal, The first 24 bits will be shifted into the first device, the second 24 bits into the second device, and so on until the last 24 bits into the last device in the chain. Once the latch signal is received, the devices will switch to the color indicated by the 24 bits currently shifted into them.

Since all of the devices use the same signaling (the only differences being supply level and the presence of a built-in RGB LED), they can be replaced freely with devices of the same or different make between the three.

# Answer
> 1 votes
Just one correction. The the first 24 bits of the data are shifted into the first WS2812. That device loads those 24 bits into its PWM registers. If more data is transmitted, the first WS2812 shifts that out to the following WS2812. So the first data sent stays in the first WS2812, the 2nd data stays in the 2nd WS2812, and so on. This is explained in the data sheet. Data-wise, it's a one-wire device. Power connections don't count.

---
Tags: led
---


# Question
Title: Ethernet shield not have MAC address sticker
Hi everyone I recently bought an Arduino Mega and Arduino Ethernet Shield. There are lots of forum posts that say the shield should have a MAC address that is written on the back side of shield, but I don't have any sticker which has the MAC address. Does anyone know how I can get my MAC address or configure it with a new MAC address? Thanks

# Answer
According to this documentation, you can just provide your own.

> mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.
> 2 votes

---
Tags: arduino-uno, arduino-mega, ethernet
---


title: Yum as eth->wlan adaptor

text:
# Question
Title: Yum as eth->wlan adaptor
Is there a way to make a yun an Ethernet-wifi bridge? Applications include giving wifi to raspberry pi and other Ethernet only devices and vice versa.

# Answer
Yes, you can. I use one to connect my Sky box (Ethernet only) to my WiFi network,

It's not an easy task though and you have to have a good understanding of networking and routing.

Basically you have to set the Yun up as a router to route packets between the Ethernet and the WiFi interfaces. You set the Ethernet interface up on a separate subnet to your existing WiFi network, and set a static route on your main router to send traffic destined to your new Ethernet subnet to the Yun's WiFi IP address.

Your Ethernet devices can then be allocated an IP address on the Ethernet subnet (turn on DCHP for that interface on the Yun) and will use the Yun as the default gateway.

There are probably ways you can enable bridging on the Yun to tie the Ethernet and WiFi interfaces together so it becomes transparent but I haven't investigated that yet.
> 0 votes

---
Tags: wifi, arduino-yun, ethernet
---


# Question
Title: Pro Mini 5v with Adafruit motor shield v1 power sharing problems
I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.

Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.

I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

1. Uses 8 AA cells to power the motor shield on EXT-PWR input.
2. From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
3. From Pro Mini, VCC connected to +5v on motor shield.
4. One micro servo having range sensor getting its current from motor shield.
5. Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.

At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.

Thanks

Qazi

# Answer
> 1 votes
I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.

# Answer
> 1 votes
Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.

---
Tags: power, arduino-pro-mini, arduino-motor-shield, adafruit
---


# Question
Title: LCD Display Flicker When Arduino Main Board Supply Voltage to GSM Shield Board
I have a 16x2 LCD display that is connected to an Arduino microcontroller. It is working fine but the LCD display flickers when I connect the Vin and GND of the main board to its slave GSM Shield.

I used main board Vin and GND to power up the GSM Shield so I only have one power supply. I was able to power up GSM Shield by adding jumper to Vin and GSM +Vin.

In additional question, is there any other way to power up Arduino GSM Shield without connecting it to another power source to still keep having only one plug for power?

# Answer
> 1 votes
This sounds like either your GSM Shield is drawing to much power (from time to time) and thus your Vin drops resulting in flickering or your GSM Shield induces ripple on top of your Vin.

To debug this I would recommed to have a look at Vin with an oscilloscope and see how stable Vin is. Additionally some capacitors between Vin and GND (100nF and 10-100µF) and a ferrit between Vin and the GSM Shields Vin might help.

---
Tags: lcd, gsm
---


# Question
Title: Receiving partial messages when using VirtualWire and ServoTimer2
I'm writing a project where an Arduino board that is connected to a servo engine receives commands from another Arduino. The possible commands are:

1. Move 10 degrees
2. Reset position
3. Sweep until you're told to stop

My problem is with the sweep-mode, when I get the sweep command, I get into a while loop, that first checks for a sweep-terminator and then sweeps.

```
} else if (message == sweep) {
  Serial.println("sweep");
  while (msg1 != sweep_term) {
    // set the direction for the servo to move
    if (val == 750){
      val = 2250;
    } else {
      val = 750;
    }

    // move the servo
    myservo.write(val);
    // wait for the servo to move
    delay(15);

    // wait for a message
    if (vw_get_message(buf1, &buflen1)) {
      buf1[buflen1] = '\0';
      msg1 = (char*)buf1;
      memset(buf1,'0',VW_MAX_MESSAGE_LEN);
      Serial.print(buflen1);
      Serial.print(" [sweep] Got: ");
      Serial.println(msg1);
    }
  }
}

```

For some reason, when I'm in this loop I don't get the sweep terminator message, or I get a part of it. I suspect that the servo is responsible for this, since when I run the same program without `myservo.write()`s I *do* receive those terminators.

# Answer
> 0 votes
I simply connected the servo to an external power 5V power source, and everything works perfectly fine. It seems like the servo's resistance was too much for the RF receiver to be able to work as well.

# Answer
> 1 votes
If `msg1` is of type `char*` (as is implied by the cast in `msg1 = (char*)buf1;`), then it seems to me that that statement will copy the address of `buf1` to `msg1`. Then, when you fill `buf1` with ascii zeroes (ie, characters `'0'`) `msg1` ends up being a string of ascii zeroes.

On the other hand, if `msg1` is of type `String` (to go along with your comment about `buf1` being of type `String`) the cast should be unnecessary.

Note, if you don't give the source for the `vw_get_message()` routine and the declarations for all of the constants and variables used in the code extract, it's unlikely anyone can definitively answer your question.

Note, the `while` test, `msg1 != sweep_term`, may not be well-defined on entry to the while loop. Or, if `msg1` is left over from a previous use, you won't enter the loop at all. Consider writing the loop in the form `do { ... } while (msg1 != sweep_term);` instead.

Note, if (as said in a comment) `buf1` is of type `String`, then the statement `memset(buf1,'0',VW_MAX_MESSAGE_LEN);` is a line of code I'd recommend against, because it treats `buf1` as a simple array rather than as an object. (In this case it *should* make no difference, but it requires some research to be sure of that. \[,,,,\])

---
Tags: servo, rf, virtualwire
---


title: Usefulness of measuring 0v using ADC

text:
# Question
Title: Usefulness of measuring 0v using ADC
I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly **0V (GND)**.

* What would be the use of measuring 0V?
* Would it ever result in a reading other than `0`? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.

AVR126 seems to give a hint:

> configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).

# Answer
That quote you mention says it all really. It's purpose is to discharge the Sample And Hold capacitor.

That capacitor is used (as I'm sure you are aware) to store the incoming voltage while it's being sampled by the ADC. The ADC operated in two main phases:

1. Acquisition
2. Sampling

During acquisition the capacitor is connected to the incoming voltage. During sampling it is disconnected from the incoming voltage and the voltage it stores is read into the internal registers.

It takes a certain amount of time for the voltage in the capacitor to equal that of the incoming voltage. If you try reading at higher speeds then what voltage was in the capacitor from the previous sample can affect the new reading. However, if you do each sample always from a known voltage in the capacitor (0V) then you get much more stable results.

Another good use for it is when using the ADC as a Charge Time Measurement Unit. This is the proper way of performing capacitative sensing. You apply a constant (tiny) current to an external capacitor (the sensing plates) for a specific period of time. When that time is up you disconnect the constant current source and measure the voltage that has developed across that capacitance. The capacitances and currents are small, and if there is a charge in your S&H capacitor at the time you do the sampling that will be back-fed into the touch sensor capacitative plates changing the voltage. By ensuring that the S&H capacitor is at 0V before you sample the plates you won't be adversely affecting the voltage on the plates with successive readings (well, you will, but it will be consistently in the same way every time so it won't affect your overall results).
> 4 votes

# Answer
> Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

The document actually says:

> The ADC can prescale the system clock to provide an ADC clock that is between 50kHz and 200kHz **to get maximum resolution**.

(My emphasis)

It goes on to say:

> If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200kHz. At 1MHz it is possible to achieve eight bits of resolution maximum.

I did some testing on this page with different prescalers. The results showed that reasonable results could be obtained even with a 1 MHz ADC clock:

```
Prescaler 2

Analog port = 0, average result = 1023
Analog port = 1, average result = 1023
Analog port = 2, average result = 1023
Analog port = 3, average result = 1022
Time taken = 26220

Prescaler 4

Analog port = 0, average result = 673
Analog port = 1, average result = 718
Analog port = 2, average result = 512
Analog port = 3, average result = 193
Time taken = 32780

Prescaler 8

Analog port = 0, average result = 842
Analog port = 1, average result = 677
Analog port = 2, average result = 509
Analog port = 3, average result = 34
Time taken = 46040

Prescaler 16

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 509
Analog port = 3, average result = 0
Time taken = 73164

Prescaler 32

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 128040

Prescaler 64

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 240972

Prescaler 128

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 448108

```

The four test voltages were, and their results *should have* been:

* 5V (should return 1023)
* 3.3V (should return 674)
* 2.5V (should return 511)
* 0V (should return 0)

---

The tests were done in rapid succession, no allowing for the ADC to recharge or anything:

```
 unsigned long startTime = micros ();
  for (int i = 0; i < ITERATIONS; i++)
    {
    for (int whichPort = lowPort; whichPort <= highPort; whichPort++)
       {
       int result = analogRead (whichPort);
       totals [whichPort - lowPort] += result;
       }
    }
  unsigned long endTime = micros ();

```
> 2 votes

---
Tags: atmega328, analogread, adc
---


# Question
Title: Sending A String from a Website to Arduino
I'm quite new to Arduino and have looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield, but haven't seen one featuring the sending of data from a website/server to an Arduino. I'm attempting to use a JavaScript then PHP script to send a string variable to the Arduino, which would then of course run its code at this point. Is this possible if I have a Wifi Shield and the Arduino's IP address?

# Answer
On the yun, this functionality is built-in via the bridge. Here's an example.

Via the shield, you now end up writing your own webserver and responding appropriately.

I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.
> 1 votes

# Answer
If you really want the Arduino to be a **web server** (that is, you connect to it with your web browser) then I made a library a little while back to simplify processing the get/post/pathname/cookie arguments.

See Tiny web server for Arduino or similar.

Example code (that comes with the library) turns on various LEDs (presumably connected to pins on the Arduino) upon getting a "get" request like this:

```
http://10.0.0.241/?on=4&off=5

```

That would turn on pin 4 and turn off pin 5. Obviously you change the IP address to suit your network, and use a suitable MAC address.

```
// Tiny web server demo
// Author: Nick Gammon
// Date:  20 July 2015

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

const int LOW_PIN = 3;
const int HIGH_PIN = 5;

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0x90, 0xA2, 0xDA, 0x00, 0x2D, 0xA1 };

// The IP address will be dependent on your local network:
byte ip[] = { 10, 0, 0, 241 };

// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };

// the subnet mask
byte subnet[] = { 255, 255, 255, 0 };

// Initialize the Ethernet server library
EthernetServer server(80);

// derive an instance of the HTTPserver class with custom handlers
class myServerClass : public HTTPserver
  {
  virtual void processPostType        (const char * key, const byte flags);
  virtual void processGetArgument     (const char * key, const char * value, const byte flags);
  };  // end of myServerClass

myServerClass myServer;

// -----------------------------------------------
//  User handlers
// -----------------------------------------------

void myServerClass::processPostType (const char * key, const byte flags)
  {
  println(F("HTTP/1.1 200 OK"));
  println(F("Content-Type: text/html\n"
            "Connection: close\n"
            "Server: HTTPserver/1.0.0 (Arduino)"));
  println();   // end of headers
  println (F("<!DOCTYPE html>\n"
             "<html>\n"
             "<head>\n"
             "<title>Arduino test</title>\n"
             "</head>\n"
             "<body>\n"));

  } // end of processPostType

void myServerClass::processGetArgument (const char * key, const char * value, const byte flags)
  {

  int which = atoi (value);
  if (which >= LOW_PIN && which <= HIGH_PIN)
    {
    if (strcmp (key, "on") == 0)
      {
      digitalWrite (which, HIGH);
      print (F("<p>Turning on pin "));
      println (which);
      }
    else  if (strcmp (key, "off") == 0)
      {
      digitalWrite (which, LOW);
      print (F("<p>Turning OFF pin "));
      println (which);
      }
    else
      {
      print (F("<p><b>Bad action: "));
      fixHTML (value);
      println (F("</b>"));
      }
    }
  else
    {
    print (F("<p><b>Bad pin number: "));
    fixHTML (value);
    println (F("</b>"));
    }

  }  // end of processGetArgument

// -----------------------------------------------
//  End of user handlers
// -----------------------------------------------

void setup ()
  {
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);

  for (int i = LOW_PIN; i <= HIGH_PIN; i++)
    pinMode (i, OUTPUT);
  }  // end of setup

void loop ()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (!client)
    {
    // do other processing here
    return;
    }

  myServer.begin (&client);
  while (client.connected() && !myServer.done)
    {
    while (client.available () > 0 && !myServer.done)
      myServer.processIncomingByte (client.read ());

    // do other stuff here

    }  // end of while client connected

  client.println(F("<hr>OK, done."));

  client.println (F("</body>\n"
                    "</html>"));

  // give the web browser time to receive the data
  delay(1);
  // close the connection:
  client.stop();

  }  // end of loop

```

Library source on GitHub at nickgammon/HTTPserver.

The library is designed to allow you to receive cookies, POST data, pathnames (on the URL) and GET parameters.
> 1 votes

---
Tags: shields, wifi, web-server
---


# Question
Title: Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi
I'd like to assemble a device that could accomplish the following:

* Connect to my home wifi (WPA2-Personal)
* Connect to my home PC with via Ethernet cable
* Able to send WoL signal to the PC when getting a signal over wireless connection
* The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).

I have no background in Arduino or Electronics in general. I program well though and learn fast.

Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?

# Answer
**The Arduino might not be a choice for you.** The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).

So, **if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi**(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.

You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.
> 3 votes

# Answer
The Raspberry Pi is definitely the easiest way to do this, however it will use more power.

You can do it within your budget by using Arduino clone hardware from places like AliExpress.

If you don't mind the extra effort, it certainly can be done using the Arduino and a wireless and ethernet shield.

A WiFi shield is around $17, an ethernet shield is less than $6 and an Arduino Uno clone is around $3. Make sure you can combine these shields (I haven't checked). There's also a combined Linux, Ethernet + Wifi Yun shield for around $30.
> 2 votes

# Answer
I doubt if you will do it in that price range. Buying genuine products (as opposed to clones from eBay) you would be paying something like:

* Arduino Uno: $US 25
* WiFi shield: $US 40
* Ethernet shield: $US 45

Prices from Adafruit \- other suppliers would have the same or similar for similar prices.

I see there is a Arduino Ethernet which combines the Uno and the Ethernet shield for $US 65.

> The whole set up needs to be less than 45USD, desirably much less ...

Maybe someone else can suggest a cheaper option, but I think you will be pushing it here.
> 1 votes

---
Tags: wifi, ethernet
---


# Question
Title: Is it possible to accept multiple web requests at once?
I have an Arduino with ethernet shield and there are 8 different URLs that can be called to perform different actions.

The program loads and runs as expected for the most part, but, if it is busy doing an action, it won't accept the next one until the current action has finished.

Basically, the code's main loop listens for a client connection, then has a bunch of ifs that look in the URL that was called (for a query string) and then process the command.

I have looked at a few answers on here, but none deal with listening to HTTP requests. One recommended a library, but, I couldn't quickly get it to compile, and the other answer recommended a state machine - I do like this approach, however, I haven't had time to implement and it doesn't "feel" right as the listening for a HTTP request works on a `if(client)` basis.

I was wondering if anyone has done this before and/or has any advice?

# Answer
> 2 votes
It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.

BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the Timer1 library.

Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.

---
Tags: web-server, threads
---


title: Measuring KWh connecting to the mains

text:
# Question
Title: Measuring KWh connecting to the mains
I need to measure KWh of the mains, connecting something like a sensor to the mains and reading its value into analog. I already know to measure KWh from a KWh meter but I need to make my own.

# Answer
> 2 votes
If i understand your question correctly, what you want to do is measure the current consumed from the mains by whatever load is connected to it (Fan, AC, computer etc).

What you need is basically a current sensor, have a look at https://www.sparkfun.com/products/8883 and https://www.sparkfun.com/products/11005

**Please understand that you are playing with the mains and unless you take the required precautions, you can get seriously injured**

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


title: Will 12.6v really damage my arduino?

text:
# Question
Title: Will 12.6v really damage my arduino?
I'm using a 12v fan and 12v LED modules in my project, so I need about 400mA by their combined specs. I have a 12.6v dc regulated power source that can give ~700mA I wish to use, and since it has a rather small form factor I would also like to power my Arduino Diecimila with it. I'm using PWM from pins 10 and 6 to go through N-channel MOSFETs in order to control both the LEDs and the fan. Anyway, in the Arduino Diecimila board page it says the recommended voltages are between 7-12v, and beyond that it can handle 6-20v, but it might cause the voltage regulator to heat too much, which might damage the board. So, my question is that: will 12.6v really damage my board, or is it within some margin of error? The actual voltage I got when I checked my power supply was 12.55V. Can I maybe just dial it down a bit somehow?

Thanks in advance,

UriSh.

# Answer
As you have already noticed, it may cause the 5V regulator to get hotter than would be normally considered reasonable. However, how hot depends entirely on how much current your board is drawing (not including the 12V devices)- the more current you draw the hotter it will get.

Even at 12V it can get uncomfortably hot.

For running off voltages greater than about 9V I usually recommend using an external 5V switching regulator. These can be easily and cheaply obtained under the name "UBEC" (Universal Battery Elimination Circuit) and are used extensively in the model aircraft arena. They don't get hot, can handle large currents, and don't waste power like the on-board linear regulator does.

So you'd connect that to your 12.6V supply, then the 5V output of the UBEC (make sure you get a 5V one) would go straight to the 5V pin of the Arduino, and you wouldn't connect the barrel jack or Vin to anything.

You can also pick up cheap switching regulators on eBay - some are adjustable, so you'd want to make sure you adjust it to 5V first before connecting the Arduino, or if you can adjust it to around 7V then you could power the Arduino through the barrel jack (or Vin) with it and avoid too much heat from the on-board linear regulator.
> 3 votes

---
Tags: power, voltage-protection
---


title: NODEMCU vs AT for esp8266

text:
# Question
Title: NODEMCU vs AT for esp8266
I have recently started working on esp8266 wifi module and arduino uno. I am a little confused.

I have created a small Web page with esp8266 AT commands. Now I want use it for receiving data such as changes on the Arduino inputs.

I have seen many similar implementations using jQuery for that purpose, but I don't know where to place that jQuery file.

Furthermore, is it possible to use NODEMCU firmware and still toggle arduino pins and transmit data to esp8266?

I want to use Arduino for:

* reading voltage levels
* publish the values read to the Web page
* toggle a relay when a button on the Web page is pressed.

Please kindly help me out or point me in the right direction to search

# Answer
> 4 votes
This is quite a huge topic to cover in one answer, but I will do my best.

The NodeMCU can be used in three distinctly different ways. First is the *AT* mode, where you have installed the *AT* firmware. In this mode the NodeMCU is purely a slave device to the Arduino. Once you have got the Arduino to configure the NodeMCU in the right way to receive data on a socket it will send that data back to the Arduino verbatim through the serial port with special tags added (indicating what the data is, and which socket it arrived on, etc). It is then up to you to receive that data, interpret it in whatever way you desire (as a HTTP GET request most likely) and craft the correct response (if any) and send it to the NodeMCU to send back (again using the *AT* commands).

What you send through the socket is entirely up to you. By the sounds of things you will be making a simple GET request from a web browser to perform an operation, and maybe respond with some data to display in the web page. That can be easy, or it can be hard - it's as hard as you want to make it. The simplest way is to rely on an external web server to serve the main content and structure of the page, then use jQuery or Prototype to make an AJAX call to your NodeMCU and receive back any data there may be. In this case everything will be on your external web server except the single (or few) URL(s) that perform operations and return data. That includes the jQuery (which is just Javascript, it's loaded from your web server into the browser and executed), any code for buttons, images, HTML, everything (on the web server, that is).

The other two ways the NodeMCU can operate are both very different to that. They differ mainly in the language that is used with them. You can use the NodeMCU with its own LUA language to get it to do almost anything you want. That includes receiving the HTTP GET request and serving the data for it, all without the help of the Arduino. In fact, doing that, there is little need for the Arduino any more - the NodeMCU has an analog input and multiple digital IO lines - it also has SPI available for interfacing with external ADC chips if you want more than one analog input. So you can have everything internal to the NodeMCU without needing the Arduino at all. If you do want to keep the Arduino then you can interface to it through the serial port (as you would in *AT* mode) but using your own custom protocol in whatever way you see fit.

The third way is to program the NodeMCU as if it were itself an Arduino. There is an ESP8266 core for the Arduino IDE (and for UECIDE Beta as well) which allows you to program the NodeMCU in the same language and with a similar API, as the Arduino. This even more removes the need for the Arduino. You can get the Arduino core from Github here: https://github.com/esp8266/Arduino

Incidentally, the Xtensa core in the ESP8266 is considerably more powerful than your typical Arduino, being 32-bit, having its own DSP, and with much more RAM and Flash memory. It kind of makes the Arduino redundant.

---
Tags: arduino-uno, wifi, web-server, esp8266
---


# Question
Title: MPU6050 or GY521/HMC5883 chips are burnt for no reason
I been trying to interface MPU6050 and HMC5883 with an Arduino Pro Mini/Nano. I²C scanner works just fine and identifies the device with no issues. I let the I²C scanner run like for 5 minutes and I see fumes coming out of the chips and sometimes the Arduino itself is burnt. I tried pull up resistors 2.2k, 7k without any luck. Has anyone got any inputs to this issue. Really frustrating to spend a weekend on this :(

To rule out the possibility of 5V supply causing the burn out I tried 3.3V from Nano and made promini 3.3V from 5V. Please see the pictures below.

Arduino Nano 3.3v was used to power up the I²C.

.

.

Pro Mini jumper was desoldered from 5V to 3.3V to see if the I²C chips are saved from being burnt. In both these setup voltage accross the I²C chip was measured and it was 3.3V.

Still no luck!

If you guys are to make the same circuit how would you do it and where would you get the components from? I must be doing something wrong and hope we together can figure it out.

Components are bought from eBay and the links are here. GY521 = goo.gl/Y4aDph HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI PROMINI = goo.gl/79PVOM

**This is some background of why this issue resolution is so important to me:** Just give you a backgroud of why I am doing this: I am building a quadcopter myself. Infact built one using GY80, but the module was expensive also it eventually got burnt out for the same reason mentioned above. Here is the first successful test flight of my first quadcopter goo.gl/rn6xWG (add https:// since I am rookie there is limitation on how many links I can post). If I can make the same thing work using GY521 and HMC5883 it would be awesome and cheaper.

Update on 08/11 @12:45 PM CST I think it is because of the Pro Mini, I²C chips are getting fried. When using Nano, I think it is because of the voltage level difference between the SDA/SCL lines causing the problem. With Pro Mini tripped for 3.3V, I was not able to see any serial data from the chip too. To end all these I placed an order for 3.3V 8 MHz Pro Mini from amazon goo.gl/FjgTGj Let see how that goes.

# Answer
Fixed the issue with a dedicated 3.3V power supply. I2C scanner is running for 30 minutes with no issues so far.
> 1 votes

---
Tags: arduino-pro-mini
---


# Question
Title: Arduino digitalWrite 1 or 0 instead of HIGH or LOW
Is it ok to use

```
digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH)

```

or

```
digitalWrite(pin, 0) instead of digitalWrite(pin, LOW)

```

I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way

```
digitalWrite(pin, EEPROM.read(1))

```

# Answer
Yes, that is fine. LOW is 0 and HIGH is 1. `digitalWrite()` sets the output to off if it receives a 0 and on if it receives anything of 1 or more.

That means that these are all equivalent:

```
digitalWrite(pin, HIGH);
digitalWrite(pin, 1);
digitalWrite(pin, 69);

```

It's especially useful when you are examining a variable for, say, a certain bit being set:

```
digitalWrite(pin, bytevar & 0x80);

```

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.
> 8 votes

# Answer
From the arduino source code:

```
#define HIGH 0x1
#define LOW  0x0

```

So `HIGH` is **exactly** the same as `1`. And `LOW` exactly the same as `0`.
> 2 votes

# Answer
When you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0 using #define.

You may heard about **Preprocessor, Compiler, and Linker**. When you build the project, preprocessor do its job before the code is compiled. What the preprocessor does is basically converting defined words into corresponding value.

For example when you write a syntax like:

```
digitalWrite(1, HIGH);

```

When you build your project, the preprocessor converts the above like into this:

```
digitalWrite(1, 1);

```

Then the code is compiled. Therefore, there is no difference between HIGH and 1. So, if the result of `EEPROM.read(1)` is either 0 or 1, there should be no problem.
> 0 votes

---
Tags: eeprom
---


# Question
Title: Toggle Button For LED Strip not executing properly
I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.

```
#include "LPD8806.h"
#include "SPI.h" // Comment out this line if using Trinket or Gemma
#ifdef __AVR_ATtiny85__
#include <avr/power.h>
#endif

int nLEDs = 160;

// Chose 2 pins for output; can be any valid output pins:
int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);

int inPin = 4;
boolean lastState = LOW;//storage for last button state

void setup(){
   pinMode(inPin, INPUT);//this time we will set the pin as INPUT
   Serial.begin(9600);//initialize Serial connection
   #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
   clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
   #endif

   strip.begin();
   // Update the strip, to start they are all 'off'
   strip.show();

 }

void loop(){

   if (digitalRead(inPin) == HIGH && lastState == LOW){//if button has just
   been pressed
   // Start up the LED strip
        theaterChase(strip.Color(127, 127, 127), 50); // White
        delay(100);
    } else if(digitalRead(inPin) == LOW && lastState == HIGH){
        digitalWrite(dataPin, LOW);
        digitalWrite(clockPin, LOW);
    }
    lastState = digitalRead(inPin);
    }

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
         for (int j=0; j<10; j++) {  //do 10 cycles of chasing
              for (int q=0; q < 3; q++) {
                   for (int i=0; i < strip.numPixels(); i=i+3) {
                      strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (int i=0; i < strip.numPixels(); i=i+3) {
      strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
  }

```

# Answer
If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:

There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:

There are other possible techniques as discussed on this page.

One is to change:

```
   pinMode(inPin, INPUT);//this time we will set the pin as INPUT

```

to:

```
   pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT

```

Then wire the switch to **ground**, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.
> 1 votes

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


# Question
Title: Delay workaround needed for RTC and LCD-shield buttons
Following configuration:

* Arduino UNO R3
* Real Time Clock DS1307RTC
* LCD1602 Shield with buttons
* Photo resistor
* DHT11 (Temp & Humidity Sensor)

I need the function delay(1000) to display the seconds properly from the RTC to the LCD. But, that way I always have to keep the buttons pressed for up to 1 second until they react.

How can I workaround or solve this problem?

Idea 1: Multitasking would come in handy here :-) pseudocode:

```
task 1: listen for LCD buttons
task 2: display seconds with a delay of 1000ms

```

But there isn’t a way Arduino could multitask, isn’t it?

Idea 2: As far as I saw in the header files for the RTC, the smallest readable unit is seconds. Otherwise I could have used something like a millisecond reader in a while condition to listen for the buttons; pseudocode:

```
while (RTC-millisecond < 1000ms) {
    // listen for buttons
    // so a second passes, which gives the RTC time to display the seconds values
}

```

-

**EDIT**

updated code, thanks to @NickGammon and Gerben:

```
#include <LiquidCrystal.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <DHT.h>

// initialize the library with the numbers of the interface pins
//                RS  E  D4 D5 D6 D7 (maybe wrong order)
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// pins on which the sensor is connected
#define DHTPIN A1
#define PHOTOPIN A2

// initialize DHT sensor
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
//#define btnRIGHT  0
//#define btnUP     1
//#define btnDOWN   2
//#define btnLEFT   3
//#define btnSELECT 4
//#define btnNONE   5

// FSM
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;
const long interval = 3000;

// prototypes
void print2digits(int number);
int read_LCD_buttons();

void setup() {
  // open a serial connection to display values on PC
  Serial.begin(9600);

  // set up the number of columns and rows on the LCD
  lcd.begin(16, 2);

  // start DHT sensor
  dht.begin();
}

void loop() {
  // set variable from struct tmElements_t
  tmElements_t tm;

/********* Reading from sensors *********/
  /*** DHT sensor ***/
  // Reading temp or RH takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float humid = dht.readHumidity();
  float tempC = dht.readTemperature();
  // Check if any reads failed and exit early (to try again).
  if (isnan(humid) || isnan(tempC)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DHT reading failed!");
    Serial.println("DHT reading failed!");
    return;
  }
  // Compute heat index in Celsius (isFahreheit = false)
  float hiC = dht.computeHeatIndex(tempC, humid, false);

  /*** Photo resistor ***/
  int lightReading = analogRead(PHOTOPIN);

/********* Print to PC over serial connection *********/
  // ...

/********* Print values to LCD *********/
  /* --- first line on LCD --- */
  /*** RTC ***/
  // set the cursor to LCD column 4, line 0 to center the clock
  lcd.setCursor(4, 0);

  // starts RTC reading and checks if it's working
  if (RTC.read(tm)) {
    static byte oldSecond = 60; // 60, because there is no 60'th second in a clock
    // display only if time changes
    if (tm.Second != oldSecond) {
      oldSecond = tm.Second;
      print2digits(tm.Hour);
      lcd.print(':');
      print2digits(tm.Minute);
      lcd.print(':');
      print2digits(tm.Second);
    }
  }
  else {
    lcd.clear();
    lcd.setCursor(0, 0);
    if (RTC.chipPresent()) {
      lcd.print("Please run SetTime function");
    } else {
      lcd.print("DS1307 read error!");
    }
    delay(9000);
  }

  /* --- second line on LCD according to button --- */
  lcd_key = ((lcd_key + read_LCD_buttons()) %3);  // call button function, modulo 3 to cycle through
    /** // Test buttons:
    lcd.setCursor(1, 1);
    lcd.print("lcd var:");
    lcd.print(lcd_key); */

  unsigned long currentMillis = millis(); // FSM used for displaying DHT and photo values without flikering

  switch (lcd_key) {
    case 0:
      /*** Weekday and Date ***/
      // display only if day changed
      static byte oldDay = 99;
      if (tm.Day != oldDay) {
        oldDay = tm.Day;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(0, 1);
        //lcd.print(dayShortStr((weekday() + 1) % 7 )); // (day+1)%7 calculation for Swiss layout
        lcd.print(tm.Wday); // TEST
        lcd.print(weekday()); // TEST
        lcd.print(", ");
        print2digits(tm.Day);
        lcd.print('.');
        print2digits(tm.Month);
        lcd.print('.');
        lcd.print(tmYearToCalendar(tm.Year));
      }
      break;

    case 1:
      /*** DHT Sensor ***/
      if (currentMillis - previousMillis1 >= interval) {
        previousMillis1 = currentMillis;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(1, 1);
        lcd.print(hiC);
        lcd.print("*C ");
        lcd.setCursor(10, 1);
        lcd.print(humid);
        lcd.setCursor(12, 1);
        lcd.print("%RH ");
      }
      break;

    case 2:
      /*** Photo resistor ***/
      if (currentMillis - previousMillis2 >= interval) {
        previousMillis2 = currentMillis;
        lcd.setCursor(0, 1);
        lcd.print("                "); // 16 spaces to clear second line before printing
        lcd.setCursor(0, 1);
        lcd.print("Light ");
        lcd.setCursor(6, 1);
        lcd.print(lightReading);
      }
      break;
  }
}

// used to print 2 digits in the time values
void print2digits(int number) {
  if (number >= 0 && number < 10) {
    lcd.print('0');
  }
  lcd.print(number);
}

// read the buttons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  //if (adc_key_in > 1000) return btnNONE; // 1st option since it will be the most likely result (speed reasons)
  //if (adc_key_in < 50)   return btnRIGHT;
  //if (adc_key_in < 195)  return btnUP; // replaced by below one
  if (adc_key_in < 195)  return 1; // my button up !
  //if (adc_key_in < 380)  return btnDOWN;
  //if (adc_key_in < 555)  return btnLEFT;
  //if (adc_key_in < 790)  return btnSELECT;
  //return btnNONE;  // when all others fail, return this...
  return 0;
}

```

# Answer
```
  // clean up screen before printing a new reply
  lcd.clear();

  /* --- first line on LCD --- */
  /*** RTC ***/
  // set the cursor to LCD column 4, line 0 to center the clock
  lcd.setCursor(4, 0);

```

Straight away, that will cause flicker, right? For a few milliseconds the screen will go blank, and then get gradually redrawn. Why not omit the clear? You could put it in if you are changing display types (eg. from date to temperature) but you don't need to clear the screen every time. So:

* Don't call `delay()`
* Don't clear the screen unless changing to displaying a different type of thing
* Only update the display at all if the new number (or time, or temperature, etc.) is **different** from what you just displayed.
* Just do the `setCursor()` to position the cursor and **overwrite** the information there previously.
* Preferably follow by a space or two in case a large number is replaced by a smaller one.

---

Side-benefit: Since you have removed the delay, your project will now be much more responsive to key presses. Win win!

---

## References

---

> I am not quite sure how to do it

```
 if (RTC.read(tm))
  {
  static byte oldSecond = 99;
  // display if time changes
  if (tm.Second != oldSecond)
    {
    oldSecond = tm.Second;
    print2digits(tm.Hour);
    lcd.print(':');
    print2digits(tm.Minute);
    lcd.print(':');
    print2digits(tm.Second);
    }
  }

```

Similarly further down where you display the date / sensor.
> 1 votes

# Answer
You need to learn a different way of programming.

Two things you need to understand:

1. Non-blocking code. Read and understand the BlinkWithoutDelay example sketch (in the Arduino IDE's File -\> Examples menu)
2. Finite State Machines. Stop thinking purely linear, and start thinking about the different states your program can be in at any one time.

Once you have those cracked you'll be an Elite Arduino Programmer (EAP™).
> 1 votes

---
Tags: lcd, button, rtc
---


# Question
Title: Arduino LED lighting up when signal is reading low on multimeter
My code is designed to play a tone when ever pin 3 is high on my Arduino. When I am examine the pins voltage with a multimeter it is always reading below 1 volt. When I examined the voltage off of a osiliscope it is reading the voltage pretty steady at 0.2 to 0.3.

**My multimeter reads at 0.26**

:

**My code is:**

```
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
  // put your main code here, to run repeatedly:
int input = digitalRead(3);
Serial.println(input);
if(input == 1){
  tone(A5,4000);
  }
}

```

**My board looks like:**  **The bottom of the board looks like:**

# Answer
You left pin 3 floating. The multimeter will lower the voltage, resulting the the led lighting. Try enabling the pull-up resistor in pin 3 by adding `pinMode(3, INPUT_PULLUP)`.

PS you might want to add a resistor in series with that led, or it will burn out and/or damage pin 3 on the arduino.
> 1 votes

---
Tags: sketch, arduino-pro-mini, signal-processing, prototype
---


title: Arduino Uno not Detecting on Laptop

text:
# Question
Title: Arduino Uno not Detecting on Laptop
I have an Arduino Uno. The story is I installed Arduino IDE and Drivers before even buying an Arduino Board. I used it a little and when I bought and connected an arduino board, I was unable to make it detect. I smacked a little usimg google and was able to somehow Fix this. but again another day, It worked a little and started creatimg problems. now its not detecting. Please suggest me a way To make it work... Should I format my windows 7 and Reinstall all the drivers as per rules?

# Answer
> 1 votes
under the IDE make sure you have set the correct board and comm port. go to tools\>\>board then choose your board then tools\>\>Comm to choose the correct comm port.

is the IDE saying anything about having problems connecting to the board?

and no re-installing all drivers should not be necessary.

---
Tags: arduino-uno
---


title: How do I compile the Marlin firmware?

text:
# Question
Title: How do I compile the Marlin firmware?
I have a folder of mostly .h and .cpp files for the Marlin firmware (3D Printing) from here.

How do I compile that so I can upload it to my Arduino Mega with Ramps?

# Answer
You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.

http://solidutopia.com/marlin-firmware-user-guide-basic/ \- heres a guide for Marlin.

the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.
> 2 votes

---
Tags: arduino-mega, compile
---


title: Tone() working on all digital pins?

text:
# Question
Title: Tone() working on all digital pins?
Looking at my Arduino Uno board, it appears the digital PWM pins are #11, #10, #9, #6, #5 and #3.

When playing around with the Theremin, it seems that the `Tone()` message works on all pins regardless of whether they are marked PWM or not?

Can anyone explain what is happening or how this is possible?

# Answer
The Tone library doesn't use the PWM mode timer functions on the atmega, instead it uses an interrupt routine to toggle the pins. You can find the source code for Tone libary here for reference:

https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/
> 2 votes

---
Tags: arduino-uno, pwm
---


# Question
Title: Will the Uno bootloader work in the Duemilanove?
I had an old duemilanove lying around (Which was not working because i accidentially busted the atmega) and I recently bought some atmegas pre-flashed with the UNO bootloader. So I tried to put one of those in it, and it seems to work fine except that I have to select the UNO board in the arduino IDE.

My question is: Is there anything problematic to be aware of when using the UNO bootloader in an duemilanove?

# Answer
> 3 votes
So I researched it a bit, and there does not seem to be any problems with running the UNO bootloader on a Duemilanove board.

The biggest difference between the two seems to be the USB interface:

**USB interface**

Duemilanove uses FTDI, UNO uses another microcontroller (ATmega8u2).

Since the USB to serial is transparent for me as an end user for the most parts, it doesn't really matter to me.

**Leaner bootloader**

The UNO bootloader is smaller than the duemilanove.

---
Tags: arduino-uno, bootloader, arduino-duemilanove
---


# Question
Title: Need help understanding how RF communication works with 2 arduinos
I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function.

```
switch (keypad())
//switch used to specify which button
     {
      case 0:
        Serial.print("Key A Pressed");
        Serial.print(keypad());
        messageToSend = 0;
      break;
        case 1:
        Serial.print("Key B Pressed");
        Serial.print(keypad());
        messageToSend = 1;
      break;
        case 2:
        Serial.print("Key C Pressed");
        Serial.print(keypad());
        messageToSend = 2;
      break;
       }

```

My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

1. What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?
2. My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?
3. Are RF units very different? Is this one particularly difficult?
4. If I just want to send with one receive with the other shouldn't this simplify the code?
5. What are pipes? How many can I open?
6. If I have 3 or more of these what changes will I need to make to the code?

Thanks!

# Answer
Many questions so broad answers, but hopefully informative for your research

1. > What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

It depends broadly on what you use. If you use an ethernet peripheral then the communications will be entire ethernet packets with whatever protocol stack you have above it in payload. For simple RF communication modules it may be as simple as a serial stream delivered 8 bits at a time. The simplest rf (buzzer-style) would simply interrupt (or drive a pin high) when the transmitter is sending a signal.

In Your case the transmitter uses an addressed protocol with a payload packet of between 1 and 25 Bytes of data. This means that you will need code to read and store the necessary payload, maintain configuration data and keep track of addresses of the other systems to message. You also need to poll (or handle interrupts from) the rf module to make sure there aren't messages from the transmit node.

How you convert the data is up to you, a string can be represented by a sequence of bytes and can be send and read as a string on the receivers end. Your rf module will deliver you data in 1-25 byte chunks, what you send in that chunk and how to encode it is entirely up to you.

On the low level,the way this module is configured, the MCU sends data into the rf ic using a serial protocol, the module incorporates a buffer to allow the MCU (slow - 8 bit) to send the data and not have to keep up with the 1Mbps throughput of the rf. On a physical level the signals of the chip look thus:

2. > My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Ping Pong is a game and not a well defined technical term. For precision you can define ping-pong as an `echo` where the transmitter effectively acknowledges the message by re-transmitting it back to you.

3. > Are RF units very different? Is this one particularly difficult?

RF units can be very different depending on what high level protocol they offer. This unit is somewhere half way between full blown wifi and simple and modulated RF communications. It gives you addressing and error correction as well as a robust communication scheme

This particular unit is made to be relatively "modern", it uses GFSK \- a frequency modulation scheme -to transmit and receive data to uniquely addressable nodes on a number of channels. At 2.4 GHz it is high throughput, legal. It is not the simplest toy.

In terms of simplicity, this module has a lot of examples and documentation, given that it has an arduino library it has a high likelihood of working and succeeding, but you will need to use more advanced microcontroller features to fully utilize the device (e.g. interrupts, DMA).

For other RF options there are lots of things to consider. Going up to wifi requires you to maintain a much more complex stack, meaning more processing power and code, if you want to offer TCP/IP services (say webserver) it is even more code but can be done on an 8 bit arduino. Going down to simpler protocol may win you less power and simpler code but a headache to expand.

4. > If I just want to send with one receive with the other shouldn't this simplify the code?

You will still need to implement both a receiving and a transmitting application so the work is still all there, it will simplify the higher level logic into separate application which is easier.

5. > What are pipes? How many can I open?

I see nothing about pipes from a cursory glance at the docs, perhaps you can illuminate more on what you are confused about?

In general pipes are a "hole" where an application (in the broadest sense) can stream data and it will be consumed by whoever is on the other end, a black hole of a serial data stream. You can implement a pipe as a high level software construct that will buffer and consume data from peripherals and wait to send it out the RF transmitter, it may also be implemented on a hardware level with discrete buffers and additional logic around the rf transmitter etc. As a conceptual element you can probably use a "pipe" concept for communication between the different devices in your code (e.g. move byte to pipe 1 for device 1, move byte to pipe 2 for device 2, let the "driver" handle order), this is a design paradigm that makes software development easier.

6. > If I have 3 or more of these what changes will I need to make to the code?

The rf module is fully capable of addressing up to 65,536 unique hosts, so the device is fully ready to talk to 3 of your hosts, however the software logic needs to track the addresses and other comms data about each host as well as process the data for them (if its different) in enough time.

If you are expecting this in advance, good design decisions early on (e.g. small API or library) will make this much easier on yourself to add features in the future.

***Final Thought***

If you need a simple echo, this may be a bit overkill for your system, however it is relatively powerful and may make it easier for you to program since you can work with "real-world" data units and send multiple byte packets easily.

I would **highly recommend** you read and understand the datasheet for the RF chip, be thankful that the nice library takes care of the messy details for you, but understanding how it works will certainly help you understand how to use it best.

An 8 bit Atmega may not be powerful enough to process and transmit 3 separate streams together (if they are identical its less difficult) if you require a constant high rate transmission or if you do a significant amount of processing on the arduino before sending you will feel the limitations of the chip and a 32 bit board may be worth looking at.
> 3 votes

# Answer
> My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

Start here, this is the absolutely best resource I could find. I use MIRF libary and there are send and receive examples. They are really, really simple. Get them working first.

> What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

*Technically*, you send between 1 and 32 *bytes* of information. However, the libraries (see examples above) will take care of the technicality and allow you to send nums, chars or strings.

> My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Not necessarily. Since does all the signal checking for you, and you know that your TX device is the only one sending, you can just reply with "data received".

Anyways, why are even concerned with this? Pinging and ponging have nothing to do with your task at hand.

> Are RF units very different? Is this one particularly difficult?

Yes, they are different in frequencies, protocols, power etc. No, this one isn't. It's an amazing, cheap and robust piece of Norwegian ingenuity.

> If I just want to send with one receive with the other shouldn't this simplify the code?

Simplify compared to what exactly? It will simplify the code compared to a two-way communication, obviously.

> What are pipes? How many can I open? As someone said before me, read the bloody manual, or a tutorial, or the data sheet, or something. The answer is 6.

Any unit can send on ONE pipe and receive on SIX pipes. Imagine having 6 phones on your table. You can simultaneously listen to all 6 phones but you can only TALK INTO ONE. You can choose which one to talk into to, at any point. Unless you have a lot of devices talking to each other (more than TWO), don't bother, forget the pipes.

> If I have 3 or more of these what changes will I need to make to the code?

Get two Arduinos talking to each other first. No one has succeeded at making anything work by getting ahead of themselves.

Now here is a video of two Arduinos talking. There's only one button but you can easily change it to a 20-button setup.

The code for sending:

```
#include <SPI.h>
#include <Mirf.h>
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <nRF24L01.h>

const int buttonPin = 2;
const int ledPin =  3;

// sends a string via the nRF24L01
void transmit(const char *string)
{
  byte c;

  for( int i=0 ; string[i]!=0x00 ; i++ )
  {
    c = string[i];
    Mirf.send(&c);
    while( Mirf.isSending() ) ;
  }
}

void setup() {
  //RADIO
  Serial.begin(9600);
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.payload = 1;
  Mirf.channel = 90;
  Mirf.config();
  Mirf.configRegister(RF_SETUP,0x06);
  Mirf.setTADDR((byte *)"serv1");

  //BUTTON AND LED
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  Serial.println("Sending ... ");
}

void loop() {
  int buttonState = digitalRead(buttonPin);
   if (buttonState == LOW) { //pressed
    digitalWrite(ledPin, HIGH);
    transmit("X");
  }
  else {
    digitalWrite(ledPin, LOW);
  }
}

```

The code for receiving:

```
#include <SPI.h>
#include <Mirf.h>
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <nRF24L01.h>

unsigned long lasttime;
unsigned long delaytime;
unsigned long time;
const int ledPin = 3;

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

  //RADIO
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = 1;
  Mirf.channel = 90;
  Mirf.config();
  Mirf.configRegister(RF_SETUP,0x06);

  //LED
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  Serial.println("Listening ... ");
}

void loop() {
  byte c;

  if( Mirf.dataReady() ) {
    Mirf.getData(&c);
    Serial.write(c);

    if (c == 'X') {
      digitalWrite(ledPin, HIGH);
    }
  } else {
      digitalWrite(ledPin, LOW);
  }
}

```
> 1 votes

---
Tags: nrf24l01+
---


# Question
Title: Reading RFID tags with Arduino IDE, not using Arduino
I am completely new to this technology, but I'm hoping to build a fairly simple program through the Arduino IDE that takes the serial numbers of RFID cards read through my ID-20LA Innovations RFID reader and send those serial numbers to an API endpoint all through the IDE (as in without using a physical Arduino).

Is this possible? Are there any tutorials out there that walk through a stripped down version of this? I don't know where to start code wise, and all tutorials I've found use physical Arduinos to accomplish this.

# Answer
> 1 votes
**Short answer:** NO

**Long Answer:**

Option 1: Use a USB RFID reader and create a basic processing/python/ app to read from the USB RFID reader and post it where ever you want it to

Option 2: Use the arduino to read from the ID-20LA and send the data via UART to your computer and then create a windows app using processing/python/ to send it to your API endpoint

Option 3: Use the arduino YUN to read from the ID-20LA and then create a basic python program to run on the YUN itself. Such that it will read data from the atmel microcontroller (on the YUN) and post it to your API endpoint. This is a much cleaner yet slightly more expensive way of doing this.

---
Tags: arduino-ide, rfid
---


# Question
Title: How do I use an Arduino as a USB output device for a 2x16 display?
Can I make a USB 2x16 display using an Arduino? I want to control a 2x16 character lcd display using USB, not com port/serial.

I need it to appear as a HID device when connected to the computer.

Please advise me.

Thanks

# Answer
HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it.

So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require
> 2 votes

---
Tags: display
---


title: Arduino User Input

text:
# Question
Title: Arduino User Input
Is it possible to accept input from an end user via terminal, or some other application?

I want to create a prototype for a friend, but he'd need to enter his wireless network and password to complete the setup of the project.

Any advice?

Thanks!

# Answer
> 1 votes
Since you have mentioned that all that you want your friend to do is enter the WiFi SSID and password, I am gonna assume that its where his interaction with the device ends.

In this case, I would recommend using the arduino YUN, it cant get simpler than that.

The YUN is capable of creating an AP network, your friend can connect to it and then go to the arduino home page and then connect to his WiFi.

**EDIT:**

Another option would be to use a matrix keypad and LCD screen and have your friend manually enter the details

---
Tags: arduino-uno, arduino-mega, arduino-ide
---


# Question
Title: MPU9150 (JEFF LIB) + FIFO_OVERFLOW INTERRUPT + SERIAL PRINT
Overflow enthusiasts!

I am trying to log accelerometer and gyro data using Serial.print. I have enabled the FIFO\_Overflow interrupt. Whenever I log data, the serial port freezes. I am suspecting an interrupt issue while I am using Serial.print. Is there any way to get continuous data for debugging purposes? I know that the Serial library can affect interrupts and wonder whether you guys could help me a little bit ?

```
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU9150.h"
#include "helper_3dmath.h"

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU9150 accelGyroMag;
#define LED_PIN 13
volatile boolean state_fifo_int = false;
uint16_t fifo_count;
uint8_t fifo_buffer[8];
int16_t acc_temp[3];
int16_t gyro_x;

void setup(){
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();
    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(115200);
    // initialize device
    Serial.println("Initializing I2C devices...");
    accelGyroMag.initialize();
    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelGyroMag.testConnection() ? "MPU9150 connection successful" : "MPU9150 connection failed");
    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    attachInterrupt(0,fifo_int,CHANGE);
}

void fifo_int() {
  state_fifo_int = true;
}

void loop(){
  while(!state_fifo_int) {
    accelGyroMag.setIntFIFOBufferOverflowEnabled(true);
    // enable fifo_interrupt
    accelGyroMag.setFIFOEnabled(true);
    accelGyroMag.setAccelFIFOEnabled(true);
    accelGyroMag.getXGyroFIFOEnabled();
    accelGyroMag.getAccelFIFOEnabled();
    fifo_count = accelGyroMag.getFIFOCount();
    accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes
    acc_temp[0] = (((int16_t)fifo_buffer[0]) << 8) | fifo_buffer[1];
    acc_temp[1] = (((int16_t)fifo_buffer[2]) << 8) | fifo_buffer[3];
    acc_temp[2] = (((int16_t)fifo_buffer[4]) << 8) | fifo_buffer[5];
    gyro_x = (((int16_t)fifo_buffer[6]) << 8) | fifo_buffer[7];
    Serial.print((float)acc_temp[0]/16384);
    Serial.print("  ");
    Serial.print((float)acc_temp[1]/16384);
    Serial.print(" ");
    Serial.print((float)acc_temp[2]/16384);
    Serial.print(" ");
    Serial.println(gyro_x);
   }
   accelGyroMag.setIntFIFOBufferOverflowEnabled(false);
   // disable fifo_interrupt
   accelGyroMag.resetFIFO();
   state_fifo_int = false;
}

```

The library for the MPU9150 is by Jeff Rowberg.

# Answer
> 1 votes
After reading the datasheet on the PS manual, I found out that the INT1 pulse had a width of 50uS.

So what I simply did was to declare a global integer and check it at the end of the loop.

Whenever I checked the incremented variable at the end, it was 48!.I personally suspected that my loop speed was to slow. Additionally the timeout value 14 ms per loop arbitrary. Clearly a disparity exists in the interrupt routine for the sensor and the microcontroller.

So what I simply did was to reconfigure the sensor output to a latched signal which clearly solved the problem. I am now getting synchronized interrupt with convincing results.

Here is the code:

```
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU9150.h"
#include "helper_3dmath.h"

#define LED_BUILTIN 13

MPU9150 accelGyroMag;

volatile boolean state_fifo_int = false;
int x = 0;

void blink(uint16_t offTime, uint16_t onTime){
digitalWrite(LED_BUILTIN,HIGH);
if(onTime) delay(onTime);
digitalWrite(LED_BUILTIN,LOW);
if(offTime) delay(offTime);
}

void resetSensor(){
  accelGyroMag.reset();
  delay(50);
  accelGyroMag.initialize();
  //Serial.println("Initialize if connection test failed");

  if(accelGyroMag.testConnection()){ //disable interrupts
     accelGyroMag.setIntFIFOBufferOverflowEnabled(false);
     // disable fifo_interrupt
     accelGyroMag.resetFIFO();
        // verify connection

     //Serial.println("Connection tested successfully, Disabling interrupts");
     }
if(!accelGyroMag.testConnection()){ // try to recover sensor
  accelGyroMag.initialize();
    //Serial.println("Initialize if connection test failed");
  }
if(accelGyroMag.testConnection()){  // reconfigure sensor for Fifo and interrupts

   accelGyroMag.setFIFOEnabled(true);
   accelGyroMag.setXGyroFIFOEnabled(true);
   accelGyroMag.setAccelFIFOEnabled(true);
   accelGyroMag.setInterruptMode(false);// Set interrupt logic level mode 0 = active-high
   accelGyroMag.setInterruptLatch(true); //set interrupt 1=latch-until-int-cleared ( latch after INT_STATUS READ)
   accelGyroMag.setIntFIFOBufferOverflowEnabled(true);

   }
else {
 // Serial.println("MPU9150 connection failed");
  //Serial.println("locking UP");
  while(true){
     for(uint8_t i=0;i<3;i++){blink(50,100);} // S
     delay(250);
     for(uint8_t i=0;i<3;i++){blink(50,300);} // O
     delay(250);
     for(uint8_t i=0;i<3;i++){blink(50,100);} // S
     delay(500);
    }
  }
}

void setup(){
  Wire.begin();
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
// other stuff
  attachInterrupt(0,fifo_int,RISING);
  resetSensor();
}

void fifo_int() {
  x++;
  state_fifo_int = true;

}

static unsigned long timeout = 0; // used to detect dead sensor/connection
uint16_t fifo_count;
uint8_t fifo_buffer[8];
int16_t acc_temp[3];
int16_t gyro_x;

void loop(){

  if(state_fifo_int){ // interrupt has triggered
    blink(0,1);  // really quick blink // really quick blink
    //Serial.println(x);
    state_fifo_int = false;
    accelGyroMag.resetFIFO();
    accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes
    accelGyroMag.getIntFIFOBufferOverflowStatus(); // read the INT_STATUS reg in order to clear the Latch.
    acc_temp[0] = (((int16_t)fifo_buffer[0]) << 8) | fifo_buffer[1];
    acc_temp[1] = (((int16_t)fifo_buffer[2]) << 8) | fifo_buffer[3];
    acc_temp[2] = (((int16_t)fifo_buffer[4]) << 8) | fifo_buffer[5];
    gyro_x = (((int16_t)fifo_buffer[7]) << 8) | fifo_buffer[8];

    timeout = millis();

  }

 if((millis()-timeout)>1000){ //last interrupt was over 1 second ago! better reset Sensor!
   blink(100,500);
   blink(100,500);

   resetSensor();
  }
}

```

# Answer
> 1 votes
When I've gotten into a bind with data being generated faster than I can dump it, or the process cannot tolerate the printing delays, I've made a memory buffer to store as much raw data as I can and print it after the test-run. If you're not using a debugger (which can print memory contents), you'll still need to have serial print code in your sketch but it can execute after the you run the code under test. Store the minimum size raw data (to maximize the amount you can store) and do the formatting on your PC.
If you need to be able see what happened prior to an unusual event your code can detect, use a ring buffer (FIFO) in memory and let it wrap around (don't even bother to detect wrap-around). As soon as your code detects the event, print the ring-buffer contents.
It's not continuous capture but often, it's enough.

---
Tags: serial, interrupt
---


# Question
Title: Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes
I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.

What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.

I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried `radio.setAutoAck(false)` in an attempt to lessen the delays but that made all my readings stop altogether.

**base node**:

```
    #include "Timer.h"
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9,10);
    Timer t;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    unsigned int values[3] = {0,0,0};
    void setup(void)
    {

      Serial.begin(115200);
      printf_begin();
      //printf("Receiver Node Active\n\r");

      radio.begin();

        radio.openReadingPipe(1,pipes[0]);
        radio.openReadingPipe(2,pipes[1]);
        radio.openReadingPipe(3,pipes[2]);
        radio.openReadingPipe(4,pipes[3]);
        radio.openReadingPipe(5,pipes[4]);

      radio.startListening();
      radio.printDetails();
      t.every(1, print_values); //call print_values() every 1ms

    }

    void loop(void)
    {
        int sender_id;
        uint8_t pipe_num;
        if ( radio.available(&pipe_num) )
        {
          unsigned int message;
          bool done = false;
            while (!done)
            {
                done = radio.read( &message, sizeof(message) );
            }
          sender_id = pipe_num - 1;
          values[sender_id-1] = message;
        }
        delay(1);
        t.update();

     }

     void print_values(){
       //formatted for arduinoscope
       printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
     }
    // vim:ai:ci sts=2 sw=2 ft=cpp

```

**child node:**

```
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(0,1);

    const int SW01 = 18;
    const int SW02 = 19;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    int node_id;

    void setup(void)
    {
      node_id=3; //hard coded id
      radio.begin();
      radio.openWritingPipe(pipes[node_id]);
    }

    void loop(void)
    {
        unsigned int val = analogRead(A0);
        radio.write( &val, sizeof(val) );
        //delay(1);
    }

```

# Answer
I am too building a RF24 based network there were two issues I encountered:

1) Update your libraries, use TMRh20 fork of RF24 (to make your life easier, use RF24Mesh too)

2) Add a decoupling cap to the NRF24L01+ power pins.
> 1 votes

# Answer
I can think of 3 ways:

1. You could have the Base polling for updates to each node sequentially, or
2. If all child nodes see each other, node2 can hear when node1 finished transmitting so it can transmit and so on. Or
3. You can punch through collisions setting random delays between each retry
> 0 votes

# Answer
1) Since these are all one-way communication, disable AutoAck on all NRFs (setAutoAck(false)). You're not doing Ack anyway which will cause retransmission when not acknowledged.

2) Change the address to something better.

Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate

3) Put a capacitor between ground and Vcc on all NRFs.
> 0 votes

---
Tags: nrf24l01+
---


title: Solutions for displays?

text:
# Question
Title: Solutions for displays?
I am trying to find cheap options for displays about 3 x 6 inches to display time, weather, simple clip-art type images, and other marquee messages. What are my best options to work with arduino if my goal is cost-cutting?

* 2" x 4" or greater in size
* 40 dpi minimum
* readable from 15 feet in normal indoor conditions
* everything else is unimportant to me at this point: RGB, pitch, power draw, etc.

# Answer
One possible option would be these 8x8 pixel displays.

I got that from eBay for $8.50 (for the 4 modules).

They come pre-assembled, this is the back:

Notice the data direction. You can connect them together like this:

That one (3 lots of 4 modules) is 25.4 cm long (10 inches) and 3.2 cm high (about 1.25 inches).

That's 96 pixels (8 x 4 x 3) in 10 inches, which is a lot less than 40 DPI, but really, if you want to read them from 15 feet away, that is probably OK.

Note: These were single-colour only.

---

If you want 40 DPI x 6 inches that means you must want 240 pixels horizontally and 120 pixels vertically. That would be `240 / 8` modules horizontally (30 modules) and `120 / 8` vertically (15 modules). That's a total of 450 modules. Since they come in lots of four that would be 116 in total (rounded up). 116 x $8.50 = $US 986.

I don't know if that is what you have in mind by "cost cutting" but that is one option.

You would need to assemble them yourself, connect them together, supply power, and have a suitable driver. I have some code that drives those boards, although I certainly have not tested it with 450 of them at once.

As you can see those boards come with mounting holes on the back, and are designed to be physically adjacent to each other. Mounting 450 of them could be quite tedious. The LED modules on the front pull off to give access to the mounting holes, but it would be a long job.

---

You can get larger modules, as mentioned in another reply, I expect they would be more expensive, but you would of course get more pixels.

Example: 64x32 RGB LED Matrix - 4mm pitch. That one is 64x32 pixels for around $US 80.

You would probably need 4 of those horizontally (256 pixels) and 4 vertically (128 pixels). Thus, a total of 16 which would cost you around $US 1280. However for that at least you get RGB. Note that the Adafruit page mentions you cannot drive that many pixels with a Uno.
> 2 votes

# Answer
How about just a computer monitor? That would be reasonably large, have high resolution, and could display whatever you want it to. That would only be a few hundred dollars (if that). You could drive it from a cheap PC, or from an Arduino using something like the MicroVGA board. That has 800x600 pixels resolution.

That would be cheaper, and less fiddly, than putting together a lot of LED display modules.

Also see http://playground.arduino.cc/Main/MicroVGA
> 2 votes

# Answer
www.aliexpress.com would be your first go for cheap stuff.

You can always chat with the guys and bargain a bit on the price. Do remember that the free shipping option means that it will take nearly a month to arrive
> 1 votes

---
Tags: lcd, display, components
---


# Question
Title: Arduino Uno (master) and ATTiny85 (slave) I2C connection not working
I am trying to send and receive data using I2C between an Arduino Uno and an ATTiny85. The Arduino Uno is using the Wire library. The ATTiny85 is using the TinyWire library and is programmed (and powered) using the Sparkfun Tiny AVR Programmer.

I am not receiving any data.

Arduino Uno I2C master code

```
#include <Wire.h>

#define SLAVE_ADDR 0x50

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

void loop()
{
  Wire.requestFrom(SLAVE_ADDR, 1);

  while(Wire.available())
  {
    byte byteReceived = Wire.read();
    Serial.println(byteReceived, DEC);
  }
}

```

ATTiny85 I2C slave code

```
#include "TinyWireS.h"

#define SLAVE_ADDR 0x50

void setup()
{
  TinyWireS.begin(SLAVE_ADDR);
  TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
  byte byteToSend = 23;
  TinyWireS.send(byteToSend);
}

```

# Answer
I modified your Uno sketch slightly to add a delay:

```
#include <Wire.h>

#define SLAVE_ADDR 0x50

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

void loop()
{
  Wire.requestFrom(SLAVE_ADDR, 1);

  if (Wire.available())
  {
    byte byteReceived = Wire.read();
    Serial.println(byteReceived, DEC);
  }

 delay (1000);
}

```

Upon testing, it worked perfectly!

```
23
23
23
23
23
23
23
23
23
23
23
23

```

I suggest a wiring error. Check you have:

```
Uno    ATtiny85
--------------------
A4      pin 5  (SDA)
A5      pin 7  (SCL)
+5V     pin 8
Gnd     pin 4

```
> 1 votes

# Answer
I think the problem is (assuming you've got the pins straight) is that there's no time for the byte to get to the Uno. Try `while(!Wire.available())` between `requestFrom...` and the `while(Wire.available())`
> 0 votes

---
Tags: arduino-uno, i2c, attiny, wire-library
---


# Question
Title: SoftwareSerial Write to return Read in Serial Monitor?
Hoping someone can help me out in my conundrum here...

I currently am testing the SoftwareSerial library out to understand how I may use it in my project.

I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.

I have written the following:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

void setup() {

  Serial.begin(1200);
  mySerial.begin(1200);
}

void loop() {

  mySerial.write('F');
  delay(100); // attempting to allow time between write and read commands

  while (mySerial.available()>0) {
  Serial.println(mySerial.read());
  }
}

```

The whole point is just to see 'F' return in the Serial Monitor.

The output, unfortunately, is absolutely nothing! If I omit the `while(mySerial.available>0)` I just get -1 's down the lines of the Serial Monitor.

Thank you in advance!

# Answer
SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.

Look at the code for `write` in SoftwareSerial:

```
size_t SoftwareSerial::write(uint8_t b)
{

...

  cli();  // turn off interrupts for a clean txmit

...

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

...

  SREG = oldSREG; // turn interrupts back on

...

}

```

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.
> 3 votes

---
Tags: serial, softwareserial, software
---


title: Arduino LCD Simple Problem

text:
# Question
Title: Arduino LCD Simple Problem
Hi my lcd doesnt display that i was expected. Can anyone help me???

RS--\>22 RW--\>GROUND E--\>23 D4--\>24 D5--\>25 D6--\>26 D7--\>27

```
    #include <LiquidCrystal.h>

LiquidCrystal lcd(22, 23, 24, 25, 26, 27);
void setup() {

lcd.begin(16,2);

lcd.setCursor(0,1);
lcd.print("Hello!");
delay(1000);
}
void loop() {
lcd.setCursor(0,1);
lcd.print(millis()/1000);
}

```

# Answer
I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.
> 3 votes

---
Tags: arduino-mega, lcd
---


# Question
Title: MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()
I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.

And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.

The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there.

This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there.

```
#include <Arduino.h>
#include <Wire.h>
#include <inttypes.h>
#include <SPI.h>
#include "flanschcontrol.h"
#define DEBUGOUTPUT
#define PROTOV2
typedef int elem_type;
#define ADDRESS (0)
#define    OPCODEW       (0b01000000)  // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3
#define    OPCODER       (0b01000001)  // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3
#define    ADDR_ENABLE   (0b00001000)  // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing
uint8_t PexSSPin=7;

void setup() {
   Serial.begin(9600);
    pinMode(PexSSPin, OUTPUT);
    SPI.begin();
    SPI.setClockDivider(2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

    delay(1000);
    PORTD &= 0b01111111;    // Slaveselect low

    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
    delay(1000);
}

void loop()
{
    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00000000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11111111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("ff");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00001111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0f");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11110000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("f0");
    delay(1000);

    int value;

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODER | (ADDRESS << 1));  // Send the MCP23S17 opcode, chip address, and read bit
    SPI.transfer(GPIOA);                      // Send the register we want to read
    value = SPI.transfer(0x00);               // Send any byte, the function will return the read value (register address pointer will auto-increment after write)
    value |= (SPI.transfer(0x00) << 8);       // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte"
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.print("pindata: ");
    Serial.println(value);
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
}

```

Definitions of some preprocessor thingies:

```
#define    IODIRA    (0x00)      // MCP23x17 I/O Direction Register
#define    IODIRB    (0x01)      // 1 = Input (default), 0 = Output
#define    GPIOA     (0x12)      // MCP23x17 GPIO Port Register
#define    GPIOB     (0x13)      // Value on the Port - Writing Sets Bits in the Output Latch

```

# Answer
> 1 votes
You've fallen for the old "slave select pin is already low" trick!

Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):

```
pinMode (2, OUTPUT);     // <--- pin 2 output
delay(1000);
PORTD |= bit (2);        // <--- pin 2 HIGH
PORTD &= 0b01111111;     // Slaveselect low
SPI.transfer(OPCODEW | (ADDRESS << 1));
SPI.transfer(IODIRB);
SPI.transfer(0b10101010);
PORTD |= 0b10000000;    // Slaveselect high
delay(1000);

```

This is the logic analyzer output of running your sketch:

Notice how SS is low all the time, and thus the chip does not respond to the command?

---

Now we add a line **before** the `SPI.begin`

```
PORTD |= 0b10000000;    // Slaveselect high
SPI.begin();
SPI.setClockDivider(2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);

```

Now look at the results:

This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.

So without bringing SS high, the **first** thing you sent was always going to fail.

---

It was nothing to do with it being in `setup` \- it couldn't be. After all the logic is basically this:

```
init ();
setup ();
while (true)
  loop ();

```

---

Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?

How about:

```
digitalWrite (PexSSPin, LOW);
/// write to chip
digitalWrite (PexSSPin, HIGH);

```

Isn't that much more readable? And easier to change later?

---
Tags: spi
---


# Question
Title: Sending Data between two boards using SoftwareSerial
I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!

The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).

The idea, is to get Serial TX on the *"MWC"* FLIP 1.5 to Serial RX on the UNO.

These are my connections thus far:

MWC Pin -------\>UNO Pin

Digital 3 (TX)---\>Digital 6 (RX)

Digital 9 (RX)---\>Digital 9 (TX)

This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)

```
#include "attout.h"
#include "SoftwareSerial.h"

SoftwareSerial altSerial(9,3); // RX=9 TX=3

void startaltserial(){

  altSerial.begin(9600);

}

void attout(){

pinMode(3,HIGH);
pinMode(9,HIGH);

  altSerial.print('1');

}

```

NOTE: I also tried `altSerial.write('1')`. Same result (or lack of one).

Then, the RX Code on the UNO Board:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); // RX=6 TX=9

void setup()
{
  // Open serial communications:
  Serial.begin(9600);

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

}

void loop()
{
  while (mySerial.available()>0) {
    Serial.println(mySerial.read());
  }
}

```

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!

This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.

Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.

Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

# Answer
Your problem here is that you are streaming out serial data non-stop.

See my answer in this thread: What is Serial.begin(9600)?

Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.

If you add one "character time" delay to the **sender**, the receiver works fine:

```
  altSerial.print('1');
  delay (2);

```

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.
> 1 votes

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