# Question
Title: Password code using interrupts and timers on Arduino Uno
I have a group project where we are trying to make a user enter a password that we have pre-selected for them. They enter the password using tactile buttons, and they have 5 tries to enter the password correctly. If they enter the password incorrectly, one of 5 LED's will light up to indicate that they have entered it wrong. If they get it right, one LED will light up.

We are using timers to time out the attempt if the users take too long to enter the entire password, or if they take too long between pressing buttons. Also, if they use all 5 tries, we are trying to make the LED's that were on turn off one by one.

Right now the code doesn't get past Serial.print("done").

This is our code:

```
int input_pin_blue = 5;
int input_pin_yellow = 6;
volatile int state_button_red = LOW;
volatile int state_button_blue = LOW;
volatile int state_button_yellow = LOW;
int num_wrong = 0;
double time_between_buttons = 0;
double time_since_first_button = 0;
const int max_time_between_buttons = 10000;
const int max_time_since_first_button = 30000;
int reset = 4;
void setup() {
    pinMode(input_pin_blue, INPUT);
    pinMode(input_pin_yellow, INPUT);
    pinMode(4, INPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);
    attachInterrupt(0, handler_red, CHANGE);
    attachInterrupt(1, handler_blue_yellow, CHANGE);
    Serial.begin(9600);
}
void loop() {
    Serial.print("bhi"); //wait for button press

    for (num_wrong = 0; num_wrong < 5; num_wrong++) {
        Serial.print("blah"); //wait for button press

        while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW) {
            Serial.print("waiting"); //wait for button press
        }

        Serial.print("DOne");

        if (state_button_red == LOW) {                  //check if first button pressed is incorrect
            digitalWrite(num_wrong + 8, HIGH);
        } else if (state_button_red == HIGH) {
            time_between_buttons = millis();
            time_since_first_button = millis();

            while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                    && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                //wait for button press
            }

            if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if second button pressed is incorrect or time has run out
            {
                digitalWrite(num_wrong + 8, HIGH);
            } else if (state_button_yellow == HIGH) {
                time_between_buttons = millis();

                while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                        && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                    //wait for button press
                }

                if (state_button_blue == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if third button pressed is incorrect or time has run out
                {
                    digitalWrite(num_wrong + 8, HIGH);
                } else if (state_button_blue == HIGH) {
                    time_between_buttons = millis();

                    while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                            && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                        //wait for button press
                    }

                    if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if fourth(last) button pressed is incorrect or time has run out
                    {
                        digitalWrite(num_wrong + 8, HIGH);
                    } else if (state_button_yellow == HIGH) {
                        digitalWrite(13, HIGH);
                        num_wrong = 10;
                    }
                }
            }
        }
    }

    if (num_wrong == 10) {
        while (digitalRead(reset) == LOW) {
            //wait for reset
        }
    } else if (num_wrong == 5) {
        while (digitalRead(reset) == LOW) {
            digitalWrite(8, LOW);
            delay(100);
            digitalWrite(8, HIGH);
            digitalWrite(9, LOW);
            delay(100);
            digitalWrite(9, HIGH);
            digitalWrite(10, LOW);
            delay(100);
            digitalWrite(10, HIGH);
            digitalWrite(11, LOW);
            delay(100);
            digitalWrite(11, HIGH);
            digitalWrite(12, LOW);
            delay(100);
            digitalWrite(12, HIGH);
        }
    }

    if (digitalRead(reset) == HIGH) {
        digitalWrite(13, LOW);
        delay(100);
        digitalWrite(12, LOW);
        delay(100);
        digitalWrite(11, LOW);
        delay(100);
        digitalWrite(10, LOW);
        delay(100);
        digitalWrite(9, LOW);
        delay(100);
        digitalWrite(8, LOW);
    }
}
// interrupt handler function
void handler_red() {
    state_button_red = !state_button_red;
}
void handler_blue_yellow() {
    if (digitalRead(input_pin_blue) == HIGH) {
        state_button_blue = !state_button_blue;
    }

    if (digitalRead(input_pin_yellow) == HIGH) {
        state_button_yellow = !state_button_yellow;
    }
}

```

# Answer
```
int input_pin_blue = 5;
int input_pin_yellow = 6;
volatile int state_button_red = LOW;
volatile int state_button_blue = LOW;
volatile int state_button_yellow = LOW;
...
pinMode(input_pin_blue, INPUT);
pinMode(input_pin_yellow, INPUT);
...
attachInterrupt(0, handler_red, CHANGE);
attachInterrupt(1, handler_blue_yellow, CHANGE);

// interrupt handler function
void handler_red() {
    state_button_red = !state_button_red;
}
void handler_blue_yellow() {
    if (digitalRead(input_pin_blue) == HIGH) {
        state_button_blue = !state_button_blue;
    }

    if (digitalRead(input_pin_yellow) == HIGH) {
        state_button_yellow = !state_button_yellow;
    }
}

```

On the Uno external interrupt 0 is pin D2 not D5, and interrupt 1 is pin D3, not D6.

Hence you are not testing the correct pins.

Also I would use INPUT\_PULLUP instead of INPUT mode for those pins, unless you have external pull-up or pull-down resistors on them.
> 0 votes

---
Tags: arduino-uno, interrupt, timers
---


# Question
Title: WizNet chip on Ethernet Shield oddly hot
I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around **110-120ºF** (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?

# Answer
According to the WizNet forums this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)
> 1 votes

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


# Question
Title: Is there an equivalent to Grbl for Excellon PCB drilling?
For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?

# Answer
> 1 votes
No, there is no existing Arduino library to parse Excellon format drill files in order to control a drilling machine. Looking at the specification it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.

---
Tags: mechanical
---


title: Arduino Xbee AT command mode

text:
# Question
Title: Arduino Xbee AT command mode
I have 2 Xbee Series 2 modules. One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx\>\>Tx and Tx\>\>Rx.

The xbee is configured AT mode Coordinator.

I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.

Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?

# Answer
> 1 votes
Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code (source):

```
void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

```

Basically what this does is it takes the data it receives from the USB port via `Serial` and transmits it to `Serial1` and then also reads from the UART port via `Serial1` and transmits it back to the computer via `Serial`. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.

# Answer
> 0 votes
Not if you have it connected to pins 0 and 1, no. You should not use those pins for anything unless you absolutely have to, since they are what are used for communication with the PC. You can't do both communication with the PC and with the XBee using the same pins.

You should ensure that the XBee is connected to one of the other serial ports on the Mega and then write a sketch that passes the data through from one port to the other as needed so you can view it on the serial monitor.

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


# Question
Title: Arduino web server: redirect to mobile site on SD card?
Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?

(My arduino server is already successfully serving pages on http://192.168.0.180, and successfully processes GET requests).

I was thinking of having this javascript code on the main page that's served by the arduino:

```
<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://192.168.0.180?mobile";
  }
  //-->
</script>

```

My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.

Do you think this is possible, and how would you recommend to do it?

# Answer
> 2 votes
Yes, it is perfectly possible. you just have to look at the right bits.

Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.

All browsers follow the same rules - if they didn't they wouldn't work on the web. Two of the rules you are interested in are:

* Browsers identify themselves along with their OS.
* Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of *headers*. These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical. For instance, the request to show this page from Firefox on Linux has these headers:

```
Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive

```

The header of note is the *User-Agent:* one. That tells the web server that I am using firefox from a 64-bit Intel Linux computer. If I were to do it from my Android phone it would tell you it's from Chrome on Android.

By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.

Now the second bullet above - browsers respond to the *response* code in different ways. Normally you send the response code `200` which means "I accepted your request and here is the page you asked for". Another response code that is useful is code `301` which means "The page you asked for isn't at this address any more - here is the new address you should go to instead". That will then cause the browser to go to the newly provided address instead.

So instead of responding with

```
HTTP/1.0 200 OK
Content-type: text/html

<web page content here>

```

You could instead respond with:

```
HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile

```

And the browser will *redirect* to the new address you give in the *Location:* response header.

The full list of response codes is here: https://en.wikipedia.org/wiki/List\_of\_HTTP\_status\_codes

If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies. After all, it's entirely down to you what is sent as the content of the page. Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.

---
Tags: ethernet, web-server
---


# Question
Title: Cannot pass objects of non-trivially-copyable type 'class String' through '...'
I'm attempting to send data from a serial connection to a GSM modem, but having problems. The string from rx looks like this:

```
1.0 2.0 3.0 4.0

```

Here's my code to replace the spaces and then I just want to pass the whole string on, regardless of what's inside (there could be negative values too).

```
                data_current[data_index++] = ',';
                char received = bike_port.read(); //bike
                char test[32];
                inData += received;
                  if (received == '\n')
                  {
                      String nospace = inData;
                      nospace.replace("\t",",");
                      debug_println("Data: ");
                      debug_println(nospace);
                      inData = ""; // Clear recieved buffer
                      delay(1000);
                  }
                  sprintf(test,32,"%d,%d,%d,%d",(String) nospace);
                //strtok(received, tmp);
                for (int i=0; i<strlen(test); i++) {
                  data_current[data_index++] = test[i];
                }

```

I have also tried

```
sprintf(test,32,"%ld,(String) nospace);

```

What I get now is this error

```
cannot pass objects of non-trivially-copyable type 'class String' through '...'

```

Without the sprintf line I can successfully echo the string to debug\_println (Serial Monitor). What am I doing wrong?

# Answer
The basic problem here is that you're trying to pass a `String` object to `sprintf()`. That isn't possible because `String` is a C++ class, and `sprintf()` is a C variadic function. The only way to pass a string to it is as a `char *`.

The rest of your call to `sprintf()` doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use `sprintf()` if you want to format several values into a string.

As you've suggested in the comments, adding the contents of `nospace` to `data_current` character-at-a-time would be the sensible approach. You could do it something like this:

```
for (int i = 0; i < nospace.length(); ++i) {
    data_current[data_index++] = nospace[i];
}

```

Note that `strlen()` won't work on `nospace` because it's a `String` object not a `char` array.

This is all assuming that there's enough space in `data_current` though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

---

**Update:**
As an alternative, you could use `memcpy()` to do a block transfer:

```
memcpy(data_current + data_index, nospace.c_str(), nospace.length());
data_index += nospace.length();

```

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)
> 1 votes

# Answer
Let me get this straight. You want to change:

```
1.0 2.0 3.0 4.0

```

to:

```
1.0,2.0,3.0,4.0

```

Right?

How about:

```
  char indata[32] = "1.0 2.0 3.0 4.0";

  int len = strlen (indata);
  for (int i = 0; i < len; i++)
    if (isspace (indata [i]))
      indata [i] = ',';

  Serial.println (indata);   // prints: 1.0,2.0,3.0,4.0

```

---

> Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike\_port.read()), than I get error ...

In that case, as Jake C said, modify the incoming byte like this:

```
 char received = bike_port.read(); //bike
 if (isspace (received))
   received = ',';

```
> 0 votes

# Answer
As a companion to Nick Gammon's excellent answer, here is a streaming version of that (assuming this is coming in one serial port and out another to the modem).

```
if (Serial.available()) {
  int inByte = Serial.read();
  if (inByte == ' ')
    Serial1.write(',');
  else
    Serial1.write(inByte);
}

```
> 0 votes

---
Tags: serial, communication
---


# Question
Title: Can I use analogRead to read a digital pin?
analogRead(nGPIO\_max + lockerVal) were nGPIO\_max(maximum digital pins in Arduino Uno is 13) and lockerval is 2. Which pin is it reading?

# Answer
> 16 votes
To answer the question in the title: No, you cannot use `analogRead()` to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).

If you call something equating to `analogRead(15)` on an Uno, then it should read pin `A1`. You can see the pin assignments in the board-specific versions of `pins_arduino.h` (shipped with the IDE):

```
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

```

Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like `analogRead(A1)`.

It's worth noting that the Arduino library fudges the pin numbers slightly. Calling `analogRead(1)` has the same result as calling `analogRead(A1)`. That means that even if you *tried* to use `analogRead()` on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.

---
Tags: arduino-uno, analogread
---


# Question
Title: How to input keyboard commands using Arduino Mega 2560?
I have an Arduino Mega 2560 connected to a Windows 8 laptop. I want to program it to send keystrokes to the attached computer (when a pin's digital read goes from HIGH to LOW.)

The trouble is, I cannot find any way to program my Arduino Mega to send keystrokes.

The supposedly "core" Keyboard and Mouse libraries only support 32u4 boards, and other libraries that give the Arduino keystroke functionality are out of sight. When I googled the issue, I found no question or explanation of how to send keystrokes on the Arduino Mega. When I searched further, I thought the V-USB library would be a potential workaround, but the library throws numerous errors when imported into an Arduino sketch (even on the 1.0.0 IDE it was designed for.)

After hours of searching, two final workarounds seem to have popped up:

1. Some method to run a Python code to send keystrokes to the PC, and then connect the Arduino code to Python. (I don't know Python...)
2. Use some program called Gobetwino, which runs between the Arduino and PC, to convert Serial commands into keystrokes somehow. (Pressing and releasing a key can't be simulated very well by repeatedly sending Serial commands, I think.)

Both are very unideal, very tedious, and are equally likely to just not work. I have spent hours on this.

Does anyone have any suggestions to get me out of this hell? Libraries, workarounds, anything?

(Feel free to PM me questions for clarification.)

# Answer
You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.

Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.

The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.

Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.

It all depends on what your project requires.
> 0 votes

---
Tags: programming, arduino-mega, pins, communication, keyboard
---


title: Arduino communication with ROS via UART

text:
# Question
Title: Arduino communication with ROS via UART
I am trying to program an Arduino Mega(Crius) from a Minnowboard Max A2 via an UART (Hardware Flow Control Off) interface.

I can successfully communicate with the ROS (robot Operating System) on the Ubuntu 12.04 installed on the Minnowboard Max via the UART1 port available on the Minnow Board.

The Crius UART has a FTDi compatible port with a DTR pin. Unfortunately the MinnowBoard does not have any DTR pin to communicate with the Arduino (Only CTS/RTS pins for 1 of the 3 UART ports). Thus I cannot upload any sketch to the Arduino via the Minnowboard over the UART. I must always connect to the onboard FTDi-USB chip of the crius and upload the sketch.

Is there any workaround to upload the sketch to the Arduino via the UART from the Minnowboard ?

# Answer
You can use any GPIO you like on the Minnow to trigger a reset of the Mega to initiate the bootloader. The Yún does just that to program the on-board ATMega chip through a script they have chosen to call "run-avrdude":

```
#!/bin/sh

echo 1 > /sys/class/gpio/gpio21/value
avrdude  -q -q -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U efuse:r:/tmp/efuse:d
read EFUSE < /tmp/efuse
rm -f /tmp/efuse
if [ "x$EFUSE" = "x203" ] # 203 = 0xCB
then
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m -Uflash:w:$1:i $2
else
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xFB:m -Uflash:w:$1:i $2
fi
echo 0 > /sys/class/gpio/gpio21/value

```

You could do something similar to initiate the bootloader on the remote board - connect any GPIO pin to the RESET line of your Mega board, then perform the following logical actions:

1. Set the GPIO to OUTPUT
2. Set the GPIO to LOW
3. Delay a few ms
4. Set the GPIO to INPUT
5. Run avrdude.

By setting the GPIO to INPUT you are emulating an open-drain output. If you were just to drive the GPIO HIGH it would hold the RESET pin HIGH and you wouldn't be able to use the USB interface, nor the RESET button. By setting it to INPUT it is then effectively disconnected from the RESET pin so won't interfere.

The Yún again has a script that works in that way, "reset-mcu":

```
#!/bin/sh

echo 18 > /sys/class/gpio/export
echo "high" > /sys/class/gpio/gpio18/direction
echo 1 > /sys/class/gpio/gpio18/value
echo 0 > /sys/class/gpio/gpio18/value
echo 18 > /sys/class/gpio/unexport

```

I have a similar setup to you but using a BeagleBone Black and a PONTECH Quick240 PIC32 based controller. In my IDE UECIDE I set up a special board definition with the following programmer added to it which performs the manual reset through GPIO and runs the upload program (pic32prog) all in one operation:

```
upload.local.name=Local upload
upload.local.using=script
upload.local.script.0=__builtin_bullet::Entering programming mode...
upload.local.script.1=__builtin_gpio::7::low
upload.local.script.2=__builtin_delay::100
upload.local.script.3=__builtin_gpio::20::low
upload.local.script.4=__builtin_delay::100
upload.local.script.5=__builtin_gpio::20::hiz
upload.local.script.6=__builtin_delay::100
upload.local.script.7=__builtin_gpio::7::hiz
upload.local.script.8=__builtin_delay::100
upload.local.script.9=__builtin_bullet::Uploading sketch...
upload.local.script.10=${core.root}/tools/linux_arm/pic32prog::-S::-d::${port}::-B::${upload.maxbaud}::-p::${build.path}/${filename}.hex
upload.local.script.11=__builtin_bullet::Resetting board...
upload.local.script.12=__builtin_delay::100
upload.local.script.13=__builtin_gpio::20::low
upload.local.script.14=__builtin_delay::100
upload.local.script.15=__builtin_gpio::20::hiz

sketch.upload=local

```

That one is a little different in that you have to hold a second GPIO LOW while you reset the board to initiate the bootloader, hence the two GPIOs in use there.
> 1 votes

---
Tags: arduino-mega, bootloader, communication, uart
---


title: Arduino Web Server and Relay Module

text:
# Question
Title: Arduino Web Server and Relay Module
I am working on a web server project for work. I have a web server setup with an Arduino Meg2560 with Ethernet. I also have a 16 relay board connected to Ethernet with its own IP. I wanted to see if there is a way I can make calls to the relay board via IP from the Arduino Webserver. For example Relay 1 on the relay board can be turned on by typing 192.168.1.4/30000/00 but this opens the web GUI on the board. I need to do the same thing but without opening the webpage or web GUI.

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

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 177); // IP address
    EthernetServer server(80);  // Server Port 80

    void setup()
    {
      Ethernet.begin(mac, ip);
      server.begin();
    }

    void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                client.println();
                // send web page
                client.println("<!DOCTYPE html>");
                client.println("<html>");
                client.println("<head>");
                client.println("<title>Arduino Web Page</title>");
                client.println("</head>");
                client.println("<body>");
                client.println("<h1>Hello from Arduino!</h1>");
                client.println("<p>A web page from the Arduino server</p>");
                client.println("</body>");
                client.println("</html>");
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)

```

}

# Answer
> 0 votes
Documentation on the controller you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.

> http://192.168.1.4/30000/00 : Relay-01 OFF
>
> http://192.168.1.4/30000/01 : Relay-01 ON
>
> http://192.168.1.4/30000/02 : Relay-02 OFF
>
> http://192.168.1.4/30000/03 : Relay-02 ON
>
> http://192.168.1.4/30000/04 : Relay-03 OFF
>
> http://192.168.1.4/30000/05 : Relay-03 ON
>
> http://192.168.1.4/30000/14 : Relay-8 OFF
>
> http://192.168.1.4/30000/15 : Relay-8 ON
>
> http://192.168.1.4/30000/41 : Enter
>
> http://192.168.1.4/30000/40 : Exit
>
> http://192.168.1.4/30000/42 : Next Page
>
> http://192.168.1.4/30000/43 : Next Page

For example If I wanted to turn off relay 3, I would simple make a GET request to `http://192.168.1.4/30000/04` and close the connection. Example code:

```
IPAddress server(192,168,1,4);
EthernetClient client;
client.connect(server, 80);
client.println("GET /30000/04 HTTP/1.1");
client.println("Connection: close");
client.println();
client.stop();

```

---
Tags: programming, arduino-mega, shields
---


title: PWM timers, channels and pins

text:
# Question
Title: PWM timers, channels and pins
I've got this code from the MultiWii project, which is relevant to the hardware, ATmega32u4, I have. It is part of a function called `initOutput()`.

In the comment it says "connect pin 6", which is the bit of that which specifies pin 6 as I would like to change it to another pin, specifically A0.

```
// Enhanced PWM mode
TCCR4E |= (1<<ENHC4);

// Prescaler to 16
TCCR4B &= ~(1<<CS41);
TCCR4B |= (1<<CS42) | (1<<CS40);

// Phase and frequency correct mode and top to 1023, but
// with enhanced PWM mode we have 2047.
TCCR4D |= (1<<WGM40);
TC4H = 0x3;
OCR4C = 0xFF;

// Connect pin 6 to timer 4 channel D
TCCR4C |= (1<<COM4D1) | (1<<PWM4D);

```

# Answer
> 1 votes
It's the `(1<<COM4D1)` that enables pin 6, or more specifically **OC4D** for timer output. You cannot use A0 instead, since there is no output compare capability on that pin; only pins 13, 5, 10, 9, 6, and 12 can be connected to timer 4. See the datasheet for details.

---
Tags: pwm, timers, avr
---


title: Using PROGMEM to store array of structs

text:
# Question
Title: Using PROGMEM to store array of structs
I am hitting the limits of my arduino's SRAM and found that SRAM usage can be reduced by storing static stuff in flash memory instead of SRAM.

My project can (optionally) be built with an included SimulatorClass. I use this to 'playback' data at home which I gathered during real-life testing of my project. My project is based on photoelectric sensors, and it's timing-critical, so all timekeeping is done using `micros()`, which returns `unsigned long` datatype.

To simulate these photoelectric sensor triggers, I need an array containing a `struct` of 3 variables each: unsigned int \_iDataPos;

```
   struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   };

```

So one these structs is 6 bytes long in my counting (2x `uint8_t` = 2 bytes, `unsigned long` = 4 bytes). A typical set of simulator records I need to use is about 25-30 records long, so worst case scenario the simulator array is 180 bytes in size.

I initialize these arrays like so:

```
SimulatorRecord SimulatorQueue[28] = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
      , { 2, 197732, 0 }
      , { 1, 4675580, 1 }
      , { 2, 4692252, 1 }
      , { 2, 4830180, 0 }
      , { 1, 4849032, 0 }
      , { 2, 9058416, 1 }
      , { 1, 9074780, 1 }
      , { 1, 9215868, 0 }
      , { 2, 9234968, 0 }
      , { 2, 13497276, 1 }
      , { 2, 13500924, 0 }
      , { 2, 13502728, 1 }
      , { 1, 13514992, 1 }
      , { 1, 13668000, 0 }
      , { 1, 13669344, 1 }
      , { 1, 13681828, 0 }
      , { 2, 13701464, 0 }
      , { 2, 18028788, 1 }
      , { 2, 18034252, 0 }
      , { 2, 18036540, 1 }
      , { 1, 18046892, 1 }
      , { 2, 18160312, 0 }
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

```

In my simulator code I then loop through these arrays like so:

```
   unsigned int _iDataPos = 0;
   SimulatorRecord PendingRecord = SimulatorQueue[_iDataPos];

   //main simulator loop
   if (PendingRecord.lTriggerTime <= lRaceElapsedTime)
   {
      //simulate signal
      digitalWrite(PendingRecord.iSensorNumber, PendingRecord.iState);

      //And increase pending record
      _iDataPos++;
      PendingRecord = SimulatorQueue[_iDataPos];
   }

```

Now I've been reading various `PROGMEM` tutorials, and storing the `SimulatorQueue` array in flash seems to be piece of cake, just change

```
SimulatorRecord SimulatorQueue[28]

```

to

```
const PROGMEM SimulatorRecord SimulatorQueue[28]

```

But for the life of me I can't find out how I should change the copying of each array item to the `PendingRecord` variable, as my `iDataPos` counter increases.

Edit: I should have mentioned that this simulator class and all it's member functions & variables reside in a seperate \*.cpp and \*.h file. I alreadt found out that since i'm initializing the `SimulatorQueue` array in the class itself, and not in the main \*.ino file, I should do it like so:

```
constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {<structs go in here>};

```

Edit2: Sample code which reproduces the problem when the simulator array is available here: http://1drv.ms/1TRwiIB

# Answer
An easy way of accessing any type of data in PROGMEM is to use this small library:

**PROGMEM\_readAnything.h**

```
#include <Arduino.h>  // for type definitions

template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
  {
  memcpy_P (&dest, sce, sizeof (T));
  }

template <typename T> T PROGMEM_getAnything (const T * sce)
  {
  static T temp;
  memcpy_P (&temp, sce, sizeof (T));
  return temp;
  }

```

You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called `PROGMEM_readAnything` and put that folder inside the `libraries` folder, which is inside your sketchbook folder.

That lets you copy from the memory in PROGMEM (using memcpy\_P) into RAM. The template is used to work out how many bytes to copy.

---

Example, using your structure:

```
#include <PROGMEM_readAnything.h>

struct SimulatorRecord
{
  uint8_t iSensorNumber;
  unsigned long lTriggerTime;
  uint8_t iState;
};

const SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
 //    ...   omitted for brevity
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

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

  for (int i = 0; i < ArraySize (SimulatorQueue); i++)
    {
    SimulatorRecord thisItem;
    PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
    Serial.print (i);
    Serial.print (F(" = "));
    Serial.print (thisItem.iSensorNumber);
    Serial.print (F(" / "));
    Serial.print (thisItem.lTriggerTime);
    Serial.print (F(" / "));
    Serial.print (thisItem.iState);
    Serial.println ();
    }  // end of for loop
}  // end of setup

void loop ()
{
}  // end of loop

```

I found that it decreased RAM usage by 166 bytes, which is almost `28 * 6` (a couple of bytes must have been used by something).

---

### Reference

Putting constant data into program memory (PROGMEM)

---

### Putting PROGMEM into a class

In response to some comments below, this explains how to put the constants into a class.

Alex originally had:

```
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

   constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
   //    ...   omitted for brevity
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

   SimulatorRecord PendingRecord;
};

```

Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:

```
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

  static const SimulatorRecord SimulatorQueue[28] PROGMEM ;

  SimulatorRecord PendingRecord;
};

```

Now in your main class file (Simulator.cpp in your case):

```
 const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
    { 1, 41708, 1 }
    , { 2, 60692, 1 }
   //    ...   omitted for brevity
    , { 1, 20454580, 1 }
    , { 1, 20456368, 0 }
   };

```

That now compiles OK.
> 6 votes

# Answer
Using it with heterogeneous types is trickier, since it has to be copied by hand instead of using one of the `pgm_read_*()` macros.

```
SimulatorRecord PendingRecord;
memcpy_P(&PendingRecord, &SimulatorQueue[_iDataPos], sizeof(PendingRecord));

```
> 2 votes

---
Tags: flash, progmem, struct
---


# Question
Title: Arduino uint8_t to String or char- retrieve from usb device
My code returns uint8\_t format when is cast to char and Display on LCD it works fine but I want to get that scanned code for further processing. not only to display on LCD 16x2 , but it returns some strange symbols. Any Idea?

```
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

class KbdRptParser : public KeyboardReportParser
{
  void PrintKey(uint8_t mod, uint8_t key);
protected:
  virtual void OnKeyDown  (uint8_t mod, uint8_t key);
  virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
    uint8_t c = OemToAscii(mod, key);

    if (c)
        OnKeyPressed(c);
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0;      //watchdog
static uint8_t current_cursor = 0;  //tracks current cursor position

    if( millis() > next_time ) {
      lcd.clear();
      current_cursor = 0;
      delay( 5 );  //LCD-specific
      lcd.setCursor( 0,0 );
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
      lcd.setCursor( 0,1 );
    }
  char keys=(char) key;
    Serial.println(keys);
// char add =keys.indexOf(5)+keys.indexOf(6)+keys.indexOf(7)+keys.indexOf(8);
    Serial.println(keys);
    lcd.print(keys);
};

KbdRptParser Prs;

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

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay( 200 );

    Hid.SetReportParser(0, (HIDReportParser*)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay( 200 );
}

void loop()
{
  Usb.Task();
}

```

# Answer
> 0 votes
A unit8\_t is an 8 bit unsigned integer - it can have any value between 0 and 255, and can be compared to any numeric value in that range.

You can do "further processing" on the received uint8\_t value whether it is a printable ASCII value or not.

# Answer
> 0 votes
If the symbols look like Japanese, then probably bit 7 of your characters is set to 1. The upper 128 characters are reserved for Katakana in many LCDs. So, if you are sure the characters are correct, you may have to be AND them with 0x7F to assure they are in the right half of the character encoder.

Do check the requirements of your LCD, and the code in the library to control the display. In one occasion, you added a 5 ms delay, and in other clear(), you didn't. One of the annoyances of LCD displays is that you have to be careful with those delay, else you can land the controller in a strange mode,

---
Tags: c++, lcd
---


title: Arduino UNO with CD4510 Counter

text:
# Question
Title: Arduino UNO with CD4510 Counter
I am new in Arduino but I have experience in electronics.

I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.

# Answer
> 0 votes
I can use CD4510 to make a countdown timer, I just need to connect CLOCK INPUT to the Digital IO pins located in the arduino microcontroller and use pulse with modulation (pwm) for the code

# Answer
> 0 votes
The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.

You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?

---
Tags: arduino-uno, programming, timers, display
---


title: QRPrint library characters limit

text:
# Question
Title: QRPrint library characters limit
I am trying to use this library to print QR codes using Arduino. There is a limit on the number of characters allowed in the string to be printed.

```
printQR("This is the string to be QR encoded !!! Tralalala. Some other random characters !!!");

```

When I scan the generated QR code, the string seems to be truncated. Did anyone run into this before? Or is there any way to get around this issue by raising the number of characters allowed in the string?

Thank you.

# Answer
> 1 votes
The code in the library truncates to 47 characters for some reason:

```
void printQR(String message) {

...

  // create QR code
  message.toCharArray((char *)strinbuf,47);
  qrencode();

```

The buffer is actually 116 bytes, oddly.

```
unsigned char strinbuf[116];

```

It's a little unclear why the limit of 47, or 116, was chosen.

You could try changing that line in qrprint.cpp to increase the number from 47 to at least 115.

---

*Edit*

After reading some of the comments, I doubt that will help. The QR code looks like it is generated into an internal array, which would have to have some size limits due to the amount of RAM available. The current array size is:

```
unsigned char qrframe[600];

```

That is already 1/3 of the available memory on a Uno.

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


# Question
Title: Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno?
I want to connect the *Arduino TFT LCD 1.77" screen* to an *Arduino Leonardo*. Acording to this tutorial I should connect some pins on LCD screen to *ICSP pins* on Leonardo but I don't have equipment to do it. Can I just connect LCD screen to Leonardo in the way it't recommanded for an *Arduino Uno* (same tutorial above) using only digital and power pins. And then use sketches for Uno. Will it work?

Also, is it safe for LCD screen?

# Answer
I think it could work, but not easily. I.e. you would need to tweak the code and anyway you will end up with really low performance.

This is the reason:

> SPI: on the ICSP header. These pins support SPI communication using the SPI library. Note that the SPI pins are not connected to any of the digital I/O pins as they are on the Uno, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Leonardo's 6-pin ICSP header, the shield will not work.

Source: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

> The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster when drawing. If you plan on using the SD card on the TFT module, you must use hardware SPI. All the examples are written for hardware SPI use.

Source: https://www.arduino.cc/en/Guide/TFT#toc4

In the end I think it would be better to get the equipment needed...

Edit: You can try with this constructor:

> When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.

```
#define SCLK 4
#define MOSI 5
#define CS   6
#define DC   7
#define RESET 8

TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

```

Source: https://www.arduino.cc/en/Reference/TFTLibrary
> 1 votes

# Answer
You can hook up the "Adafruit\_ST7735" or from what i later learned after getting my Esplora. Thats when i had my adruino-epiphany. Okay so IF your wondering why im including this super rad Controller shaped arduino, the answer is, its a leonardo. well its just a different flavor of the Atmega32u4 whis is the chip that made ext serial programmers kinda obsolete and makes the uno and megas so unique as well. so with that being said the Esplora has a native language when refering back the tft libraries, but its not too far from a simple (ctrl+F) and replace Esplora references with actual defines and references. and in this case the Leonardo would need to have the icsp header used by the corresponding pins on the display (for this instance of using an SPI connection with the serial display we will not swap the Miso and Mosi like we would a nother instance.just connect miso to miso and mosi to mosi i usually plug up the whole icsp header and then that wwill leave you with the two pins you MUST DEFINE to make it work which would be :

```
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

```

// must be an output //#define sclk 13 // for MEGAs use pin 52 //#define mosi 11 // for MEGAs use pin 51

# define cs 10 // for MEGAs you probably want this to be pin 53

# define dc 9

# define rst 8 // you can also connect this to the Arduino reset

```
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

```

// must be an output //#define sclk 13 // for MEGAs use pin 52 //#define mosi 11 // for MEGAs use pin 51

# define cs 10 // for MEGAs you probably want this to be pin 53

# define dc 9

# define rst 8 // you can also connect this to the Arduino reset

// Color definitions

# define BLACK 0x0000

# define BLUE 0x001F

# define RED 0xF800

# define GREEN 0x07E0

# define CYAN 0x07FF

# define MAGENTA 0xF81F

# define YELLOW 0xFFE0

# define WHITE 0xFFFF

# include

# include

// Option 1: use any pins but a little slower //ST7735 tft = ST7735(cs, dc, mosi, sclk, rst);

// Option 2: must use the hardware SPI pins // (for UNO thats sclk = 13 and sid = 11) and pin 10 must be // an output. This is much faster - also required if you want // to use the microSD card (see the image drawing example) ST7735 tft = ST7735(cs, dc, rst); float p = 3.141592; // value for pi int tft\_width = 128; int tft\_height = 160; int x1 = 60; int y1 = 60; int x2 = 20; int y2 = 80; int ballx = 60; int bally = 60; int deltay = 1; int deltax = 1;

int ball\_speed = 24;

int left\_score = 4; int right\_score = 4;

int background\_color = 0x00; void setup(void) { tft.initR(); // initialize a ST7735R chip

tft.writecommand(ST7735\_DISPON); tft.fillScreen(background\_color); delay(700); for(int i = 0; i \< 9; i++){ pinMode(i,OUTPUT); } for(int i = 0; i \< 9; i++){ digitalWrite(i,HIGH); } delay(500);

}

void loop() {
for(int i = 0; i \< left\_score; i++){ digitalWrite(i,HIGH); } for(int i = 0; i \< right\_score; i++){ digitalWrite(i+4,HIGH); } int cur\_r = random(20,32); int cur\_g = random(55,64); int cur\_b = random(10,32); int color = cur\_r | (cur\_g \<\< 5) | (cur\_b \<\< 11); int radius = 4; draw\_paddles(); draw\_ball(color); delay(ball\_speed); } void draw\_input\_text(){ int cur\_x2 = analogRead(2); int cur\_y2 = analogRead(3);
String xs = String(cur\_x2); String ys = String(cur\_y2); char cx\[4\]; cx\[0\] = xs.charAt(0); cx\[1\] = xs.charAt(1); cx\[2\] = xs.charAt(2); cx\[3\] =0; char cy\[4\]; cy\[0\] = ys.charAt(0); cy\[1\] = ys.charAt(1); cy\[2\] = ys.charAt(2); cy\[3\] =0; tft.fillRect(10,20,40,40,background\_color); tft.drawString(12,22,cx ,YELLOW); tft.drawString(12,40,cy ,YELLOW); } void draw\_paddles(){ int cur\_x = analogRead(0); int cur\_y = analogRead(1);
int hval = 620; int lval = 350;

if ( y1 \< tft\_height - 20 && cur\_y \> hval) y1++; else if ( y1 \> 0 && cur\_y \< lval ) y1--;

int cur\_x2 = analogRead(2); int cur\_y2 = analogRead(3);

if ( y2 \< tft\_height - 20 && cur\_y2 \> hval ) y2++; else if (y2 \> 0 && cur\_y2 \< lval ) y2--; tft.fillRect(2, y1-3, 5, 27, background\_color); tft.fillRect(3, y1, 3, 20, YELLOW); tft.fillRect(tft\_width-3, y2-3, 5, 27,background\_color); tft.fillRect(tft\_width-3, y2, 3, 20, YELLOW); } void draw\_ball(int color){ int bradius = 6; tft.fillCircle(ballx, bally, bradius , color); ballx += deltax; bally += deltay; if ( ballx \< 7 && bally \> y1 && bally \< y1+20) deltax \*= -1; else if ( ballx \> tft\_width-7 && bally \> y2 && bally \< y2+20) deltax \*= -1; else if ( bally \<= bradius || bally \>= tft\_height - bradius ) deltay \*= -1; if (ballx \<= 0 ) { left\_score--; tft.drawString(2,42, "Right Won!" ,~background\_color,2); tft.drawString(2,62, "Get Ready!" ,CYAN,2); for (int i = 0; i \<250; i++){ delay(10); draw\_paddles(); } int cur\_r = random(0,26); int cur\_g = random(0,30); int cur\_b = random(0,18); background\_color = cur\_r | (cur\_g \<\< 5) | (cur\_b \<\< 11); tft.fillScreen(background\_color); ballx = 64; bally = 80; if (ball\_speed \> 1) ball\_speed--; digitalWrite(left\_score,LOW); } else if (ballx \>= tft\_width ) { right\_score --; tft.drawString(2,42, "Left Won!" ,YELLOW,2); tft.drawString(2,62, "Get Ready!" ,GREEN,2); for (int i = 0; i \<250; i++){ delay(10); draw\_paddles(); } int cur\_r = random(0,26); int cur\_g = random(0,30); int cur\_b = random(0,18); background\_color = cur\_r | (cur\_g \<\< 5) | (cur\_b \<\< 11); tft.fillScreen(background\_color); ballx = 64; bally = 80; if (ball\_speed \> 1) ball\_speed--;

```
  digitalWrite(4+right_score,LOW);

}

```

}

enjoy getting that code to fudge around with i stole it right form here http://lucidtronix.com/tutorials/7 but the point i had to bring up is that i believe the guy before mentioned that it is a muchslower connectionor process than if it were.....were you saying softwareserial was the option then? because im not an explert or novice or maker by any means. but i have picked up along the lines that hardware serial will always trump software serial compilation any day once you get your head wrapped around the brevity of what ports and pins are actually what are used or have the data displayed on the serial ports. and like software is a necessity im afraid, but its as simple as reasigning pins and when that gets too hard going out and just bbuying a mega, haahah hope i sorta helped. id say go out and snag an esplora whilst their like toing a fire clearance sale on the originallt 50$+ boards. but their reference and prebuilt array of sensors is a bit underwhelming for the newbies in what it alll does, but kinda overwhelmine and difficult to transistion onece having looked at some code as it is, but the language is more forg9ving, but i believe their also officially retiring the leonardo espolora and micro series so good luck this tft display kicks bum man and is the only one that hsnt broke
> 0 votes

---
Tags: lcd, pins
---


title: Interrupt fires multiple times

text:
# Question
Title: Interrupt fires multiple times
I have a Photo Interrupter which I am using to count the RPM of a motor.

I am incrementing an integer to show the amount of interrupts there have been.

The issue is that there can be several interrupts fired for each time the "beam" of the Photo Interrupter is broken.

I have a 5mm length of plastic which breaks the "beam". If I make the plastic shorter than that, the Photo Interrupter doesn't pick up the break.

I am using the following, very basic code:

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

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

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

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

```

# Answer
> 1 votes
I would recommend adding a comparator with hysteresis so as to get a clean digital pulse, pictured below:

simulate this circuit – Schematic created using CircuitLab

This has the correct values.

I recommend the comparator with hysteresis as the phototransistors are prone to cause issues with interrupts even when used with pul-up/pull-down resistors, thus is as they very the voltage more than give a clean `0/1` digitally.

Here is your code, modified with the addition of `RISING` and of a 10mS delay.

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

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

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

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

```

This method produces very reliable results. It is also accurate with objects moving rapidly because of the interrupt.

---

I would also say that the problem you have when you use a piece of plastic \< 5mm is that the length of the slit in the sensor is *6.0±0.1*(seen below). If the plastic is less you probably find that the phototransistor still has enough IR falling on it to allow voltage to flow, but enough to trigger and interrupt. With the comparator you could probably use a smaller piece of plastic and find the voltage swing with a DMM and modify the voltage divider (**R1** and **R2**) to suite the needs.

# Answer
> 3 votes
Two other possible problems, apart from what Jake C has adressed in his answer are:

**1. Hardware bounce**

If your signal from the sensor isn't a clean transition from high to low but rather "bouncy" (see image below). The microcontroller will register multiple transitions in the meantime.

Solution to this would be to add a small capacitor (wil slow it down though) or add debouncing code... Best would be to get a "clean" sensor.

**2. Floating contact**

> When I even move my finger close to the wire running to PIN2 the interrupt fires.

That kinda seems like it's a floating contact, where it's not really connected to anything.

This is usually solved by using a pullup/pulldown resistor. Or maybe there is something wrong with the connection.

---

Also:

> Maybe due to the type of sensor?

You should note the part number of the sensor or link a datasheet, so we can see if it's typical behaviour for this type of sensor.

# Answer
> 0 votes
As far as it firing multiple times, are you aware that you have the interrupt mode set to CHANGE? This means the interrupt will fire once when something enters the beam, and again when something leaves the beam. You will probably want to set it to RISING or FALLING so that it only fires on one of those events, not both.

As to the not detecting issue I can think of a few reasons why this could be:

1. Your motor is moving so fast that the sensor changes again before it has had the chance to finish the interrupt service routine and reset the interrupt on the pin.
2. The photo interrupter you are using is too slow to report the piece of plastic passing through it. Sensors like this usually indicate a rise time and a fall time, and if it moves through the beam faster than these times it will not register the interruption.
3. The piece of plastic isn't large enough to block the beam. Depending on the photo interrupter, the beam used could be laser like and very narrow, or it could be wide and more like a flashlight. If it is more like the latter, you will need to have enough material present to block enough light to set off the sensor.

# Answer
> 0 votes
If you want to count RPM, maybe this link will help you: http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html

---
Tags: arduino-uno, programming, interrupt, sketch
---


# Question
Title: How to change LDR output in simulator 123D Circuits?
I used simulator 123d.circuits.io to create simulation of basic circuit with LDR: LDR is connected to 5V and via 10K resistor to GND. Wire between LDR and resistor is connected to analog pin where I read ADC values and display them using serial monitor. This works fine. But I would like to *how to change lighting level of LDR in simulation* because this way LDR shows still the same value. I tried putting LED or light bulb near LDR but it doesn't seem to have any influence. Any ideas?

# Answer
> 1 votes
Ok, so I found it myself. You can click on LDR during simulation and bar to adjust lighting appears above it.

---
Tags: simulator, photoresistor
---


title: How to disable Due USB power?

text:
# Question
Title: How to disable Due USB power?
I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks

# Answer
Disabling USB power is slightly tricky, as the incoming USB power is not only used for potentially powering the system, but it is also used by the various USB interfaces to indicate the presence of a connection.

The best way, looking at the schematics of the Due, would be to remove one or both MOSFETs that switch the USB power - that's T1 for the native port and T2 for the ATMega interface. That will isolate the USB power from the 5V system while keeping it connected to the VBUS pins of the relevant microcontrollers.
> 2 votes

# Answer
There is four ways I know of you can do to achieve exactly this :

* You can remove the usb polyfuse from your board, which will make the usb behave exactly as you need it to. Between the 2 two usb connections in this picture is a smd component marked 501V. This is your polyfuse. Disabling this cuts the +5v line to the board from the usb but leaves the data lines open.
* If you dont want to physically modify your board, then there is 2 other solutions you could use instead. You can buy a data-only usb cable, but they will probably be expensive and difficult to find.
* Modify your usb cable. It has 4 pins used by the board, +5v, GND, and the 2 data comms pins. All you have to do here is cut out or block the +5v. The GND pin is still needed as the data pins still draw power off the board.
* **The arduino boards auto select a power source(the usb usually) if you have both usb and external power connected at the same time. A way to force the board into switching to the external power source instead, while supplying power to the data lines on the usb is to make sure the dc supply is greater than 6.6v.**

**Edit: That last one is for the 5v arduino boards, I just remebered the due works on 3.3v instead so this probably won't work on your board**
> 2 votes

---
Tags: power, arduino-due, usb
---


title: Standard Length Messages over RS-485

text:
# Question
Title: Standard Length Messages over RS-485
I am a bit confused. So I want to send messages between two arduinos over RS485, but these are not fixed length, naturally, I have to send the length of the message or add a delimiter to understand that my message has ended.

Suppose, now I create a placeholder for the message, and both ends communicating are receiving the placeholder, rather than the message itself. This placeholder is x bytes long always, and each arduino can look it up from its memory what message corresponds to the placeholder.

Lets say I create a message.h file with contents like this

```
#define A "First Message"
#define B "Second Message"

```

When the two devices are communicating, they send each other A or B, and the Arduino looks it up in its .h file what A and B mean.

My question is when the Arduino recieves the A, it recieves a character 'A', but how can I use this to fetch the value assigned to variable A in memory?

# Answer
> 2 votes
There is no "variable A" - there is only a *macro* called "A" which gets replaced by the contents of the #define for "A" at compile time.

You have to remember that the "A" that the Arduino receives is just a number. It is only us humans who choose to associate that number with the letter A, and write software that takes that number and display it as an A. The letter A is number 65. The mapping between numbers and letters is called ASCII - or American Standard Code for Information Interchange.

What you do with that number is entirely up to you. If you want to use it to display pre-defined messages, then there's a number of ways you could do it. You could:

* Use a series of `if` statements to compare the number you have
* Use a switch/case construct in a similar way
* Store the messages in an array and use the received number as the index

For string constants the last option is tricky to get right on an Arduino where there is very limited RAM - you have to ensure that you use PROGMEM and access it properly, and doing that from an array is not as trivial as it would otherwise be.

The best method would probably be the `switch/case` option:

```
switch (letter) {
    case 'A': Serial.println(F("First Message")); break;
    case 'B': Serial.println(F("Second Message")); break;
}

```

# Answer
> 1 votes
I have a write-up about RS485 including a small library to handle this situation.

It can be downloaded from http://www.gammon.com.au/Arduino/RS485\_protocol.zip.

---

### Library features

* Handles "packets" of between 1 and 255 bytes.
* Uses a "begin packet" character (Start of Text, STX, 0x02) to reliably indicate that a packet is starting.
* Uses an "end packet" character (End of Text, ETX, 0x03) to reliably indicate that a packet is ending.
* Each data byte (other than STX/ETX) is sent in a "doubled/inverted" form. That is, each nibble (4 bits) is sent twice, once normally, and once inverted. Thus the only valid values for each nibble are:

```
0F, 1E, 2D, 3C, 4B, 5A, 69, 78, 87, 96, A5, B4, C3, D2, E1, F0

```
* The inverse (ones complement) of 0 is F, hence 0 becomes 0F. The inverse of 1 is E, hence 1 becomes 1E. And so on.
* This guards somewhat against "bursts" of noise. A burst of either 0s or 1s is unlikely to corrupt a byte preserving this normal/inverse relationship. Also there are only 16/256 valid combinations, so noise has only a 6% chance of becoming a valid byte.
* Because of this, also, the STX and ETX characters cannot appear in ordinary data (they are not one of the 16 valid values).
* Each packet is followed by a CRC (cyclic redundancy check). This is a further test that the packet was received completely. It guards against noise, or possibly some bytes just becoming missing.

---

More details on the linked page, but basically you provide a few functions to:

* test if a byte is available for reading
* read a byte
* write a byte

These could be with SoftwareSerial, HardwareSerial, or whatever you choose.

Then you either send or receive a "packet" which is the data you want transmitted to the other end.

There is a "blocking" and "non-blocking" version. The blocking version (when reading) waits for an entire packet to arrive. The non-blocking one lets you do other things while waiting for the entire packet.

---
Tags: rs485
---


# Question
Title: Sending data from Processing and receiving as uint32_t
I need to send data from a processing sketch to an Arduino to pass to a function that takes a uint32\_t. How to I send the data in Processing to be run on the Arduino

# Answer
> 1 votes
I recommend studying up on bitwise shifts (`<<` and `>>`), along with the bitwise OR and AND. They're what you're going to need, especially since `atoi()` would only give you a 16 bit, signed integer.

Let's say that your variable's binary is this (split up into 4 segments):

```
10010010 10110101 01010010 10010100

```

## Sending

```
uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

```

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the `& 255` part. This allows us to split this int up into four bytes.

How the `myVarCopy` variable would look over the four iterations:

```
After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

```

## Reading

```
uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

```

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.

This is how the `buffer` variable would look over the four iterations:

```
After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

```

Depending on how Processing works, you might have to worry about **little/big endian encoding** to ensure that your data is in the right order. **Warning:** I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.

---
Tags: data-type, processing-lang
---


title: Set Bluno Beetle to Broadcast mode

text:
# Question
Title: Set Bluno Beetle to Broadcast mode
I recently purchased Bluno Beetle (basically a smaller Arduino with a BLE chip). It is based on the Bluno: Wiki I know that its Bluetooth Chip, the TI CC2540, supports the Broadcast mode: Official page

However I can't find any AT commands that would allow me to set it to this mode, does anyone of you have an idea? I am trying to relay the messages they are sending (sensor readings), essentially building an interconnected network.

# Answer
It looks like the Bluno only supports the Central and Peripheral roles (i.e. not the Broadcaster and Observer roles.) Keep in mind AT commands are a feature of the firmware, not the actual chip. As such, even if the chip supports a particular mode or role, that doesn't necessarily mean the firmware makes the feature available.
> 1 votes

---
Tags: bluetooth
---


title: Software I2C - ATmega8

text:
# Question
Title: Software I2C - ATmega8
I am using ATmega8 with 12MHz crystal, on my breadboard. I can use `SDA` and `SCL` pins with default arduino library `wire.h`, and it works. But I want another pins to use I2C protocol.

I tried this library, even on real `SDA` and `SCL` pins, but it doesn't work.

I have pull up resistors, I tried with 10k and 4.7k without any success. (But those resistors worked with hardware I2C | TWI)

What am I doing wrong? (All connections is fine, because hardware TWI works but software does not.) Thank you for your help.

(Fuses are ok, because the Atmega won't respond if I remove the crystal oscillator, the LED blinking duration is ok.)

What i want to run (that doesn't work):

```
#define SDA_PORT PORTC
#define SDA_PIN 4
#define SCL_PORT PORTC
#define SCL_PIN 5

//#define I2C_TIMEOUT 100

#include <SoftI2CMaster.h>

uint8_t ADDR  = 0x68;

void setup(void) {

  Serial.begin(19200);
  Serial.println("Initializing ...");
  i2c_init();

  if (!i2c_start(ADDR | I2C_WRITE)) Serial.println(F("Device does not respond"));
  if (!i2c_write(0x00)) Serial.println(F("Cannot address reg 0"));
  i2c_stop();
}

void loop (void) {
  unsigned int low0, high0, low1, high1;
  unsigned int chan0, chan1;
  unsigned int lux;
  int state1;
  int state2;

  delay(1000);
  i2c_start(ADDR | I2C_WRITE);
  i2c_write(0x00);
  i2c_rep_start(ADDR | I2C_READ);
  low0 = i2c_read(false);
  high0 = i2c_read(false);
  low1 = i2c_read(false);
  high1 = i2c_read(true);
  i2c_stop();
  Serial.print(low0);
}

```

And the code with hardware TWI that works:

```
#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}
void setup()
{
  Wire.begin();
  Serial.begin(19200);
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

```

Schematic is the same as: https://www.arduino.cc/en/main/standalone.

Except instead of 16MHz, I use a 12MHz and ch210x serial.

Arduino's bootloader works well, I compiled it from source.

# Answer
OK let me cry till morning...

i was having this issue during day, but the solution was sooo easy

i need to pay attention more ...

> i2c\_start(addr | R/W-bit) Initiates a transfer to the slave device with the (8-bit) I2C address addr.

what i was trying is to push **7 bit** address.

i hope this might help some others.

Thank you for help.
> 1 votes

---
Tags: i2c, c, avr
---


title: How do I burn the bootloader?

text:
# Question
Title: How do I burn the bootloader?
I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)

# Answer
The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

---

To burn the bootloader:

1. Obtain an AVR ISP, USBtinyISP, ParallelProgrammer, or similar; or use another Arduino board. This will be your ISP.
2. Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
3. Power your board with either a USB cable or an external power supply.
4. Open up the Arduino IDE.
5. Make sure you selected the correct board that you are burning to at `Tools ► Board ►` in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
6. Select the appropriate programmer at `Tools ► Programmer ►`.
7. Click `Tools ► Burn Bootloader`, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

---

Sources:
> 23 votes

# Answer
### What is a bootloader?

> And what exactly is the bootloader?

The bootloader is a small piece of code residing in the "high" part of program memory. Normally it is not erased when you upload new sketches. Its purpose it to be activated immediately after a reset (the fuses are configured to commence code at the bootloader address rather than address 0x0000). The bootloader will wait a short time (such as one second) to see if "programming" data is arriving on the serial port.

* If so, it reads that data, and decodes it to reprogram the rest of the flash memory. Working in conjunction with the uploading program (normally avrdude) the new sketch is sent via the serial port. The bootloader erases pages of flash memory, and replaces them with the new code. Once done, it executes the new code.
* If no instructions arrive, the bootloader jumps to address 0x0000 to execute the existing sketch on the board.

---

### How to replace the bootloader

An alternative method to program a bootloader is to use a sketch I wrote a while ago which runs on a:

* Uno (or similar, such as Duemilanove)
* Leonardo
* Mega2560

The "programming" board runs the sketch which has bootloaders for a number of boards hard-coded into it. You connect the programming board to the target board (the board wanting the bootloader) with 6 hook-up wires as shown.

That particular photo illustrates one Uno programming another one.

You run the sketch (operating via the Serial Monitor to give it commands). First it identifies the target chip:

```
Atmega chip programmer.
Written by Nick Gammon.
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xCF
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
Type 'G' to program the chip with the bootloader ...

```

The you press **G** to program it.

```
Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xCF
Done.
Type 'C' when ready to continue with another chip ...

```

For a Uno this takes one second. To program a Mega2560 takes 3 seconds.

Detailed instructions at Atmega bootloader programmer

Code can be downloaded from Github: nickgammon/arduino\_sketches
> 10 votes

---
Tags: bootloader
---


title: Arduino restarts problem

text:
# Question
Title: Arduino restarts problem
I want to assign `-1` to `count` variable again when `count == 16` but when I have assigned `-1` inside the `if` condition I have marked below in the code, the Arduino restarts.

Can anyone guess what is wrong here?

```
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
#define DISPLAY_WIDTH 16

// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

int count = -1;
char drawNo[4];
int m = 0;
int turn;
class KbdRptParser : public KeyboardReportParser {
    void PrintKey(uint8_t mod, uint8_t key);
protected:
    virtual void OnKeyDown(uint8_t mod, uint8_t key);
    virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
    uint8_t c = OemToAscii(mod, key);
    count++;

    if (c)
    { OnKeyPressed(c); }
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key) {
    static uint32_t next_time = 0;      //watchdog
    static uint8_t current_cursor = 0;  //tracks current cursor position

    if (millis() > next_time) {
        lcd.clear();
        current_cursor = 0;
        delay(5);    //LCD-specific
        lcd.setCursor(0, 0);
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if (current_cursor++ == (DISPLAY_WIDTH + 1)) {    //switch to second line if cursor outside the screen
        lcd.setCursor(0, 1);
    }

    int keys = (int) key;

    if (count == 4 | count == 5 | count == 6 | count == 7) {
        turn++;
        drawNo[m] = (char)keys;
        //lcd.print(drawNo[m]);
        Serial.print(drawNo[m]);
        Serial.print(m);
        ++m;
    }

    if (count == 16) {
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }
    }
}
void printScreen() {
    int j;
    lcd.print(" DRAW NO : ");

    for (j = 0; j < 4; j++) {
        lcd.print(drawNo[j]);
    }
}
KbdRptParser Prs;

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

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay(200);
    Hid.SetReportParser(0, (HIDReportParser *)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay(200);
}

void loop() {
    Usb.Task();
}

```

# Answer
> 2 votes
```
int m = 0;
...
    drawNo[m] = (char)keys;
...
    ++m;

```

No other references to *m* in your code. Therefore *m* keeps increasing and you are writing outside the bounds of the array *drawNo*, corrupting memory.

# Answer
> 0 votes
I doubt it is the count. Did you try moving it to above the serial print so that you can be sure of the report?

```
if (count == 16) {
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }

```

---
Tags: arduino-mega
---


title: Perfect copy of Yun with Micro SD

text:
# Question
Title: Perfect copy of Yun with Micro SD
My Yun has a micro SD card with shared file system using ExpandingYunDiskSpace.

I would like to copy my Yun/SD card data **perfectly** onto my backup Yun/SD card. Because I have made many changes to the filesystem, just re-running the whole process manually would take a long time.

What methods can I use to transfer my Yun's data onto my other Yun?

My other Yun is brand new (never plugged in), and I have a brand new SD card in there. If I can do a 'bit-perfect' transfer for Yun and Micro SD in one shot that would be ideal.

# Answer
> 0 votes
Copying an SD card (cloning) is easy enough to do. On Windows you can use Win32DiskImager. On Linux and OS X you can either use `dd` from the command line:

```
(read)
$ dd if=/dev/sdb of=MySD.img bs=32k

(write)
$ dd id=MySD.img of=/dev/sdb bs=32k

```

For OS X the device names will be different, also in Linux you need to check which /dev/sd?? it is.

Also in Linux and OS X there are GUI applications that can do it for you - the Disk Manager in OS X, and "Gnome Disks" in Linux.

That is only good for the actual SD card contents though. If you need to clone the actual Yún itself then it becomes more tricky.

Fortunately there are tools available to help you.

Details on how to create and restore a backup of an OpenWRT system (which is what the Yún is) can be found on the OpenWRT Wiki: http://wiki.openwrt.org/doc/howto/generic.backup

Note that again it requires a Linux or OS X (preferably the former) system to do it since it relies on the standard Unix scripting tools and commands that are lacking on a Windows system.

You may be able to do all the above on a Windows system if you make it look like a Linux system by installing Cygwin.

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


title: About Making Library

text:
# Question
Title: About Making Library
There is a tutorial in the Arduino website on how to create a library. The tutorial gives the following codes for the header:

```
class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

```

My questions are:

1. What is the purpose of this line: `Morse(int pin);`
2. If any, what is the name of this line?

# Answer
> 1. What is the purpose of this line: `Morse(int pin);`

It is the method that is called when you create an object of class `Morse` when only passing a single `int`:

```
Morse somemorse(1);

```

> 2. If any, what is the name of this line?

It has multiple names, depending on what aspect you care about:

* It is a **constructor** for the class `Morse`.
* It is a **forward declaration** for the method `Morse::Morse(int)`.
> 2 votes

# Answer
```
Morse(int pin);

```

is the **constructor** for the class, `Morse`.

The name of this line, and all of the other lines between the curly braces`{` and `}` are **declarations** of the members of the class `Morse`.

So, the line

```
Morse(int pin);

```

is the *declaration* of the *constructor*, to answer both of your questions in one line.

Constructors are required pieces of code for Object Oriented Programming. When the constructor is called, it creates an object which is an instance of the class `Morse`. In this constructor is where all of the initialisation of the oblject goes. In the case of `Morse` it just initialises pin, which is specified in the parameter `pin`, by setting it to be an `OUTPUT`.

It is declared here, as a "signpost" if you will, for other parts of the code to know that it exists and is available to be called.
> 1 votes

---
Tags: c++
---


# Question
Title: Finding connectors for push button component
What type of connectors would I use for these buttons?:

http://www.adafruit.com/product/1477

They sell wires with the connectors already crimped on, but I only need the connectors.

I found https://www.jameco.com, but i'm not sure which connector would be right, or what to look for specifically.

# Answer
Go down to your local (decently-stocked) hardware store and ask for "quick connect terminals". From the dimensional drawing you'll need 2mm or 5/64" terminals.
> 2 votes

---
Tags: arduino-uno, button, wires
---


# Question
Title: Prevent hardware and library examples from showing in the Sketchbook menu
I have various subdirectories in `{SKETCHBOOK}/hardware/` and `{SKETCHBOOK}/libraries/` that contain an `examples/` subdirectory. These examples are showing up in `File` | `Sketchbook` | `hardware` and `File` | `Sketchbook` | `libraries`. Is there any way I can prevent them from showing up in that menu without moving them under the system-level Arduino directory?

# Answer
> 0 votes
Looking at the code it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.

The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.

---
Tags: arduino-ide
---


# Question
Title: USB Device not Recognised - Custom Wattuino Nanite 841
What I have done:

I have made a custom Nanite 841 which uses an ATTINY841 microcontroller. I have used the schematics from Wattuino to design my circuit, my PCB was made using a router with all excess copper removed. I have built the circuit and have ensured that every component and track does not short circuit. I have successfully uploaded the Wattuino bootloader using ISP.

The Problem:

The problem that I am getting is when the microcontroller is connected to any computer I get an error message saying...

> "USB device not recognised"

The device status shows this...

> Windows has stopped this device because it has reported problems. (Code 43)
>
> A request for the USB device descriptor failed.

I hope you can help as this is a bit of a bummer after just building my new device. Thank you for your time.

# Answer
> 0 votes
According to Github: micronucleus/micronucleus :

> Windows machines will need to install the libusb drivers found in the /windows\_drivers folder. Clean Micronucleus devices without uploaded userprogram will not time out and allow sufficient time for proper driver installation. Linux and OS X do not require custom drivers.

Make sure you have installed the device drivers.

---

Also you need to attempt an upload *shortly* after reset:

> The bootloader allows uploading of new firmware via USB. In its usual configuration it is invoked at device reset and will identify to the host computer. If no communication is initiated by the host machine within a given time, the bootloader will time out and enter the user program, if one is present.

---

See the troubleshooting page Code 43: Windows has stopped this device because it has reported problems from Microsoft.

---

You should be able to use a spare Uno or similar device to check the chip response. See Sketch to detect Atmega chip types.

Possibly you have the "divide clock by 8" fuse set. You could clear that if so.

---
Tags: attiny, hardware
---


title: 32u4 timer 4 pwm frequency help

text:
# Question
Title: 32u4 timer 4 pwm frequency help
I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.

I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)

```
void setup() {
    pinMode(6, OUTPUT);
    TCCR4E |= (1<<ENHC4); // enhanced pwm mode
    TCCR4B &= ~(1<<CS41); TCCR4B |= (1<<CS42)|(1<<CS40); // prescaler to 16
    TCCR4D |= (1<<WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode & top to 1023 but with enhanced pwm mode we have 2047

    TCCR4C |= (1<<COM4D1)|(1<<PWM4D); // connect pin 6 to timer 4 channel D

}

void loop() {
    //write out
    int value = 1500;
    TC4H = value>>8;
    OCR4D = (value&0xFF);
}

```

here is the new code so far working off the solution provided below:

```
void setup() {
    pinMode(6, OUTPUT);
    TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
    TCCR4B |= _BV(CS43) | _BV(CS41);
    TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
    TC4H = 624 >> 8; // B10 0x2
    OCR4C = 624 & 0xff;//B1110000 0x70
    TCCR4C |= (1<<COM4D1)|(1<<PWM4D);
}
void loop() {
    //write out
    //30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
    int value = 30;
    TC4H = value >> 8;
    OCR4D = value & 0xff;
}

```

the wave form i want:

# Answer
Yeah... sometimes it's easier to scrap what's already there and start fresh.

We need to:

* Pick a suitable prescaler to get close to the desired cycle length
* Fine-tune the value in TOP in order to get an exact value

Assuming this is a 16MHz Leonardo, and we have Fast 10-bit PWM (PWM4x = 1, WGM4x = 0b00) available:

16MHz / 50Hz / (1 \<\< 10) = 312.5

Therefore we need a prescaler of 512 (CS4x = 0b1010).

16MHz / 50Hz / 512 = 625

Therefore we need a TOP of 624 (OCR4C = 624).

```
TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 >> 8;
OCR4C = 624 & 0xff;

```

And then you set COM4xn and PWM4x to appropriate values for whichever pin(s) you want to output PWM on, and set OCR4x to a value between 0 and 624 (using TC4H appropriately; see the datasheet for details) to control the duty cycle.
> 2 votes

# Answer
To get finer resolution use Timer 1 - as Ignacio Vazquez-Abrams suggested.

```
void setup ()
  {
  pinMode (10, OUTPUT);   // OC1B on the Leonardo / Micro
  TCCR1A = 0;   // stop Timer 1
  TCCR1B = 0;   //     ditto

  // set up Timer 1
  TCCR1A = bit (COM1B1) | bit (WGM11) | bit (WGM10);  // toggle OC1B on Compare Match
  TCCR1B = bit (WGM13) | bit (CS11);   // PWM phase correct, prescaler of 8
  OCR1A = 20000;  // frequency: 50 Hz
  OCR1B = 1000;   // duty cycle - 1 ms
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

```

As you can see from the scope output, the pulse width is 1 ms, which extremely conveniently corresponds to the duty cycle of 1000. Thus, therefore, the duty cycle figure is exactly related to microseconds.

Also you can see that the frequency is 50 Hz.

This uses a prescaler of 8 to give high resolution. It takes two pulses to make one "cycle" (one on, one off) and thus it effectively divides the system clock by 16. Since the system clock is 16 MHz, that is why one "unit" is 1 µs.

The OCR1A figure is arrived at easily:

```
 1000000 / 50 = 20000  (1 MHz / 50 Hz)

```

Now you can just tweak your desired pulse width knowing that each unit is 1 µs. So for 2 ms OCR1B would need to be 2000.
> 2 votes

---
Tags: pwm, timers, avr
---


# Question
Title: USB and UART simultaneous power to Arduino?
I am connecting an Arduino Mega (Crius) to a Intel Embedded processor (Minnowboard) via the following to Peripherals:

1. Minnowboard USB -\> Arduino (to flash the micro-controller)
2. Minnowbaord Highspeed UART -\> Arduino UART (to communicate)

Now both the peripherals are supplying +5V Vcc to the Arduino from the Minnowbaord but via different ports. Both the channels shall always remain connected.

Is it safe to power +5V from different ports to the Arduino (because i am technically bypassing all the voltage regulators available on board) ?

Will this cause any problems for the Arduino in regards to difference in voltage levels?

# Answer
> 1 votes
That's perfectly fine. As it's the same 5V source the voltage *should* be the same and it'll just combine them together as if you had 2 wires in parallel. However, if there are things like diodes in the path of one connection that causes the voltage to be slightly lower then the increased voltage imposed on the lower voltage side would reverse bias those diodes and end up cutting off that one source, so only one would be used.

So no, it's nothing to concern yourself over.

---
Tags: arduino-mega, power, usb, communication, uart
---


title: 5V+ Voltage to the arduino analog

text:
# Question
Title: 5V+ Voltage to the arduino analog
If I connect a 12V / 12V+ battery to the arduino (uno) analog, will it be damaged ? What if I connect 230-240V to it ? Don't worry I haven't tried it yet. :D

Thanks in advance.

# Answer
Yes, it will be damaged. Especially if you connect mains direct to it.

The Arduino is designed to take *up to* 5V on any of its IO pins. Any more than that is asking for trouble. A slight amount above (as in say 5.5V) is usually tolerated OK, but anything more than that WILL cause irreparable damage.

And with mains, maybe even death.

For low DC voltages, like +12V, you can use a voltage divider to reduce the voltage to a 0-5V range.

For mains you will need to first reduce it down massively to a safe level (for example through a transformer) then re-scale and adjust it from there. Note that mains is AC not DC so it has a negative value of voltage as well, so you will either need to rectify and smooth it to create a DC voltage or, if you are interested in the waveform itself, reduce the voltage even more and add a DC offset into it to move the mid-point of the AC waveform up to around 2.5V.
> 1 votes

# Answer
For the 12 V battery, let's assume it might get up to 15 to 20 V when charging, so we need a voltage divider to divide that down.

The zener diode is there to clamp the input to no more than 5.1 V in case of spikes or other damaging things on the input.

The voltage divider will divide down to 25% of the input, ie.

```
output = R2 / (R1 + R2) = 10 / (30 + 10) = 0.25

```

So now if you measure 5 V on the analog input you know you have 20 V on the battery. Thus you can scale your calculations appropriately.

(A more common value would be a 33 k resistor, in which case redo the calculation and scale accordingly).

---

For 240 V I strongly advise against trying something like that with bigger resistors. For one thing, 240 V RMS will have 240 * sqrt (2) = **340 V** peak to peak. And that is both negative and positive.

A suitable approach would be to run through a small transformer, which will reduce the voltage and also isolate you from (almost) certain death.

In addition to that you would need to rectify the resulting voltage (say, 12 V) so that you don't put negative voltages into your input pin. And on top of that filter it so smooth out the peaks and troughs.
> 2 votes

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


# Question
Title: How to mimic soft-power button in inexpensive toys & flashlights?
My kids have a few odd inexpensive toys with a soft push-button that will turn on the toy, and subsequent pushes change the toy's mode of operation in some fashon. A flashlight comes to mind, where the button is pushed once and it turns on, push again and it blinks, and a 3rd time and the light turns off.

I've looked inside one of these flashlights, and there's a small blob covering some IC, what looks to be a diode, and the usual connections for the batteries and lights.

How do these circuits "work" without immediately draining the batteries? I'm looking to mimic this behaviour on a battery powered arduino Uno (or possibly Pro Mini).

What comes to mind is that the button is on an interrupt line, which wakes the system up from some sleep state.. when the button cycles around to an "off" state, the system goes back to sleep.

# Answer
> 1 votes
I have a lengthy write-up about saving power at Power saving techniques for microprocessors.

One of the sample sketches on that page (Sketch J) does what you ask:

```
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precaution while we are doing other things
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  digitalWrite (2, HIGH);  // enable pull-up
  }  // end of setup

void loop ()
{

  pinMode (LED, OUTPUT);
  digitalWrite (LED, HIGH);
  delay (50);
  digitalWrite (LED, LOW);
  delay (50);
  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes low
  attachInterrupt (0, wake, FALLING);

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

```

According to when I tested that, it used 0.116 µA when asleep (116 nA). That is well below the rate at which batteries self-discharge.

Basically that code does what you described. It sleeps, when pin D2 goes low it wakes and flashes an LED.

I should point out though that any "development board" Arduino with a voltage regulator, USB interface, and power LED on it will consume *considerably more power* because of the current drain they consume.

For low-power applications you need the bare chip (with appropriate supporting circuitry, like decoupling capacitors).

# Answer
> 0 votes
I have made a circuit in the past that does more or less this:

There are two switches in the diagram - the one on the top right turns the circuit on, and the one lower-middle turns it off. Once turned on, it will stay on until the bottom switch is pressed.

The two resistors bottom left, and the switch at the bottom, represent your Arduino.

Note that, this diagram is OUTSIDE the arduino - it provides power TO the Arduino (and any other components relating to your project). That is, the bottom of the 1MOhm resistor, and the bottom of the left transistor, connect to the power pin on the Arduino. Those two resistors don't literally, exist.

It works as follows: The transistors do pretty much all the work. Both transistors work as switches. At the start (as shown in the diagram), both transistors have the same voltage at the base, and the emitter (the top one +5v between top and center/left; the bottom one 0v between center/right and bottom). This turns both switches off, and preserves the status quo, and consuming nearly no power.

As soon as the switch at the top is closed, the base (center/right) of the lower transistor is pulled up to +5V, switches this transistor on, and power can flow from this collector to the emitter. This means power can flow through the TOP transistor from emitter (top) to base (center/left), switching on the TOP transistor. This allows power to flow from the emitter (top) to collector (bottom). This takes over from the pushbutton, keeping the bottom transistor on. This is the other stable state.

At this point, power goes to the Arduino (bottom two resistors, representing load, and bottom switch, which is one of the pins on the Arduino. This pin should be set to "high impedance" until the Arduino wants to switch itself off, then it should go low.

I built the top part of the circuit, with an LED for the bottom half (both switches were just wires), and it worked, but I'd have to consider what would happen if the arduino pin is high or low while the top button is being pressed.

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