body:
# 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

![enter image description here][1]

### 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:
     - [2 motor drivers][2], (one fried)
     - [4 wheel motors][3], (24v, 360mA with no load)
     - 4 wheels, (plastic jar lids)
 - [Easy Button][4]
 - Arm:
     - [Servo][5], (continuous rotation)
     - [Motor driver][6], (fried)
     - Motor, (12v, found in teacher's junk pile)
     - Eraser
     - Counterweight, (homemade paper bag filled with pennies)
 - [2 battery packs][7], (12V, 1300mAh, Ni-MH rechargeable)
 - 2 solderless breadboards
 - Laser, (5mW)
 - Bluetooth:
     - [mdfly Bluetooth module][8], (5v, 30ft)
     - [Bluetooth adapter][9], (USB, 300+ ft)
 - 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.

 - Arduino: https://github.com/TheGuywithTheHat/robotics-2013/tree/master/Arduino
 - Processing: https://github.com/TheGuywithTheHat/robotics-2013/tree/master/Processing

### More pictures

![enter image description here][10]
![enter image description here][11]

### 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.

  [1]: https://i.stack.imgur.com/w7Gs6.png
  [2]: http://www.pololu.com/product/2136/
  [3]: http://www.allelectronics.com/make-a-store/item/dcm-395/3-24vdc-gear-motor-used/1.html
  [4]: http://www.staples.com/Easy-Button/cat_CL163314
  [5]: http://www.parallax.com/product/900-00008
  [6]: http://www.pololu.com/product/2136/
  [7]: http://compare.ebay.com/like/140474546940?var=lv&ltyp=AllFixedPriceItemTypes&var=sbar
  [8]: http://www.mdfly.com/index.php?main_page=product_info&cPath=&products_id=769&zenid=2qgknl98q9kppt6q14hk70rlr3
  [9]: http://www.aziocorp.com/en/connectivity/16-usb-micro-bluetooth-adapter-v21-edr.html
  [10]: https://i.stack.imgur.com/XoTWl.png
  [11]: https://i.stack.imgur.com/pWIw8.jpg


sender: user

message:
Project Showcase '14

>

> The logo is a derivative of the [Arduino Community Logo][1] licensed under [Creative Commons license CC-SA-BY-NC 3.0][2]

# Update: Winners Announced
The winners of the contest have been announced. Please see the [Meta post for details][3].

To celebrate [10 years of Arduino][4], 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][5]

# 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][6] 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][7] 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.

  [1]: http://arduino.cc/en/Trademark/HomePage?from=Main.Trademark
  [2]: http://creativecommons.org/licenses/
  [3]: https://arduino.meta.stackexchange.com/questions/184/project-showcase-14-winners
  [4]: http://day.arduino.cc/
  [5]: https://arduino.meta.stackexchange.com/questions/153/project-showcase-14-is-coming-to-arduino-stack-exchange-updated-3-19-14
  [6]: https://arduino.meta.stackexchange.com/questions/171/project-showcase-14-detailed-information
  [7]: http://fritzing.org/home/
  [8]: http://fritzing.org/home/

sender: assistant

body:
# 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](http://antoinettejcitizen.files.wordpress.com/2011/03/piezo.jpg) 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
![Photo][1]
*Image taken with webcam hanging over monitor... eek!*

![Fritzing Diagram][2]

**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.

  [1]: https://i.stack.imgur.com/KxflQ.png
  [2]: https://i.stack.imgur.com/yScgU.png


body:
# Stateful questbox
**A [GPS][1] powered box that makes you visit a few spots before opening**

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

# Design

Needed hardware:

* [Arduino Uno][4]
* 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][5] (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**:

* [Persistent state machine library][6]

Inspiration:![Original questbox][7]

# 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](http://forum.arduino.cc/index.php/topic,64596.0.html)

  [1]: http://en.wikipedia.org/wiki/Global_Positioning_System
  [2]: https://www.sundial.com/
  [3]: http://en.wikipedia.org/wiki/EEPROM
  [4]: http://arduino.cc/en/Main/ArduinoBoardUno
  [5]: https://www.sundial.com/quest-box/notes-for-builders/
  [6]: https://www.biicode.com/hithwen/blocks/hithwen/statemachine/branches/master#.UzSTlmR5NUk
  [7]: https://i.stack.imgur.com/864pF.jpg


body:
![MySensors][1]

*- 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.
![Arduino + NRF24L01+][2]

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.

![The sensor network][3]

In the middle you place an Arduion or Raspberry gateway that collects the information from your sensors.
![Raspberry Controller][4]

![Arduino Gateway][5]

# 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.
![enter image description here][6]

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.

![Hello][7]

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.

  [1]: https://i.stack.imgur.com/UKSL4.png
  [2]: https://i.stack.imgur.com/VfWYX.png
  [3]: https://i.stack.imgur.com/ETVDA.png
  [4]: https://i.stack.imgur.com/s8GkQ.jpg
  [5]: https://i.stack.imgur.com/35AcP.jpg
  [6]: https://i.stack.imgur.com/DE5oE.jpg
  [7]: https://i.stack.imgur.com/VYgX4.png


body:
**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!

![Controller Image 1][1]
![Controller Image 2][2]

  [1]: https://i.stack.imgur.com/yYGiv.jpg
  [2]: https://i.stack.imgur.com/raCwl.jpg


body:
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](https://www.u-blox.com/de/lea-6t.html) 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!
![enter image description here][1]
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.

---

![enter image description here][2]
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.

---

![enter image description here][3]
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.

---

![enter image description here][4]
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.

---

![enter image description here][5]
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!
![enter image description here][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.

![enter image description here][7]
And bonus Nyan-Cat!

![enter image description here][8]

(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 systems/
(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.

  [1]: https://i.stack.imgur.com/Zt8N8.jpg
  [2]: https://i.stack.imgur.com/m40P9.jpg
  [3]: https://i.stack.imgur.com/PjfGb.jpg
  [4]: https://i.stack.imgur.com/18PyD.jpg
  [5]: https://i.stack.imgur.com/qLfpS.jpg
  [6]: https://i.stack.imgur.com/zdher.jpg
  [7]: https://i.stack.imgur.com/fdMJZ.jpg
  [8]: https://i.stack.imgur.com/lJSUA.png


body:
# 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:

![3d mockup of the Serial Box design][1]

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][2] 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.

![Preliminary circuit layout][3]

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.

![The prototype in action][4]

# 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.

 * https://github.com/avid-insight/LiquidCrystalEAX

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! :)

  [1]: https://i.stack.imgur.com/m8Les.jpg
  [2]: https://github.com/avid-insight/LiquidCrystalEAX
  [3]: https://i.stack.imgur.com/plAfe.png
  [4]: https://i.stack.imgur.com/9xlB6.jpg


body:
# 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).

![display board with counter][1]

# 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][2] 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!

![Board Schematic][3]

During my tests, I have found a useful [Arduino library for working with MAX-7219][4] which I decided to reuse. I have built my [own library][5] 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][6] 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:

![STRIPBOARD DESIGN #1][7]

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:

![STRIPBOARD DESIGN #2][8]

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

![PICTURE][9]

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

  [1]: https://i.stack.imgur.com/XAvXo.png
  [2]: http://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
  [3]: https://i.stack.imgur.com/PnB3n.jpg
  [4]: http://playground.arduino.cc/uploads/Main/LedControl.zip
  [5]: https://github.com/jfpoilpret/arduino-libraries/tree/master/DisplayDriver
  [6]: http://www.abacom-online.de/uk/html/lochmaster.html
  [7]: https://i.stack.imgur.com/iE37V.png
  [8]: https://i.stack.imgur.com/3dTgz.png
  [9]: https://i.stack.imgur.com/MiLnL.jpg


body:
# Digital Wall Clock with Radio Frequency (RF) Remote Control
**A large (40x30cm / 16x12") 7-segment display wall clock with R/F remote control.**

![enter image description here][1]

# 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:

![enter image description here][2]
![enter image description here][3]

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

![enter image description here][4]
![enter image description here][5]
![enter image description here][6]

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.

![enter image description here][7]

# 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.

1. Crimping KK molex and modu connectors takes A LOT OF TIME!!

1. Laser cut acrylic pieces are the future. They add a lot of quality to the device even if you are clumsy.

  [1]: https://i.stack.imgur.com/T0XE7.jpg
  [2]: https://i.stack.imgur.com/TAqPM.png
  [3]: https://i.stack.imgur.com/yIV4x.png
  [4]: https://i.stack.imgur.com/tnZ5K.jpg
  [5]: https://i.stack.imgur.com/7AtQ4.jpg
  [6]: https://i.stack.imgur.com/r6aQR.jpg
  [7]: https://i.stack.imgur.com/iicCN.jpg


body:
# 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,

![behind TV][1]
![Arduino w/ IR receiver up front][2]
![Close up of box and bearing][3]
![Swiffer handle][4]
![These two buttons don't do anything on the TV anyways][5]

# 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.

  [1]: https://i.stack.imgur.com/KyUOA.jpg
  [2]: https://i.stack.imgur.com/4q8mv.jpg
  [3]: https://i.stack.imgur.com/t4len.jpg
  [4]: https://i.stack.imgur.com/n80OR.jpg
  [5]: https://i.stack.imgur.com/hAevo.jpg

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


message:
Opamp for amplifying 1V signal voltage to 2V

I'm doing my first electronics project where a signal that varies between -1 to 1 V is going into an analog pin on the Arduino. The amplified signal has to be read as fast as possible by Arduino. The source signal is at 60 Hz.

Will [this LM324][1] be a suitable 4-channel opamp for my needs? How concerned should I be about the 2 mV input offset and 20 nA input current bias?

To make full use of the 10bit ADC, would you recommend using an opamp with gain of 2 and biasing the signal by +2.5V? If so, will it be better to create the bias using a potential divider across +5V and GND, or using a 2.5V voltage regulator?

Or would it be better to set AREF to 2V and bias the signal by +1V? In this case, will it be better to use a 2V voltage regulator, or a voltage divider across Arduino's 3V3 and GND using 20M and 33M resistors?

  [1]: http://www.digikey.com/product-detail/en/LM324N/296-1391-5-ND/277627
  [2]: http://www.ebay.com/itm/SOP14-SSOP14-TSSOP14-to-DIP14-PCB-SMD-to-DIP-Adapter-plate-Pitch-0-65-1-27mm-/231183888806?pt=LH_DefaultDomain_0&hash=item35d3a231a6

body:
A 2mV offset voltage will become a 4mV error after amplification. You haven't shown the schematic for your amplification, but the current bias will also become error after amplification.

*That* LM324 variant is surface mount, but there are other LM324 variants in a DIP package, which will work fine in a breadboard.


body:
Just an alternate idea I saw: If you dont need high accuracy, you can use a voltage divider to bias -1 to +1 into 0 to 1, and set the analog reference to 1.2, and get almost the same result but skip the op amp.

A voltage divider with 2 equal resistors will give you the voltage halfway between its two inputs. If the bottom of the voltage divider is at 1v, and the top input is at -1, you get 0 out.

If the bottom is at +1, you get 1 out.

I saw a really clever design using 2 1 megaohm resistors, and actually using the aref pin as an output to provide the bias for the divider, setting the reference to the 1.2v setting, putting the signal in the top of the divider and ground and connecting the adc to the output of the divider.

Aref wasnt meant as a current source, but they use 1meg resistors so the current draw will be at most a few microamps.

A filter cap on aref probably draws more than that if vcc is noisy(if there wasnt current to filter we wouldnt need the cap!) So a few uA should be fine.

They put a 1nf capacitor betcan the input and ground to fix the issues with the ADC input current causing voltage drop. It worked up to 100hz. They never tested accuracy because it wasnt needed though. I'd guess that the adc internal reference was the major error source, probably a few percent.

You can also actually bias with a voltage divider to the 5V supply, and get a 0 to ~1.6V output, it's just a little harder to understand.

This simulation explains the concept(5v version)
http://www.falstad.com/circuit/#$+1+5.0E-6+81.92041607667615+50+5.0+50
r+304+160+304+224+0+1000.0
r+304+224+304+304+0+5000.0
R+304+304+256+304+0+0+40.0+5.0+0.0+0.0+0.5
R+304+160+208+160+0+1+40.0+1.0+0.0+0.0+0.5
w+304+224+400+224+0
x+368+208+456+214+0+24+To+ADC
o+3+64+0+35+2.5+0.00625+0+-1
o+4+64+0+35+2.5+9.765625E-5+1+-1

Left click the output, use view in scope.


message:
Ultrasonic Sensor scanning too often resulting in a whirring noise

I am using an HC-SRO4 ultrasonic sensor for a wall-avoidance, maze-solving robot. However, I have recently run into an issue where I am getting a whirring noise from the sensor because it is taking measurements way too often.

This is the code I have right now:

    const int serialPeriod = 250;       // only print to the serial console every 1/4 second
    unsigned long timeSerialDelay = 0;

    const int loopPeriod = 20;          // a period of 20ms = a frequency of 50Hz
    unsigned long timeLoopDelay   = 0;

    // specify the trig & echo pins used for the ultrasonic sensors
    const int ultrasonic2TrigPin = 8;
    const int ultrasonic2EchoPin = 9;

    int ultrasonic2Distance;
    int ultrasonic2Duration;

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

        // ultrasonic sensor pin configurations
        pinMode(ultrasonic2TrigPin, OUTPUT);
        pinMode(ultrasonic2EchoPin, INPUT);
    }

    void loop()
    {
        debugOutput(); // prints debugging messages to the serial console

        if(millis() - timeLoopDelay >= loopPeriod)
        {
            readUltrasonicSensors(); // read and store the measured distances

            timeLoopDelay = millis();
        }
    }

    void readUltrasonicSensors()
    {
        // ultrasonic 2
        digitalWrite(ultrasonic2TrigPin, HIGH);
        delayMicroseconds(10);                  // must keep the trig pin high for at least 10us
        digitalWrite(ultrasonic2TrigPin, LOW);

        ultrasonic2Duration = pulseIn(ultrasonic2EchoPin, HIGH);
        ultrasonic2Distance = (ultrasonic2Duration/2)/29;
    }

    void debugOutput()
    {
        Serial.print("timeSerialDelay: ");
        Serial.print(timeSerialDelay);
        Serial.println();

        if((millis() - timeSerialDelay) > serialPeriod)
        {
            Serial.print("ultrasonic2Distance: ");
            Serial.print(ultrasonic2Distance);
            Serial.print("cm: ");
            Serial.println();

            timeSerialDelay = millis();
        }
    }

and my wiring:

![breadboard wiring][1]

[Link to product](https://www.foxytronics.com/products/181-4-pin-female-to-female-cable)

Does anyone know why the scanning is happening constantly? It should only be happening every 1/4 of a second, not constantly. The weird thing is that this wasn't happening earlier before I started using the cable.

I believe it has something to do with the 8.5" extension cable I have (needed because I can't mount three sensors, one facing to each side and one in front, on a single breadboard). This is because when I mounted the sensor directly onto the breadboard, the delay was correct and the whirring was not present. However, as I just mentioned, I *need* the extension cable to be able to have the three sensors.

Does anyone have a solution for this?

Thanks!

  [1]: https://i.stack.imgur.com/yzG9F.jpg

body:
If you want to sample at 4Hz (4 times per second), you need to change your headers accordingly:

    const int serialPeriod = 250;       // only print to the serial console every 1/4 second
    unsigned long timeSerialDelay = 0;

    const int loopPeriod = 250;          // a period of 250ms = a frequency of 4Hz
    unsigned long timeLoopDelay   = 0;


message:
Is there a way to make wiring a bare microprocessor to a shield easier?

I currently do most of my AVR work on breadboards, but the large variety of Arduino shields and code out there makes me wonder if I'm not beating my head against the wall sometimes, and looking up port to pin mappings both wastes time and slows me down. Is there any convenient way to adapt AVRs (*other* than those pin-compatible with current Arduinos) to Arduino shields?

body:
The Arduino-way of doing that is making a lookup table that translates pin number to PORTn / DDRn / PINn SFR and the related bit. You can use the same trick and make GPIO pins count in a convenient way as they are in the package. Only special peripherals (like SPI / PWM) cannot be accounted for in this way because they are hard wired to a pin.

A good start is the below `Arduino.h` library sniplet if you want to re-use that concept.

    // Get the bit location within the hardware port of the given virtual pin.
    // This comes from the pins_*.c file for the active board configuration.

    #define analogInPinToBit(P) (P)

    // On the ATmega1280, the addresses of some of the port registers are
    // greater than 255, so we can't store them in uint8_t's.
    extern const uint16_t PROGMEM port_to_mode_PGM[];
    extern const uint16_t PROGMEM port_to_input_PGM[];
    extern const uint16_t PROGMEM port_to_output_PGM[];

    extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
    // extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
    extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
    extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];

    // Get the bit location within the hardware port of the given virtual pin.
    // This comes from the pins_*.c file for the active board configuration.
    //
    // These perform slightly better as macros compared to inline functions
    //
    #define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
    #define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
    #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
    #define analogInPinToBit(P) (P)
    #define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
    #define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
    #define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )

The `pinMode`, `digitalWrite` and `digitalRead` functions are defined in `/usr/share/arduino/hardware/arduino/cores/arduino/wiring_digital.c` which can be used for further inspiration.


body:
You can make adapter boards (one for each mcu model).

The bottom side (male headers) would plug to the breadboard and the upper side would have female headers with the same pinout as an Arduino board (female hearers placed in the appropriate positions to match Arduino shields).

Such a board shouldn't be difficult to design.

Here is an image that resembles what I describe

![enter image description here][1]

It would adapt the pinout of a bare AVR to the pinout of a typical Arduino so that shields can by directly plugged on top of it.

----------
Also a pinout diagram may come handy to speedup things when you use a bare chip with Arduino code.
([image source](http://forum.arduino.cc/index.php/topic,146315.0.html))
![enter image description here][2]

Another similar solution is a small printed sticker placed on top of the AVR
([image source](http://makezine.com/2011/01/12/free-print-and-stick-pinout-label-f/))

![enter image description here][3]

  [1]: https://i.stack.imgur.com/LdseD.jpg
  [2]: https://i.stack.imgur.com/gNAJG.png
  [3]: https://i.stack.imgur.com/AMuWs.jpg


message:
Reading three signals sent serially on Simulink from Arduino

I am sending three signals from one Arduino mega to another using xbees. On the receiving end I am using these signals in a Simulink code to control servo motors. Currently it is set up to read from analog pins without the wireless set up. With the wireless technology the signals are all being sent and received through one serial port. I believe I would need to change the inputs in Simulink to a serial receive block instead of an analog pin block. The problem is the documentation for the serial receive block says you can not assign more than one serial receive block to the same serial port. If anyone has a solution to this it would be greatly appreciated!

receiving code

<!-- language-all: lang-cpp -->

    int received1;
    int received2;
    int received3;
    void setup() {
      Serial.begin(9600);
    }
    void loop() {
      if(Serial.available() )
      {
        received1, received2, received3 = Serial.read();
      }
    }

transmitting code:

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

    void loop() {
      int sensorValue1 = analogRead(A0);
      int sensorValue2 = analogRead(A1);
      int sensorValue3 = analogRead(A2);
      Serial.write(sensorValue1, sensorValue2, sensorValue3);
      delay(1);
    }

body:
You need to put your data into a packet and then send the packet to Simulink.

You have tried this by this line in your transmitting code:
<!-- language-all: lang-cpp -->

    Serial.write(sensorValue1, sensorValue2, sensorValue3);

However, as you can see from the [Serial Write documentation][1] it does not work like that. The function cannot accept 3 arguments.

Try this instead:

    Serial.write(sensorValue1);
    Serial.write(sensorValue2);
    Serial.write(sensorValue3);

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/write/


message:
How to find out whether an arduino can control a servo motor

I have a servo motor with following specs
Torque - 1.08Nm
Max rpm - 3000
Current rating - 7.8 amp
Max voltage - 56V DC

Please tell me how to calculate whether an arduino board - uno rev 3 can control the servo motor? If not, how to find out how many such boards are required?

body:
An Uno most definitely cannot directly control that motor. According to the specs [here][1],

> They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA

So your motor has needs about ten times the voltage and _200_ times the amps that the Uno can supply. Of course, you can always get a driver of some sort for the servo.

  [1]: http://arduino.cc/en/Main/ArduinoBoardUno


body:
The optical encoder you link to has 500 pulses per revolution. This means at 3000rpm , you will be generating pulses 25,000 times a second. You will also need to deal with overshoot (as there is nothing worse than a motor going overspeed and the feedback loop being unable to detect it).

Dealing with an optical encoder generating pulses this quickly is actually quite a challenge, especially with Arduino (which has rather slow native I/O using digitalRead and digitalWrite), and the ATmega328 (which doesn't have any dedicated hardware to deal with high speed optical encoders).

Driving a 56VDC, 7.8A motor isn't an easy challenge either - a motor driver for this isn't going to be easy to design.

I'd probably look for a dedicated servo or CNC motor controller to deal with something like this.


message:
What happens if I power the Arduino with both the USB and external power voltage simultaneously?

I am a new Arduino user. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Basically, I want to automatically shut down the computer after saving all open documents before my UPS battery goes out whenever I am not there to manually shut it down. I am trying to notify the computer about the power failures of main supply - AC 220V 50 Hz (notification/signal sent when power goes out) via USB using Arduino. I am thinking that this can be done by using the external voltage power supply pin. Whenever power goes out in the mains, the external voltage power supply pin will drop to 0 V from 7 V. The value of the voltage can be read using software ( I am unclear about this: Can it be done? If yes, how?). The Arduino will still be powered up as it is connected to USB of computer and thereby communicates to the computer about the power failure.

body:
From arduinoBoardUno:

># Power
>
>The Arduino Uno can be powered via the USB connection or with an external power supply. The power source is selected automatically.

Put the external power through a voltage divider or transistor-based inverter and into an analog (divider) or digital (inverter) pin and check the appropriate value from the pin. Note that this does not require powering the Uno from external power, only connecting the grounds.


body:
>I am a novice user of Arduino. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Lets study the schematic of [Arduino UNO R3](http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf)

The input from the power supply plug (PWRIN, the power jack) goes through a diode D1 (to prevent reverse polarity), and feeds a [NCP1117](http://www.onsemi.com/pub/Collateral/NCP1117-D.PDF) regulator that down converts it to the 5v supply that feeds the 5v parts.

![Power input][1]

The alternative supply comes from the USB plug (USBVCC). The relevant circuit is shown below

![enter image description here][2]

The USB power lines goes through a P-mosfet (T1) that operates as a switch and then goes to the +5V node (that is the +5v regulator output as shown in the first schematic).

The mosfet is controlled by an [LMV358](http://www.onsemi.com/pub/Collateral/LMV321-LMV358-LMV324-D.PDF) operational amplifier (OPAMP) that operates as a comparator.
The negative input of the opamp is tied to 3.3V and the positive one fed through a voltage divider with half the Vin supply level.

 - When Vin >6.6V then the + input of the opamp become higher than the - input and the opamp turns the mosfet off.

 - When Vin <6.6V then the + input of the opamp become lower than the - input and the opamp turns the mosfet on.

Note that Vin is after the input diode so it's about 0.6V lower than the external connected power supply level. So when there is power supply connected to the power input that is higher than 6.6V+0.6V (where 0.6V is the diode D1 voltage drop), then the USB supply line is cutoff (because the mosfet turns off) and the power is provided from the power plug. Connecting or disconnecting the USB supply in this case will not make a difference, so you can have both power supplies connected simultaneously, only when the power input drops below the specified level (about 6.6V+0.6V=7.2V), the USB will start powering the board.

  [1]: https://i.stack.imgur.com/bNsoC.jpg
  [2]: https://i.stack.imgur.com/r9NgC.gif


message:
Arduino Yun does it have a RTC?

Does the Arduino Yun does it have a RTC?

And if so is it connected to the Atheros AR9331 or the ATmega32u4?

If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

body:
> the Yún doesn’t have a real time clock IC on board, so it can’t keep time when is powered off. Instead, it synchronizes with time servers automatically when it powers up and connects to a network using NTP.

*([Arduino Blog](http://blog.arduino.cc/2013/09/02/arduino-yun-hardware-review/))*

Therefore, the **Yun does *not* have a onboard RTC.**

> If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

Probably not. It comes in a [LPCC package](https://www.google.com/search?q=LPCC+package&espv=210&es_sm=122&source=lnms&tbm=isch&sa=X&ei=n6kwU5ncHaSHygGduoGYDQ&ved=0CAoQ_AUoAg&biw=1280&bih=899), which has the solder joints on the bottom. This needs to be soldered by reflow. The Yun does not have any pins connected directly to that chip. You're probably thinking of the ATmega32u4, the actual Arduino chip. The other one is for a router.

**To get the time, you have two options:**

 - **[Use the time from the time server](http://arduino.cc/en/Tutorial/TimeCheck)**

    A few notes:
    > The Yún must be connected to a network to get the correct time. If you used the web-based WiFi interface to configure the Yún for the network, make sure you've selected the proper time zone.
 - **Connect it to a DS1307** (I find [this Adafruit tutorial helpful](http://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit)) You'll need only two pins to use this board. One note: there is a way to connect up to 121 I2C devices using these two pins. However, that gets a little more complicated.


body:
What happens with your Arduino YUN is that it has an internal clock which sincronizes with a computer (at least this is what I do).
However I have read that it can be automatically but I could not do that; have you got a probable solution?


message:
Can I compile c/c++ code on the linux part of the Arduino Yun?

How complete is the linux part of the Arduino Yun?
Can I scp some c/c++ code onto the Atheros AR9331 chip compile it?

Or must I first crosscompile all software and then put them onto the Atheros?

body:
The Yun's OS (Linino) is based on OpenWRT, and the official toolchain from OpenWRT does not appear to have changed much. It could probably be done, the question is if you'd really want to though.

The limited resources (storage, RAM, CPU) means you would most likely not fit all the parts of the toolchain for C/C++ compilation (perhaps with the exception of very basic programs without many dependencies). The YUN's package manager (opkg) should contain pre-built packackes if they exist, but given that even the list of packages is only kept in RAM to conserve space, I doubt the entire toolchain with libraries needed to compile useful stuff would fit.

The official way to build things for OpenWRT appears to be cross-compilation on a much beefier machine, if only because it takes a fraction of the time needed by a native compiler. All in all, you're also very likely to save time and resources by cross-compiling and have more resources left on the YUN itself.


message:
Should a delay be expected to cause deadlock?

I have made a simple program using the `int main() {}` function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?

If I rename the method and call it exactly once from the `loop() {}` function though, it does work.

**Edit:**

The code borrowed the 'main()' function and I suppose redefined it:

    int main() {
        Forward();
        delay(3000);
        Reverse();
    }

    void Forward() {
        //...
    }

    void Reverse() {
        //...
    }

I can see this redefinition of `main()` could cause some serious issues based on the answer below.

body:
You don't seem to use standard Arduino stuff since you defined your own `main()` which is normally avoided when programming Arduino.

If you take a look at Arduino provided `main()` (in **hardware/cores/arduino/main.cpp**), you'll see how it is defined:

    #include <Arduino.h>

    int main(void)
    {
     init();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

Did you notice the `init()` function call at the beginning?

Its code is defined in **hardware/cores/arduino/wiring.c**; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by `delay()`.

In the same **wiring.c** file, you can also find the definition of `delay()`:

    void delay(unsigned long ms)
    {
     uint16_t start = (uint16_t)micros();

     while (ms > 0) {
      if (((uint16_t)micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }

This will turn into an infinite loop if `micros()` always return the same value, and it does so if `init()` has never been called before.

This is what happens with your code.


message:
Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S

On Mac OSX Mavericks, why does Arduino Uno uses serial port named `/dev/cu.usbmodemfa131` while Arduino Nano uses `/dev/cu.usbserial-A702NY8S`?

Are they using different FTDI drivers?

body:
Drivers are different. On older boards, such as Duemilanove you may need to actually [download serial drivers][1] to [talk to them][2] at all in Lion, Mountain Lion, Mavericks.
There's some discussion of that problem [here][3].

  [1]: http://www.ftdichip.com/Drivers/VCP.htm
  [2]: https://pixhawk.ethz.ch/tutorials/serial_terminal
  [3]: http://forum.arduino.cc/index.php?topic=114652.0


body: The Uno is not using FTDI drivers **at all**, since it does USB through an ATmega16u2, not an FTDI chip.


body: It's really down to the manufacturer and what they identify their USB side as. I have found that Arduino(tm) provide a more meaningful (to me) identifier, eg `/dev/cu.usbmodemfa131` Whilst the boards that use the FTDI chip have the more serialised numbers `/dev/cu.usbserial-A702NY8S`.


message:
Serial.read has garbled data after a Serial.write

I'm using the `Serial1` of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:

    byte streamReadResponse;
    Serial1.begin(115200);
    Serial1.setTimeout(9000);
    Serial1.print(cmd);
    Serial1.print('\r');
    Serial1.flush();  //wait for all the data to be sent to the serial
    streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

But, if I add a `delay(50)` before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.

What am I missing? Why is the `flush()` command not working as expected?

body:
Usually, this kind of issue is the result of the several times by time unity of loop statements execution, with the baudrate defined for your serial i/o it's very possible that the flush are override by the new information input and the result are the "garbage" on that.

On my sketches, ever I put "idle function calls"  in some points of the code to avoid this and works succesfully.


body:
I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to ```flush``` the Arduino serial RX before sending any data. So:

    byte streamReadResponse;
    Serial1.begin(115200);
    Serial1.setTimeout(9000);
    while (Serial1.read() >= 0)
               ; // do nothing
    Serial1.print(cmd);
    Serial1.print('\r');
    Serial1.flush();  //wait for all the data to be sent to the serial
    streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);


message:
Warning Arduino CMakeLists "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES"

I'm trying to build an Arduino example without using its IDE. My OS is **Windows 8.1** and I'm using the last version of **CMake (2.8.12.2)** and **MinGW (GNU Make 3.82.90)**.

I downloaded [the Arduino CMakeLists](https://github.com/queezythegreat/arduino-cmake) and I learned all about ``make/upload`` any firmware in my Arduino. I'm using **Arduino UNO**.

Then, if I modify the CMakeLists saved in ``~/arduino-cmake-master/example/CMakeLists.txt`` (***arduino-cmake-master*** is the repository folder) to build the WiFi example ***WiFiWebClient*** too:

    ...

    #Add the WiFi example -> WiFiWebClient
    generate_arduino_example(wifi_example
                         LIBRARY WiFi
                         EXAMPLE WiFiWebClient)
    ...

And execute:

      $ cmake -G "MinGW Makefiles"

      ...

      CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_example" has an INTERFACE_LINK_LIBRARIES property.  This should
      be preferred as the source of the link interface for this library but
      because CMP0022 is not set CMake is ignoring the property and using the
      link implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_example;uno_Wire

      Link implementation:

        uno_CORE;uno_Wire

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_Wire" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_Wire

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_SPI" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_SPI

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_WiFi" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_WiFi

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    -- Generating done
    -- Build files have been written to: ~/arduino-cmake-master

Later I execute:

    $ mingw32-make

    ...

    Linking CXX static library libuno_WiFi.a
    [ 89%] Built target uno_WiFi
    Scanning dependencies of target wifi_example
    [ 92%] Building CXX object example/CMakeFiles/wifi_example.dir/wifi_example_WiFiWebClient.cpp.obj
    Linking CXX executable wifi_example.elf
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::status()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:160: undefined reference to `ServerDrv::getClientState(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::stop()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:131: undefined reference to `ServerDrv::stopClient(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::peek()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:117: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:101: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read(unsigned char*, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:107: undefined reference to `ServerDrv::getDataBuf(unsigned char, unsigned char*, unsigned int*)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::available()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:90: undefined reference to `ServerDrv::availData(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::write(unsigned char const*, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:73: undefined reference to `ServerDrv::sendData(unsigned char, unsigned char const*, unsigned int)'
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:78: undefined reference to `ServerDrv::checkDataSent(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::connect(IPAddress, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:36: undefined reference to `ServerDrv::startClient(unsigned long, unsigned int, unsigned char, unsigned char)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::hostByName(char const*, IPAddress&)':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:228: undefined reference to `WiFiDrv::getHostByName(char const*, IPAddress&)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::status()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:223: undefined reference to `WiFiDrv::getConnectionStatus()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::RSSI()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:181: undefined reference to `WiFiDrv::getCurrentRSSI()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::SSID()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:169: undefined reference to `WiFiDrv::getCurrentSSID()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::localIP()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:149: undefined reference to `WiFiDrv::getIpAddress(IPAddress&)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::begin(char*, char const*)':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:87: undefined reference to `WiFiDrv::wifiSetPassphrase(char*, unsigned char, char const*, unsigned char)'
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:92: undefined reference to `WiFiDrv::getConnectionStatus()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::init()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:22: undefined reference to `WiFiDrv::wifiDriverInit()'
    example\CMakeFiles\wifi_example.dir\build.make:95: recipe for target 'example/wifi_example.elf' failed
    mingw32-make[2]: *** [example/wifi_example.elf] Error 1
    CMakeFiles\Makefile2:748: recipe for target 'example/CMakeFiles/wifi_example.dir/all' failed
    mingw32-make[1]: *** [example/CMakeFiles/wifi_example.dir/all] Error 2
    Makefile:74: recipe for target 'all' failed
    mingw32-make: *** [all] Error 2

The problem is the Arduino.cmake because it's not linking correctly with the library WiFi, but it links with the Wire library.

Anyone knows why that warning appears and why Wire links ok but WiFi doesn't?

Thanks!

**Note**: I'm using original code which is in the repository example, I've not modified this one.

body:
Your question actually has 2 distinct parts:

 1. Why does arduino-cmake generate the warning "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES..."?
 2. Why does `make`, using the generated MakeFile, fail when building WiFi example?

**First off**, the arduino-cmake "**Policy CMP0022**" is just a warning, not an error. As per [this cmake article][1], that CMP policy has been only recently introduced in **CMake 2.8.12**.

You get this warning simply because arduino-cmake has been created based on an older version of cmake and thus does not specifically support this new policy.

In order to get rid of this warning, the documentation mentions you should add the `cmake_policy(SET CMP0022 OLD)` command to your cmake configuration.

Unfortunately I tried it in the example `CMakeLists.txt` to no avail; maybe it has to be set directly in arduino-cmake files (which I have not tested).

Thus, if you want to get rid of this boring warning, it seems the only solution you are left with is to disable all warnings when launching cmake:

> cmake -G "MinGW Makefiles" -Wno-dev

This works fine and has removed all warnings..

**Your second problem** (the real one I would say) is due to to the structure of WiFi library:
![enter image description here][2]

Indeed, as you can see above, it has a `utility` subdirectory that contains additional source code that **cannot be found by arduino-cmake**, as by default it searches for source code files only at first level directory.

How to solve it? Just tell arduino-cmake to do a **recursive search for the WiFi library**; in your `CMakeLists.txt`, ensure you add the following line:

    set(WiFi_RECURSE True)
    generate_arduino_example(wifi_example
                         LIBRARY WiFi
                         EXAMPLE WiFiWebClient)

The added `set(WiFi_RECURSE True)` line just tells arduino-cmake that, for WiFi library, it should recurse through subdirectories when looking for source code.

I have checked it with "Unix Makefiles" (not "MinGW Makefiles" but I guess that won't make any difference) and it worked fine.

  [1]: https://github.com/Kitware/CMake/blob/master/Help/policy/CMP0022.rst
  [2]: https://i.stack.imgur.com/JUqed.png


message:
What's the most efficient implementation of map(x,0,1023,50,250)?

I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with `long` and involves a division and multiplication.

Many times you can replace maps with more basic functions i.e.

    output = map(input,0,1023,0,255);

can become

    output = input >> 2;

or

    output = map(input,0,1023,1023,0);

can become

    output = 1023 - input;

I have one line in some code that says:

    backlight = map(LDRreading,0,1023,50,250);

How could this be simplified so that it is both space and time efficient?

I'll allow slight differences in output values if it results in a much better solution.

body:
You could approximate it quite closely using only two integer operations:

    backlight = (LDRreading / 5) + 46;

That effectively maps input range 0 - 1023 onto output range 46 - 250, so it's fairly accurate. If `LDRreading` is a 2 byte integer type then it should be significantly more efficient (comparatively speaking) than anything which uses `long`.


body:
![Scaling calculation][1]

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:

x * 0.0012 = x >> 3

x * 0.00012 = x >> 4

x * 0.00000012 = x >> 7

Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.

This doesn't get you right to 250, but pretty close:

    >>> for i in range(0, 1024, 34):
    ...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
    ...
    50
    56
    62
       [snip]
    235
    241
    247
    >>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
    247

Do all your processing with a left-justified `int` (`ADLAR`=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.

  [1]: https://i.stack.imgur.com/SJsei.png


body:
How about this, mapping to 50..249?

    output = ((input * 25) >> 7)+50;

Your input range was 1024 (0..1023). Output range is 200 (In the original specification, it would have been 201, which does not divide as neatly). These have a gcd of 8, so `output = (input * (200/8)) / (1024/8) + 50` will do, and the division by a power of 2 can be expressed with a shift. The nice thing is that `1024*25` still fits into a 16 bit integer, so no longs are needed.

If you want full range, you can try throwing in rounding

    output = ((input*25+64) >> 7)+50;


body:
If the input range is limited in size and you have the memory for it nothing beats a simple lookup-table.

like
unsigned char map[1024] = { 50, 50, << more entries here  >>, 250 } ;

You can pre-compute the content in a part of the program that isn't time-critical or just compute the entire table-content beforehand and put it verbatim in the source-code.

Doing a map is just a read of map[] with the original value as index.

If you input range starts with a non-zero number just decrement all inputs by the lower-bound value so you have a 0-base index for the map array. (That works for negative lower-bounds too !)

At most 1 substract (to adjust for a non-zero lower-bound) and 1 addition to calculate the array-base + index.
And a good compiler will be able to optimize it further.

You can't get more efficient than that, but you do need the space to store the table somewhere.


message:
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.

![enter image description here][1]

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][2]
*NOTE* I have used both a direct connection to the `5V` and also used a Voltage Divider. Neither changes the `NUL` return.

  [1]: https://i.stack.imgur.com/NnELQ.png
  [2]: http://www.instructables.com/file/FM8W4A2HKZAVRT9

body:
This sounds like baud-rate mismatch. These dongles don't have a reset ability; they remember their most recent settings. [See my answer][1] to another user having trouble communicating with one these.

  [1]: https://electronics.stackexchange.com/a/103868/3361


body:
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);
      }
    }


message:
What is the maximum power consumption of the Arduino Nano 3.0?

What is the maximum power consumption (in mW) of the [Arduino Nano 3.0][1], when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?

This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

![enter image description here][2]

  [1]: http://arduino.cc/en/Main/arduinoBoardNano
  [2]: https://i.stack.imgur.com/ugt9m.png

body:
Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.

If you **ONLY want to power the Arduino**, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )

Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf

The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf

Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.

So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA

33.4 mA * 5V  = 0.167 Watts

I suspect you want to know to the **total amount of power the Arduino can source**, which is a bit harder to calculate.

The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4

I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.

**280 mA * 5 = 1.4 Watts**

Let me know if my numbers are way off.

P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a [linear regulator][1], like the [LM7805][2]. or maybe the [LM317][3]

  [1]: http://en.wikipedia.org/wiki/Linear_regulator
  [2]: http://www.fairchildsemi.com/ds/LM/LM7805.pdf
  [3]: http://www.fairchildsemi.com/ds/LM/LM317.pdf


body:
From website https://store.arduino.cc/usa/arduino-nano:  Each of the 14 digital pins on the Nano can be used as an input or output. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA.
Therefore i would assume maximum power consumption is 14 x 40mA x 5V = 2.8W, depends on the board effeciency %, for example let's say 80%, so input could be 3.5W, but again you rarely use all 14 pins at once as outputs hence it is way way lower than 3.5W.This is just a ballpoint figure.


body:
"Each of the 14 digital pins on the Nano can be used as an input or output."

There are 6 analog input pins which are also digital pins, you must take those into account.

However, Note 3 under Table 32-2 of the '328P datasheet says:
"Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:

3.1. The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 100mA.

3.2. The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 100mA.

(but ADC6 and ADC7 are analog input only, and should not be sourcing current)

So I would suggest that to keep your Nano healthy, 200mA x 5V = 1W be considered for the IO, and then the amounts noted above for the Power LED, L LED (which is driven by D13), and internal running of the chip be taken into account.


body: Yes, the i/o can source 40mA @ 5v (or 3v3) per pin, but the limit is'nt 40mA from each pin simultainiously but the limit is the processors dissipation. Read the 328A data sheet carefully and the truth will become clear.


message:
How frequently do you need to poll UI buttons before they are perceived as laggy?

Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in `loop()`. This is a commonly used technique.

If you `loop()` executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.

It is possible that your loop would take so long as to cause a delay or lag to be perceived.

The question is, how long would it be, in general, before a user would see this?

body:
The short answer is that you have **100 miliseconds** to respond to the user if you want them to feel the action occurred instantaneously.

According to [Jacob Nielsen](http://www.nngroup.com/articles/author/jakob-nielsen/) in his book [Usability Engineering](http://www.nngroup.com/books/usability-engineering/), from 1993, which is considered an important reference in Systems Usability and User Experience:

> * **0.1 second** is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].

I've taken this citation from this article: [Response Times: The 3 Important Limits](http://www.nngroup.com/articles/response-times-3-important-limits/), also writen by Jacob Nielsen.

Note that in this time you must include all time taken to read the button press and give feedback to the user.

Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

> * 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
>
> * 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.


body:
It's commonly known that people are unable to perceive changes when they happen underneath 10ms after their action. This responsiveness will result in an experience that has recently mostly been described as "snappy". It's noticeable but for users it's hard to put a name on it.

So if you want perfection, take about 15ms of delay. If you want really good, take 100 ms of delay. 100ms is 50ms on average, and will certainly pass for people.

The application and the expected response time is vital too. A sliding door or elevator is given very large tolerance (as the physical object will always take a lot more time) whereas ticket vending machine interfaces are not given any time at all.

The upper limit for polling would be around 1500ms. Around there people will always notice it is slow.

This data is purely personal experience as a gamer and programmer. YMMV and remember that just trying it yourself is the best way to find out how it feels. The only "scientific" answer is the <10 milliseconds, beyond that it's about the ability to perceive the delay (which varies per person and moment) and the tolerance of the user.

As a side note, you can try fluctuating the delays in order to conserve battery or CPU time when the interface is not being used. The user-action, the faster the polling. When the application is doing it's thing, poll very slowly. Better to poll when it matters!


message:
Writing First Library - Serial Stream Object

I have done quite a few projects with Arduino, but have never done more than a "Hello World" in C. I am writing my first library, and a lot of the object oriented stuff is going over my head. Anyway, my library is working as it is supposed to, I pass a float to my function and it formats it properly and sends it out over serial. However, I implemented it in a clunky way. The [Arduino API Style Guide](http://arduino.cc/en/Reference/APIStyleGuide) mentions a way that seems much better:

> When using serial communication, allow the user to specify any Stream object, rather than hard-coding "Serial". This will make your library compatible all serial ports on Mega and the Due, and can also use alternate interfaces like SoftwareSerial. The Stream object can be passed to your library's constructor or to a begin() function (as a reference, not a pointer). See Firmata 2.3 or XBee 0.4 for examples of each approach.

Can anybody elaborate on how to do this, or show me some code?

body:
Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:

    #include "Arduino.h"

    class MyProtocol
    {
    public:
     MyProtocol(Stream& s):serial(s){}
     void send(){
      serial.println("Hello");
     }
    private:
     Stream& serial;
    };

    MyProtocol p(Serial);

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

    void loop() {
        delay(1000);
     p.send();
    }

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.

If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:

    #include "Arduino.h"

    void send(Stream& serial){
     serial.println("Hello");
    }

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

    void loop() {
        delay(1000);
        if(someCondition)
            send(Serial);
        else
            send(Serial1);
    }


message:
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!

body:
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][1] 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][2] 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][3]

[FANCY UNIPOLAR STEPPER MOTOR DRIVER][4]

  [1]: https://www.sparkfun.com/products/11876
  [2]: http://www.pcbheaven.com/circuitpages/Simple_Unipolar_Stepper_Motor_Full_Step_Controller/
  [3]: http://www.electronickits.com/kit/complete/motor/ck1405.htm
  [4]: http://www.stepperboard.com/SS1010.htm


message:
Changing the brightness on a Hitachi HD44780 LCD screen

I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.

body:
Instead of tying the backlight directly to V+ and GND, connect it to a PWM pin (you may need to use a separate driver if the pin cannot source/sink enough current). This will allow you to control the brightness via `analogWrite()`.

Turn the LCD display off (`LiquidCrystal::noDisplay()`) when not actively in use. The contents will remain in memory but the LCD segments will not be driven.

Set the various bits in the `PRR` register to disable any peripherals not it use.

And *don't forget to sleep the CPU when it doesn't need to run*. See the "Power Management and Sleep Modes" section of the datasheet for more information about this and the `PRR` register, as well as the `<avr/sleep.h>` documentation for AVR Libc.


body:
Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.

You can have a finer control over brightness if you put a PWM pulse on said pin. Just call `analogWrite(D3, value)` where `value` is the desired brightness.

The schematics is below. It's from [Freetronics 16x2 LCD SHield](http://freetronics.com/16x2lcd).

![LCD Brightness control][1]

  [1]: https://i.stack.imgur.com/g0D2T.png