title: Project Showcase '14

text:
# Question
Title: Project Showcase '14
> The logo is a derivative of the Arduino Community Logo licensed under Creative Commons license CC-SA-BY-NC 3.0

# Update: Winners Announced

The winners of the contest have been announced. Please see the Meta post for details.

To celebrate 10 years of Arduino, we are proud to announce the *first event ever* on Arduino Stack Exchange.

> Get your boards and soldering equipment out, dig out the ICs and resistors. The first Arduino Stack Exchange contest is just round the corner. We will be looking for interesting projects that are built using Arduinos. The contest is aimed towards sharing, discussing and providing feedback on projects that you and other members are working on. See announcement post

# Details:

* The prize is an official **Stack Exchange t-shirt**
* Limit two entries per person. If more than two are provided, only the first two will be considered.
* Clones *are* allowed.
* Projects for consideration will be accepted through **March 29th, 2014 at 4:00 UTC.** The question will still remain open in case someone wants to show off their project they made on Arduino Day 2014.

Visit the Meta post for discussion about this event and further information.

# Answer Format

You may post up to two projects (as two separate answers) as entries for the contest. All extra entries will be deleted. Consider following the following template for entries:

> # Project Title
>
> **Very Brief Description**
>
> # Description
>
> What is your project? What does it do? What problem does it solve?
>
> # Design
>
> Things to include in this section:
>
> * Schematics and other design documentation. Fritzing is a good tool for drawing breadboard schematics like the one shown in the project logo above.
> * Components used to build the project
> * Pictures or video
>
> # Conclusion
>
> Final thoughts. What did you learn from doing this project? What would you do differently if you had to start over?

You can copy/paste the following text if you want to use this template.

```
# Project Title
**Very Brief Description**

# Description
What is your project? What does it do? What problem does it solve?

# Design
Things to include in this section:

- Schematics and other design documentation. [Fritzing][8] is a good tool for drawing breadboard schematics like the one shown in the project logo above.
- Components used to build the project
- Pictures or video

# Conclusion
Final thoughts. What did you learn from doing this project? What would you do differently if you had to start over?

```

# Prizes

There are two prizes! The winner will be the submission getting the maximum number of upvotes (downvotes do not count) and will get a Stack Exchange T-shirt\*! There will be something for the runner-up as well. The runner-up will be decided at the discretion of the event organizers.

\*Certain restrictions may apply. International shipping may take a few weeks.

# Where do I submit my projects?

Post your projects as answers to this post.

# Answer
> 14 votes
# Stateful questbox

**A GPS powered box that makes you visit a few spots before opening**

# Description

It is similar to questbox, but it stores a small amount state of information in EEPROM, so you have to visit two or three different places before it opens.

# Design

Needed hardware:

* Arduino Uno
* Reverse Geocache Version 2 (or a protoshield)
* GlobalSat EM-406A GPS module
* 2×8 blue LCD with connector header and cable
* Hitec HS-55 servo motor
* 4-40 push rod and clevis for latch (some versions provide a Z-bend rod instead)
* 2 AA battery holder
* Metallic push button with embedded blue LED and 4-pin cable
* Pololu low voltage switch
* Pololu 5 V boost regulator
* JST connector for EM-406A GPS module
* Straight and right-angle header pins for the display, servo, and pushbutton connectors
* Two resistors for current limiting and display contrast adjustment
* Two small capacitors for power smoothing
* larger capacitor for display contrast circuit

Total hardware cost: **137$ + shipping**

Aditional materials:

* A nice box
* Epoxy glue, wood to cover pieces, tools

You can find assembling instructions in sundial page (you can buy most materials from them)

I will upload stateful code and post a link here, unfortunately I wont get all need hardware on time, so this is just an idea :)

**Code written so far**:

Inspiration:

# Conclusion

Learned how to integrate many components and libraries all toghether, I'll have to travel a bit to test it :)

Budget can be cut quite a bit changing the concept a bit:

* Change GPS with a numerical keypad: the 'player' has to guess/obtain a code instead of traveling to a location
* Polulu switch and regulator can be exchanged for a latching relay with capacitance coupling

# Answer
> 11 votes
# Energy saver for the absent-minded PC user

**This device switches on/off my desk lights when it is dark(ish) and in sync with my PC screensaver.**

# Description

The project is little more than an combination of a light sensitive sensor, a relay and some smart code that monitors the screensaver on my PC. When it is dusk and when screen saver is not active, it switches on the lights over my desk. When I subsequently leave my desk the screensaver will activate, which will in turn trigger the desk light to be turned off. When there is enough light during day time, the lights are not switched on at all. The problem solved is to reduce the waste of energy due to the lighting in my office being switched on when I have left the room.

# Design

Because the power of microcontrollers / Arduino only a little extra hardware is required to create a useful project. The same goes for this project where the hardware is little more than:

* An Arduino
* A couple of screw shields to connect the external components
* An LDR in series with a resistor to measure ambient light
* A relay card to switch on and off the mains powered lights
* A 10 μF capacitor from GND to RST to prevent the board from being reset and accidentally being programmed.

simulate this circuit – Schematic created using CircuitLab

# Conclusion

I learned how to interface the PC over the USB serial link with Arduino and how to read current state of the screensaver on my PC. If I would start over, I'd use a much smaller controller as I really only need a single digital output and a single analog input. Probably base the project on V-USB. Arduino however is excellent for the quick and easy proof of concept (PoC). (The PoC has been on my desk for at least two years already).

# Answer
> 7 votes
# (fake) Linux on Arduino

**I recently acquired a small composite LCD screen, which I quickly began playing with using the Arduino TVout library. What came next? Linux!**

## Description

While playing around with my TV screen and the TVout library, I discovered there is a premade terminal handler for the TV. I soon began to experiment with using it as a TV terminal hooked up to a PS/2 keyboard. There were some problems with the PS/2 library I used, so I transitioned it to use the USB library on my Mega ADK along with a USB keyboard. That worked much better. Now for storage.

My SD card shield isn't compatible with my Mega, so I wired it up somewhat haphazardly to the SPI at the end of the board. I wrote command handling to preform a few tasks like listing files and finding disk size, free space, etc.. The entire assembly isn't by any means finished, but I am happy with the progress I have made.

The code will be relocated to Github eventually, watch the comments.

## Design

## Challenges

I had a lot of trouble concatenating the inputted charactars to the string storing the current command because I wasn't casting right. Once I got that figured out, I also needed to fix the problem where some keys printed random garbage to the screen. This was caused by reading memory before the letter definitions, so a few `if`s cleared that up.

## Conclusion

I am very satisfied with the code. Once I add a few more utilities to it, I will put it on Github, so watch the comments. Overall, it was a very fun project. I learned how to use Stino in the process.

# Answer
> 7 votes
# Sonic Ray Gun

**Two projects by kids**

I'm working with a couple of home educated kids and we are having a lot of fun with an arduino. Their first project was a fake-bomb, like you see in the movies, with a LCD countdown timer and a classic "do you cut the red or blue wire?" type problem.

Project two started with showing them the toneMelody example and a small speaker. The quickly found out that if you turn the frequency up to 15kHz it was rather annoying to teenagers. An hour later they had improved the design with a cup, toilet roll and a switch made from a paperclip making a directional sonic ray gun.

Sadly no pictures.

# Conclusion

Don't leave kids unattended with an arduino.

# Answer
> 7 votes
I think this kind of barely fits within the rules, but it's interesting enough that I figure I'd post it anyways.

# High-Precision, GPS-Synchronized timestamp generator for data-acquisition purposes.

This is a rather interesting project that is intended to be used for providing a easy way of synchronizing multiple independent data-acquisition systems.

Basically, I work in a research lab, and we often have instruments that have multiple independent data-acquisition systems, which can be physically separated by as much as 50 feet. We need to be able to correlate the time at which samples from each system were taken, which can be difficult if you want to resolve sampling-times to a great degree of precision. Using something like a USB data-acquisition system, just the USB latency can introduce several hundred milliseconds of unknown latency, that can vary from acquisition to acquisition.

The previous solution was a 24-bit parallel counter that was simply bussed everywhere, requiring an enormous wiring harness, and was kind of a pain in the butt.

This system uses a specialized timing GPS module that can synthesize arbitrary frequency clocks, that are phase and frequency locked to the atomic clocks in the GPS satellites.

The MCU is responsible for tying together the GPS data messages (I had to heavily extend and optimize a existing protocol parser for the GPS data). The GPS is configured to use a proprietary binary protocol, and it's all parsed by the parser I wrote.

The project has gone through a number of revisions (pictured below).

# Design

Revisions!
Rev 1: Never worked, due to the fact that I was initially hoping to use a software dPLL off a much less expensive GPS, to synthesize a higher-frequency clock from only the 1 PPS output. It's probably possible to make it work, but the time-investment just made it not worthwhile. (and I'm too crappy a coder)

Used a parallax propeller MCU. The lack of decent compiled languages was a major issue as well.

---

Rev 2: Shifted to a ATmega2560. Worked, had lots of funky design aspects inherited from the first rev. Primarily, the continued use of shift-registers for the 32-bit output, despite the more then sufficient number of IO on the ATmega2560.

First board that ran Optiboot, and was actually programmed entirely using the standard Arduino toolchain, before I got irritated with it and started modifying the toolchain to better suit my purposes.

---

Rev 3: Also worked. The bodged wiring is because this board incorporated a built-in USB hub to reduce the number of required USB ports (the FTDI interface requires 1 USB, and the GPS has a USB interface as well). Unfortunately, the GPS wouldn't properly enumerate, though the FTDI device worked fine, and I've used this hub elsewhere without issue. Weird.

I don't have a proper USB debugger, so I just dropped the USB hub entirely, rather then trying to fix the issue. The GPS usb isn't *really* used much outside of set-up anyways.

---

Rev 4: Semi-final ATmega2560 version. Added a LCD for GPS status, fiddled with LEDs and so forth. Also, better footprints for the possible super-capacitors for maintaining the GPS status when not powered.

This is the last Optiboot version.

`MStime` is the `MSTOW`, or Millisecond-Time-Of-Week, which is the name of the GPS data value that is output on the timestamp out. It's a 32-bit variable that increments once per milliseond, and rolls over each week. It's a more obscure part of the GPS standard.

`ITOW` is another GPS-related value, being a value that corresponds to the 1PPS signal. The correlation between the two isn't properly reflected on the LCD, since I do not have the CPU time to update the LCD at the rate I'd like. This was actually one of the major things that improved in the upgrade to the Xmega devices.

---

Rev 5: Complete architecture switch. Now uses a ATxmega128A1U processor. Not really "Arduino" at all anymore, but the ability to have multiple interrupt levels on the xmega processor series allowed me to considerably improve the code structure.

The two bodge-wires are from me doing some experimentation, the board worked fine without them as well.

### Looking forward:

Rev 6!
Add the ability to use different LCD sizes, more ESD protection on GPS antenna connection (that was an issue), ability to use a CR2032 battery for maintaining the GPS clock instead of super-capacitors.

Also, much better labeling of debug and status LEDs.

And bonus Nyan-Cat!

(These boards are out for fabrication right now. When I get them, I'll add pictures of the real board.)

---

I did some long-duration testing between two of the ATmega2560 boards, and over 72 hours, the RMS time-error between the two units was ~20 uS. This was with two completely independent antennas too. My design goal was \< 1 ms, so I'm pretty damn happy with that.

On the whole, I think this does a good job illustrating how Arduino can be a useful tool for early prototyping for "real" products/systems. I use it for getting an initial test-version running with minimal effort, and when I'm confident the *idea* will work, I actually put the work in to migrate away to a completely custom, purpose-specific implementation.

---

Design files:
https://fake-server.no-ip.org/svn/FPGAStuff/DAQ%20systems/
(In the "GPS Timestamp" series of directories).
(Note: Files are from Altium Designer. The are **not** eagle files).

Source code:
https://fake-server.no-ip.org/svn/Programming/Code/AVR/
Again, in the "gpsTimeStamp" series of directories.

Sorry for the crappy cell-phone pictures.

# Answer
> 6 votes
# TV Antenna Rotator

**IR remote controlled antenna rotation**

Can't get off the couch to adjust the direction of the TV antenna? And even if you do, sometimes your proximity to the antenna changes the reception. It would be nice to be able to adjust the antenna from the couch. Using the TV remote.

# Components

Arduino Uno, IR receiver, Stepper motor w/ driver board, 1" ID bearing, Swiffer mop handle, Plastic box,

# Description

Use an old Swiffer mop handle as the antenna post. Got a 1" ID bearing from my favorite online store, which the mop handle just squeezes into and stops. I drilled a hole into the plastic box big enough for the mop handle to fit through, but not for the bearing. I drilled a rectangular hole into the mop handle end to fit the shaft of a 28BYJ-48 stepper motor, and stuck the contraption into the box as shown. The mop handle actually rests on the bearing, and the bearing is super glued to the top of the plastic box.

Used the stepper.h library to rotate the motor from an Uno.

I took apart an unused DVD player and salvaged the IR receiver from it. You can take apart any consumer appliance that has a remote and use the IR receiver from it, it'll work. The IR receiver uses the IRremote.h library. Using the serial monitor, I printed out the hex code that corresponded to the two buttons on the TV remote that I want to use to operate the antenna motor. One for rotating left, one for right.

To save energy, use the small\_stepper.motorOff() function to turn off the coils after each movement.

# Conclusion

This was a fun project that was also useful for my wife. I didn't implement any acceleration/deceleration in the movement, which might be nice, especially if the antenna had more rotational inertia.

Edit: sorry about the picture being sideways! It's right side up on my computer, I have no idea why it's sideways online.

# Answer
> 5 votes
# ShiftLCD

**AVR based, Arduino compatible, board that mounts to the back of an 8x1 up to 20x4 Character LCD Screen.**

# Description

I just designed this board and the custom library to make it easier to use and LCD. Though they are pretty easy to use at the moment. It cuts down the number of output pins used from 6 to 3. It also has the option to expand the I/O by adding more shift registers on to the one that drives the display. The processor used is an ATTiny45 or ATTiny85 which has, after using the shift register, digital pins 1 (PWM) and 4 available and analog pin 2 (same pin as digital pin 4) available.

# Design

# Challenges

One unforeseen challenge I faced was when I started I was using digital pins 0-2 to run the shift register, these also happened to be the programming pins (MISO, MOSI, SCK). So every time I reprogrammed the device the LCD would get sent a whole bunch of gibberish messages where the power would have to be turned off in order to reset the display. I solved this problem by moving the shift registers latch pin to digital pin 3 which is not a programming pin. Solving this also solved another problem for me because when I moved the latch pin it opened up digital pin 1 which had PWM usage, allowing for more things to be done with the board.

# Conclusion

Granted this may not be the coolest product or idea, it still has its uses. The answer the question directly, "What did you learn from doing this project" I learned how to design from start to finish a PCB board. If I could do anything differently it would have been to use surface mount parts instead of through hole, then again it is just a prototype, one-off board.

# Answer
> 5 votes
# Button-pushing robot.

**A four-wheeled eight-pound remote-control laser-shooting robot that pushes buttons.**

# Description

I made this project over the course of last school year. I was in robotics class, and we decided to have a competition. Each team would make a robot that has a large button and a way to push other buttons. At the end of the year, we would have the final contest, where the three robots would try to push each other's buttons.

By the end of the year, my robot only partially worked. Every part of the robot had at some point been working, but between a fried Arduino, fried motor drivers, terrible code organization, and me being the only person on my team to work on the robot for a total of more than five hours, I couldn't get it completely working.

I haven't touched my robot in almost a year, so I know that if I wanted to get it working again I would have to rewire the bot and rewrite the code. I may decide to do that some day, but for now I'm going to work on less ambitious projects.

# Design

### Overall Design

### Information/electricity flow

```
+--------------------------+   +-------------------------------------------------+
|         Computer         |   |      Robot                                      |
|--------------------------|   |-------------------------------------------------|
|                          |   |                                                 |
| Keyboard +--> Processing |   |  Button +-------------+        Motor    Motor   |
|                          |   |                       |          ^       ^      |
|                    +     |   |                       |          |       |      |
|                    |     |   |  Batteries +-----+    |          +       +      |
|                    v     |   |                  |    |   +----> Motor Driver   |
|                          |   |                  v    v   +                     |
|               Bluetooth +-----> Bluetooth +--> Arduino Uno +--> Motor driver   |
|                          |   |                  +    +  +       +       +      |
+--------------------------+   |                  |    |  |       |       |      |
                               |                  |    |  |       v       v      |
                               |                  |    |  |    Motor     Motor   |
                               |                  |    |  |                      |
                               |                  |    |  |                      |
                               |                  |    |  +-----> Laser          |
                               |  +---------------|----|----+                    |
                               |  |       Arm     |    |    |                    |
                               |  |---------------|----|----|                    |
                               |  |     +---------+    v    |                    |
                               |  |     |      Motor Driver |                    |
                               |  |     v              +    |                    |
                               |  |  Servo             |    |                    |
                               |  |                    v    |                    |
                               |  |                  Motor  |                    |
                               |  +-------------------------+                    |
                               +-------------------------------------------------+

```

### Components

* Arduino Uno, (fried)
* Transportation:
* Easy Button
* Arm:
    + Servo, (continuous rotation)
    + Motor driver, (fried)
    + Motor, (12v, found in teacher's junk pile)
    + Eraser
    + Counterweight, (homemade paper bag filled with pennies)
* 2 battery packs, (12V, 1300mAh, Ni-MH rechargeable)
* 2 solderless breadboards
* Laser, (5mW)
* Bluetooth:
* Lots of wires
* Lots of scrap metal and plexiglass, (found in teacher's machine shop)

### Code

I didn't organize my code very well, so I hope this is the right code.

### More pictures

### Terrible video of a slow, armless, buttonless, laserless, and bluetoothless early version of the robot.

https://www.youtube.com/watch?v=Q7MvE7-Xb0E

# Conclusion

I'm really good at frying electronics.

This was my first experience in an actual machine shop. I got to use a CNC milling machine, manual milling machine, lathe, and bandsaw. If I started a project like this again, I would make much better documentation, so I could figure out what the heck I was doing a year later.

# Answer
> 5 votes
# The Knock-knock lamp

**A lamp that toggles on/off when the desk is knocked on.** Currently in alpha phase, still prototyping, but I think it's the most useful Arduino project in existence. *Included corny joke generator... from previously recorded knock-knock jokes.* Note: I know I can't win in the rules, but there's no rule about entering... I can show off my project, too.

# Description

So far I've pretty much explained most of it. You knock, and the light turns on and off. I'm currently on breadboard. I'm using a piezo element to detect the knocks with vibrations. In parallel, I have a 1 megaohm resistor to protect my Arduino Uno SMD.

I thought of this design after nearly knocking (haha punny) my lamp off of my desk while searching for the little toggle switch. I'm not exactly... well *adroit*. It's nice just to knock on the desk and then have light. I'm also using a Power Switch Tail SSR (solid state relay: no noise) to control it with two of my Arduino's pins.

# Design

*Image taken with webcam hanging over monitor... eek!*

**Components used to build the project:**

* Piezo element ($3.00 USD)
* Megaohm resistor ($0.30 USD each in 5pk)
* Arduino Uno SMD (on hand)
* Power Switch Tail SSR (~$25.00 USD with ship, but had on hand so no cost)
* Breadboard and jumpers/extra wire (~$5.00 USD, but had on hand so no cost)

**Cost to me: $3.30 USD + $0.02 USD (tax) == Only $3.32!**

# Conclusion

Overall, it is a simple project but it's actually useful. That's a struggle with my Arduino projects: can I build something that I would actually *use*? Blinking an LED isn't exactly going to help you in life. It's fun, but that's about it.

The biggest issue I faced (and kinda still do) is not getting a strong enough signal. I learned a lot about electrical signals: I figured out how to find the "peak" of a pulse and not just read the pin at a random interval and miss the higher voltage. I would try getting more sensitive piezo element. A larger one would help. I'm trying to modify my circuit to not limit the voltage as much, but protect the Arduino. Some sort of fuse would help in this situation. I'm also playing around with resistor values. It'd help a lot to have a scope for this, but I guess not... :P

After I perfect the circuit, I'm going to work on getting it on a PCB with an ATtiny... and maybe even develop some kits. I'll try to publish my findings on how to make the element more sensitive without risking my board in the process.

**Status update:** I've been really busy recently. I'm going to order a zener diode (4.3V) here in a week or two to remove the megaohm resistor to prevent diluting the signal while protection the chip. I may build a simple voltage amp here if needed (alongside the zener) to try to make the sensor more sensitive.

# Answer
> 5 votes
*\- Learn how to create your own low cost wireless sensors and connect them to the world.*

http://www.mysensors.org

We call it **"Internet of Your Things"**

# Description

We've combined the Arduino platform with a small radio transceiver into a fun, flexible world of low cost wireless sensors.

All the nitty-gritty details about the sensor communication has been packaged into a convenient software library so you don't have to worry about them.

It is as easy as 1, 2, 3.

1. Connect the parts. 2. Download the provided examples. 3. Start measuring and controlling the world!

Read more about how the sensor network is automatically being formed using our Arduino Library on the site. It basically forms a star network and can reach hundred of meters.

In the middle you place an Arduion or Raspberry gateway that collects the information from your sensors.

# Design and schematics

Here is one of the prototype motion sensors I created to control the garden light outside of my house. The motions status is sent to my HA controller which turns on the light (via z-wave) when motion has been detected. A light sensor (not in the image) makes sure only to turn on the lights at night.

You will find all the build instructions here: http://www.mysensors.org/build/

Othe site there is also easy-to-follow build instructions for a bunch of other wireless sensors and actuators. Here are some examples:

Distance Sensor, Motion sensor, Relay actuator, Humidity, Light, Pressure, Rain, Temperature, ...

# Conclusion

The project is still in the starting blocks and we hope to provide plugins for a growing list of Home Automation controllers. The first thing on our list right now is to provide a DIY controller that provides a free cloud storage for your sensor data.

See you @ mysensors.org

/Henrik Ekblad (the creator of the Open Source Arduino Library used for the communication between the sensors)

* UPDATE 27/3. Made the example more concrete and added my affiliation with the open source project.

# Answer
> 5 votes
# 4-Digits LED display for Arduino

**Small board with 4 7-segments LED digits, managed through 3 pins.**

# Description

When I started working with Arduino, I wanted a way to display values collected by various sensors I experimented, but I did not want to output these values through `Serial` to a PC.

I wanted a small board that I could easily reuse from one project to another and I wanted to spare a breadboard.

This board, along with its small library, currently allows 4-digits numbers display and does not source any Arduino current during display (current is sourced only when communicating to the board the new value to display from now on).

# Design

The design is rather simple as I decided to reuse a **MAX-7219** chip to drive my LED display (I had a few of them on hand).

Thanks to this chip, the schematic was much simple, but it was important to correctly understand how to use it; fortunately, its datasheet was pretty clear.

The original design was done on a breadboard and used **4 single LED 7-segment digits**; but it required too much wiring for my taste (need to connect segments by groups of 4). Also, during my very first experiment with 7-segment LED digits, I have fried one: it had 2 Ground pins, but I connected only one to GND instead of both :-(

Then I decided to go for a **4x7-segment display, common cathode**, with segment anodes already connected for 4 digits: that's only 4+8 pins!

During my tests, I have found a useful Arduino library for working with MAX-7219 which I decided to reuse. I have built my own library upon it, with a very simple API.

After breadboarding, it was time to make the design more permanent; since I had a bunch of stripboards on hand, I decided to go for it.

I searched and found an easy Stripboard designer for PC that I have used for designing my board.

The first stripboard design was not optimized in terms of space and I decided not to implement it:

Then I have reviewed the design to optimize the cost and size (just one small 50x75mm stripboard); that was easy with the stripboard designer I found before:

Once the board was ready, I decided to check it with an Arduino UNO and an Ultrasonic Sensor:

It seemed to work except I often had strange, inconsistent displayed values; after investigation, I found it was due to **noise triggered by the display board**, noise that interfered with the sensor. I just needed to **add a decoupling cap** as near the current supply pins of the sensor as possible and that worked perfectly (note that the display board already had decoupling caps for the MAX-7219 chip).

Parts list:

* 1 x LN5461AS: common cathode 7-segments block of 4 digits
* 1 x MAX7219: multiplexed LED driver chip
* 1 x IC support (24 pins)
* 1 x 22K resistor
* 1 x 10uF electrolytic cap
* 1 x 100nF cap
* 1 x male pin header (5 pins)
* 1 x 90x50mm stripboard
* wires, solder...

# Conclusion

30 years after my last electronics experiments, I could get the virus again with Arduino and with this very first project which, although rather simple, taught me several things:

* interpret datasheets for the components used (MAX7219 and LED display)
* learn how to use and be effective with stripboard design
* all pins marked GND or V+ should be connected: you don't choose the one you feel like connecting!
* if there's something that appears strange when you test your circuit and you don't understand why: don't search, it must be noise, try to add a decoupling cap and that should do it!
* learn how to create an Arduino library (not just a sketch)

If I was to start this project again today, I would:

* try to optimize further the stripboard design (probably I could reduce the size a bit further)
* replace the straight pin headers on the board with right-angled headers so that wires connecting to Arduino are more protruding in front of the board

# Answer
> 5 votes
# Digital Wall Clock with Radio Frequency (RF) Remote Control

**A large (40x30cm / 16x12") 7-segment display wall clock with R/F remote control.**

# Description

This project features a large (40x30cm / 16x12") 7-segment display **digital wall clock** with R/F remote control. It has the following features:

* It shows the current time and date (hours, minutes, seconds, day, month, year) in two formats (hours or date in the large digits).
* It shows the current temperature in °C.
* Has a user defined countdown which will sound an (annoying) alarm when it reaches zero.
* All functions controlled remotely by an RF remote control.
* Has a small cursor keypad for controlling its functions (when the remote control isn't available).
* Brightness control independent for each display line.
* It continues to keep the current time accurately even when off, thanks to a real time clock IC powered by a coin cell battery.

# Design

The key aspects of this project were the following:

* It's completely based on Arduino and AVR ATmega328 microcontroller.
* It keeps current time even when off, thanks to DR1307 RTC powered by a coin cell battery.
* The digits are never multiplexed. Instead, each digit has a dedicated 8-bit serial shift register IC (74HC595) that keeps selected segments on independently of what's being displayed on the other digits and what the MCU is doing.
* Segments are powered by Darlington arrays due to current consumption that exceeds that of the MCU or the shift registers.
* The clock is controlled by a keypad on the controller board and also by an RF remote control. Radio communication is performed by a pair of inexpensive 434MHz radio receiver and transmitter.
* The project has a modular design in which a single controller can manage up 12 single digits. Controller also accepts expandable modules for unlimited number of digits (maximum number of digits is limited by timing delay due to daisy chaining of shift registers and the attenuation of their clock signal).
* The design supports a number of ready-made 7-segment display digits or custom digits made with LEDs.

Below are the schematics for the controller and one of the 7-segments boards:

Here are some pictures of the boards that I designed, etched, and assembled, and the remote control:

And finally, here's a picture of another version of the clock. In this one, I'm making the 7-segment displays myself using rectangular LEDs and discrete components.

# Conclusion

This project took me a lot of time, effort and learning to get to this stage (it's never finished, as I've learned), but it was lots of fun. A few things I've learned:

1. Study **all the libs** you're going to use in your project **before you assign GPIO pins in your controller** so you avoid potential conflicts. I've been unlucky to use the same PWM pin for brightness control that is associated with VirtualWire timer, so I had to patch the board to get brightness and RF working at the same time.
2. Crimping KK molex and modu connectors takes A LOT OF TIME!!
3. Laser cut acrylic pieces are the future. They add a lot of quality to the device even if you are clumsy.

# Answer
> 4 votes
**Heating Controller**

You know how it is - you set the heating to come on at a certain time and how many days do you work late and it's been on full bore for hours, or you go away for a few days and forget to turn it off? Or the rare occasion that you get home early and the house is cold? I decided that the simple way to get around this was to build a device that would allow me to turn my heating on or off by text message / sms. It would be in addition to the existing control system so as not to lose the flexibility which that can provide.

The project consists of a few major parts: an Arduino Uno clone, a Seeedstudio GSM shield, a DHT22 temperature sensor and a 25 amp SSR.

**How it works:**

The existing heating controls are set to 'Off' and the new controller is wired up to override them. The Uno is programmed to respond to three different messages - On, Off and Query. In the case of the latter the unit will read the DHT22 and reply to the sender with the current temperature and the status of the unit (on or off). If the command is either On or Off then it will respond with a confirmation of the action carried out. Once messages have been acted upon they are deleted; any messages that do not conform to the specific message structure are left in the SIM card memory and can be examined later if desired.

Power to the unit is supplied by a five volt three amp switch mode power supply. As the power pins on the Arduino are simply exposing the board's internal 5v bus I decided to power the ensemble through these and configure the shield to draw power from the Arduino.

The unit has three status LEDs. One green one to indicate that there is power, a blue one to indicate that the GSM board is 'live' and a red one to indicate the status of the heating. These are in addition to the status LEDs provided on the Arduino and shield. There is also a push button switch that allows manual control of the heating, with a 100nF capacitor to handle the debounce.

**Next:**

Much of the code relies upon good old delay() to give the shield enough time to perform its actions. I plan to improve the code so that it waits for confirmation from the shield rather than assuming that it has done what it was told to within the time allocated! I will also add a 'still alive' feature - at fixed intervals turn off the blue LED, send the AT command to the shield and on an acknowledgement turn the LED on again. The shield is under software control so if it fails to respond then turn it off and back on again.

The whole ensemble is to be mounted in a suitable enclosure and mounted adjacent to the existing controller. I have an internally illuminated push button switch that I will use instead of separate switch and red LED to handle the override.

Longer term I'm planning to add an RTC, a 20 x 4 LCD and additional push buttons to allow the unit to be programmed and act as a time switch as well.

Prototyping has already started!

**Conclusion.**

There is something slightly decadent about waking up on a cold winter's rest day, sending a text message / sms to turn the heating on, and rolling over and going back to sleep for an hour! And when you realise that you haven't turned it off on a night you can do so from the comfort of your bed!

# Answer
> 4 votes
# Serial Box

**A portable serial monitor in a box**

# Description

Sometimes it's useful for a device (Arduino or otherwise) to output some debug information via serial. That's great if you've got a computer on hand with an appropriate serial input. However, that's not always the case for a variety of reasons.

This project is my attempt to address that problem by creating a portable Arduino-powered serial monitor, which I can hook-up to other devices in the field.

By default, it will simply display text in a scrollback format; i.e. text appears on the bottom line, and everything scrolls up to make room when more arrives. This means it should work very neatly with all sorts of generic devices. However, it will also be possible to use escape sequences to control the display more precisely, so that devices can also be programmed specifically to take advantage of its capabilities.

# Design

The design consists of a set of 4 alphanumeric LCD displays (16x2 characters each), aligned in a box something like this:

The displays are Epson EAX16027AR's, which unfortunately are not compatible with the standard Hitachi HD44780 driver. As such, I had to write my own library for them.

I chose to use these displays (rather than e.g. one large display) mainly because I just had them lying around, and wanted to do something interesting with them. I also thought it would be quite handy to be able to control each display independently for some applications (e.g. displaying different information on each one).

In terms of circuit design, the displays are connected in parallel, with chip select pins being used to direct data/commands to each one as needed.

An ATMega328 will be the brains of the final unit, with serial data coming from a TTL-level line (for connecting directly to the TX of a similar MCU), or optionally from an RS232 9-pin D-sub socket (for connecting to various other systems). The unit will also have a contrast dial, a button for clearing the display, and a button for initiating a self-test mode. In future, I'd like to add buttons which let the user move through a scrollback history too.

Below is a very preliminary circuit layout (I had a lot of trouble getting Fritzing to play nicely for some reason!). It includes an 8-bit SIPO shift register for driving the LCDs' data lines, which are shown in green. You can also see the chip select lines in orange.

At the moment, the project is still at the working prototype stage, driven from an Uno (clone) board. Below, you can see a photo of it in action, displaying text which was passed via serial from my computer.

# Source code

I'm making my LCD library available on GitHub at the link below. Please note that it's at an early stage in development. In the near future, I intend to make it much more similar to the core LiquidCrystal library so that it's easier to transition between the two.

You can find some basic code for my Serial Box prototype in the "examples" folder.

# Conclusion

I think the project is coming along very nicely, and I was extremely pleased to get the prototype working. My main challenge is going to be mounting the whole thing in a box. I've already made a start on cutting out suitable holes for the displays, but I'm not very experienced at that sort of thing, and am finding it quite tricky to line everything up.

I'll get there in the end though. It just may not look very pretty by the time I'm finished! :)

---
Tags: events
---


# Question
Title: "Broken Pipe" when uploading to Arduino UNO
I just got my Arduino UNO and I'm trying to upload the blink example but the upload fails with

```
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMSET"): Broken pipe
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Broken pipe

```

I have tried both Arduino IDE 1.0.1 (which I installed via my package manager) as well as version 1.0.5 which I downloaded from the arduino.cc website. I'm running Ubuntu Linux 12.10 if that makes a difference.

I'd appreciate any and all help in getting my arduino up and running!

# Answer
> 3 votes
As with any communication error, try these:

* Disconnect and reconnect the USB cable.
* Use a different USB cable.
* Press the reset button on the board.
* Restart the Arduino IDE.
* Make sure you select the right board in `Tools ► Board ►`, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
* Make sure you selected the right port in `Tools ► Serial Port ►`. One way to figure out which port it is on is by following these steps:
    1. Disconnect the USB cable.
    2. Go to `Tools ► Serial Port ►` and see which ports are listed (e.g. COM4 COM5 COM14).
    3. Reconnect the USB cable.
    4. Go back to `Tools ► Serial Port ►`, and see which port appeared that wasn't there before.
* In extreme cases, you may need to burn the bootloader.

Answer adapted from here.

# Answer
> 1 votes
## It sounds like you have incorrect drivers or the wrong COM port (USB) selected in the IDE

Both are easy to fix. I'd imagine that it would be the COM port.

To do this:

> Tools → Serial Port → \[COM port... try a few different ones. Also you can use device manager to see which one disappears when you unplug your Arduino\]

Few notes on photo:

#1. The selector for the COM port. Choose which one your board is on.

#2. That shows the COM port selected and board. I don't have my UNO connected: ignore that the COM port isn't showing up on the menu.

---
Tags: arduino-uno, uploading
---


# Question
Title: LEDs on TX/RX lines interfering with the programmig of the device
I have recently designed a shield to my Arduino Duemilanove, which has 8 LEDs, on the digital GPIO, from 0 to 7, but it won't program with the shield on because the voltage drop is too much on the RX and TX lines. My question is: can I have a LED on the TX/RX line with a minimum resistor value that allows me to program the Arduino?

# Answer
I just found this reference (using ICSP for output as well as programming -- essentially the same thing), and it suggests a 4.7kOhm.

I didn't have a 4.7k handy, and used a 15k instead and it works.

In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and `GND`. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).

If I put the resistor in series with it, the sketch uploads without fail.

You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use `Serial.[anything]`. Make sure to not even initialise the port.
> 1 votes

---
Tags: led, shields
---


# Question
Title: Shield interfere with Serial Communication
I'm new to arduino. I have nexus duino robot as described in http://www.aliexpress.com/item/3WD-48mm-Omni-Wheel-Mobile-Arduino-Robot-Kit-10019/688287804.html, the shield connected with motors and support xbee.

With simple serial comm sketch, I'm able to communicate between arduino and PC if the shield not inserted, but not if I insert the shield as it seem arduino can't receive serial data (still can send data to PC tough). Someone says that the shield might be use RX TX so it interfere with serial comm.

My Questions are, is there a way to check whether the shield use RX TX? If yes, can we make it not interfere with serial comm? Could be other problem causing this serial comm problem? Thanks in advance.

# Answer
You really do need to provide information on the shield, there are many versions out there (and I own half of them ).

In essence, unless you are using an alternate serial port (`SerialN`) or software serial, then YES, your XBee will be using the same lines as your Arduino. If you are using `Serial.print` or `Serial.write` to talk to the XBee, then that is a giveaway too.

The reason for this is the XBee talks to your Arduino through the serial port, but the Arduino IDE also talks to your Arduino (for programming and `Serial.print`) as well. You can only do one successfully.

In answer to your second question, most likely not. It will be the XBee shield causing you your problems.

edit: I thought I would add, I actually have ONE shield that uses RX and TX but also allows for programming at the same time. This is achieved through a series resistor and (in the case of the shield) an amplifier as well.
> 2 votes

---
Tags: serial, xbee
---


# Question
Title: What's the 2nd ICSP header for in Arduino Uno R3?
Looking at my Arduino Uno R3 board and its reference design schematic I noticed that there's a second ICSP 6-pin header. In the schematic, the connector I'm referring to is named ICSP1.

**What's that for?** What useful things can an average Arduino user like me do with it?

The relevant part of the schematic is below (marked in red).

# Answer
> 15 votes
It's for the other MCU on the board.

The main MCU on the Uno is labelled "ZIC1". This is the one that is programmed when you press "Upload" in the IDE. But unlike other Arduinos that use a FTDI chip to connect to the serial port on the main MCU, the Uno uses another MCU instead, labelled "U3" on the left. This MCU runs a small bit of code that acts as a serial port via USB and passes through the bytes to its USART1. This then connects to the USART on the main MCU, where the bootloader on that chip accepts the bytes coming through and writes to flash and EEPROM on the main MCU.

You can use this additional MCU as you would any other, but the only I/O it has available are the USB connection, the SPI connection via its ICSP header, the UART1 connection to both the main MCU and pins 0 and 1, and two LEDs on PD4 and PD5.

---
Tags: arduino-uno, icsp
---


# Question
Title: How do I use a i2c port expander to read buttons with pull ups and inverting the resulting uint16_t?
I am using a mcp23017 to read button presses for my joystick project and am using the internal pullup to minimize complications. Is there a way to invert all the bits in the uint16\_t so i can send the values as normally off?

I'm using this Adafruit library.

And the reading code: `uint16_t buttons = mcp.readGPIOAB();`

# Answer
The inversion operator in C++ is `~`.

```
Serial.print(buttons, BIN);
Serial.print(~buttons, BIN);

```
> 3 votes

---
Tags: programming, arduino-leonardo
---


# Question
Title: Can the 2nd MCU on the UNO R3 be used for keyboard emulation?
Following on from What's the 2nd ICSP header for in Arduino Uno R3? I was wondering how this could be hacked to our advantage.

For example, could that firmware be rewritten to have the UNO recognised as a mouse/keyboard input? Could this be done after the boot loader process and leave the uploading process in tact?

Given the limited IO, it seems it's functions might be limited. Plus I have no idea how much code is space is available.

# Answer
Yes, it is possible. using LUFA, you can burn new firmware to the Serial converter. The only problem is that you need to re-burn the USB-Serial converter to upload another program.

Info: http://www.fourwalledcubicle.com/LUFA.php

Specific page: http://mitchtech.net/arduino-usb-hid-keyboard/
> 7 votes

# Answer
The second MCU is similar to that used in the Leonardo, but is smaller and less capable (ATmega16U2 vs. ATmega32U4). It is certainly possible to reprogram it to do what you like, but its limits means that you can have fewer USB "devices" at the same time.

I have not looked at the existing firmware, but it should certainly be possible to add your own custom code into it such that both the normal serial connection to the main MCU as well as your additional code can coexist.
> 3 votes

---
Tags: arduino-uno, programming
---


title: Problem with Xbee or Arduino?

text:
# Question
Title: Problem with Xbee or Arduino?
I am sending three analog signals through the xbees to be written to analog pins on the receiving side so they can be read in Simulink. I connected both of the arduino megas to my laptop and uploaded the sketches. I have a shield and a series one xbee connected to each arduino. I pulled up the serial monitor for each sketch. I connected a 1 volt DC power supply to all three analog pins. On the transmitting serial monitor I got numbers close to 200 which I believe is correct but on the receiving side I was not getting anything. I believe the problem is with the arduino. After I uploaded the code on the transmitting side the TX led was green but the RX led on the receiving side was not lit up at all. The power LED on the transmitting arduino is red but it is green on the receiving side. The 'L' led on the transmitting side is red on the transmitting side is read and yellow on the receiving side. On both of the xbee shield the power led's are red and the DIO5 led blinks green. On the receiving xbee shield the DOUT LED is red and the DI LED is green. If more information is needed let me know.

Here is my configuration for the xbees: (series 1. firmware version: 10ed)
Transmitting Xbee:
PAN ID: 1234
MY:10
DL:11

Receiving Xbee:
PAN ID: 1234
MY: 11
DL: 10

Transmitting arduino program:

```
int val1 = 0;
int val2 = 0;
int val3 = 0;
int analogPin1 = 0; //these are you analog in pins
int analogPin2 = 1;
int analogPin3 = 2;
void setup()  {
  Serial.begin(9600);  //start serial
}
void loop()                               // run over and over again
{
        Serial.print("<");                // This character signifies the begining of our data cycle
            val1 = analogRead(analogPin1);    // read the input pin
        Serial.println(val1);             // output the signal
        Serial.print("\t");               // Signifies end of 1st piece of data
            val2 = analogRead(analogPin2);    // read the input pin
        Serial.println(val2);             // output the signal
        Serial.print("\t");               // Signifies end of 2nd piece of data
            val3 = analogRead(analogPin3);    // read the input pin
        Serial.println(val3);             // output the signal
        Serial.print(">");                // This character signifies the end of our data cycle
        delay(100);
}

```

Receiving Arduino program:

```
#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 0, RX = digital pin 1
SoftwareSerial portOne(0,1);
int Apin1 = 0; // These variables hold the current incoming value
int Apin2 = 0;
int Apin3 = 0;
int AnalogOut1 = 0;  //Set our analog pins
int AnalogOut2 = 1;
int AnalogOut3 = 2;
int Digits = 0; // Helps watch for comma
int Mode = 0; // This designates which section of reading we are doing - begin = 0, Apin1 = 1, Apin2 = 2, APin3 = 3, end = 4
void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // Start each software serial port
  portOne.begin(9600);
}
void loop()
{
  portOne.listen();
  while (portOne.available() > 0) {
  // read the incoming byte:
    char inByte = portOne.read();

    if (isdigit(inByte) && Mode == 1) {
    int temp = inByte - '0';
    Apin1 = (Apin1 * 10) + temp;
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(temp);
    Serial.print('\n');
    Serial.print(Apin1);
    Serial.print('\n');
    }
   if (isdigit(inByte) && Mode == 2) {
    int temp = inByte - '0';
    Apin2 = (Apin2 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    }
  if (isdigit(inByte) && Mode == 3) {
    int temp = inByte - '0';
    Apin3 = (Apin3 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    }
    if (inByte == ',') {
    Mode++;
    }
    if (inByte == '<') {
    Mode = 1;
    }
    if (inByte == '>') {
    Mode = 4;
    if (Apin1 > 0 && Apin2 > 0 && Apin3 > 0) {
    analogWrite(AnalogOut1, Apin1);
    analogWrite(AnalogOut2, Apin2);
    analogWrite(AnalogOut3, Apin3);
    }
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(Apin1);
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    Apin1 = 0; // These variables hold the current incoming value
    Apin2 = 0;
    Apin3 = 0;
          }
    }
}

```

# Answer
The problem is the same as last time (XBee+Arduino communication problem)

You are sending the data via:

```
Serial.println(val1);

```

which outputs an `ASCII` representation of the number.

But in your reading, you are reading in a `byte` value. Actually, I just realised you are reading in a `char` which is a signed (-128 to 127) value:

```
char inByte = portOne.read();

```

first, change that to:

```
byte inByte = portOne.read();

```

Now, you have three options:

1. If (as you say) the numbers you expect are around `200` and will **always** be below `256` (and positive) then you could send a byte value instead. That way, when you read the byte in, you get the same value. You would do this using `Serial.write(val1);` instead of `print`.
2. If you need to send larger than a byte value, eg `int`, then send as two bytes, HIGH and LOW. Then on the receiving end, take in two bytes when reading that data.
3. Send as plain text but read in as plain text. Since you have delimiters, keep reading in the serial until you have all the data you need and then break it down. (You could adapt the code I posted in the answer above to do that).

**edit:** a couple of other points with your code:

* You're doing an `analogWrite` to digital pins `0, 1,` and `2`. Was that your intention? `analogWrite` is reserved for sending out PWM signals on only those pins that are capable (see: http://arduino.cc/en/Reference/analogWrite )
* `analogRead` will read a value of `0-1023` and if your intention is to just use PWM at the other end, then step it down to a value of `0-255`. In that case you can get away with writing byte values to `Serial.write`.
* You're never setting the `pinMode` of the outputs in the receiver.
* You're sending `val1`, `val2`, and `val3` out via `Serial.println` which will send your value out (as `ASCII`), followed by a newline, so the bytes sent from that one line will be `32 30 30 0D 0A`. You have to interpret that at the other end.
* You're also using software serial on the hardware serial port (you're assigning digital pins 0 and 1. These are the hardware serial pins). **BUT** you're also initialising it via hardware serial. I'm guessing that it really wouldn't matter (if the pins are aligned), but you can't expect to receive data via software serial and send data via hardware serial if they're all using the same pins.
> 1 votes

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


# Question
Title: How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?
I'm debugging a couple of RS232-to-TTL converter boards that I'm trying to use to program my Arduinos and one thing I would like to try would be to reduce the upload serial speed from 115200 to 19200.

**How do I do that?**

I imagine that there's a setting that can be easily changed on the Arduino IDE preferences. But where is it? But then the bootloader speed would have to match that? **How do I change the serial upload speed on optiboot, too?**

# Answer
> 2 votes
On Arduino IDE side, the upload speed is coded in `hardware/arduino/boards.txt`

```
uno.upload.speed=115200
...

```

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the **expected speed for the actual bootloader** of every board).

Now as per the optiboot loader side, the upload speed is defined in `BAUD_RATE` macro, in `optiboot.c`:

```
/* set the UART baud rate defaults */
#ifndef BAUD_RATE
#if F_CPU >= 8000000L
#define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
#elsif F_CPU >= 1000000L
#define BAUD_RATE   9600L   // 19200 also supported, but with significant error
#elsif F_CPU >= 128000L
#define BAUD_RATE   4800L   // Good for 128kHz internal RC
#else
#define BAUD_RATE 1200L     // Good even at 32768Hz
#endif
#endif

```

So I guess you can:

1. `#define BAUD_RATE 19200` before that block of code
2. recompile the optiboot loader
3. upload your own new bootloader version
4. update `uno.upload.speed` accordingly in `boards.txt`
5. check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing. Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!

---
Tags: arduino-uno, serial, arduino-ide, bootloader
---


# Question
Title: Nothng Written to Serial when using sprintf
I'm using `sprintf` to use a format specifier `myTemplate` with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.

Is `sprintf` being used wrongly here?

```
char* result;
char* myTemplate;

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
}

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";
    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");

}

```

---

When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me! Why is this?

**Sketch**

```
char received;
char* message = "";

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

void loop() {

    // Echos back
    if(Serial.available() > 0) {
        received = Serial.read();
        Serial.println(message);

        if(received == '\n') {
            message = "";
        }  else {
            message += received;
        }

    }
}

```

# Answer
> 3 votes
When you use `sprintf()`, you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (`result`), meaning the behaviour of `sprintf()` is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static `char` buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

```
char* myTemplate = "";
char result[64] = {0};

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";

    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");
}

```

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.

---
Tags: arduino-uno, programming, string
---


title: Acrylic enclosure for Arduino

text:
# Question
Title: Acrylic enclosure for Arduino
I've been browsing Aliexpress and eBay for decent Arduino enclusures, but I've found out they are even pricier then boards themselves.

Then I've realized that there are multiple firms that offer cheap laser cutting - I can buy 1 sq.m acrylic sheet and order cutting multiple parts of boxes at once.

Obviously I am not the first one who came up with this idea. Has anyone seen downloadable vector layouts I can use as something to start from? Thanks.

# Answer
Making your own is quite possible, especially if you own a router (or even better a router table). You need a V shaped 90 degree router bit, a tube of proper perspex glue and some acrylic sheet. The glue is hard to find, but plastic sign manufacturers generally will sell it. Unless you are a DIY expert, I suggest the gap filling type of glue rather than the watery product that only fills perfectly matched surfaces. Try searching Youtube on "acrylic box making". There are several videos. My first two efforts were pretty bad, but the last couple are fine, and are of course exactly the right size.
> 1 votes

---
Tags: enclosure
---


title: Timer2 does not work as it should

text:
# Question
Title: Timer2 does not work as it should
I am currently playing with Arduino timers (on UNO currently) and I am building a library that has a function that must be called every millisecond.

There is plenty of code samples on Internet so I went with something that seemed perfect for my needs. I have then updated it to make it a reusable C++ class.

Here is my code (simplified to just isolate the issue):

```
#define BIT(x) (0x01 << (x))

static volatile uint32_t milliseconds = 0;

class Timer
{
    public:
    Timer()
    {
        // Disable interrupts
        uint8_t savedStatus = SREG;
        cli();
        // Use Timer2 with 1 ms interrupts
        // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
        TCCR2A = BIT(WGM21);
        // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
        TCCR2B = BIT(CS22) | BIT(CS20);
        // Set timer counter compare match (when value reached, 1ms has elapsed)
        OCR2A = 125 - 1;
        // Reset Timer2 counter
        TCNT2 = 0;
        // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
        TIMSK2 = BIT(OCIE2A);

        // Restore interrupt enabling state
        SREG = savedStatus;
    }
};

static void callEveryMillisecond(uint32_t ms)
{
    // Do something here
}

// Attach interrupt routine to the Timer Compare Interrupt
ISR(TIMER2_COMPA_vect)
{
    milliseconds++;
    callEveryMillisecond(milliseconds);
}

```

After checking ATmega328 datasheet (section 17) several times, I came to the conclusion that what I do in `Timer` class constructor above is correct, and for Arduino UNO, the values used must lead to one call of the ISR every ms:

* CPU frequency = **16MHz**
* Prescaler = **128**
* -\> timer frequency = **16MHz/128 = 125KHz**
* -\> max counter value = **125**

I decided to use the **CTC** (Clear Timer on Compare match) mode, which means that when the timer `TCNT2` (which is incremented at 125KHz frequency), reaches `OCR2A` value, then it will trigger the ISR, and then will be reset on next tick; the additional tick to reset the counter explains why we use `125 - 1` for `OCR2A` and not just `125`.

Now comes the weird stuff. In order to check that my code worked, I decided to blink the LED on pin 13 every 10 seconds, hence I have added the following code to my program:

```
static void callEveryMillisecond(uint32_t ms)
{
    if (ms % 10000 == 0)
        digitalWrite(13, digitalRead(13) ^ 1);
}

static Timer timer;

void setup()
{
    pinMode(13, OUTPUT);
}

void loop()
{
}

```

Then I measured the time during which pin 13 LED is lit on (or off, both measures are the same). Measures are not very accurate (I just used my wristwatch) but good enough for my check.

I was surprised to see the measured time to be about **20 seconds instead of 10s**.

Initially I thought about a mismatch in CPU frequency, but after performing a lot of small changes, here is what I found which worked perfectly:

```
//static Timer timer;

void setup()
{
    static Timer timer;
    pinMode(13, OUTPUT);
}

```

Just moving the `Timer` instance into `setup()` did the trick: my measures rightly indicated **10 seconds** between 2 states of the pin 13 LED.

**Now my questions are:**

1. Why the second code sample works perfectly, whereas the first does not?
2. Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in `Timer::Timer()`?
3. Is there a way to make the first code sample work? Note that I don't like the second sample because it does not seem natural coding, also, I will need access to `Timer` `timer` instance in several locations of my future program, hence it can't be possible if it is declared in the scope of `setup()`.

# Answer
I have located the source of the problem.

In file wiring.c (arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino) which gets called before setup(), there is the following part that tries to changes the timer 2 prescaller to 64 by setting the `CS22` bit.

```
// set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

```

You already set `CS20` and `CS22` so this doesn't affect you. What does affect you is the following part which sets bit `WGM20`

```
    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

```

and you have already set `WGM21` so `WGM21` and `WGM20` set changes the timer mode to fast PWM , top=0xFF which gives almost double delay that the mode you were trying to use (CTC top=124).

**How to workaround this issue?**

Timer2 is used when its associated PWM pins are used with an `analogWrite()` call, so the Arduino setup code sets all prescalers to well-defined values just in case the timers might get used later.

I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate `setup()` method in your `Timer` class and calling that from the global `setup()` routine.
> 4 votes

# Answer
As a follow-up up to @alexan\_e answer, here is what I finally did to ensure that my Timer2 settings are not overwritten by the `init()` method in Arduino `wiring.c`.

```
#define BIT(x) (0x01 << (x))

static volatile uint32_t milliseconds = 0;

class Timer
{
    public:
    // Don't use the constructor anymore
    void init()
    {
        // Disable interrupts
        uint8_t savedStatus = SREG;
        cli();
        // Use Timer2 with 1 ms interrupts
        // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
        TCCR2A = BIT(WGM21);
        // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
        TCCR2B = BIT(CS22) | BIT(CS20);
        // Set timer counter compare match (when value reached, 1ms has elapsed)
        OCR2A = 125 - 1;
        // Reset Timer2 counter
        TCNT2 = 0;
        // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
        TIMSK2 = BIT(OCIE2A);

        // Restore interrupt enabling state
        SREG = savedStatus;
    }
};

static void callEveryMillisecond(uint32_t ms)
{
    if (ms % 10000 == 0)
        digitalWrite(13, digitalRead(13) ^ 1);
}

// Attach interrupt routine to the Timer Compare Interrupt
ISR(TIMER2_COMPA_vect)
{
    milliseconds++;
    callEveryMillisecond(milliseconds);
}

static Timer timer;

void setup()
{
    // Explicit call to Timer initialization; this occurs AFTER
    // Arduino wiring.c init() has been called
    timer.init();
    pinMode(13, OUTPUT);
}

void loop()
{
}

```
> 1 votes

# Answer
In your setup function, you need to instantiate your timer, like this:

```
static Timer timer;

void setup()
{
    timer = new Timer();                       <<<--- here
    pinMode(13, OUTPUT);
}

void loop()
{
}

```
> 0 votes

# Answer
The way most of the libraries do this is to put an instance of (in your case) Timer in the Timer.cpp file, and reference it with an extern definition when needed - typically in your main cpp file. Also you are calling digitalWrite() and digitalRead() during an ISR. This can be bad since those functions are slow, and may not be guaranteed to behave when interrupts are disabled (as they are during an ISR). A safer approach is for your ISR to set a flag in your Timer class that can be read by an Timer.isExpired() or similar method in your loop() code.
> 0 votes

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


# Question
Title: Can the Arduino Uno become an AVR programmer and use the ICSP header to program the target board
The Arduino Uno has an ICSP header that I imagine is for programming the board using a separate ICSP programmer. That is, its ICSP header turn the board into a target.

**Can one use that same ICSP to program other boards, turning the Arduino Uno effectively into a ICSP AVR programmer? How?**

I'm assuming that the target boards would also be Arduinos and wanted the Uno to program them using the Arduino IDE. Is that possible?

Reading the AVR In-System Programming Application Note it looks to me that the only issue would be to make the programmer (the Arduino Uno) control the target board reset line. I've seen something like that in ArduinoISP sketch, but in that sketch, the target reset is controlled by port D10. But one could program the reset line to be an output, right? So could we change the ArduinoISP sketch to use its own reset line as output to control the target board reset line? If not, **why not?**

# Answer
> 5 votes
First of all, as configured, the RESET pin can **not** be used as an output pin. In order to use it as an I/O pin, you would have to program the RSTDISBL fuse. But once you do that, as jippie said, it becomes near-impossible to reprogram your Arduino (if you have the socketed through hole variety of the MCU, you could pull it out and put it into a high voltage programmer; in all other cases, it's effectively impossible).

So in theory, you can use the ICSP header the way you suggest. In practice, it's under almost any conceivable circumstance a terrible idea.

# Answer
> 5 votes
I recommend going out and buying an AVR Dragon - costs aroud $US50. That gives you ISCP programming plus debugwire debugging (using the Atmel Studio IDE).

# Answer
> 4 votes
To answer my own question, just to report that I found something close to what I was looking for, which I link and describe briefly below.

Gammon Software Solutions forum - Atmega Bootloader Programmer - Programming Cable

On that page, the author suggest that we cut pin 5 from the 6-pin ICSP programming cable, solder a pin to it, and wire it to pin D10. Like so:

Then, you can load the Arduino Uno with the ArduinoISP sketch and program the target board as usual.

# Answer
> 3 votes
Yes you can program the Arduino's reset input pin as an output and use that to program another AVR, but you can no longer program your Arduino as that relies on the controller being reset through its own reset pin.

Coming to think about it, I am not sure how the other devices (like the USB controller) responds to being reset by Arduino's controller itself. It resets the USB controller which may or may not reset the connection to the computer, possibly loosing data. With the USB controller being reset, GPIO-pins D0 and D1 (the serial interface between PC and Arduino's AVR) may corrupt the datastream.

---
Tags: arduino-uno, icsp, arduinoisp
---


# Question
Title: Arduino Uno R3 ISR does not work on pin 2?
I have an Arduino Uno R3. I have a paddlewheel waterspeed sensor that I use on an ISR on pin 2. The power supply is approximately 8v stepped down to 4.92v with a circuit yanked from the phone charger. I have also tried this with the arduino 5v.

The pin returns the correct values with digitalRead(), so it's cycling between 1 and 0.

The ISR works fine on pin3. Why does it work on pin 3 and not pin 2 ISR?

```
void itest() {
    Serial.println( "test" );
}

void setup() {
    attachInterrupt(0, itest, FALLING);
}

```

# Answer
> 3 votes
never use Serial inside an interrupt handler, increment a (volatile) variable and print it in the loop().

---
Tags: arduino-uno, interrupt, isr
---


# Question
Title: Arduino Serial Monitor only returning Null Characters
I'm trying to simply access my HC\_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, **it only seems to be returning Null characters,** though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

So you can clearly see that the command `AT` and `AT+NAMEdevice` return different data, but they are both all `NUL` blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.

Code for this simple program is below:

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

```

Wire Diagram is as here *NOTE* I have used both a direct connection to the `5V` and also used a Voltage Divider. Neither changes the `NUL` return.

# Answer
First, change all `Serial.write` to `Serial.print` I think that might be half your problem.

Next,

```
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);

```

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:

Change `BTSerial.begin(38400);` to `BTSerial.begin(9600);`

Or, as jfpoilpret suggested, tie the Key pin directly to VCC. The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up. By the time the digital write in your code happens, it's too late.

If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's `AT+UART=` off the top of my head.

Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX
char myChar;

void setup()
{
  ...
}

void loop() {
  while (BTSerial.available()) {
    myChar = BTSerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    BTSerial.print(myChar);
  }
}

```
> 1 votes

# Answer
This sounds like baud-rate mismatch. These dongles don't have a reset ability; they remember their most recent settings. See my answer to another user having trouble communicating with one these.
> 0 votes

---
Tags: serial, bluetooth
---


title: What is the library m in C++ linker?

text:
# Question
Title: What is the library m in C++ linker?
Following this guide, it says to include a library in the C++ Linker called `m`. What is this for?

Specifically, Your second Arduino project.

4) **Configure project**

5th dot point:

> AVR C++ Linker -\> Libraries: Under libraries, add arduino\_core and m (in that order). Under path, add the path to the correct core library, e.g. "`${workspace_loc:/arduino_core/328P_16MHz}`"

# Answer
The m library is the "math" library. You have to link with it in most flavours of gnu compilers (it is typically not required in other, as it is included in the standard lib) when using functions and stuff from the header file "math.h".
> 4 votes

---
Tags: c++
---


# Question
Title: Save some arduino pins when driving a 4 digits 7 segments display
I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.

Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.

I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.

Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:

```
IN     OUT
P0 P1  D0 D1 D2 D3
0  0   1  0  0  0
0  1   0  1  0  0
1  0   0  0  1  0
1  1   0  0  0  1

```

This way I can connect OUT to digit selection and spare 2 pins.

Thanks for your hints.

# Answer
A 2-to-4 line decoder should do what you need. I've used a 74HC139 with Arduino before, which contains two decoders in a 16-pin DIP.

There are lots of other options though. In the past, I've used an 8 bit serial-to-parallel shift register (74HC595) to control a 7 segment display. It effectively lets you control 8 (or more) outputs using only 3 pins on your microcontroller. You have to be careful of power requirements though. Most shift registers aren't able to drive such a display directly, but I was able to incorporate transistors quite easily to get around that.
> 2 votes

# Answer
I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? This one from adafruit includes a single 4x7 segment display.

given your comment, another option would be an I2C/SPI 7 Segment driver. (datasheet).

new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.

max7219/7221 datasheet and digikey source:
> 3 votes

# Answer
Are you using your analog pins? Did you know they can be used as digital pins?

> The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:
>
> ```
> pinMode(A0, OUTPUT);
> digitalWrite(A0, HIGH);
>
> ```

This is your best bet if you aren't using all your analog pins.
> 3 votes

# Answer
An I2C IO expander might be your best bet. If your existing I2C device uses a different address, you may be able to put both devices on the same I2C bus. You would then use 0 additional pins compared to your current design.
> 2 votes

---
Tags: lcd, display
---


# Question
Title: Which type of Motor Drivers to drive Unipolar Stepper Motors?
I hope this question is specific enough. Basically I want to know if it matters a great deal what kind of Motor Driver IC(s) or pre-assembled kits you use to drive a Unipolar Stepper Motor.

For example: Can the following Driver be used to control this Stepper Motor?

Driver: https://www.sparkfun.com/products/9670

Motor: http://www.jaycar.com.au/productView.asp?ID=YM2754

Thanks!

# Answer
> 2 votes
It does matter. There are pros and cons to each different driver setup.

If you wire the motor as a bipolar, which I'm not sure that you can, you can use the driver that you linked, but it is not very good for driving stepper motors. https://www.sparkfun.com/products/11876 is a better driver for steppers for half the price. (still have to wire it bipolar)

If you need to stick with unipolar wiring, PCBheaven.com shows an example using a CD4017, MOSFETs, and diodes to run a unipolar motor. It will only turn one direction. Instead you could use a micro-controller, such as an Arduino, in place of the CD4017 along with logic-level MOSFETs to go both directions.

A tutorial on the Arduino site uses a ULN2003A, which is not powerful enough to drive your motor to its full potential (does it need to turn, or turn well?) and doesn't have the diodes (important to protect your IC!), but the Arduino sketches would still work using the schematic from PCBheaven.

A couple of complete driver boards:

UNIPOLAR STEPPER MOTOR DRIVER

FANCY UNIPOLAR STEPPER MOTOR DRIVER

---
Tags: motor
---


title: Building Arduino Nano from components

text:
# Question
Title: Building Arduino Nano from components
At this stage, my finalized design includes Arduino Nano 3.0, a breakout board and a few electrical components on a breadboard.

Will there be an appreciable cost savings from not buying a ready-made Arduino? The Arduino Nano clone being used costs $17.20.

And is it a good idea if everything is soldered on to a custom fabricated PCB board, including the components of Arduino Nano 3.0? The PCB board will cost around $10 at the quantities I'm starting with.

# Answer
You can probably do a lot better than $17 but not much better than $8:

http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH\_DefaultDomain\_0&hash=item1e7ed94ffb

If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.
> 3 votes

---
Tags: arduino-nano
---


# Question
Title: How can an Arduino output a specific (i.e. 56 kHz) carrier frequency?
I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56 kHz carrier frequency for the transmitter and a second Arduino with a 56 kHz IR detector module for the receiver.

I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.

Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56 kHz pulse using the timers?

# Answer
It is indeed possible to generate a 56 kHz signal with an Arduino **timer**.

A timer actually can be seen as a special register, in the MCU, that holds a value (starting at 0) that gets incremented at a frequency that is the MCU clock frequency (16 MHz on Arduino Uno), possibility divided by a factor called *prescaler*. When that value reaches a limit, called **Compare Match**, that you specify, then two things happen:

* The timer register value is reset to 0.
* One **ISR** (interrupt service routine) callback function gets called (you can define it to point to your own code).

The idea is to use that ISR to change the output of a logical pin every time it is called (`HIGH`, then `LOW`, then `HIGH`...).

Now, in order to generate a 56 kHz square wave, you'll need your ISR to be called `56000 * 2` times per second (`* 2` because you need to change the output value twice per period).

You can choose the prescaler value you want for a timer among the following list:

* 1 (clock frequency is not divided, hence 16 MHz)
* 8 (clock frequency is divided by 8, hence 2 MHz)
* 64
* 256
* 1024

There are two sizes of timers/counters on Arduino Uno (they are called *timer/counter* actually): 8 bits and 16 bits.

On Arduino Uno (ATmega328P), you have three timers overall, but some may be used by the Arduino core library or other libraries used in your sketches (you'll have to check that by yourself):

* timer0 (8-bit)
* timer1 (16-bit)
* timer2 (8-bit): this one has more prescaling options (1, 8, 32, 64, 128, 256, and 1024)

Now you need to generate a 56 kHz wave from 16 MHz, hence, without prescaling, you would need to count to:

`16000000 / (56000 * 2) - 1 = 141.857` (`- 1` because a timer counts from 0 to this value and resets only **after** it has been reached)

From this calculation, we can draw two observations:

1. `141.857` is not an integer and thus you won't be able to generate a wave of exactly 56 kHz.
2. Without prescaling, you need a 16-bit timer as 285 is not representable as an 8-bit unsigned integer.

From now you have two options:

1. Use a 16-bit timer (**timer1**), use prescaler = 1, and select `142` as the Compare Match; that will give you the following frequency: `16000000 / (2 * (142 + 1)) = 55944 Hz`
2. Use an 8-bit timer (**timer0**), use prescaler = 8, and select `17` as the Compare Match; that will give less precision with the following frequency: `16000000 / (8 * 2 * (17 + 1)) = 55555 Hz` which is still within the required range.

Now, regarding how to write your sketch for that, I advise you to check out this instructable which is very complete and very interesting to read.

Of course, the ATmega328P complete datasheet is also important if you want to understand, in the slightest details, what you are doing.

Some important notes:

* An ISR is executed with disabled interrupts and must thus be as short as possible. In particular, there are several functions from the Arduino library that shall not be called from an ISR.
* Arduino Uno clock is not very accurate (it uses a ceramic resonator instead of a quartz, which would have been much more accurate), so this means the output frequency will shift further.
> 10 votes

# Answer
I've found `tone()` useful for generating high frequency pulses on any pin. It should be able to handle 56 KHz. *(Edit: As noted by jfpoilpret, the closest you could actually get on a 16 MHz Arduino is about 55.944 KHz)*

The difficulty will obviously be combining it with your data signal. I don't think you could do that in software without resorting to low level code. It should be pretty easy in hardware though, since it's digital.

All you'd need to do is output your data signal on a different pin, and then combine it with the carrier using an AND gate. The combined signal can go straight to your IR transmitter.

If you don't have an AND gate handy then it's quite simple to make your own using a pair of transistors. Just search online for "transistor and gate".
> 2 votes

# Answer
The accepted answer of jfpoilpret is very well written, perfectly valid and in 99% of the cases I will do exactly what he explains. His solutions are well within your defined parameters, so they should work very well. But what is better than "*very well*"? **Perfection!** After all, the question is about generating a exact value. As said close enough is good in most cases (arguably all), and even when dealing with something as a clocks when 1 second need to be 1 second, you still have to suffer inherited parts imperfections.

What I will suggest is not always possible. In some cases, it's possible, but with much more hassle and effort than this case. Is it worthy depend on a case-by-case basis. My goal is mostly to show a alternative for future references that is better in somewhat fringe cases. This is written with novice Arduino users in mind that don't have extensive experience in electronics.

For more advanced people this probably will look too verbose and dumbed down. But I believe that, those same people probably already know it and don't need this answer. This is also applicable to every microcontroller and every manufacturer and architecture. But for other microcontrollers you will need to consult the correct datasheet to find out proper registers and prescale names and values.

In your case, you need a specific frequency and the nice thing about it, is that exactly 56 kHz actually can be achieved very easy (not counting practical imperfections of the parts). So this is also a perfect example case.

Generating a signal depends on the timers and clock source of the microcontroller, as explained well by jfpoilpret. His answer deals with the problem of one point of view only and that is fiddling with timers. But you can fiddle with the clock source too, or even better with both for synergy and awesome results. By changing the parameters of the environment, in this case hacking the system and replacing the clock source, we can deal with a specific problem with much, much more ease and simplicity.

First to remind, because of toggling the pin state, you need to execute the ISR two times more than the signal frequency. This is 112,000 times per second. 56,000 and 16,000,000 don't add up very nicely as pointed out already. We need to change either the signal frequency or tact frequency. Let's deal for now with an immutable signal frequency and find a better clock speed.

It would be most straightforward to choose a clock with some order of magnitude bigger than 56 kHz (or 112 kHz, but it is practically the same), as you only add zeros and this kind of math is simplest for most people. Unfortunately everything in this world is some kind of compromise with something. Not every value will work.

The first example is with a too low tact generator speed.

If you choose a 56,000 Hz clock you won't be able to do anything as you will need to call the ISR every cycle and can't do anything else. It is utterly useless. If you choose 10 times faster speed (560 kHz), you will have 9 (10 cycles for the timer to reach its max value - one cycle to call ISR function) microcontroller cycles to do your work and this quite possible can be not enough. You simply often need more computational power.

If you choose a value far too great at other hand, as 56 MHz the microcontroller simply can't work with it. It is way too fast. So, simply choosing the biggest value in the shop won't cut it either.

Original Arduino Uno R3 have a stock clock at 16 MHz, so anything slower that that is guaranteed to work. The next value that is an order of magnitude bigger than 56 and lower than 16 MHz is 5.6 MHz. This will lead to be able to call the ISR every 50 cycles and will create the perfect 112,000 Hz timer frequency. And your signal will be exactly 56 kHz. You will have 49 MCU cycles to execute your program between ISR calls, but it is still around 1/3 of the speed of the original clock. One can use 112 as base and use a 11.2 MHz clock and this will give a about 2/3 of the stock 16 MHz resonator. The ISR function will be called every 100 cycles and still generating a perfect 56 kHz signal.

However two major problems exist with these values.

* The first problem severely depends on your needs: You sacrifice about 1/3 (with 11.2 MHz) of your maximum computational power to get the exact signal frequency that use an easy-to-find register value (OCR *iirc*). You may be fine with it or you may not.
* The second problem is a **hard showstopper**: It is very easy to find values, but very often they simply do not exist as a manufactured clock source. This is **Farnell's resonator web page** that simply lack both 5.6 MHz and 11.2 MHz.

To circumvent this we can look at available resonator values and find out something else that can be used to generate exactly desired values. If we divide 56 by 4 we get 14 and luckily there is a 14 MHz resonator. This provides us with much higher speed and more power and with equally easy to find register value. To call the ISR 112,000 times per second we need to put value of decimal 124 or hexadecimal 0x7C in the OCR register, so with counting 124 cycles + 1 for calling the ISR, we get our desired perfect value.

# N.B.

1. ISR - interrupt service routine (this is the code that is executed only on generated interrupts)
2. How big your program can be depends on the memory size! It has nothing to do with the clock speed and has nothing to do with how often you call the ISR.
3. When the microcontroller starts with program command a counter is incremented. If an interrupt is generated, the ISR is called and this value is stored in a special register. When the ISR code completes, the value of the program counter is restored from this special register and the program continues from where it was interrupted as if it had never happened.

I will give an extremely dumbed-down example. If you are a purist, I warn you: Nose and eye bleeding can occur.

Imagine you have to walk from somewhere to somewhere. The step-by-step route instructions are your main program and its commands. How fast you walk or run, depends on your "clock speed", but not on the route instructions (30 steps forward, 1 turn 90 grad. left, 10 steps forward, 45 grad. right, etc.) They are always the same. Now imagine a little kid or a greedy corrupt local politician untie your shoes now and then. This is the event that generates an interrupt. Then you halt after your last step, kneel and tie your shoe again. This is your ISR program.

Then you continue from the place you have stopped; you do not start from beginning. When you walk without a care in the world and with all the time, you don't care even if you have to tie your shoe every other step. If you however do it with time constrains, like running in 100 meters on the Olympics (or running from a hungry flesh-eating predator), stopping and tieing your shoes can have dire consequences. The same is with microcontrollers. Even if you execute only one line of code your program will continue, albeit slow. If you don't care about speed at all, it won't be a problem. If you have to do some time related, like using other timer dependent actions, interference can be very unwanted and problematic.
4. Less is more! A faster clock is not always better. Slower clocked devices use considerably less power. This can be a crucial point in a battery-operated device.
5. The needed cycles are derived from this formulae:
(clock speed / (prescaler value * needed ISR calling frequency)) - 1
> 2 votes

# Answer
You can turn the carrier on and off simply by toggling the carrier pin mode between output and input. I have used this to control a heat pump through the 37KHz infrared (remote control) port.
> 1 votes

# Answer
There is no need to use an ISR to create the carrier. Just set up a timer to produce a 50% PWM output at the required carrier frequency. The ISR is then just in charge of modulating the carrier - typically at 0.5 or 1ms intervals - a far more comfortable rate. In my experience a 5% error in carrier frequency is tolerated by most IR receivers. I used a Freetronics EtherMega 2560 (which has plenty of timers) but I'm sure other CPUs will do just as well.
> 0 votes

---
Tags: arduino-uno, ir, timers
---


# Question
Title: Do gyroscopes purposefully show erroneous data?
I tested an MPU-6050 (GY-521) using an Arduino Nano. I used the I2CDevLib and opened the MPU6050\_DMP6.ino with the Arduino IDE. I opened the MPUTeapot.pde Processing-file with Processing. A few changes was necessary to make it work:

```
MPU6050 mpu;

```

was changed into:

```
MPU6050 mpu(0x68);

```

Additionally I commented out this line:

```
#define OUTPUT_READABLE_YAWPITCHROLL

```

and uncommented this line:

```
#define OUTPUT_TEAPOT

```

When turning everything on, the arrow (Processing) would turn with 5 degrees/s clockwise around the z-axis (plus a very small amount around the other two axes). After about 20 seconds, it would stop, and turn around the x-axis pretty fast for 3 seconds. Then it would stop. Now, the gyroscope+accelerometer would work perfectly. This happens every time I test it.

This happens only when the gyroscope is perfectly still on the ground. It does not stabilize if I move it around. Only after it is left completely still, it'll stabilize after 23 seconds.

Is this how it should work, or is it a problem with the gyroscope? Could it even be caused by the I2CDevLib? Can anybody else confirm this?

# Answer
> 1 votes
MPU6050 is a chip that has an intenal (closed and unknown) algorith to calculate orientation. Because you ar reading ANGLE, that means you are using that algoritm, and that "time" may be the time needed for the calibration.

what do you have as output on the serial?

---
Tags: gyroscope, accelerometer, mpu6050
---