# Question
Title: Arduino and WS2812 RGB LED Strip "freezing"
I have been working on a project as a gift for my girlfriend for Christmas which involves some a bunch of standard "white" LEDs controlled by shift registers and darlington arrays, and also some RGB LED strips (WS2812B strip, 29 LEDs on strip). Everything is going fine with the white LEDs, but not so much with the RGB ones.

If I leave the RGB leds running for a while all of the LEDs on the strip turn red, except for the first one, which continues to change color. I am not sure how long "a while" is because in "short term" testing, approximately running continuously for an hour, it works fine and all of the LEDs change appropriately, but if I leave it running overnight I wake up with the issue of all red and one single RGB "working". I then have to reset to get it working again. These RGB LEDSs need to be run for long periods (24 hours) of time without "freezing". The rest of the program (with the normal LEDs) continues to work fine despite the RGB ones not.

Let me explain how I am controlling them. `V_rgb` is 5V (5V - 8A power supply), which it is also grounded to. Then the data line, `C`, is connected to an Arduino Uno, on pin 12, which is a PWM pin.

In software, I am using a Adafruit Neopixel Library to control the RGB LEDs and write their respective colors, based off the examples given in their git repo and the tutorial here.

I have pasted my code below in case that may help, but honestly I am not sure if it is software or hardware related. (unrelated code has been removed)

```
#include <Adafruit_NeoPixel.h>
#define rgbPin 11
#define numRGBleds 29

Adafruit_NeoPixel strip = Adafruit_NeoPixel(numRGBleds, rgbPin, NEO_GRB + NEO_KHZ800);
int colorStep = 0;
int rgbIndex = 0;

void shiftColor() {
  int i = 0;
  for (i = 0; i < numRGBleds; i++) {
    int idx = (rgbIndex + i) % numRGBleds;
    int colorVal = round(i * colorStep);
    strip.setPixelColor(idx, Wheel(colorVal & 255));
  }
  strip.show();
  rgbIndex++;
}

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  } if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

void setup()
{
  strip.begin();
  strip.show();
  rgbIndex = 0;
  colorStep = 255 / (numRGBleds - 1);
}

void loop()
{
  shiftColor();
  delay(1000); // Redo every second
}

```

My thoughts of what it could be are the following, let me know if any make any sense or are known issues:

* Having issues with `micros()` value rollover
* Overheating
* Noisy power supply
* Defective LED strip
* black magic?

Thanks in advance for any help.

**UPDATE**

My current solution to the problem is to just reset the board using the watchdog functionality. It reboots in a few milliseconds and sometimes flashes in the process, but I would like to figure out the real problem.

**UPDATE #2**

So with the reset solution, I left it running overnight and it did not freeze which leads me to think it is definitely a software, not hardware, issue. I have changed some of the wiring and coding to make sure the watchdog reset is not noticeable. It resets every half hour or so. This will make sure all of the memory is cleaned, except stuff I store in the EEPROM (which I do use to make the reset less noticeable). This reset delays processing by a few milliseconds, but time is not critical, so it is not a big deal.

I still however, would like to know a more elegant way of doing this. The software reset is a bit "hacky"

# Answer
> 3 votes
Try changing `rgbIndex++;` to `rgbIndex=(rgbIndex+1)%numRGBleds;`. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.

Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster.

---
Tags: arduino-uno, led, rgb-led, neopixel
---


# Question
Title: Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding
I'm newbie in Arduino Dev

I got Arduino Uno R3, at first it just worked fine. I tried to upload my whole project sketch which almost up to the max size of arduino memory.

Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.

I already remove all cables connected, still failed to upload.

I really dont know how to fix this.

# Answer
> 1 votes
First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate. If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening. It sounds like you've covered this as well by trying simple sketches. Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window. Also, double check inside the IDE that you still have the correct board selected. Occasionally / rarely, I've had to reboot Windows to cure the problem.

The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....

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


# Question
Title: Help putting an Arduino project on the Internet
I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?

Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?

And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?

Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.

# Answer
> 3 votes
> What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is WAMP (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this comparison table and select the one that most helps you. Based on that what I suggest is crossbar.io. Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266) or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.

Take a look at this video as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.

As for the second part.

If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports. Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.

Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.

# Answer
> 2 votes
If I'm understanding you correctly, you have your application running on a LAN and now want to figure out how to make it accessible over the Internet (WAN). If you're there the next step is relatively straight forward. All you need is an IP address that is visible on the Internet.

You don't say what your connection to the Internet is, so let's look at both of the likely (IPv4) possibilities:

* You have a block of publicly visible addresses (something other than an IP address starting with 10, 172.16, or 192.168 that are allocated by RFC 1918), or
* You are behind a single IP address using NAT (network address translation) to provide the internal machines with access to the Internet. The internal machines (and devices) will all have an RFC 1918 address and will not be accessible from the Internet – except by traffic responding to requests made by those machines which are routed to them using NAT. For many users this is the more likely case.

In the first case it is simply a matter of connecting the Arduino to a network segment that is connected to the Internet and assigning an IP address (or configuring DHCP). Also, make sure that the UDP port you are using is not assigned to another service.

In the second case you will also need to connect the Arduino to a network segment with access to the Internet, but because of NAT users outside will not be able to get to the Arduino (yet). To solve that problem you will need to map a port and your external address (the address of your router) to a port and the internal address of your Arduino. For example:

* Assume your service runs on port 3142 and your IP address on the Internet is 8.9.10.11 and the Arduino is at 192.168.0.42 on your internal network.
* Then you would configure the port forwarding settings on your router to direct UDP traffic bound for port 3142 to the internal IP address of 192.168.0.42. Some routers will only allow you to forward to the same port, others will also allow you to use a different internal port as well.
* You may also need to open up a "hole" in your firewall to allow traffic to the port where your service runs. The truly cautious will connect the Arduino to a network segment in the DMZ and there will be another firewall protecting your internal computers and devices.

Once you have this set up anybody on the outside will be able to use the service on the Arduino – if they know the IP address and the port number. Typically you would run the service at a well known host name and use DNS to translate the host name to an IP address. From your question I can't tell how you want to advertise the service, that would be another good question…

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


title: Connect Digital monitor to Arduino?

text:
# Question
Title: Connect Digital monitor to Arduino?
I need a small display with ~ 5 digits. The display needs to show number of visits to my site in real-time.

(Every time someone visits it needs to increase by one).

I thought to create an app, that fetches server stats every 10 seconds, and checks new number of visitors.

Do you think it is better to do with Arduino or Raspberry Pi?

Do you know of a digits monitor that can be connected to it?

# Answer
> 1 votes
It all depends on how used to you are with using pi or arduino. What you want can be done in both ways. The displaying of count is common for both. It can be done using a 16X1 LCD display, 5 different 7 segment LED connected via decoders or a graphic display module. Interfacing all these with Arduino will be relatively simpler than Pi.

For the fetching of data and sending it to your device for displaying it. You can use ESP8266 Wi-Fi module with arduino and pull the data. Which is not as simple as it sounds but it is not impossible too.

For pi, (like @max246 said) you can run a python script and use another api to get the data.

# Answer
> 1 votes
For the complexity of the pulling of the data from a specific API, I would suggest to use i2c screen from adafruit and a python script running on raspberry pi. this will save you time on coding eth interface and just mostly copy and paste some simple code to communicate to the display

This is one module that I used and it is simple to use: https://www.adafruit.com/products/1270

---
Tags: programming, web-server, display
---


title: Arduino using LCD

text:
# Question
Title: Arduino using LCD
I am building a project that is using A12864ZW 128X64 LCD, the question I have is should there be anything in the circuit to prevent damage to the Arduino Mega or the LCD? I am using this example here for a start.

I think I damaged one LCD with the current circuit because everything was working perfect then all of a sudden it was like the LCD Contrast was set all the way up, displaying only a dark screen but I couldn't adjust it with the U8Glib or with the V0. During programming I would disconnect the ground from the Arduino to the Breadboard, when I would do this the LCD would still flicker as it was being programmed. This is why I am wondering if I am missing something.

I read somewhere that putting a MOSFET on the Ground of the LCD that is connected to the Reset pin helps. Another problem that I am having is I am using Eclipse with the Arduino C++ add in and sometimes I can program easily, everything goes as expected but then it will fail to upload until I unplug and reset the board sometimes several times.

Because the program is using pins 11-13 it can create problems because these are the same pins used for programming if I remember correctly. I tried changing the pins used but didn't seem to help anything.

# Answer
> 1 votes
Disconnecting ground while all the other pins are connected and the Arduino is powered up is a *very* bad idea. Either manually, or using a MOSFET.

Simply because the power you are feeding in to the screen wants to try and find a way to ground through some means or other - and if the ground is disconnected then that means muscling its way through the IO pins into the Arduino and through to ground that way. The result is that you damage the LCD screen's fragile circuitry.

If you want to disconnect the ground pin at any time, you must ensure that either the power is turned off, or the power connections to the LCD are disconnected first.

If you want to have the Arduino's RESET toggle the power to the LCD to force a hard reset then you need to use a P-channel MOSFET in the power connection instead, so the ground connection is always connected.

---
Tags: programming, arduino-mega, lcd, eclipse
---


# Question
Title: Controlling DC motor from Android device
Ref: https://robotics.stackexchange.com/q/8526/11146

I want to build a simple android controlled robot

I will connect `android phone<usb>arduino<wire>motor controller<wire>dc motor`

I wonder why I have to write two programs (android java & arduino c++)?

How can I directly control the DC motor from android java program without writing arduino code?

# Answer
> 2 votes
The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.

Your project requires a number of small hunks of code on the Arduino to:

* Listen for commands from the Android.
* Validate the commands received.
* Turn on or off the motor.

Roughly speaking your loop() function might look something like this:

```
void loop() {
  // look for a command
  // validate the command
  if (valid && turn_motor_on) {
    motor_on();
  } else {
    motor_off();
  }
}

```

Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.

---
Tags: arduino-uno, usb, android
---


# Question
Title: Issues in interfacing relay with Arduino
I want to control AC bulb with Arduino, 5v-relay. My connections are

My code is

```
#define RELAY1  7

void setup()
{
  pinMode(RELAY1, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(RELAY1,LOW); // Turns ON Relays 1
  Serial.println("Light OFF");
  delay(15000); // Wait 5 seconds
  digitalWrite(RELAY1,HIGH); // Turns Relay Off
  Serial.println("Light ON");
  delay(20000);
}

```
* Red LED is on according to AC bulb.
* Power LED (Green colored one) is also on as I have given 5v supply from Arduino.

The issues are

1. Bulb is not following the delay given in the code. The output for the above code is 20sec ON - 15sec OFF -20sec ON - 15sec OFF- 20sec ON -15sec OFF - 1sec ON - 20sec ON - 15sec OFF etc. means apart from 20,15 sec duration there is a duration of 1sec is coming in between as noise. What might be the reason?
2. On monitor also, only first 3 actions are getting printed after that no printing is observed.

==\>The relay I am using is:

# Answer
what i would do is test the parts one by one. so first look if you're signal is good by attaching a led to it. then test you're relay with 5v.

now you should know what the problem is the arduino or the relay
> 1 votes

# Answer
Everything looks good, however Try a different relay, and double check your AC side and be sure the bulb voltage is correct for the AC and the bulb is OK.

You may have a power shortage from your USB or however you are powering it. If you can monitor the 5VDC and be sure it is stable.

Good Luck
> 0 votes

---
Tags: arduino-uno, relay
---


# Question
Title: When it says the Uno has logic level at 5 V is that also true of a bareduino/breadboard Arduino?
I want to hook up ESP8266, which has a 3.3v logic level to my bare-bones Arduino (basically a minimal interface for the ATmega382P IC).

I can power my circuit at 3.3 V without a 5 V regulator so will the voltage of the logic level also be 3.3 V?

I don't think there is a tiny boost converter in the IC... but I'm uncertain.

# Answer
> 7 votes
The logic level is the same as the voltage you supply the chip.

You can think of the IO pins as tiny switches that either connect the output pin to the supply voltage or to ground (when in output mode) or compare the incoming voltage to an input pin to a percentage of the supply voltage (typically \<0.3×Vcc for low and \>0.6Vcc for high)

So yes, if you run the chip at 3.3V the logic level will be 3.3V logic (or more specifically \< 1.1v for low and \> 2.2v for high).

---
Tags: voltage-level, esp8266
---


title: Simple URL decoding

text:
# Question
Title: Simple URL decoding
How can I do a readable, small, smart and good URL decoder in Arduino?

Now I'm using this code:

```
String GetRidOfurlCharacters(String urlChars)
{

  urlChars.replace("%0D%0A", String('\n'));

  urlChars.replace("+",   " ");
  urlChars.replace("%20", " ");
  urlChars.replace("%21", "!");
  urlChars.replace("%22", String(char('\"')));
  urlChars.replace("%23", "#");
  urlChars.replace("%24", "$");
  urlChars.replace("%25", "%");
  urlChars.replace("%26", "&");
  urlChars.replace("%27", String(char(39)));
  urlChars.replace("%28", "(");
  urlChars.replace("%29", ")");
  urlChars.replace("%2A", "*");
  urlChars.replace("%2B", "+");
  urlChars.replace("%2C", ",");
  urlChars.replace("%2D", "-");
  urlChars.replace("%2E", ".");
  urlChars.replace("%2F", "/");
  urlChars.replace("%30", "0");
  urlChars.replace("%31", "1");
  urlChars.replace("%32", "2");
  urlChars.replace("%33", "3");
  urlChars.replace("%34", "4");
  urlChars.replace("%35", "5");
  urlChars.replace("%36", "6");
  urlChars.replace("%37", "7");
  urlChars.replace("%38", "8");
  urlChars.replace("%39", "9");
  urlChars.replace("%3A", ":");
  urlChars.replace("%3B", ";");
  urlChars.replace("%3C", "<");
  urlChars.replace("%3D", "=");
  urlChars.replace("%3E", ">");
  urlChars.replace("%3F", "?");
  urlChars.replace("%40", "@");
  urlChars.replace("%41", "A");
  urlChars.replace("%42", "B");
  urlChars.replace("%43", "C");
  urlChars.replace("%44", "D");
  urlChars.replace("%45", "E");
  urlChars.replace("%46", "F");
  urlChars.replace("%47", "G");
  urlChars.replace("%48", "H");
  urlChars.replace("%49", "I");
  urlChars.replace("%4A", "J");
  urlChars.replace("%4B", "K");
  urlChars.replace("%4C", "L");
  urlChars.replace("%4D", "M");
  urlChars.replace("%4E", "N");
  urlChars.replace("%4F", "O");
  urlChars.replace("%50", "P");
  urlChars.replace("%51", "Q");
  urlChars.replace("%52", "R");
  urlChars.replace("%53", "S");
  urlChars.replace("%54", "T");
  urlChars.replace("%55", "U");
  urlChars.replace("%56", "V");
  urlChars.replace("%57", "W");
  urlChars.replace("%58", "X");
  urlChars.replace("%59", "Y");
  urlChars.replace("%5A", "Z");
  urlChars.replace("%5B", "[");
  urlChars.replace("%5C", String(char(65)));
  urlChars.replace("%5D", "]");
  urlChars.replace("%5E", "^");
  urlChars.replace("%5F", "_");
  urlChars.replace("%60", "`");
  urlChars.replace("%61", "a");
  urlChars.replace("%62", "b");
  urlChars.replace("%63", "c");
  urlChars.replace("%64", "d");
  urlChars.replace("%65", "e");
  urlChars.replace("%66", "f");
  urlChars.replace("%67", "g");
  urlChars.replace("%68", "h");
  urlChars.replace("%69", "i");
  urlChars.replace("%6A", "j");
  urlChars.replace("%6B", "k");
  urlChars.replace("%6C", "l");
  urlChars.replace("%6D", "m");
  urlChars.replace("%6E", "n");
  urlChars.replace("%6F", "o");
  urlChars.replace("%70", "p");
  urlChars.replace("%71", "q");
  urlChars.replace("%72", "r");
  urlChars.replace("%73", "s");
  urlChars.replace("%74", "t");
  urlChars.replace("%75", "u");
  urlChars.replace("%76", "v");
  urlChars.replace("%77", "w");
  urlChars.replace("%78", "x");
  urlChars.replace("%79", "y");
  urlChars.replace("%7A", "z");
  urlChars.replace("%7B", String(char(123)));
  urlChars.replace("%7C", "|");
  urlChars.replace("%7D", String(char(125)));
  urlChars.replace("%7E", "~");
  urlChars.replace("%7F", "Â");
  urlChars.replace("%80", "`");
  urlChars.replace("%81", "Â");
  urlChars.replace("%82", "â");
  urlChars.replace("%83", "Æ");
  urlChars.replace("%84", "â");
  urlChars.replace("%85", "â¦");
  urlChars.replace("%86", "â");
  urlChars.replace("%87", "â¡");
  urlChars.replace("%88", "Ë");
  urlChars.replace("%89", "â°");
  urlChars.replace("%8A", "Å");
  urlChars.replace("%8B", "â¹");
  urlChars.replace("%8C", "Å");
  urlChars.replace("%8D", "Â");
  urlChars.replace("%8E", "Å½");
  urlChars.replace("%8F", "Â");
  urlChars.replace("%90", "Â");
  urlChars.replace("%91", "â");
  urlChars.replace("%92", "â");
  urlChars.replace("%93", "â");
  urlChars.replace("%94", "â");
  urlChars.replace("%95", "â¢");
  urlChars.replace("%96", "â");
  urlChars.replace("%97", "â");
  urlChars.replace("%98", "Ë");
  urlChars.replace("%99", "â¢");
  urlChars.replace("%9A", "Å¡");
  urlChars.replace("%9B", "âº");
  urlChars.replace("%9C", "Å");
  urlChars.replace("%9D", "Â");
  urlChars.replace("%9E", "Å¾");
  urlChars.replace("%9F", "Å¸");
  urlChars.replace("%A0", "Â");
  urlChars.replace("%A1", "Â¡");
  urlChars.replace("%A2", "Â¢");
  urlChars.replace("%A3", "Â£");
  urlChars.replace("%A4", "Â¤");
  urlChars.replace("%A5", "Â¥");
  urlChars.replace("%A6", "Â¦");
  urlChars.replace("%A7", "Â§");
  urlChars.replace("%A8", "Â¨");
  urlChars.replace("%A9", "Â©");
  urlChars.replace("%AA", "Âª");
  urlChars.replace("%AB", "Â«");
  urlChars.replace("%AC", "Â¬");
  urlChars.replace("%AE", "Â®");
  urlChars.replace("%AF", "Â¯");
  urlChars.replace("%B0", "Â°");
  urlChars.replace("%B1", "Â±");
  urlChars.replace("%B2", "Â²");
  urlChars.replace("%B3", "Â³");
  urlChars.replace("%B4", "Â´");
  urlChars.replace("%B5", "Âµ");
  urlChars.replace("%B6", "Â¶");
  urlChars.replace("%B7", "Â·");
  urlChars.replace("%B8", "Â¸");
  urlChars.replace("%B9", "Â¹");
  urlChars.replace("%BA", "Âº");
  urlChars.replace("%BB", "Â»");
  urlChars.replace("%BC", "Â¼");
  urlChars.replace("%BD", "Â½");
  urlChars.replace("%BE", "Â¾");
  urlChars.replace("%BF", "Â¿");
  urlChars.replace("%C0", "Ã");
  urlChars.replace("%C1", "Ã");
  urlChars.replace("%C2", "Ã");
  urlChars.replace("%C3", "Ã");
  urlChars.replace("%C4", "Ã");
  urlChars.replace("%C5", "Ã");
  urlChars.replace("%C6", "Ã");
  urlChars.replace("%C7", "Ã");
  urlChars.replace("%C8", "Ã");
  urlChars.replace("%C9", "Ã");
  urlChars.replace("%CA", "Ã");
  urlChars.replace("%CB", "Ã");
  urlChars.replace("%CC", "Ã");
  urlChars.replace("%CD", "Ã");
  urlChars.replace("%CE", "Ã");
  urlChars.replace("%CF", "Ã");
  urlChars.replace("%D0", "Ã");
  urlChars.replace("%D1", "Ã");
  urlChars.replace("%D2", "Ã");
  urlChars.replace("%D3", "Ã");
  urlChars.replace("%D4", "Ã");
  urlChars.replace("%D5", "Ã");
  urlChars.replace("%D6", "Ã");
  urlChars.replace("%D7", "Ã");
  urlChars.replace("%D8", "Ã");
  urlChars.replace("%D9", "Ã");
  urlChars.replace("%DA", "Ã");
  urlChars.replace("%DB", "Ã");
  urlChars.replace("%DC", "Ã");
  urlChars.replace("%DD", "Ã");
  urlChars.replace("%DE", "Ã");
  urlChars.replace("%DF", "Ã");
  urlChars.replace("%E0", "Ã");
  urlChars.replace("%E1", "Ã¡");
  urlChars.replace("%E2", "Ã¢");
  urlChars.replace("%E3", "Ã£");
  urlChars.replace("%E4", "Ã¤");
  urlChars.replace("%E5", "Ã¥");
  urlChars.replace("%E6", "Ã¦");
  urlChars.replace("%E7", "Ã§");
  urlChars.replace("%E8", "Ã¨");
  urlChars.replace("%E9", "Ã©");
  urlChars.replace("%EA", "Ãª");
  urlChars.replace("%EB", "Ã«");
  urlChars.replace("%EC", "Ã¬");
  urlChars.replace("%ED", "Ã");
  urlChars.replace("%EE", "Ã®");
  urlChars.replace("%EF", "Ã¯");
  urlChars.replace("%F0", "Ã°");
  urlChars.replace("%F1", "Ã±");
  urlChars.replace("%F2", "Ã²");
  urlChars.replace("%F3", "Ã³");
  urlChars.replace("%F4", "Ã´");
  urlChars.replace("%F5", "Ãµ");
  urlChars.replace("%F6", "Ã¶");
  urlChars.replace("%F7", "Ã·");
  urlChars.replace("%F8", "Ã¸");
  urlChars.replace("%F9", "Ã¹");
  urlChars.replace("%FA", "Ãº");
  urlChars.replace("%FB", "Ã»");
  urlChars.replace("%FC", "Ã¼");
  urlChars.replace("%FD", "Ã½");
  urlChars.replace("%FE", "Ã¾");
  urlChars.replace("%FF", "Ã¿");

  return urlChars;
}

```

However I want to make a loop and only replace a url escaping if it exists, not trying to replace all the (possible) occurrences.

# Answer
> 4 votes
The fact that you're using a String (urgh, shudder shudder... you should read this: http://hacking.majenko.co.uk/the-evils-of-arduino-strings) actually makes it a little harder to work with. Instead you should have your String data in a character array ("C string"). Then a parser is much easier to write using a pair of character pointers.

Basically the theory is you scan from the start of the string to the end of the string using both pointers copying characters as you go, and as soon as you hit a `%` you read ahead 2 characters using the first pointer (the second pointer stays where it is) and you convert the two read characters as hex into the ASCII equivalent and use the second pointer to replace the `%`.

Then both pointers keep moving forward, but they stay out of step. As each `%` crops up the pointers get further and further out of step until you reach the end of the string and all the `%xx` have been replaced with a single character.

For instance, this code I have just knocked up does the job:

```
char data[50] = "http://foo/bar?x=hello%20there%3A%20majenko";

// Create two pointers that point to the start of the data
char *leader = data;
char *follower = leader;

// While we're not at the end of the string (current character not NULL)
while (*leader) {
    // Check to see if the current character is a %
    if (*leader == '%') {

        // Grab the next two characters and move leader forwards
        leader++;
        char high = *leader;
        leader++;
        char low = *leader;

        // Convert ASCII 0-9A-F to a value 0-15
        if (high > 0x39) high -= 7;
        high &= 0x0f;

        // Same again for the low byte:
        if (low > 0x39) low -= 7;
        low &= 0x0f;

        // Combine the two into a single byte and store in follower:
        *follower = (high << 4) | low;
    } else {
        // All other characters copy verbatim
        *follower = *leader;
    }

    // Move both pointers to the next character:
    leader++;
    follower++;
}
// Terminate the new string with a NULL character to trim it off
*follower = 0;

```

The `data` array now contains:

```
http://foo/bar?x=hello there: majenko

```

# Answer
> 3 votes
I wrote a Tiny web server for the Arduino which has a similar thing in it. You might find it useful for your project. Inside there is a function that decodes the URL codes on-the-fly (ie. in a state machine). The code is a bit different to Majenko's because he assumes that you have the string in memory. In my case I am decoding a byte at a time (so you don't have to hold a long string in memory before you decode it).

The snippet that does the decoding is this:

```
  // percent-encoding: possible states
  enum EncodePhaseType {
    ENCODE_NONE,
    ENCODE_GOT_PERCENT,
    ENCODE_GOT_FIRST_CHAR,
  };
  // percent-encoding: current state
  EncodePhaseType encodePhase;
  byte encodeByte;  // encoded byte being assembled (first nybble)

```

...

```
// ---------------------------------------------------------------------------
// add a character to the value buffer - percent-encoded (if wanted)
// ---------------------------------------------------------------------------
 void HTTPserver::addToValueBuffer (byte inByte, const bool percentEncoded)
  {
  if (valueBufferPos >= MAX_VALUE_LENGTH)
    {
    flags |= FLAG_VALUE_BUFFER_OVERFLOW;
    return;
    }  // end of overflow

  // look for stuff like "foo+bar" (turn the "+" into a space)
  // and also "foo%21bar" (turn %21 into one character)
  if (percentEncoded)
    {
    switch (encodePhase)
      {

      // if in "normal" mode, turn a "+" into a space, and look for "%"
      case ENCODE_NONE:
        if (inByte == '+')
          inByte = ' ';
        else if (inByte == '%')
          {
          encodePhase = ENCODE_GOT_PERCENT;
          return;  // no addition to buffer yet
          }
        break;

      // we had the "%" last time, this should be the first hex digit
      case ENCODE_GOT_PERCENT:
        if (isxdigit (inByte))
          {
          byte c = toupper (inByte) - '0';
          if (c > 9)
            c -= 7;  // Fix A-F
          encodeByte = c << 4;
          encodePhase = ENCODE_GOT_FIRST_CHAR;
          return;  // no addition to buffer yet
          }
        // not a hex digit, give up
        encodePhase = ENCODE_NONE;
        flags |= FLAG_ENCODING_ERROR;
        break;

      // this should be the second hex digit
      case ENCODE_GOT_FIRST_CHAR:
        if (isxdigit (inByte))
          {
          byte c = toupper (inByte) - '0';
          if (c > 9)
            c -= 7;  // Fix A-F
          inByte = encodeByte | c;
          }
        else
          flags |= FLAG_ENCODING_ERROR;

        // done with encoding it, or not a hex digit
        encodePhase = ENCODE_NONE;

      } // end of switch on encodePhase
    } // end of percent-encoded

  // add to value buffer, encoding has been dealt with
  valueBuffer [valueBufferPos++] = inByte;
  valueBuffer [valueBufferPos] = 0;  // trailing null-terminator
  } // end of HTTPserver::addToValueBuffer

```

---
Tags: programming, c++, string
---


# Question
Title: Speed of built in DAC/ADC in Arduino Due
Can someone tell me how fast the built in DAC (and ADC) in an Arduino Due can be written or read? I currently don't have the equipment to measure but need the information to plan my next steps.

I try to move galvanometer mirrors and want to make the voltage/position updates as small as possible. How fast are the internal DACs compared to an SPI connection (where I have to write 2 Byte).

# Answer
> 3 votes
See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A\_Datasheet.pdf specsheet.

In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”. Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.

For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:

> The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock. Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog output.

AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.

For more details about the ADC, see eg Analog performance, particularly of Due's 12 bit ADC at djerickson.com.

---
Tags: arduino-due, adc
---


title: Controlling relays with IR and button

text:
# Question
Title: Controlling relays with IR and button
What I have:

* 1 x 8 channel relay
* 1 x IR receiver
* 1x Arduino Uno
* 1x momentary switch
* 1x breadboard
* 1x 10K resister

I think the wiring is all ok as for the most part things are working as they should..ish.

Just a few bugs I need to fix.

The goal was to toggle just 2 relays (at the moment) on/off with the hardwired switch and individually toggle the a relay using an IR remote control.

Like I said this sort of works....

If I press the momentary button it does indeed toggle both relays...yeah! then as long as the 2 relays are toggled to the on position by the momentary switch I can toggle each relay using buttons on a remote.

However if I turn the relays off with the momentary button I can't turn them on with the remote. Also if I turn off one of the relays with the remote and then press momentary switch it alternates the toggle between the 2 relays rather than just turning the other one off.

I have been using various example sketches to achieve all this and just trying to stitch them together as best I can but something is telling me that the approach is all wrong and that I should maybe be looking into Boolean's perhaps?

Hope you can shed some light on this for me.

```
#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State;
int relay2State;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = ~relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = ~relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        relay1State = !relay1State;
        relay2State = !relay2State;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

```

# Answer
> 3 votes
So according to your comments this should be the code if no mistake was made

```
#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = !relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = !relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        masterState = !masterState;
        relay1State = masterState;
        relay2State = masterState;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

```

what I've done is create a masterState that only changes whenever you press the buttonPin and by pressing it will also change both relays to the value of new masterState independently of their actual state.

Another advice: is a bad practice to not initialize variables before use, because when you declare it is not granted that they are automatically equal to zero.

---
Tags: button, relay, ir
---


# Question
Title: Modifying Arduino IMU library to rely on DSSCircuit's I2C Master Library
For an Arduino project I am working on, I am trying to modify the SparkFun 6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345 to support DSSCircuit's I2C Master Library (https://github.com/DSSCircuits/I2C-Master-Library). This is to combat the known issue of the Arduino Wire library to often get hung up while trying to run the EndTransmission function.

I'm new to this and do not understand how the terms 'slave address' and 'register address' and 'bytes you want to send' are different, if they are. I also do not understand how buffering works in the base IMU library. Any information on those would be appreciated, but is not the focus of my question.

I use the example code of the IMU unit...

```
#include <FreeSixIMU.h>
#include <FIMU_ADXL345.h>
#include <FIMU_ITG3200.h>
#include <Wire.h>
#include <I2C.h>

int raw[6]; // x y z yaw pitch roll

// Set the FreeSixIMU object
FreeSixIMU sixDOF = FreeSixIMU();

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

  delay(100);
  sixDOF.init(); //begin the IMU
  delay(100);
}

void loop() {
  sixDOF.getRawValues(raw);
  Serial.print(raw[0]);
  Serial.print(" x | ");
  Serial.print(raw[1]);
  Serial.print(" y | ");
  Serial.print(raw[2]);
  Serial.println(" z");
  delay(100);
}

```

And I changed the selected IMU library functions as follows:

```
// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
  I2c.write(address, val);
  // send register address
}

// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read(address, (byte) num);
  // sends address to read from
}

void ITG3200::writemem(uint8_t _addr, uint8_t _val) {
  I2c.write(_addr, _val);   // start transmission to device
}

void ITG3200::readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]) {
  I2c.read(_addr, _addr, _nbytes);   // start transmission to device
}

```

And added the `#include <I2C.h>` statements to the headers files where applicable.

When running the example code, the serial output will not change values based on how I move the accelerometer, which makes me think I used the wrong slave address to read data from, or some other issue.

Can someone help me modify the IMU library to include DSSCircuit's Master I2C Library?

Thank you Stack Exchange Community! John

**EDIT:**

Please see PersonAGem's edit below. Using the wire library is known to have arbitrary hangups, and in this example PersonAGem lists the edits I should make to the other libraries I am using as well as gives me the code I should use in my `.ino`.

I ask a new question about this topic here.

# Answer
> 1 votes
You are missing the rest of the code in reading operations. You are just requesting the data, no actually reading it from the device:

the original code of adlx345::read

```
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  Wire.beginTransmission(_dev_address); // start transmission to device
  Wire.write(address);             // sends address to read from
  Wire.endTransmission();         // end transmission

  Wire.beginTransmission(_dev_address); // start transmission to device
  Wire.requestFrom(_dev_address, num);    // request 6 bytes from device

  int i = 0;
  while(Wire.available())         // device may send less than requested (abnormal)
  {
    _buff[i] = Wire.read();    // receive a byte
    i++;
  }
  if(i != num){
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }
  Wire.endTransmission();         // end transmission
}

```

would change to (if no mistakes made):

```
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read(_dev_address, address, num) // request 6 bytes from device
  if(I2c.available() != num){  // device may send less than requested (abnormal)
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }

  int i = 0;
  while(I2c.available())
  {
    _buff[i] = I2c.receive();    // receive a byte
    i++;
  }
}

```

you may need to force cast parameters between functions.

If for some reason you don't want the actual code and want to use another library, I'll suggest I2Cdev site with a well documented classes for adlx345 and ITG3200.

**Edit:**

This caused me no problem. That is the only 2 functions I changed:

```
// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
  I2c.write((uint8_t) _dev_address, (uint8_t) address, (uint8_t) val);
}

// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read((uint8_t) _dev_address, (uint8_t) address, (uint8_t) num);  // request 6 bytes from device
  if(I2c.available() != num){  // device may send less than requested (abnormal)
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }

  int i = 0;
  while(I2c.available())
  {
    _buff[i] = I2c.receive();    // receive a byte
    i++;
  }
}

```

**Arduino code used:**

```
#include <I2C.h>
#include "FIMU_ADXL345.h"

ADXL345 acc = ADXL345();
int x=0,  y=0, z=0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2c.begin();
  delay(100);
  acc.init(ADXL345_ADDR_ALT_LOW);
  delay(100);
  Serial.print("Is ACC OK?: ");
  Serial.println(acc.status);
  Serial.print("Any Error code?: ");
  Serial.println(acc.error_code);
  Serial.println("********Print all register current values********");
  acc.printAllRegister();
  Serial.println("********END register print******");
  Serial.println(acc.getRate());
}

void loop() {
  // put your main code here, to run repeatedly:
  acc.readAccel(&x,&y,&z);
  Serial.print(x);
  Serial.print('\t');
  Serial.print(y);
  Serial.print('\t');
  Serial.println(z);
  delay(500);
}

```

**Output given:**

```
Is ACC OK?: 1
Any Error code?: 0
********Print all register current values********
0x00: B11100101
0x1D: B00000000
0x1E: B00000000
0x1F: B00000000
0x20: B00000000
0x21: B00000000
0x22: B00000000
0x23: B00000000
0x24: B00000000
0x25: B00000000
0x26: B00000000
0x27: B00000000
0x28: B00000000
0x29: B00000000
0x2A: B00000000
0x2B: B00000000
0x2C: B00001010
0x2D: B00001000
0x2E: B00000000
0x2F: B00000000
0x30: B10000011
0x31: B00000000
0x32: B11110101
0x33: B11111111
0x34: B00000011
0x35: B00000000
0x36: B11100101
0x37: B00000000
0x38: B00000000
0x39: B00000000
********END register print******
100.00
-12 4   230
-10 2   231
-11 3   231
-12 3   228
-10 3   230
-11 2   231
-12 2   229
-11 3   229
-10 3   231
-11 3   229
-10 2   230
-12 4   230
-12 3   229
-10 2   229
-13 4   230
-11 3   230
-10 3   230
-11 2   230
-11 4   229
-11 3   230
-11 3   230
-11 3   229
-12 3   229
-10 2   229
-11 3   230
-11 3   231
-11 3   230
-15 14  227
34  104 210
138 95  191
243 18  88
323 -15 74
280 -8  -2
263 -2  37
212 10  163
16  39  233
28  114 195
29  161 170
33  124 211
5   49  244
7   22  224
-10 3   229
-11 2   230
-12 2   230
-11 3   231
-12 4   228

```

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


title: "Sharing" used GPIO pins

text:
# Question
Title: "Sharing" used GPIO pins
I have a question regarding the ARDuino uno and some shields. I currently have a shield on my Uno, which takes the pins 0 to 7. However, on top of that board there is an extension of those 8 pins. If they were always in use, I suppose that the extra ports wouldn't be on top of the board, right?

Here's how it looks:

So it seems like you're able to "share" them. Is it possible to do so in real-time or is that there so you can use the ports when you disable the shield?

If its possible in real-time, how would I go about doing that? I've searched a little but couldn't find anything. I suppose i'd need some kind of clock to make the switch between the shield and the other components on pins 0-7, but not sure how to do that.

I'm kind of an electrics newbie, so hence the question might be a little silly :)

# Answer
No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc). General GPIO pins connect to just one device at a time.

I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use. You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.

However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.
> 2 votes

---
Tags: shields, pins
---


title: Updating the ARDuino code over GPRS

text:
# Question
Title: Updating the ARDuino code over GPRS
I've been searching a little for self-updating the ARDuino, and most i've come about is updating it using a wifi / lan shield.

Now I have a GPRS shield that can connect it to the internet. Say that I want to remotely update the shield - how would I go about doing that?

I'm guessing I need some kind of bootloader - but is that extra hardware?

Actually the question boils down to:

* How can I flash the ARDuino Uno with new software, that I'll receive over a GPRS connection using a GPRS shield?

# Answer
You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino. That could be another Arduino.

The second option is probably the simplest to create:

1. The GPRS is connected to Arduino A.
2. Your main software runs on Ardiuno B.
3. Both Arduinos are connected by serial
4. Normal operation Arduino A passes all serial verbatim through to Arduno B
5. Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.
6. Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.

Arduino A is then a proxy between the GPRS and Arduino B. Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.

Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.
> 4 votes

---
Tags: software
---


# Question
Title: How to access parse cloud functions using arduino?
I have created rest service using .js file on Parse.com. I want to access cloud function from arduino.

i tried this

client.get(https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello");

i am getting error "Method not allowed".

Solution : Somehow i got the answer which is as follows.I hope it will help others.

```
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(function_name);  //string ("hello")
 cloudFunction.add("light_sensor", light); //pass parameter to cloud

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());

```

# Answer
> 0 votes
I read api of Parse and there i got the class to call cloud function from Arduino.I hope it will help others.

```
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(fnname); //String ("hello")
 cloudFunction.add("light_sensor", 139); //parameter

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());

```

---
Tags: arduino-yun
---


title: use arduino IDE for USB isp programmer

text:
# Question
Title: use arduino IDE for USB isp programmer
A few years ago I programmed AVR ATmega8 with AVR studio by USB isp programmer. I was using C language. Now I would like to use arduino(C++) langauge and my external USB isp programmer. Is it possible?

# Answer
The Arduino IDE compiles and outputs standard Intel HEX format files that are compatible with (nearly?) all programmers. If you enable detailed logging in the preferences panel you can find out which directory the IDE is building your code in and if the IDE does not include specific support for your programmer you can then locate the .hex file and upload it using the tool you are familiar with. The projects are typically built in a `build.*` subdirectory under %TEMP% (or /tmp on unix).
> 1 votes

# Answer
If you want to use arduino IDE to program the atmega328 you don't need a USB ISP programmer. The only thing you have to do is load the arduino bootloader on the atmega328 in order to program it through the arduino IDE. In the ide you can program the board with c++. But if you want to program the atmega328 through you're USB ISP programmer (assuming it is capable of programming the Atmega 328) you have to use other IDE in which you can program in c++ and produce an hex file that can be burned on the chip through you're programmer on the atmega328.
> 0 votes

# Answer
The programmers supported by the Arduino IDE are listed under `Tools` | `Programmer`. In order to upload your sketch using the programmer either Shift-click the upload button, select `File` | `Upload Using Programmer`, or press `Ctrl``Shift``U`.
> 0 votes

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


# Question
Title: Run code via NRF24L01+ command "dynamically"?
I'm trying to make a home automation setup but I'm having a bit of trouble.

I want to be able to send commands of varying sizes to my arduino, separated by "|" and after receiving it completely it runs code corresponding to the command.

Example:

input "RCP=10001|CMD=D|VAL=120" would result in an array like:

```
String cmd[][] = {{"RCP", "10001"}, {"CMD", "D"}, {"VAL", "120"}}

```

with the amount of 'variables' being... well, variable.

The code would continue checking if the RCP (recipient) ID corresponds with the ID of the current client and then run code based on the following variables. But I don't think that's important info for the code which separated the string.

This string would be sent through an NRF24L01+ (That code already works)

# Answer
What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.

Instead you will need to "distil" the information as it comes in and store the distilled information.

If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc. If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.

Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory. If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.

For instance it may be good to define a structure which is the content of a message:

```
struct message {
    uint8_t key;
    uint16_t val;
};

```

Then make an array of that structure - one slice per possible command, say 10 of them:

```
struct message messageQueue[10];

```

That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value). Now you can set the keys and values to the correct data as it arrives.

Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a *circular buffer*. This is basically how the Serial port on the Arduino works - in involves having two *pointers* to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again. As you read from the array the reading pointer moves along too. If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full. Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.

As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.
> 3 votes

---
Tags: communication, nrf24l01+, string, variables
---


title: Emulate RFID Tag

text:
# Question
Title: Emulate RFID Tag
I just got my RFID-RC522 Reader and was wondering one thing. Can i Use an RFID Reader to emulate an RFID Tag, so that if i have another reader it will detect the other one as a card and transfer data. It should be detected as a Tag like a midfare Classic but the data sould be supplied by the Arduino. Is this possible? At all? Or does it require another type of reader? If you know a solution please share it.

# Answer
> 0 votes
I'm almost positive you cant use a RFID Reader to talk to another RFID Reader with the basic libraries and resources we have. You are best just getting an actual tag may it be Mifare classic or another type of RFID Tag.

I'm sure this is possible but the amount of development you will need to dedicate towards this would out weigh just getting a cheap RFID tag.

What you can do is look around see what type of things you have laying around maybe something has an RFID tag in it, or maybe you have a phone with NFC. You can use your phones NFC to send data to a RFID reader, but you will need to find the resources to do this. Sorry I'm not much help but maybe someone has done this before and has a simple solution.

---
Tags: rfid, emulation
---


title: RFduino communication capabilities

text:
# Question
Title: RFduino communication capabilities
Is there any way to connect RFduino's via radio frequency? Or any capability to transmit information between RFduino's for distances up to 200 feet?

I would like to purchase a dev kit (for RF duino) but i'm not sure what parts I will need to transmit info longish (200 feet) distances.

# Answer
> 2 votes
https://blog.adafruit.com/2010/06/11/aprs-radio-shield-for-arduino/ Be warned you need a license to transmit on amateur frequencies at least in the US, you will also need to hook up a transmitter for this shield.

GSMShield would also be great and is something I'm thinking about using for my project, the way the Arduino IDE is setup and the libraries already in place I'm sure it would be easy to turn text messages into commands or readable and usable data between the sender and receiver.

Here are two ways one using a long range radio frequency or the GSM network. We would need to know more exact data of your project on how to implement these two solutions to accomplish what you would like to do.

The first option is most likely going to be the lesser option if you don't have a license to transmit long range frequencies and do not have experience.

The second option is easy and all you would have to do is make sure both sender and receiver are within a GSM network.

Good luck and I'm excited to see what other solutions others may post since I'm in the same boat.

---
Tags: rf
---


# Question
Title: ATmega 8 wrong timing with Arduino NG bootloader
I have build simple Arduino ISP programmer, which works fine on ATmega 328 chips (when I select Arduino UNO board) and a ton of others (tiny45, tiny2313). But, when I want to program an ATmega8 chip, it writes it succesfuly, but then the chip runs at 1/16 of the desired speed! (for example a delay(1000) in code takes 16 seconds real-life). I have a 16 MHz crystal oscillator with capacitors connected to the chip, so I thought that the problem is not there but... when I remove the crystal, the chip still runs the same, it still takes 16 seconds. So I assume two possibilities:

1. the crystal is somehow broken, so the chip runs from some internal thing? But I tried multiple crystals, all the same,

OR

2. I am doing something wrong, but I really don't know what...

Does somebody have an idea what may be wrong or how to test it? Or feel free for more details...Thanks

EDIT: In IDE, I am selecting "Arduino NG or older" and then I select ATmega8 as processor. I am uploading the sketches directly, without bootloader.

# Answer
> 1 votes
Ok, I finally solved it, so I will write it here so somebody may learn from it in the future :) The problem was really in the fuses, thanks Chris Stratton. Most of my chips were bought already modified for working with Arduino. But this ATmega 8 had the factory fuses, which were setting it for working with internal 1MHz oscillator. You can read and your write your fuse settings with avrdude, so I set them to arduino default (lfuse 0xDF, hfuse 0xCA, from boards.txt). Now it works perfectly even without uploading bootloader.

---
Tags: isp, frequency
---


# Question
Title: Why can't I connect more than one Arduino Uno + Ethernet Shield to my network?
I'm using 3 Arduino Uno boards with Ethernet shields. Each is connected to my home Internet switch with an Ethernet cable. I assigned a different local IP address to each Arduino and gave each board a different MAC Address.

Each Uno is collecting temperature/humidity for a bedroom in my house. The data is sent to a MySQL Database using PHP/HTML.

They work fine for a while (5 minutes) and then they conflict each other. If I use one Arduino at a time it works fine, but I can't get them to work together.

Any idea how to solve the problem?

# Answer
> 1 votes
It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?

Some things to try:

* Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.
* Run the command `arp -a` (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.
* Try to `ping` the Arudinos. Do they respond?
* Use `WireShark` or `tcpdump` to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).
* Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with `tcpdump`).

---
Tags: arduino-uno, shields, ethernet, networking
---


# Question
Title: Any way to include the text of a file inside a sketch, to make it shorter and neater?
I'm wondering if there is any way to include the text of a file into a sketch by using a single placeholder command, similar to the "#Include" command when using Server Side Includes on .shtml files.

I'm sorry if I'm not wording this correctly. It was hard for me to phrase it and also hard for me to search about it, since the nouns seem so generic.

I understand that some parts of code can be separated out into their own functions, and that those functions could be saved in a different .ino file. But I'm wondering about for the cases that can't be separated out into functions (like for declarations at the beginning of a sketch, or an area in loop() that would require too many variables to be passed to the function).

---

EDIT: I think I should've been more specific: In one example, I have lots of html code being served from the loop() function. The Arduino webserver is serving a complex page that shows about 100 buttons on the webpage. I would like to separate the page-serving code to a separate .ino file and have it opened as a separate tab in the Arduino IDE. That way it's easy for me to open that tab whenever I want to modify the webpage, but also the code for serving the page won't take up so much space in my main file. The code isn't completely html (it has lots of functions and conditionals), so that's why I can't just save it as an external .html file and have it served from that file.

As another example: At the top of my sketch I have lots of defines for wireless signals that need to be sent. They look like this:

```
const unsigned long a1o = 4216115, a1c = 4216124, a2o = 4216259, a2c = 4216268, a3o = 4216579, a3c = 4216588, a4o = 4218115, a4c = 4218124, a5o = 4224259, a5c = 4224268; //remote control 1

```

There are 10 lines of code that look like that, and I never have to modify them because they're all constants. When I'm searching for bugs in my code, I never have to refer to those lines, and they're usually just in my way.

# Answer
> 1 votes
As suggested in comments, you can use `#include` statements to include texts of files into a sketch. For example, suppose files c1.h, c2.h, c3.h, c4.h, and c5.h are in directory `~/sketchbook/tincludes`, along with the file `tincludes.ino`, which is as follows:

```
#include <Streaming.h>
void setup() {
  const long int
#include "c1.h"
#include "c2.h"
#include "c3.h"
#include "c4.h"
#include "c5.h"
 etc=5   ;
  Serial.begin(115200);
  Serial << z1o <<  z1c <<  z2o <<  z2c <<  z3o <<  z3c <<  z4o <<  z4c <<  z5o <<  z5c;
}

```

Further, suppose c1.h ... c5.h each contain one line of code, as follows:

```
==> c1.h <==
  z1o=25829, z1c=9774,

==> c2.h <==
  z2o=7850, z2c=25585,

==> c3.h <==
  z3o=7103, z3c=17981,

==> c4.h <==
  z4o=30827, z4c=24511,

==> c5.h <==
  z5o=4167, z5c=10036,

```

Then the sketch will compile ok, and the sketch-lines with `const long int` through `etc=5 ;` will compile the same as if they were replaced by

```
const long int z1o=25829, z1c=9774, z2o=7850, z2c=25585, z3o=7103,
     z3c=17981, z4o=30827, z4c=24511, z5o=4167, z5c=10036, etc=5;

```

# Answer
> 1 votes
Usually you should not define a variable inside a header file. If, for example, you write

```
// file myvars.h
int var_a = 10;

// file main.ino
#include "myvars.h"

// file another.cpp
#include "myvars.h"

```

the linker will fail, because there are two definitions of the same variable `var_a`.

The correct way to do it is to declare a variable as extern inside the header file, then define them into a cpp (or ino) file just once. I mean

```
// file myvars.h
extern int var_a;

// file myvars.cpp
int var_a = 10;

// file main.ino
#include "myvars.h"

// file another.cpp
#include "myvars.h"

```

This way you will be able to access `var_a` from both main.ino and another.cpp. If you don't want to add another cpp file for the definitions, you just have to provide the definition inside ONE of the ino or cpp files you already have.

So, in your case, just make two more files:

file remote\_control\_1.h:

```
extern const unsigned long a1o, a1c, a2o, a2c, a3o, a3c, a4o, a4c, a5o, a5c;

```

file remote\_control\_1.cpp:

```
#include "remote_control_1.h"
const unsigned long a1o = 4216115;
const unsigned long a1c = 4216124;
const unsigned long a2o = 4216259;
const unsigned long a2c = 4216268;
const unsigned long a3o = 4216579;
const unsigned long a3c = 4216588;
const unsigned long a4o = 4218115;
const unsigned long a4c = 4218124;
const unsigned long a5o = 4224259;
const unsigned long a5c = 4224268;

```

and in your files just write `#include "remote_control_1.h"` to access those variables

---
Tags: compile
---


title: Error uploading on Arduino Mega 2560

text:
# Question
Title: Error uploading on Arduino Mega 2560
I'm completely new to Arduino, I bought a Rampos 1.4 and an Arduino Mega 2560 to build a Prusa Mendel 3D printer.

But when I connect the Arduino via USB to my computer, open the software and click to upload the blink example, it does anything and says Uploading to i/o board.

This happens when I use Arduino 0022 and then when I use Arduino 1.0.5 r2 that is the problem:

```
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

```

I don't know what is happening, and I don't know what to do.

# Answer
Sorry I do not have the reputation to comment. I think your problem can be because you selected the wrong settings for your board. Check in Tools option, and make sure Board, Processor and Port is correct.
> 1 votes

---
Tags: avrdude
---


# Question
Title: sending multiple signals at the same time, with short delay
Is it possible to do something like this: send a HIGH signal to an output pin, after a 0.33s delay arduino sends HIGH signal to another pin, and after another 0.33s delay, arduino sends signal to third pin. There has to be 90 seconds long high signal for each pin, but with 0.33s delay between each other.

Sooo something like this; start of the high signal on left, stop on right side:

```
pin1: 0 ...... 90.00
pin2: 0.33 ... 90.33
pin3: 0.66 ... 90.66

```

Is there a way to solve this?

# Answer
Yes. Read the BlinkWithoutDelay example and triplicate it.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: I want to move the mouse pointer with an Arduino and ultrasonic sensor
I want to move the mouse pointer with an Arduino and ultrasonic sensor but when I compiled it says

> Mouse.h not found

and I don't know what I can do.

Here is my code;

```
 #include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

    //mover el cursor
  int direccionx=moverx();
  int direcciony=movery();

  Mouse.move(direccionx, direcciony,0);
  delay(2);

}

int moverx(){
      distanciaCursor=obtener_distanciaCursor();
  if (distanciaCursor >= 1  || distanciaCursor <= 11){
       x--;
     }
   if (distanciaCursor >= 12 || distanciaCursor <= 24){
       x++;
      }
     return x;
}

int movery(){
      distanciaCursor=obtener_distanciaCursor();
     if (distanciaCursor >= 25 || distanciaCursor <= 37){
       y--;
       }
   if (distanciaCursor >= 38 || distanciaCursor <= 50){
       y++;
      }
  return y;
}

long obtener_distanciaCursor(void)
{
  digitalWrite(trigPinCursor, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPinCursor, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPinCursor, LOW);
 duracionCursor = pulseIn(echoPinCursor, HIGH);

 distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

```

# Answer
> 2 votes
That's because the Uno can't be a mouse. For that you need the Leonardo or something else with a similar "U" style microcontroller.

If you are adventurous, and you have a genuine Arduino, you can reprogram the USB controller chip with new firmware so it thinks it's a mouse, but programming the main MCU is then a real chore.

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


# Question
Title: TCP connection CPU usage, multiple signals?
I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?

My code looks like this:

```
EthernetClient client = server.available();

if(client){
    Serial.println("Connected");
    server.write("Hello\n");

    //check if client is still connected
    while (client.connected()){
        Serial.println("Still there");
        delay(2000);
       //check if client received any data
       if(client.available()){
           //read message from client
     }
  }
} else {
     Serial.println("Nope");
     server.write("Hello\n");
     ???????????? delay(2000); ??????????????
}

```

Thank you for your help.

# Answer
You don't need to do anything. If the else clause has a delay (e.g. of 2 seconds), then it will take up to that long before the arduino accepts the connection.

The "server.write" in the "else" clause doesn't make any sense - who are you sendin it to? server.write will normally write to all available connections.

If there's nothing else you want to do, you might as well retry straight away.

Note that, if you are doing a serial.println statement, and you have no delay, then, while waiting for a connection, it will print the "Nope" message, as fast as it can.
> 2 votes

# Answer
As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.

However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is. This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.

If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.
> 2 votes

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


# Question
Title: Audio Frequency White Noise generation using Arduino Mini Pro
For DIY, how to program Arduino Mini Pro to act as an **Audio Frequency White Noise generator**?

Presumably,

a) using one Digital Output pin

b) feed to a simple passive RC low pass filter to reduce out of band signal

c) feed to a simple class-D IC chip audio amplifier and speaker

d) since it is DIY and noise, lo-fi (not hi-fi) is good enough.

Specific questions,

a) How to program?

b) Wonder if it is better to use to chip act a Pulse Width Modulated 'digital to analogue converter'?

c) How to calculate value for RC filter (assume amplifier has high input impedance)?

Many years ago, I have programmed a hardware sound generator chip as part of a game machine. It has two registers for amplitude and 'frequency' control (band of 'white' noise). It worked very well. I once looked at the output using oscilloscope and it was square wave. I believe that it works, basically, using the above principles. Since I do not have the chip now, I cannot verify it. Now, I would like to duplicate its function using Arduino in software.

# Answer
I don't know that you need all that - just an Arduino and a piezo speaker and a pot if you want to play with the volume.

```
byte speakerPin = 1;

void generateNoise() {
  static unsigned long int reg = 0x12345678; //seed
  unsigned long int newr;
  unsigned char lobit;
  unsigned char b31, b29, b25, b24;
  b31 = (reg & (1L << 31)) >> 31;
  b29 = (reg & (1L << 29)) >> 29;
  b25 = (reg & (1L << 25)) >> 25;
  b24 = (reg & (1L << 24)) >> 24;
  lobit = b31 ^ b29 ^ b25 ^ b24;
  newr = (reg << 1) | lobit;
  reg = newr;
  digitalWrite (speakerPin, reg & 1);
  delayMicroseconds (50);  // Changing this value changes the frequency.
}

```
> 6 votes

# Answer
Mike's answer uses a Fibonacci Linear Feedback Shift Register configuration, but the compactness Galois Linear Feedback Shift Register Configuration could be faster:

```
#define speakerPin 8

unsigned long lastClick;

void setup() {
  // put your setup code here, to run once:
   pinMode(speakerPin,OUTPUT);
   lastClick = micros();
}

/* initialize with any 32 bit non-zero  unsigned long value. */
#define LFSR_INIT  0xfeedfaceUL
/* Choose bits 32, 30, 26, 24 from  http://arduino.stackexchange.com/a/6725/6628
 *  or 32, 22, 2, 1 from
 *  http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
 *  or bits 32, 16, 3,2  or 0x80010006UL per http://users.ece.cmu.edu/~koopman/lfsr/index.html
 *  and http://users.ece.cmu.edu/~koopman/lfsr/32.dat.gz
 *  or generate a one with https://github.com/hayguen/mlpolygen
 */
#define LFSR_MASK  ((unsigned long)( 1UL<<31 | 1UL <<15 | 1UL <<2 | 1UL <<1  ))

unsigned int generateNoise(){
  // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs
   static unsigned long int lfsr = LFSR_INIT;  /* 32 bit init, nonzero */
   /* If the output bit is 1, apply toggle mask.
                                    * The value has 1 at bits corresponding
                                    * to taps, 0 elsewhere. */

   if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
   else         { lfsr >>= 1;                      return(0);}
}

void loop() {
      /* ... */
      if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
        lastClick = micros();
        digitalWrite (speakerPin, generateNoise());
      }

}

```

For a 16 bit implementation (faster, but only a cycle of 2^16) try:

```
#define LFSR_MASK 0x8016
static uint16_t lfsr = LFSR_INIT;  /* 16 bit init, nonzero */

```

Written in a more compact form:

```
#define speakerPin 8

#define LFSR_INIT 0xfeed /* non-zero seed value for generateNoise() */
#define LFSR_MASK 0x8016 /* magic number from http://users.ece.cmu.edu/~koopman/lfsr/ */

unsigned long lastClick;

void setup() {
  // put your setup code here, to run once:
   pinMode(speakerPin,OUTPUT);
   lastClick = micros();
}

unsigned int generateNoise(){
   // Return 1 bit of noise using a Galois Linear Feedback Shift Register
   // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs

   static uint16_t lfsr = LFSR_INIT;

   if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
   else         { lfsr >>= 1;                      return(0);}
}

void loop() {
      /* ... */
      if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
        lastClick = micros();
        digitalWrite (speakerPin, generateNoise());
      }

}

```

For an 8 bit implementation (faster than 32 bit, slightly slower than 16, but only a cycle of 2^8) try:

```
#define LFSR_MASK 0x8e

static byte lfsr = LFSR_INIT;  /* 8 bit init, nonzero */

```

Where the mask constants are from the 8.txt and 16.txt files at http://users.ece.cmu.edu/~koopman/lfsr/index.html

The https://github.com/hayguen/mlpolygen program can search for maximum length feedback polynomials of various bit sizes.
> 5 votes

---
Tags: arduino-pro-mini, audio
---


title: Problem up loading to board

text:
# Question
Title: Problem up loading to board
I'm a newbee to Arduino programming and hoping someone can help me with this. These are the errors when uploading the proceeding sketch. Thanks in advance!

avrdude: stk500\_rcv() : programmer is not responding

avrdude: stk500\_getsync() attempt 10 of 10:not in sync:

Problem uploading to board.

```
//www.RobotLinking.com
//2015.5.7
/************************************************/
#include <Servo.h>
/************************************************/
Servo myservo;//create servo object to control a servo
/************************************************/
void setup()
{
  myservo.attach(9);//attachs the servo on pin 9 to servo object
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/*************************************************/
void loop()
{
  myservo.write(15);//goes to 15 degrees
  delay(1000);//wait for a second
  myservo.write(30);//goes to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//goes to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//goes to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(75);//goes to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(90);//goes to 90 degrees
  delay(1000);//wait for a second
  myservo.write(75);//back to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//back to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//back to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(30);//back to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(15);//back to 15 degrees
  delay(1000);//wait for a second
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/**************************************************/

```

# Answer
> 1 votes
One of the first things to know about Arduinos is that that there are a lot of them – and a lot of tools for programming them. For your problem this means that the most likely reason for the problem you are having is a mismatch between the board your are using and the board your tools are set to upload to. Since you've said you're new to the Arduino I'm assuming that you're using the "official" IDE.

So, here are some things to try:

1. From the IDE main menu, choose **Tools \> Board** and select your board, then
2. Choose **Tools \> Programmer** and select an appropriate programmer for your board. Without knowing what board you're using and how you're connecting to it I can't offer more specific advice. However, if you Google for something like "beginner tutorial " you're likely to find an answer. Or more likely three answers. You'll need to look at the one that matches the OS you're using on your development machine.
3. You may also need to select the port that the Arduino is connected to.

If you've gotten this far and haven't solved the problem, here's what I'd do next:

1. Do a search on the exact error message you're getting – copy it out of the IDE and the paste it into your favorite search engine. Put quotes around the message so that you don't get a bunch of unrelated hits for your search.
2. Search for tutorials on the board and/or IDE vendor site.
3. Work through a tutorial from a good beginner's site. I like the materials the Adafruit folks have developed, but there are lots of good resources out there.
4. Post a question. When you do be sure to:

* Describe your environment: the board you're using, the IDE you're using, the OS you're working on, how the board is connected to the development machine, and the basic settings of the IDE.
    * Explain what you've tried.
    * Describe, or better, include a screen shot or the actual text of the problem that you're seeing (like you did here).
    * For some problems it will also be useful to include the code. If you include the complete code then it is possible that somebody could try to actually reproduce your problem.

---
Tags: servo
---


# Question
Title: UART Software Serial - Syncing two different sensors with start and stop bytes
I'm using 2 SRF02 sensors on the same Arduino board to attempt to have the transmitter only pulse the 40 KHz wave, while the receiver will be only taking a fake range, i.e. picking up a reading based on another transmission.

I've been using SoftwareSerial and need to know how to synchronize the time for the receiver to know when the transmitter sent the data. What I found is that I'm going to have to do this using start and stop bytes to set them in the same cycle.

How can I do this?

This is my current code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd) {
  mySerial.write(address);
  //set the address of SRF02(factory default is 0)
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
  mySerial.write(cmd);
  //send the command to SRF02
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
}
void setup(void) {
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}

void loop(void) {
  unsigned int reading;
  SendCmd(0x00,0x5C);
  //Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
  delay(70);
  //time for SRF02 to measure the range
  SendCmd(0x02,0x57);
  //Get Fake Range at Address 0x02 - receiver
  delay(10);
  //wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
  if(mySerial.available()>=2) {
    //if two bytes were received
    reading = mySerial.read()<<8;
    //receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    reading |= mySerial.read();
    // receive low byte as lower 8 bits
    Serial.print(reading);
    // print the reading
    Serial.println("cm");
    //Serial.println("Time Sent: ");
    //Serial.print(T_sent);
  }
  delay(250);
  // wait a bit since people have to read the output :)
}

```

# Answer
Your code bit

```
SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
delay(70);//time for SRF02 to measure the range
SendCmd(0x02,0x57); //Get Fake Range at Address 0x02 - receiver

```

will send a sound burst, delay 70 ms, then start listening for the burst, which by then will have traveled around 24 meters and probably be no longer audible.

You should instead start the fake range listener immediately after sending the burst. The general idea for one approach is as follows:

* Record time (eg, `t1=micros();`)
* Send burst (eg, `SendCmd(0,0x5C);`)
* Record time (eg, `t2=micros();`)
* Listen for burst (eg, `SendCmd(2,0x58); // Get microseconds`)
* Wait 70 ms, then read microseconds result `t3`
* Compute corrected total microseconds, `tm=t3+t2-t1`
* Convert microseconds to cm

Note use of command 0x58 instead of 0x57 to get microseconds instead of cm. If you used 0x57, instead of adding `t2-t1` to `t3`, you would add `t2-t1` microseconds-converted-to-cm to a cm reading.

The reason for the computation `tm=t3+t2-t1` is that the second command is issued about `t2-t1` microseconds later than the first command, as explained in the next paragraph.

There is an unknown delay `d1` between when `t1` is recorded and when the first SRF02 acts; and there is an unknown delay `d2` between when `t2` is recorded and when the second SRF02 begins listening. The correct amount to add to `t3` is `t2+d2-(t1+d1)`, which is `t2-t1` if `d1` equals `d2`, a more-or-less plausible assumption. If your experiments reveal a constant error, add a small constant offset to compensate.

I doubt you should have the `delayMicroseconds(100);` statements in `SendCmd()`, and would recommend getting the code to work ok, then see if it still works ok when you take them out. The `delay(10);` is unnecessary if you rewrite your 2-character-wait correctly (ie as a `while` rather than an `if`), and the `delay(70);` is unnecessary if you start conversion with command `0x5A`, “Fake Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete” and then properly wait for two characters to arrive, instead of a blind wait followed by a test if they've arrrived.
> 0 votes

# Answer
```
 unsigned int reading;
  unsigned long t1=micros();
  SendCmd(0, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();
  SendCmd(2, 0x58);//return value in microseconds

  delay(70);//time for SRF02 to measure the range
  //SendCmd(0x02,0x5E);
  unsigned long t3 = SendCmd(2,0x5E);
  unsigned long tm = t3+t2-t1;

```

Hey thanks for the input. When I created t3, I get an error saying void value not ignored as ought to be.
> 0 votes

# Answer
This is my updated code based on your suggestions, jwpat, although I did not understand your comment with `delay(70);` not being needed if I start conversion with `(2,0x5A)`.

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
  mySerial.write(cmd);//send the command to SRF02
  //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(0, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x58);//listen for pulse
  //SendCmd(2, 0x5A);
  delay(70);//time for SRF02 to measure the range
  //SendCmd(0x02,0x5E);
  SendCmd(2,0x5E);//Get range

 while(mySerial.available()>=2)//if two bytes were received
  {
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(Dist); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  }
  delay(250); // wait a bit since people have to read the output :)
}

```

After running this code my results keep being the following values regardless of me shifting the distance between the sensors: 72cm
> 0 votes

---
Tags: uart
---


# Question
Title: Digital pin input stays high after receiving a high signal
I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
int thermPin = A5;
int relayPin = 9;
int upButton = 10;
int downButton = 11;
int rawVoltage;
float mv;
float desiredTemp = 20.5;
float currentTemp = 20;
long newSetTime = millis();
long oldSetTime = newSetTime;
long newUpPushTime = millis();
long newDownPushTime = millis();
long oldUpPushTime = millis();
long oldDownPushTime = millis();
int mainDelay = 600;
int flashDelay = 600;
boolean isSetting = true;

void drawCurrentTemp(){
  lcd.setCursor(0, 1);
  lcd.print(currentTemp);
}

void drawDesiredTemp(){
  lcd.setCursor(12, 1);
  lcd.print(desiredTemp);
}

void drawMainScreen(){
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("TEMP");
  lcd.setCursor(12, 0);
  lcd.print("SET");
  drawCurrentTemp();
  drawDesiredTemp();
}
String setString = "SET";
void flashSet(){
  if(newSetTime - oldSetTime > flashDelay) {
    if(setString == "SET"){
      setString = "   ";
    }else{
      setString = "SET";
    }
    lcd.setCursor(12, 0);
    lcd.print(setString);
    oldSetTime = millis();
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(relayPin, OUTPUT);
  pinMode(upButton, INPUT);
  pinMode(downButton, INPUT);
  drawMainScreen();
}

void checkInput(){
  if(digitalRead(upButton) == HIGH){
    newUpPushTime = millis();
  } else {
    oldUpPushTime = millis();
  }
  if(digitalRead(downButton) == HIGH){
    newDownPushTime = millis();
  } else {
    oldDownPushTime = millis();
  }
  long upButtonTimePushed = newUpPushTime - oldUpPushTime;
  long downButtonTimePushed = newDownPushTime - oldDownPushTime;
  if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
    oldDownPushTime = millis();
    oldUpPushTime = millis();
    if(!isSetting){
      isSetting = true;
    } else {
      isSetting = false;
      drawMainScreen();
    }
  }
  if(isSetting){
    if(digitalRead(upButton) == HIGH) {
      desiredTemp +=0.5;
    } else if(digitalRead(downButton) == HIGH) {
      desiredTemp -=0.5;
    }
    drawDesiredTemp();
  }
}

void loop() {
  newSetTime = millis();
  if(isSetting) {
    flashSet();
  }
  checkInput();
  Serial.println(digitalRead(upButton));
}

```

# Answer
> 4 votes
I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.

When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.

So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.

As you mentioned using the code:

```
pinMode(PIN, INPUT_PULLUP);

```

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:

```
pinMode(PIN, INPUT);
digitalWrite(PIN, HIGH);

```

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.

Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):

```
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

```

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.

# Answer
> 1 votes
*Comment by Glen Cashen turned into an answer*:

I just found out about the pullup resistors and how exactly the INPUT works it's all fixed now thanks :)

I just made them:

```
 pinMode(pin, INPUT_PULLUP);

```

---
Tags: arduino-uno, input
---


title: How to check if a pin is set from bank?

text:
# Question
Title: How to check if a pin is set from bank?
How would you go about checking if an input pin has been set using the entire bank? I am thinking that I need to use bit twiddling with a bit mask but I have not used this enough to figure out how to do what I want.

Basically I have the following code:

```
void setup() {
   DDRA = 0x00;
   PORTA = 0xff;
}

void loop(){
   //Check if any pin from Port A has been pressed
   if (PINA & 0xff){
      //do stuff
   }
}

```

But the code above is not working how I expected it to. Has anyone tried to use this approach before? Am I going about this the wrong way? I figured since I was using all 8 pins from one bank, it would be better to check if any of the pins on that bank have been set instead of checking each individual pin. My thinking on this was to prevent any user input from being skipped in case a button press was initiated while the program was running other code. This way I only check if anything in the bank has been set saving time (I think).

# Answer
> 2 votes
The problem is here:

> ```
> //Check if any pin from Port A has been pressed
> if (PINA & 0xff){
>
> ```

Since the pullups are enabled, the default state of the pins is high. To detect a "press", they have to be pulled to ground. This changes the test to:

```
//Check if any pin from Port A has been pressed
if (~PINA) {

```

And for individual pins:

```
//Check if PA3 has been pressed
if (!(PINA & _BV(PA3))) {

```

# Answer
> 0 votes
The simplest way is to use DigitalRead in a loop. It makes your code more portable, and easier to read.

# Answer
> 0 votes
I'm not really an expert in "plain avr code" but I've modified arduino blink and got (almost) a perfect example. Placed a jumper between 5v and pin 8 of arduino and uploaded the following code:

```
void setup() {
  // initialize digital pin 13 as an output.
  DDRB = 0b00100000;

}

// the loop function runs over and over again forever
void loop() {
  if (PINB & 0x1) {
    PORTB =  0b00100000;  // turn the LED on (HIGH is the voltage level)
    delay(500);              // wait for a second
    PORTB = 0;    // turn the LED off by making the voltage LOW
    delay(500);              // wait for a second
  }
}

```

according to following picture pin8 on arduino is PB0 and pin13 is PB5. So using DDRB I set PB5 as output and all others as input. Then in loop I check as you do PINB register and use bitmask to check first pin (the PB0). And it works... well not quite well. For some reason the loop goes a few times more before goes really low. I believe is because I just remove the jumper and do not actually ground pin 8 ( is left float) and maybe the extra loops are discharging some capacitance on that pin 8.

<sub>(source: arduinoexperts.com)</sub>

So, to your specific question, your bitmask is right. This instruction `PORTA = 0xff;` is useless because, as far as I know, this settings are ignored because you set Pin direction in pins of PORTA to input. However, according to that image, atmega328 doesn't have a PORTA. Is that your error or are you using another microcontroller?

**EDIT** Capacitance thing is confirmed, maked it swing between gnd and vcc with a switch and all works fine.

---
Tags: programming, arduino-mega, avr, input
---