body:
Yes you can, and fairly easily. There is a wonderful online simulation (completely free) called [TinkerCAD][1]. It has an excellent breadboard simulation, with parts like transistors, LEDs, ICs, and Arduino. You can program the Arduino and run it all in a live simulation that includes interactive inputs (pushbuttons, DIP switches, etc.).

----------
[Edit: The following text refers to functionality that has been moved to [Circuits.io][1], namely [Eagle PCB][2]\]

That's not all. It also includes in a separate tab schematics for your circuit, and another tab for PCB design of your breadboard circuit! Or, you can just make your schematics from scratch and make your PCB from there.

You can have your circuit designs made and you can buy them. You can do all of this in circuits.io, and you aren't risking messing up your actual Arduino. It also has warning indicators in the simulation (for example, if you didn't use enough resistance on an LED, or an IC).

  [1]: https://circuits.io/
  [2]: https://www.autodesk.com/products/eagle/free-download


sender: user

message:
Can I program for Arduino without having a real board?

I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

sender: assistant

body:
> a way I can write my code and emulate/test it using a desktop computer

If you mean being able to "unit test" using a desktop computer, I can offer a library I wrote called [arduino_ci](https://github.com/ianfixes/arduino_ci).

It doesn't offer emulation.  You would express your tests in code.  For example, here is a test pulled from [the reference documentation](https://github.com/ianfixes/arduino_ci/blob/master/REFERENCE.md#mocks) that validates the data written to a port:

    unittest(pin_history)
    {
      GodmodeState* state = GODMODE();
      int myPin = 3;
      state->reset();            // pin will start LOW
      digitalWrite(myPin, HIGH);
      digitalWrite(myPin, LOW);
      digitalWrite(myPin, LOW);
      digitalWrite(myPin, HIGH);
      digitalWrite(myPin, HIGH);

      // pin history is queued in case we want to analyze it later.
      // we expect 6 values in that queue.
      assertEqual(6, state->digitalPin[1].size());
      bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
      bool actual[6];

      // convert history queue into an array so we can verify it.
      // we expect to find 6 values: the 5 we set, plus the initial LOW
      // and this is where/how we assert that
      int numMoved = state->digitalPin[myPin].toArray(actual, 6);
      assertEqual(6, numMoved);

      // verify each element
      for (int i = 0; i < 6; ++i) {
        assertEqual(expected[i], actual[i]);
      }
    }

In practice, you would probably not be calling the `digitalWrite` functions directly -- you'd call a function in your library, then verify that the "world state" (represented here by the `GODMODE` construct) matches what you expected your library to do.


body:
**Edit 2:**
Please hit the like button to support free Arduino simulator

I am working with the new Wokwi Arduino Simulator. Wokwi Arduino simulator is based on AVR8js engine which is made open-source. You can find the link [here][1]

Following are the main features of the simulator

• Supports **multiple file** projects

• Supports the Arduino libraries

• Whatever compiles on the Arduino IDE will compile on the simulator

• Supported by **all browsers**

• Compiles with **latest Arduino IDE**

• Supports **FastLED** and many other peripherals

• **No** download or installation needed

• **Easy to share** the code and project with just a single click

• Smart - Code **Autocompletion**, Code **auto-formatting** are supported

• Provides standard library **demo examples**

• Project can be compiled on **RUN on Mobile browsers** as well

• Tries to be closer to real circuits – Example – **Button bounce** like in real hardware

• Supports Arduino Mega, Arduino Nano, Arduino UNO, **ATtiny85**

• Supports **assembly instruction** execution

• Provides **LED power** and **FPS features** for FastLED projects

• Supports a **plethora of Arduino peripherals** for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more

• **Serial monitor** is supported as well

A few Arduino Examples
======================

Simon game using ATTiny85, buttons, buzzer, and LEDs
----------------------------------------------------
Project link: https://wokwi.com/arduino/projects/285525640477671948

• Note the use of the same pins for both output and input
• The code can be written for ATTiny85 the same way how it is written for Arduino

[![enter image description here][2]][2]
_______________
Slide switch demo example
-------------------------
Project link: https://wokwi.com/arduino/projects/292033853022798344

The slide switch can also be used as an ON-OFF switch

[![enter image description here][3]][3]
____________
Simple Piano Example
--------------------
Project link: https://wokwi.com/arduino/projects/291958456169005577

Plays several notes based on Arduino built-in library support

[![enter image description here][4]][4]
_______________
Max7219 LED dot matrix Arduino UNO project Example
--------------------------------------------------
Project link: https://wokwi.com/arduino/projects/290144516831183368

Supports concatenation of the Max7219 modules

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

__________
HC-SR04 Ultrasonic sensor Example
---------------------------------
Project link: https://wokwi.com/arduino/projects/290056311044833800

A very useful project to build several interesting projects (RADAR 3D mapping and more  )

[![enter image description here][6]][6]
___________
Bounce feature example in Arduino Simulator
-----------------------------------------
Project link: https://wokwi.com/arduino/projects/288332630964830728

Bounce is the basic problem in most beginner projects. That can create multiple input triggers, unwanted noise and makes the project to misbehave. Sometimes can be difficult to identify without proper debug or measurement tools. Knowing about the bounce in switches and tips and tricks on how to solve it is an interesting study for every beginner hobbyist.

[![enter image description here][7]][7]
__________________
LCD1602 display example in Wokwi Arduino Simulator
--------------------------------------------------
Project link: https://wokwi.com/arduino/projects/287736345015616008

LCD1602 is one of the best HMI and has been here for a long time. It helps in debugging projects during run time, we can also use it along with a keypad to make a completely practical HMI (human-machine interface). Very easy to use, and easy to learn about programming.

[![enter image description here][8]][8]
_________________
FastLED example with FPS and LED power
--------------------------------------
Project link: https://wokwi.com/arduino/projects/287736345015616008

Second link: https://wokwi.com/arduino/projects/281176629596652040

FastLED is a second revolution in the history of LEDs. It was never easier than now to program multiple LEDs with just one Arduino Pin. With the growing FastLED community ([reddit][9], wokwi-[Discord][10], and others) and [FastLED][11] examples and libraries, This is one of the most important elements in the wokwi [Simulator][12].

[![enter image description here][13]][13]
[![enter image description here][14]][14]
________________
Temperature and humidity sensor, Real time clock module example
---------------------------------------------------------------
Project link: https://wokwi.com/arduino/projects/287736345015616008

[![enter image description here][15]][15]
______________
Serial Monitor example
-----------------------------
Project link: https://wokwi.com/arduino/projects/286653669554782732

The serial plotter is a very useful feature when working with analog peripherals.

[![enter image description here][16]][16]
________________

 - **Adafruit SSD1306 Library** [Adafruit SSD1306 Library][17]
 - **Adafruit DHT Sensor** [Library][18]
 - **Another DHT** [library][19] from GitHub
 - **FastLED example** [Library][12]
 - **SSD1306 GitHub** [example][20]
 - **Arduino Servo** [Library][21]
 - **Task Scheduler** [Library][22]
 - **Simon Game, Electronic Safe** [Example][23]
 - **LCDGFX on Arduino** [Example][24]
 - **SSD1306 Library** [Examples][25]

The Arduino simulator is free for the Arduino Community to use. We are adding more elements one after the other. It is free and we invite you to try it as well.

Please leave a comment to add more libraries or features as well

[![enter image description here][26]][26]
[![enter image description here][27]][27]

[![enter image description here][28]][28]

![enter image description here](https://i.stack.imgur.com/ZUXY2.gif)![enter image description here](https://i.stack.imgur.com/ItJjP.gif)![enter image description here](https://i.stack.imgur.com/qneEo.gif)![enter image description here](https://i.stack.imgur.com/cibqF.gif)

  [1]: https://github.com/wokwi/avr8js
  [2]: https://i.stack.imgur.com/aN0Yg.png
  [3]: https://i.stack.imgur.com/43k3T.png
  [4]: https://i.stack.imgur.com/MXiKQ.png
  [5]: https://i.stack.imgur.com/mWqpA.png
  [6]: https://i.stack.imgur.com/VwTyz.png
  [7]: https://i.stack.imgur.com/eFneH.png
  [8]: https://i.stack.imgur.com/mc0Zo.png
  [9]: https://www.reddit.com/r/FastLED/
  [10]: http://www.wokwi.com/discord
  [11]: https://www.hackster.io/ldir-arcostasi-urish-sutaburosu-stevesigma-stepko-on-wokwi-discord/100-beautiful-fastled-projects-wokwi-arduino-simulator-2021-39fcc0
  [12]: https://wokwi.com/arduino/libraries/FastLED
  [13]: https://i.stack.imgur.com/z2mQ6.png
  [14]: https://i.stack.imgur.com/I23iD.png
  [15]: https://i.stack.imgur.com/U8V91.png
  [16]: https://i.stack.imgur.com/OdeRN.png
  [17]: https://wokwi.com/arduino/libraries/Adafruit_SSD1306
  [18]: https://wokwi.com/arduino/libraries/DHT-sensor-library
  [19]: https://wokwi.com/arduino/libraries/DHTlib
  [20]: https://wokwi.com/arduino/libraries/SSD1306Ascii
  [21]: https://wokwi.com/arduino/libraries/Servo
  [22]: https://wokwi.com/arduino/libraries/TaskScheduler
  [23]: https://wokwi.com/arduino/libraries/demo
  [24]: https://wokwi.com/arduino/libraries/lcdgfx
  [25]: https://wokwi.com/arduino/libraries/ssd1306
  [26]: https://i.stack.imgur.com/AnjIw.gif
  [27]: https://i.stack.imgur.com/4l4XH.gif
  [28]: https://i.stack.imgur.com/rkNt4.gif


body:
An alternative to simulators are services similar to online compilers like [coliru](http://coliru.stacked-crooked.com/), which allow users to build and run their code on a remote system. This approach has the same limitations as online compilers:

- The hardware configuration and state cannot be altered remotely, except for explicitly defined interfaces.

- The changes to the hardware state cannot be observed, again, except for explicitly defined interfaces.

Typically, most online compilers provide users with access to command line and process STDOUT. On Arduino, providing remote access to the serial port would provide a similar degree of control: users would be able to observe and control their running sketch through UART, but would not be able to connect/remove wires, push buttons, act on external sensors, etc.

Surprisingly, I couldn't find any such online services, so I ended up writing my own - [HW Farm](https://github.com/dimag0g/hwfarm). If you have a web server and Arduinos you can connect to it, you can install HW Farm on it and let people access those Arduinos through a web interface. I also [host](https://dimagog.ddns.net/hwfarm/) such a server myself, which has a single Arduino Mega with a bunch of I2C devices connected to it. You can try it out, but don't expect it to be online and available all the time.


message:
Compatibility between Arduino and Arduino clones

In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that

>  It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.

In fact I never had any problems with shields or the IDE.

My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.

body:
If you closely look at the Arduino circuit diagram, You'll notice that it is little more than power supply, a USB-serial interface and the microcontroller itself.

The 'hard' part for compatibility is getting the board layout right (which connector goes where on the circuit board), and to load a compatible bootloader in the chip (which is free/open software, so why bother making your own?).

I've used several el-cheapo Arduino clones and apart from apparent physical construction (one feels a bit flimsy), they all work just like the 'real thing'. I guess the major difference between original and clone is the quality of the board, the used components and quality of assembly.


body:
Over the years I have used original Arduino boards as well as a multitude of clones of varying provenance, from the excellent [InduinoX][1] that is listed on [the Arduino site][2] as an official compatible board, to the very well-made Chinese [Meduino Nano Enhancement][3] (3.3 / 5 Volt switchable), to dirt-cheap clones from eBay that are sometimes better constructed than the official boards.

There is nothing unique or sophisticated about the Arduino board: It's basically just the microcontroller (atMEGA328, atMEGA1280, SAM3X8E or others) and its minimal support hardware. Not much that can go wrong with that little, really.

The two common elements that ensure compatibility across these boards are:

1. The Arduino bootloader
2. Support for the board within the official Arduino software distribution

The bootloader can be replaced with a better or more up-to-date version if one is available for the microcontroller on your board.

The support files can either be found online, or minor edits to the nearest similar board's files can provide the requisite support for the Arduino environment.

In short: *Yes, clones typically work just as well as the original Arduino, and clones with enhanced features often work far better while retaining compatibility (e.g. InduinoX)*

  [1]: http://www.simplelabs.co.in/content/induino-r3-low-cost-arduino-r3-usb-clone-board
  [2]: http://playground.arduino.cc/Main/SimilarBoards#goArdComp
  [3]: http://youtu.be/DXwezev713s


body:
Check twice !

Most clones are exact clones with copies of the flaws that original Arduino board had. Like for example Arduino Nano not having proper RESET and TEST pin connection of FT232RL USB-serial bridge. This flaw may lead to FT232RL not responding to PC and was eventually fixed in later revisions of Arduino Nano board. Some clones were not updated.

Another "not exactly Arduino clones" example are numerous boards with CP2102 USB to serial bridge instead of FT232RL. This may pass unnoticed, but may give frustration when one clone board connects and works with your PC, but another generates system complains on missing drivers.

So again - be prepared !


body:
I have found that most clones will do what you expect them to do, but as [x4mer][1] states in his [answer][2], be prepared.

The most annoying issue, and even then it *is* quite minor, is that a lot of Chinese clones do not use an ATMega for the USB and instead use a **CH340G**.  These chips, while fine when connecting to a PC running Windows 7, have great difficulties with the drivers on OS X, and end up just not being recognised. It is possible [to find a driver for the CH340G][3], but when I installed it, it immediately crashed the MacBook, upon plugging in the cloned UNO..!

 I had to buy three or four clones on eBay until I got an Uno with an _actual_ 16u2 implementing the USB interface, which would actually be recognised by the MacBook Pro, and would allow me to code using the Arduino IDE running on OS X.

Before that, I had to use a Wintel laptop.

  [1]: https://arduino.stackexchange.com/users/32/x4mer
  [2]: https://arduino.stackexchange.com/questions/71/compatibility-between-arduino-and-arduino-clones#answer-90
  [3]: http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html


message:
Does Arduino Uno R3 require cooling in a closure?

I was looking at getting an enclosure to house my Arduino Uno R3, but I'm not sure if I should also attach a fan.  Does anyone have experience with this?  It doesn't look like much heat is being generated, but with no ventilation except some slits in the enclosure, there won't be much air circulation without a fan.  My concern with adding a fan was the fact that I'd need to power it.

body:
The only times I had an AVR run hot was when I applied reverse power to it. You'll be fine without a fan for the Arduino board itself, as long as you don't run power hungry peripherals from it.

Probably the only thing you really need to check (apart from absolute maximum ratings: 40mA max per IO pin and 200mA max for the whole microcontroller) is the on board voltage regulator (usually three pin device with a heat sink soldered down to the PCB) if you power it from a voltage > 7V or so.


body: No, You shouldn't need any type of cooling device such as a fan as long as the case has a few holes in order to allow the heat to rise out of the case. I do not recommend using cases that are completely sealed, unless you are using it in an environment that has things that could hard the Arduino such as  ROVs or Nuclear waste facility (although I don't know why you would be at one in the first place).


message:
Why can't I upload a sketch while other components/devices are connected to my Uno?

I wanted to make a fairly simple circuit which would flash a series of LEDs in sequence, using my Arduino Uno (more specifically, a SainSmart clone). I wrote my sketch and it compiled fine. After that, I connected 8 LEDS+resistors to pins 0 through 7, and then connected the Uno to my computer via USB.

I've uploaded sketches successfully in the past, so I'm sure my settings and drivers etc. are correct. However, when I tried to upload my sketch this time, it didn't work.

I tried removing everything I'd connected to the Arduino's pins, and suddenly the upload worked again.

Why does this happen? Does it mean I have to disconnect everything from the board every time I upload a sketch?

body:
The problem is specifically pins 0 and 1. Although they can be used as regular digital IO pins, they also serve as the RX and TX pins for the Uno's serial port. The USB connection (for uploading sketches etc.) is routed to the same pins internally. Unfortunately that means anything connected on pins 0 and 1 can interfere with the serial connection, preventing communication via USB.

In short, it's not necessary to disconnect *everything* when uploading a sketch. It should only be necessary to disconnect anything from pins 0 and 1. Rather than going through that hassle every time a sketch is uploaded though, it may be best just to avoid using those pins unless necessary (e.g. you run out of other pins, or your project needs a serial connection to another device).


body:
" Peter R. Bloomfield " I used to upload sketch in my arduino uno by connecting Rx and Tx pin but my sketch get uploaded.
Actually problem is arduino uno driver may be deleted in your case


message:
Is there an Arduino simulator that runs on Mac OS X?

I need to simulate my Arduino project with other circuit components before implementing the project. Is there a decent simulator that runs on Mac platform?

body:
There is a decent program called [Simulator for Arduino][1] made by Virtronics. Although it is made to run only in windows, you could run it in a [WINE environment][2]. WINE allows windows programs to be ran in Mac and Linux OS.

  [1]: http://virtronics.com.au/Simulator-for-Arduino.html
  [2]: http://wiki.winehq.org/MacOSX#head-43b0651931c700b0f796ab7d5280a08eb58d51e0


message:
Is there a limit on how much current a pin can sink?

I've been experimenting with an 8x8 LED matrix controlled by an Arduino Uno. As I think is typical, the matrix uses a common anode for each row, and a common cathode for each column.

At the moment, I've got all the matrix pins connected directly to IO pins on the Uno, and I haven't had any problems lighting the LEDs one-by-one. Going through the whole matrix like this makes updates a little slow though, meaning the LEDs aren't as bright as I'd like.

As far as I know, I can't safely light up an entire row at once, because an individual pin on the Uno isn't capable of sourcing enough current to drive 8 separate LEDs at the same time (requiring at least 10mA each to be bright enough).

It occurred to me that the reverse might be safer. If I light up an entire column at a time, then each pin only has to source enough current for one LED, which should be no problem. However, it relies on one pin potentially sinking the current from all 8, totalling at least 80mA.

Is this possible, or am I going to fry my board?

body:
> am I going to fry my board?

Pretty likely outcome. Here's why:

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of <s>150</s> 200 mA.

Realistically, the current graphs in the atMEGA328 datasheet do not even go all the way to 40 mA, hence it is safest to restrict the current to perhaps 20 mA total per GPIO.

In other words, whether a GPIO is used as source or sink, the limits remain pretty low, and in practice, should be kept much lower than the absolute maximum ratings. Even below absolute maximum, running a microcontroller to too high a temperature reduces its life expectancy.

**Solution**:

Use either BJTs, MOSFETs, or some driver IC such as the [ULN2003][1] to actually drive the current through the LEDs.

  [1]: http://www.ti.com/lit/ds/symlink/uln2003a.pdf


body:
[I'm going to steal my answer from when I answered this question on the last arduino SE attempt.][5]

---

This is a bit complex. Basically, there are a number of limiting factors:

The IO lines from the microcontroller (i.e. the analog and digital pins) have both an aggregate (e.g. total) current limit, and an per-pin limit:

![enter image description here][1]
From the [ATmega328P datasheet][2].

However, depending on how you define the Arduino "Pins", this is not the entire story.

The 5V pin of the arduino is *not connected through the microcontroller*. As such, it can source significantly more power. When you are powering your arduino from USB, the USB interface limits your total power consumption to 500 mA. This is shared with the devices on the arduino board, so the available power will be somewhat less.
When you are using an external power supply, through the barrel power connector, you are limited by the local 5V regulator, which is rated for a maximum of **1 Amp**. However, this it also *thermally limited*, meaning that as you draw power, the regulator will heat up. When it overheats, it will shut down temporarily.

The 3.3V regulated output is able to supply 150 mA max, which is the limit of the 3.3V regulator.

---

In Summary
-

 - The *absolute maximum* for any single IO pin is **40 mA** (this is the *maximum*. You should never actually pull a full 40 mA from a pin. Basically, it's the threshold at which Atmel can no longer guarantee the chip won't be damaged. You should always ensure you're safely *below* this current limit.)
 - The total current from all the IO pins together is **200 mA max**
 - The 5V output pin is good for **~400 mA on USB, ~900 mA when using an external power adapter**
    - The 900 mA is for an adapter that provides ~7V. As the adapter voltage increases, the amount of heat the regulator has to deal with also increases, so the maximum current will drop as the voltage increases. This is called *thermal limiting*
 - The 3.3V output is capable of supplying **150 mA**.
   - Note - Any power drawn from the 3.3V rail *has to go through the 5V rail*. Therefore, if you have a 100 mA device on the 3.3V output, you need to *also* count it against the 5V total current.

**Note: This does not apply to the Arduino Due, and there are likely some differences for the Arduino Mega. It is likely generally true for any Arduino based off the ATmega328 microcontroller.**

  [1]: https://i.stack.imgur.com/nLAlB.png
  [2]: http://www.atmel.com/Images/doc8161.pdf

  [5]: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins/67094#67094


message:
Is there a color LCD display for an arduino?

I currently have a Mega2560 with the LCD4884 Shield. The Shield is good for putting out text and simple pixel images. But I am wondering if there is something that has a full range of colours that would work with the Arduino? The screen size would only have to be a few inches in size.

body:
There are actually several shields that have color screens on them. Many of the shields are just regular mini TFT displays, however there are also touch screen ones.

[Here is one][1] from Adafruit that includes a MicroSD holder and a Joystick.

[Here is one][2] from Radio Shack that features a 2.8 inch screen with touch capabilities

As far as screen size, many of the screens are only about an 1 inch across, however the biggest I have ever been able to find are 2.8 in.

  [1]: http://www.adafruit.com/products/802?gclid=CK3Mk63SxrwCFedlOgodA3IABQ
  [2]: http://www.radioshack.com/product/index.jsp?productId=12688460&CAWELAID=120125420000001702&catargetid=120125420000031766&cadevice=c&cagpspn=pla&gclid=CMbdyJ_TxrwCFW1nOgodHF4AGg


body:
There's also a [2.2" Adafruit TFT][1].

The nice things about the Adafruit displays are:
i) library support for both the [display][2] and the [graphics core library][3]. So it's easy to get it up and running.

The built in frame buffer reduces resource requirements on Arduino.

  [1]: http://www.adafruit.com/products/1480
  [2]: https://github.com/adafruit/Adafruit_ILI9340
  [3]: https://github.com/adafruit/Adafruit-GFX-Library


body:
Another very cool screen is the official [Arduino TFT LCD Screen][1]. ([Datasheet][2] if you're curious.)

It's a 1.77" screen, with a resolution of 160x128. It has a micro-SD slot in it, which is easily accessible. It is a color screen, with up to 18 bit per pixel.

The extremely nice thing with this screen is that since it's officially supported, you don't need to do anything extra to support it. The [official Arduino TFT library][3] works perfectly with it. However, according to [Jameco][4]:

> Library Update: There is a known issue with the TFT library supplied
> in IDE versions 1.0.5 and 1.5.4 Beta. You will need to replace the
> library. We have zipped up the updated TFT library for both versions
> available here. Just delete the existing library and copy in the
> replacement for the appropriate IDE version and restart the IDE. (IDE
> v1.0.5 or v1.5.4)

So beside that minor fix, everything should be easy and quick to work with. [This page][3] has some code samples which should make it easy to work with.

  [1]: http://store.arduino.cc/index.php?main_page=product_info&products_id=288#.UwlAY_kiEw8
  [2]: http://arduino.cc/documents/datasheets/A000096_Datasheet_HTF0177SN-01-SPEC.pdf
  [3]: http://arduino.cc/en/Reference/TFTLibrary#.UwlB__kiEw8
  [4]: http://www.jameco.com/1/1/52373-a000096-tft-lcd-screen-runs-5vdc-shields.html


message:
Why is the regulator very hot?

We have an LED strip connected to output 6 and is powered by the Uno board itself.  Shouldn't be drawing too much current, only have 10 elements on the LED strip.  While this LED strip is connected to the Uno, I noticed that the regulator is getting very hot.

One thing we haven't done yet is to power the LED strips from an external source, which will be necessary since there will be many strips.  At the moment, the students are simply trying to debug their program with the small strip.

body:
A regulator normally get hot when is driven a current near to the maximum that could be driven, and its a normal thing the regulator keep warm.

A normal regulator like [LM7805][1] could work until 125 C°.

If you try to drive more current that it can probably it will burn, so, maybe its time to you change your power supply to an external one to keep safe your Arduino board.

  [1]: http://www.fairchildsemi.com/ds/LM/LM7805.pdf


body:
If you power the Arduino with an external power supply the on board regulator has to *dissipate* the voltage difference between input and 5VDC at the total current you draw from the board.

As Klaus Warzecha wrote in an [answer](https://arduino.stackexchange.com/questions/60/how-to-prevent-breaking-my-arduino-by-mistake/72#72) to [another question](https://arduino.stackexchange.com/questions/60/how-to-prevent-breaking-my-arduino-by-mistake)

> The Arduino is just the brain, not the power station.

If the output voltage of your power supply is 12V, then the regulator will be dissipating 12-5V = 7 V at the total current drawn. Total dissipated power for eg. 150mA (just an estimate) would be P = V × I = 7 × 0.150 = 1W
The regulator will be pretty hot from dissipating 1W.

Mind you that the current is not limited to 150mA, enough LEDs can easily increase current and power. If the regulator is stressed (often) enough, sooner or later it will fail. It is better practice to power any load directly from the external power supply, taking the higher voltage into account.


body:
When a circuit is hot, it's very likely that it is drawing too much current. It may be a component that's getting more current than it's designed for, or a PCB track, or a wire.

So, before you do anything else, I strongly suggest that you get a DMM and measure the current drawn by the board when powering the led strip. Google for ways to measure current with a DMM, as it can be tricky if you never done it before.

Then, compare the value to those specified by the voltage regulator datasheet. The current should be within those values shown in the "Electrical Characteristics", and well below those from "Absolute Maximum Ratings".


message:
Is it possible to upload a program from a tablet?

Is there any easy way to upload a program/sketch from an iPad or Android tablet without adding extra an shield (Bluetooth or Wi-Fi)?

If not, can it be done using shield? Which shield is preferred?

Also what are the IDE options available?

body:
Unfortunately Apple doesn't allow apps that implement programming languages. This being said, it is unclear why they would not allow an app that has to do with the Arduino IDE due to the fact that the code doesn't actually run on the Ipad itself.

See [here][1] for more Info.

As far as an Android IDE, I have heard that there are a few people working on different IDEs that sends the code to the Arduino over the internet, although they have not been released yet, and the details are still a bit unclear.

  [1]: http://www.libertypages.com/clarktech/?p=1690

Source:
http://forum.arduino.cc/index.php?topic=61305.0


body:
I figured out a way to do this without having to port the compiler to iOS. It only works with the arduino Yún, but the Yún can send code to other arduinos with an spi cable.

* Install an SSH app on your device so you can communicate with the arduino
* Using that, install [Ino][1] on your Yún, a command line arduino compiler
* Create a file, put your code in it, then save it
* use [Ino][1] to upload your code!

kind of confusing, but it could work!

  [1]: http://inotool.org "Ino"


body:
You can always upload to the Arduino via Bluetooth.

 1. You must have a bluetooth chip/shield (any should do) and a PC that has bluetooth (or a table that can compile, most likely an Android tablet)
 2. You must change the BT baud rate to the same as normal arduino upload, which is 19200 (default BT baud is 9600).
 3. Connect the BT to Pin 0 and 1 so act the same as having a USB cord connected
 4. Connect a wire to the reset pin to allow remote resetting the arduino to statup the bootloader
 - There must be a delay before
    hitting the reset pin as the bootloader must be active when hitting
    the upload button.
 5. Enjoy

For a more detailed description please read: http://ame2.asu.edu/staff/kidane/ArdWilessBtProg.pdf


body:
Since your question is only about uploading, this will work with a Yun

- compile your sketches with the IDE on your pc
- for each hex file, copy it to the yun and run `merge-sketch-with-bootloader.lua PATH_TO_HEX_FILE`
- manage to connect to the Yun from your tablet via SSH
- once logged in, run `run-avrdude PATH_TO_HEX_FILE`


body:
> Is there any easy way to upload a program/sketch from an iPad or
> Android tablet without a shield (Bluetooth or Wi-Fi)?

If you don't mind re-writing your program in an interpreted language,
one option is:

* Install an [interpreter on the Arduino][1], perhaps using the standard Arduino IDE running on a standard desktop PC -- like the bootloader, this only needs to be done once.

Then:

* Use your favorite terminal emulator on the tablet
* Somehow link the Arduino and the Android together, and tell the terminal emulator to talk over that link.(*)
* Tell the terminal emulator to send the (more-or-less human-readable plain text) program to the interpreter over the link. (No compiler necessary on the tablet).

(*) There are several different ways to make this link; some of them are mentioned at https://arduino.stackexchange.com/questions/253/how-do-i-write-an-arduino-sketch-and-an-android-application-to-talk-to-each-othe .

  [1]: http://playground.arduino.cc/CommonTopics/InterpretedLanguages


body:
i have been trying out arduinodroid - it's an ide that claims you can upload to your arduino from it. you need an OTG cable (on the go) and to be honest i never actually managed to upload from arduinodroid but others seem to be able to...

my arduino is currently not talking to my computer - a bootloader problem it seems - so i'm getting hold of an AVR ISP MKii - with one of them it is apparently possible to send from terminal ide - an android app, will feedback when and if i get it to work.


body:
I have tried android app to programming Arduino Uno via bluetooth, simply by adding [Bluino_Shield][1] to your Arduino Uno. This link app [https://play.google.com/store/apps/details?id=com.bluino.bluinoloader][2]

  [1]: http://www.bluino.com/2015/10/bluino-shield-pre-order.html#.Vkaz9NIrK70
  [2]: https://play.google.com/store/apps/details?id=com.bluino.bluinoloader


message:
Programming an Arduino using Python, rather than C/C++

I am not very skilled with the C Language and I was wondering if there is a way in which python could be used to program an Arduino. This would most likely require a different IDE in order to be able to debug the scripts them self.

body:
Yes, it is (somewhat) possible to program the Arduino using Python. One such project on Github is the [Python Arduino Prototyping API v2][1]. It provides very basic functionality such as digital I/O and analog I/O.

This can be used for very simple projects.

---
*This project is a bit of a hack at "programming" the board using the serial connection. It passes the commands over the serial connection to a sketch running on the board which then "executes" the Python command.

  [1]: http://github.com/vascop/Python-Arduino-Proto-API-v2


body:
It's going to be extremely difficult to get any kind of Python script running directly on the Arduino. The reason is that it's an interpreted language, so you would need the interpreter on-board in addition to the plain text script. There's probably not going to be enough memory for all of that.

Your best bet would probably be finding a way to compile a Python script to native machine code (which is how C/C++ works). I believe there are projects around to do something like that for other platforms, but (as far as I know) none which does it successfully for Arduino yet.

You might find some more useful information on this question at Stack Overflow: [Is there a way to "compile" Python code onto an Arduino (Uno)][1].

  [1]: https://stackoverflow.com/questions/8114916/is-there-a-way-to-compile-python-code-onto-an-arduino-uno


body:
There is a project which brings a [Python virtual machine](https://code.google.com/p/python-on-a-chip/) to micro-controllers, including the [Arduino Mega](https://code.google.com/p/python-on-a-chip/source/browse/#hg/src/platform/arduino_mega).

Here's a quote from the Ardunio Mega [README](https://code.google.com/p/python-on-a-chip/source/browse/src/platform/arduino_mega/README), which gives a feel for what this could be like (though, I've not tested this!):

> The following is an example session using ipm::
>
>     ipm> import avr, sys
>     ipm> avr.ddrA(0xff)
>     ipm> avr.portA(0)       # Pins 22-29 all at 0 V
>     ipm> avr.portA(0xa5)
>     ipm> sys.heap()
>     (2622, 7424)
>


body:
I have used pyserial with great success in controlling the pins on the arduino.  Your workstation (laptop, etc) runs a python script that then communicates in real time to the arduino.

It's not quite the same as running the script directly on the arduino but I was doing quite a bit more than I thought the arduino could handle (some music analysis, hitting a REST api, etc).


body:
We know this is an open issue in Arduino programming and in the embedded world in general.
There are various solutions available on the market like MicroPython but most of them are dedicated to specific boards and don't allow to keep the system real-time.
We are working on a solution!
VIPER is a Python Virtual Machine for Arduino DUE and all ARM 32 bit architectures that runs on top of a real-time operating system.
This means that you can develop Python scripts that can be exexuted by Arduino DUE, UDOO, Spark (all boards) and also on the new ST nucleo boards.
Moreover if you need high performances and you re skilled in C you can develop real-time modules for VIPER that can be called and managed by the Python scripts.

You can see VIPER in action here [http://bit.ly/kickviper][1]

  [1]: http://bit.ly/kickviper


body:
Another option to consider is the [Arduino Yun](http://arduino.cc/en/Products/ArduinoYUN). In addition to the AVR chip which most Arduinos have, it also includes a MIPS chip running Linux. Since it's linux, you can easily run python code, and any pure-python package can be easily installed.

However, all the interesting input/output capability is on the AVR chip, not on the MIPS chip. Projects such as [Autobahn](tavendo.com/blog/post/arduino-yun-with-autobahn/) and [LininoIO](http://www.linino.org/) solve this problem by running a special program on the AVR chip which performs I/O operations under instruction from the MIPS chip.


body: Yes. Python can be used to program an Arduino, simply by importing pyfirmata, which can interface the arduino with Python.


body:
You could learn from C (AVR) how sensors work but it needs much more time.
Arduino IDE Code and Python Code for Arduino use C Code functions to make things simple.
Python and Arduino IDE if use Firmata they use serial communication and you think you code self.


body: Yes,its possible with the recent new ArduinoPro H7 which has abilities to upload a written programme in Python and JavaScript and its a dual core,32bit.


body: You gotta use pyfirmata because that's the only way to make your son a PRO engineer who makes robots. Also, python can do more advanced stuff so use pyfirmata.


message:
Is it possible to find the time taken by millis?

The function `millis` would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?

One approach that comes to mind is using `micros`, however, a call to `micros` will include the time taken by the function call of `micros` itself as well, so depending on how long micros takes, the measurement for `millis` may be off.

I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including `millis`.

body:
Write a sketch that millis 1000 times, not by making a loop, but by copy and paste. Measure that and compare it to the actual expected time. Mind you that that the results may vary with different versions of the IDE (and its compiler in particular).

Another option is to toggle an IO pin before and after the millis call, then measure the time for a very small value and a somewhat larger value. Compare the measured timings and calculate the overhead.

The most accurate way is to take a look at the disassembly listing, the generated code. But that is not for the faint of heart. You'll have to carefully study the datasheet how long each instruction cycle takes.


body:
I second calling millis repeatedly and then comparing actual vs. expected.

There will be some minimal overhead, but it will diminish in significance the more times you call millis().

If you look at

    C:\Program Files (x86)\Arduino\Arduino ERW 1.0.5\hardware\arduino\cores\arduino\wiring.c

You can see that millis() is very tiny at only 4 instructions `(cli is simply # define cli()  \__asm__ \__volatile__ ("cli" ::))` and a return.

I'd call it about 10 million times using a FOR loop which has a volatile as the conditional. The volatile keyword will prevent the compiler from attempting any optimization on the loop itself.

I don't guarantee the following to be syntactically perfect..

    int temp1,temp2;
    temp1=millis();
    for (volatile unsigned int j=0;j<1000000;++j){
    temp2=millis();}
    Serial.print("Execution time = ");
    Serial.print((temp2-temp1,DEC);
    Serial.print("ms");

my guess is that takes ~900ms or about 56us per call to millis. ( I don't have an aruduino handy ATM.


body:
If you want to know *exactly* how long something will take, there is only one solution: Look at the disassembly!

Starting with the minimal code:

    void setup(){};

    volatile uint16_t x;
    void loop()
    {
      x = millis();

    }

This code compiled and then fed into `avr-objdump -S` produces a documented disassembly. Here are the interesting excerpts:

`void loop()` produces:

    000000a8 <loop>:
      a8: 0e 94 a7 00  call 0x14e ; 0x14e <millis>
      ac: 60 93 00 01  sts 0x0100, r22
      b0: 70 93 01 01  sts 0x0101, r23
      b4: 80 93 02 01  sts 0x0102, r24
      b8: 90 93 03 01  sts 0x0103, r25
      bc: 08 95        ret

Which is a function call (`call`), four copies (which copy each of the bytes in the `uint32_t` return value of `millis()` (note that the arduino docs call this a `long`, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.

`call` requires 4 clock cycles, and each `sts` requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.

Now, lets look at the disassembly of the `<millis>` function, which is located at `0x14e`:

    unsigned long millis()
    {
     unsigned long m;
     uint8_t oldSREG = SREG;
     14e: 8f b7        in r24, 0x3f ; 63

     // disable interrupts while we read timer0_millis or we might get an
     // inconsistent value (e.g. in the middle of a write to timer0_millis)
     cli();
     150: f8 94        cli
     m = timer0_millis;
     152: 20 91 08 01  lds r18, 0x0108
     156: 30 91 09 01  lds r19, 0x0109
     15a: 40 91 0a 01  lds r20, 0x010A
     15e: 50 91 0b 01  lds r21, 0x010B
     SREG = oldSREG;
     162: 8f bf        out 0x3f, r24 ; 63

     return m;
    }
     164: b9 01        movw r22, r18
     166: ca 01        movw r24, r20
     168: 08 95        ret

As you can see, the `millis()` function is fairly simple:

1. `in` saves the interrupt register settings (1 cycle)
2. `cli` turns off the interrupts (1 cycle)
3. `lds` copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)
4. `lds` Byte 2 (2 clock cycles)
5. `lds` Byte 3 (2 clock cycles)
6. `lds` Byte 4 (2 clock cycles)
7. `out` restore interrupt settings (1 clock cycle)
8. `movw` shuffle registers around (1 clock cycle)
9. `movw` and again (1 clock cycle)
10. `ret` return from subroutine  (4 cycles)

So, if we add them all up, we have a total of 17 clock cycles in the `millis()` function itself, plus a call overhead of 12, for a total of 29 clock cycles.

Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is `1 / 16e6` seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.

Therefore, the total execution time for a single `millis()` call on *most* Arduinos will be **1.812 microseconds**.

---

[AVR Assembly reference][1]

As a side-note, there is space for optimization here! If you update the `unsigned long millis(){}` function definition to be `inline unsigned long millis(){}`, you would remove the call overhead (at the cost of *slightly* larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two `movw` calls, but I haven't looked at it that closely).

Really, considering the function call overhead is 5 instructions, and the actual *contents* of the `millis()` function is only 6 instructions, I think the `millis()` function should really be `inline` by default, but the Arduino codebase is rather poorly optimized.

---

Here is the full disassemby for anyone interested:

    sketch_feb13a.cpp.elf:     file format elf32-avr

    Disassembly of section .text:

    00000000 <__vectors>:
     SREG = oldSREG;

     return m;
    }

    unsigned long micros() {
       0: 0c 94 34 00  jmp 0x68 ; 0x68 <__ctors_end>
       4: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
       8: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
       c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      10: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      14: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      18: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      1c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      20: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      24: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      28: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      2c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      30: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      34: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      38: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      3c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      40: 0c 94 5f 00  jmp 0xbe ; 0xbe <__vector_16>
      44: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      48: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      4c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      50: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      54: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      58: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      5c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      60: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
      64: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>

    00000068 <__ctors_end>:
      68: 11 24        eor r1, r1
      6a: 1f be        out 0x3f, r1 ; 63
      6c: cf ef        ldi r28, 0xFF ; 255
      6e: d8 e0        ldi r29, 0x08 ; 8
      70: de bf        out 0x3e, r29 ; 62
      72: cd bf        out 0x3d, r28 ; 61

    00000074 <__do_copy_data>:
      74: 11 e0        ldi r17, 0x01 ; 1
      76: a0 e0        ldi r26, 0x00 ; 0
      78: b1 e0        ldi r27, 0x01 ; 1
      7a: e2 e0        ldi r30, 0x02 ; 2
      7c: f2 e0        ldi r31, 0x02 ; 2
      7e: 02 c0        rjmp .+4       ; 0x84 <.do_copy_data_start>

    00000080 <.do_copy_data_loop>:
      80: 05 90        lpm r0, Z+
      82: 0d 92        st X+, r0

    00000084 <.do_copy_data_start>:
      84: a0 30        cpi r26, 0x00 ; 0
      86: b1 07        cpc r27, r17
      88: d9 f7        brne .-10      ; 0x80 <.do_copy_data_loop>

    0000008a <__do_clear_bss>:
      8a: 11 e0        ldi r17, 0x01 ; 1
      8c: a0 e0        ldi r26, 0x00 ; 0
      8e: b1 e0        ldi r27, 0x01 ; 1
      90: 01 c0        rjmp .+2       ; 0x94 <.do_clear_bss_start>

    00000092 <.do_clear_bss_loop>:
      92: 1d 92        st X+, r1

    00000094 <.do_clear_bss_start>:
      94: ad 30        cpi r26, 0x0D ; 13
      96: b1 07        cpc r27, r17
      98: e1 f7        brne .-8       ; 0x92 <.do_clear_bss_loop>
      9a: 0e 94 f0 00  call 0x1e0 ; 0x1e0
      9e: 0c 94 ff 00  jmp 0x1fe ; 0x1fe <_exit>

    000000a2 <__bad_interrupt>:
      a2: 0c 94 00 00  jmp 0 ; 0x0 <__vectors>

    000000a6 <setup>:
      a6: 08 95        ret

    000000a8 <loop>:
      a8: 0e 94 a7 00  call 0x14e ; 0x14e <millis>
      ac: 60 93 00 01  sts 0x0100, r22
      b0: 70 93 01 01  sts 0x0101, r23
      b4: 80 93 02 01  sts 0x0102, r24
      b8: 90 93 03 01  sts 0x0103, r25
      bc: 08 95        ret

    000000be <__vector_16>:
    #if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
    ISR(TIM0_OVF_vect)
    #else
    ISR(TIMER0_OVF_vect)
    #endif
    {
      be: 1f 92        push r1
      c0: 0f 92        push r0
      c2: 0f b6        in r0, 0x3f ; 63
      c4: 0f 92        push r0
      c6: 11 24        eor r1, r1
      c8: 2f 93        push r18
      ca: 3f 93        push r19
      cc: 8f 93        push r24
      ce: 9f 93        push r25
      d0: af 93        push r26
      d2: bf 93        push r27
     // copy these to local variables so they can be stored in registers
     // (volatile variables must be read from memory on every access)
     unsigned long m = timer0_millis;
      d4: 80 91 08 01  lds r24, 0x0108
      d8: 90 91 09 01  lds r25, 0x0109
      dc: a0 91 0a 01  lds r26, 0x010A
      e0: b0 91 0b 01  lds r27, 0x010B
     unsigned char f = timer0_fract;
      e4: 30 91 0c 01  lds r19, 0x010C

     m += MILLIS_INC;
      e8: 01 96        adiw r24, 0x01 ; 1
      ea: a1 1d        adc r26, r1
      ec: b1 1d        adc r27, r1
     f += FRACT_INC;
      ee: 23 2f        mov r18, r19
      f0: 2d 5f        subi r18, 0xFD ; 253
     if (f >= FRACT_MAX) {
      f2: 2d 37        cpi r18, 0x7D ; 125
      f4: 20 f0        brcs .+8       ; 0xfe <__vector_16+0x40>
      f -= FRACT_MAX;
      f6: 2d 57        subi r18, 0x7D ; 125
      m += 1;
      f8: 01 96        adiw r24, 0x01 ; 1
      fa: a1 1d        adc r26, r1
      fc: b1 1d        adc r27, r1
     }

     timer0_fract = f;
      fe: 20 93 0c 01  sts 0x010C, r18
     timer0_millis = m;
     102: 80 93 08 01  sts 0x0108, r24
     106: 90 93 09 01  sts 0x0109, r25
     10a: a0 93 0a 01  sts 0x010A, r26
     10e: b0 93 0b 01  sts 0x010B, r27
     timer0_overflow_count++;
     112: 80 91 04 01  lds r24, 0x0104
     116: 90 91 05 01  lds r25, 0x0105
     11a: a0 91 06 01  lds r26, 0x0106
     11e: b0 91 07 01  lds r27, 0x0107
     122: 01 96        adiw r24, 0x01 ; 1
     124: a1 1d        adc r26, r1
     126: b1 1d        adc r27, r1
     128: 80 93 04 01  sts 0x0104, r24
     12c: 90 93 05 01  sts 0x0105, r25
     130: a0 93 06 01  sts 0x0106, r26
     134: b0 93 07 01  sts 0x0107, r27
    }
     138: bf 91        pop r27
     13a: af 91        pop r26
     13c: 9f 91        pop r25
     13e: 8f 91        pop r24
     140: 3f 91        pop r19
     142: 2f 91        pop r18
     144: 0f 90        pop r0
     146: 0f be        out 0x3f, r0 ; 63
     148: 0f 90        pop r0
     14a: 1f 90        pop r1
     14c: 18 95        reti

    0000014e <millis>:

    unsigned long millis()
    {
     unsigned long m;
     uint8_t oldSREG = SREG;
     14e: 8f b7        in r24, 0x3f ; 63

     // disable interrupts while we read timer0_millis or we might get an
     // inconsistent value (e.g. in the middle of a write to timer0_millis)
     cli();
     150: f8 94        cli
     m = timer0_millis;
     152: 20 91 08 01  lds r18, 0x0108
     156: 30 91 09 01  lds r19, 0x0109
     15a: 40 91 0a 01  lds r20, 0x010A
     15e: 50 91 0b 01  lds r21, 0x010B
     SREG = oldSREG;
     162: 8f bf        out 0x3f, r24 ; 63

     return m;
    }
     164: b9 01        movw r22, r18
     166: ca 01        movw r24, r20
     168: 08 95        ret

    0000016a <init>:

    void init()
    {
     // this needs to be called before setup() or some functions won't
     // work there
     sei();
     16a: 78 94        sei

     // on the ATmega168, timer 0 is also used for fast hardware pwm
     // (using phase-correct PWM would mean that timer 0 overflowed half as often
     // resulting in different millis() behavior on the ATmega8 and ATmega168)
    #if defined(TCCR0A) && defined(WGM01)
     sbi(TCCR0A, WGM01);
     16c: 84 b5        in r24, 0x24 ; 36
     16e: 82 60        ori r24, 0x02 ; 2
     170: 84 bd        out 0x24, r24 ; 36
     sbi(TCCR0A, WGM00);
     172: 84 b5        in r24, 0x24 ; 36
     174: 81 60        ori r24, 0x01 ; 1
     176: 84 bd        out 0x24, r24 ; 36
     // this combination is for the standard atmega8
     sbi(TCCR0, CS01);
     sbi(TCCR0, CS00);
    #elif defined(TCCR0B) && defined(CS01) && defined(CS00)
     // this combination is for the standard 168/328/1280/2560
     sbi(TCCR0B, CS01);
     178: 85 b5        in r24, 0x25 ; 37
     17a: 82 60        ori r24, 0x02 ; 2
     17c: 85 bd        out 0x25, r24 ; 37
     sbi(TCCR0B, CS00);
     17e: 85 b5        in r24, 0x25 ; 37
     180: 81 60        ori r24, 0x01 ; 1
     182: 85 bd        out 0x25, r24 ; 37

     // enable timer 0 overflow interrupt
    #if defined(TIMSK) && defined(TOIE0)
     sbi(TIMSK, TOIE0);
    #elif defined(TIMSK0) && defined(TOIE0)
     sbi(TIMSK0, TOIE0);
     184: ee e6        ldi r30, 0x6E ; 110
     186: f0 e0        ldi r31, 0x00 ; 0
     188: 80 81        ld r24, Z
     18a: 81 60        ori r24, 0x01 ; 1
     18c: 80 83        st Z, r24
     // this is better for motors as it ensures an even waveform
     // note, however, that fast pwm mode can achieve a frequency of up
     // 8 MHz (with a 16 MHz clock) at 50% duty cycle

    #if defined(TCCR1B) && defined(CS11) && defined(CS10)
     TCCR1B = 0;
     18e: e1 e8        ldi r30, 0x81 ; 129
     190: f0 e0        ldi r31, 0x00 ; 0
     192: 10 82        st Z, r1

     // set timer 1 prescale factor to 64
     sbi(TCCR1B, CS11);
     194: 80 81        ld r24, Z
     196: 82 60        ori r24, 0x02 ; 2
     198: 80 83        st Z, r24
    #if F_CPU >= 8000000L
     sbi(TCCR1B, CS10);
     19a: 80 81        ld r24, Z
     19c: 81 60        ori r24, 0x01 ; 1
     19e: 80 83        st Z, r24
     sbi(TCCR1, CS10);
    #endif
    #endif
     // put timer 1 in 8-bit phase correct pwm mode
    #if defined(TCCR1A) && defined(WGM10)
     sbi(TCCR1A, WGM10);
     1a0: e0 e8        ldi r30, 0x80 ; 128
     1a2: f0 e0        ldi r31, 0x00 ; 0
     1a4: 80 81        ld r24, Z
     1a6: 81 60        ori r24, 0x01 ; 1
     1a8: 80 83        st Z, r24

     // set timer 2 prescale factor to 64
    #if defined(TCCR2) && defined(CS22)
     sbi(TCCR2, CS22);
    #elif defined(TCCR2B) && defined(CS22)
     sbi(TCCR2B, CS22);
     1aa: e1 eb        ldi r30, 0xB1 ; 177
     1ac: f0 e0        ldi r31, 0x00 ; 0
     1ae: 80 81        ld r24, Z
     1b0: 84 60        ori r24, 0x04 ; 4
     1b2: 80 83        st Z, r24

     // configure timer 2 for phase correct pwm (8-bit)
    #if defined(TCCR2) && defined(WGM20)
     sbi(TCCR2, WGM20);
    #elif defined(TCCR2A) && defined(WGM20)
     sbi(TCCR2A, WGM20);
     1b4: e0 eb        ldi r30, 0xB0 ; 176
     1b6: f0 e0        ldi r31, 0x00 ; 0
     1b8: 80 81        ld r24, Z
     1ba: 81 60        ori r24, 0x01 ; 1
     1bc: 80 83        st Z, r24
    #if defined(ADCSRA)
     // set a2d prescale factor to 128
     // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
     // XXX: this will not work properly for other clock speeds, and
     // this code should use F_CPU to determine the prescale factor.
     sbi(ADCSRA, ADPS2);
     1be: ea e7        ldi r30, 0x7A ; 122
     1c0: f0 e0        ldi r31, 0x00 ; 0
     1c2: 80 81        ld r24, Z
     1c4: 84 60        ori r24, 0x04 ; 4
     1c6: 80 83        st Z, r24
     sbi(ADCSRA, ADPS1);
     1c8: 80 81        ld r24, Z
     1ca: 82 60        ori r24, 0x02 ; 2
     1cc: 80 83        st Z, r24
     sbi(ADCSRA, ADPS0);
     1ce: 80 81        ld r24, Z
     1d0: 81 60        ori r24, 0x01 ; 1
     1d2: 80 83        st Z, r24

     // enable a2d conversions
     sbi(ADCSRA, ADEN);
     1d4: 80 81        ld r24, Z
     1d6: 80 68        ori r24, 0x80 ; 128
     1d8: 80 83        st Z, r24
     // here so they can be used as normal digital i/o; they will be
     // reconnected in Serial.begin()
    #if defined(UCSRB)
     UCSRB = 0;
    #elif defined(UCSR0B)
     UCSR0B = 0;
     1da: 10 92 c1 00  sts 0x00C1, r1
    #endif
    }
     1de: 08 95        ret

    000001e0 :
    #include <Arduino.h>

    int main(void)
     1e0: cf 93        push r28
     1e2: df 93        push r29
    {
     init();
     1e4: 0e 94 b5 00  call 0x16a ; 0x16a <init>

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

     setup();
     1e8: 0e 94 53 00  call 0xa6 ; 0xa6 <setup>

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     1ec: c0 e0        ldi r28, 0x00 ; 0
     1ee: d0 e0        ldi r29, 0x00 ; 0
    #endif

     setup();

     for (;;) {
      loop();
     1f0: 0e 94 54 00  call 0xa8 ; 0xa8 <loop>
      if (serialEventRun) serialEventRun();
     1f4: 20 97        sbiw r28, 0x00 ; 0
     1f6: e1 f3        breq .-8       ; 0x1f0
     1f8: 0e 94 00 00  call 0 ; 0x0 <__vectors>
     1fc: f9 cf        rjmp .-14      ; 0x1f0

    000001fe <_exit>:
     1fe: f8 94        cli

    00000200 <__stop_program>:
     200: ff cf        rjmp .-2       ; 0x200 <__stop_program>

  [1]: http://www.atmel.com/images/doc0856.pdf


message:
Is there a way to have more than 14 Output pins on arduino?

Is it possible to have more than 14 output pins on the Arduino, I am working on a project in which I need to light up several LEDs individually. I only have an Arduino Uno, and I don't want to get a Mega.

body:
There are two ways you can get more pins out of an arduino.

The first way is by using the Analog pins as digital output pins, which is really easy to do. All you need to do is refer to A0-A5 as pins 14,15,16,17,18,19. For example to write high to pin A0 just use digitalWrite(14, HIGH).

The other way to get more pins out of the Arduino is by using a Shift Register. To do this I recommend using the [EZ-Expander Shield][1], which allows you to use digitalWrite([20-35], HIGH) when you import the EZ-Expander Library. This shield however only allows the pins to be used as outputs only and uses pins 8,12 and 13 to control the shift registers.

The great thing is, is that you can use both of the two methods above together, without any problems.

  [1]: https://nootropicdesign.com/ez-expander/


body:
A common way to expand the set of available output pins on the Arduino is to use shift registers like the 74HC595 IC ([link to datasheet](http://www.nxp.com/documents/data_sheet/74HC_HCT595.pdf)).

You need 3 pins to control these chips:

1. Clock
2. Latch
3. Data

In a program, you pass on the data one bit at a time to the shift register using the [shiftOut() command][1], like so:

    shiftOut(dataPin, clockPin, data);

With that command, you set each of the 8 outputs on the 595 IC with the 8 bits in the `data` variable.

With one 595, you gain 5 pins (8 on the IC, but you spend 3 to talk to it). To get more outputs, you can daisy-chain a series of 595 together, by connecting its serial-out pin, to the data pin of the next one. You also must connect together the clock and latch pins of all of the 595 ICs.

The resulting circuit (using one 595) would look like this:

![Circuit using 595 shift register][2]

The figure above was taken from this [codeproject.com](http://codeproject.com) webpage:

* [Arduino Platform - Working with Shift Registers](http://www.codeproject.com/Articles/144606/Arduino-Platform-Working-with-Shift-Registers)

The latch pin is used to keep the 595 outputs steady while you are shifting out data into it, like so:

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, data);
    digitalWrite(latchPin, HIGH);

  [1]: http://arduino.cc/en/tutorial/ShiftOut
  [2]: https://i.stack.imgur.com/mUyUl.jpg


body:
If you want to drive LEDs, then you can also use a MAX7219 that can drive 64 LEDs, without extra circuitry (no need for transistor to amplify signal).

Driving a [MAX7219][1] requires only 3 output pins on Arduino.
Also, you can find a few [Arduino libraries][2] for it.

You can also chain several of them if you need to power more than 64 LEDs.

I have used it successfully for multiple 7-segment LED displays.

Downside: it is expensive (about $10).

  [1]: http://www.maximintegrated.com/datasheet/index.mvp/id/1339
  [2]: http://playground.arduino.cc/Main/LedControl


body:
As you wrote already already, you can use all pins, including TX and RX as digital output. I did that a while ago for a demonstrator and recorded a video - [20 LEDS on 20 pins][1] - of this rather nonsensical project.

As described by *Peter R. Bloomfield* [here][2], you a have to disconnect TX and RX for upload. Moreover, you're out of pins to read sensors for possible interactivity and have to make sure that the total current limit isn't reached. Not to forget that you're limited to 5V leds if you drive them directly with your Arduino.

The use of shift registers in general and the 595, described by *Ricardo* is therefore highly recommended.

 - They are cheap!
 - It's rather easy to cascade them.
 - A lot of speed can be gained when you use hardware-SPI.

I used them a while ago when I realized the soldering and programming part of [Kawaii me][3] (text of the link is in German) of the upcycling artist *Dominik Jais*.

Here, just a bunch of **595** were used to drive a display of 8x11 leds. Since the leds were cut from a stripe of 12V SMD leds, an additional power supply and some **UDN2803A** Darlington arrays, hooked to the output pins of the shift registers, were necessary.

Other general methods would include the use of PCF8574(A) 8bit port expanders, which are controlled via the I2C bus.

Anyway, I'd give the 595 shift registers a try first.

If you need to control a couple of RGB leds, however, you might want to look for more specialized solutions. Some RGB leds come with their own **WS2812**. These fine pieces can be cascaded (1-Wire bus) and are addressed via their position in the chain.

[1]:http://www.youtube.com/watch?v=ibhoqUkiSys
[2]:https://arduino.stackexchange.com/questions/85/why-cant-i-upload-a-sketch-while-other-components-devices-are-connected-to-my-u
[3]:http://www.heise.de/hardware-hacks/projekte/Kawaii-me-2073147.html


body:
In addition to [Ricardo][1]'s answer, what Wikipedia states on [shift registers][2]:

> One of the most common uses of a shift register is to convert between serial and parallel interfaces. [...] SIPO registers are commonly attached to the output of microprocessors when more General Purpose Input/Output pins are required than are available. This allows several binary devices to be controlled using only two or three pins, but slower than parallel I/O.

In the [article][3] Ricardo linked you can see the diagram of the shift register.

![Shift register diagram][4]

What happens here is that you put the data of the 8 pins in a sequence and for each clock tick the shift register will shift (move the binary data from each latch to the next one) until it "makes a circle" i.e. the first bit arrives to the last pin. Shift registers also have an input where you can turn on/off the shifting so the status can be kept after the data is shifted to the position. For a simple demonstration see the following animation.

![Shift register animation][5]

Here the red light is the serial input and the green ones are showing the state of the latches in this simplified [SIPO shift register][6]. After the data shifted to place shifting can be turned off and you can read the pins. In this example I shifted out `10101011`.

From these examples you can realize that serial transfer will be slower than parallel, because you have to wait for the shift register to shift the bits to their place. You will have to wait the same amount of clock tick as many bits you want to load. This is one of the many reasons why you can't chain them indefinitely, because loading would take forever.

  [1]: https://arduino.stackexchange.com/users/46/ricardo
  [2]: http://en.wikipedia.org/wiki/Shift_register#Uses
  [3]: http://www.codeproject.com/Articles/144606/Arduino-Platform-Working-with-Shift-Registers
  [4]: https://i.stack.imgur.com/fnNDa.png
  [5]: https://i.stack.imgur.com/JgnIV.gif
  [6]: http://en.wikipedia.org/wiki/Shift_register#Serial-in.2C_parallel-out_.28SIPO.29


body:
Shift registers have been mentioned in other answers, and they are definitely an excellent choice for many projects. They are cheap, simple, moderately fast, and can typically be chained together to add more outputs. However, they have the downside that they usually need exclusive use of several pins (between 2 and 4, depending on how you set them up).

An alternative is to use more advanced port expanders, such as the [16-bit MCP23017 and MCP23S17][1]. These support I2C and SPI respectively, which means you can place them on a bus with several other devices (potentially of different types). Each device on the bus can be individually addressed, meaning you only need 2 or 3 pins to talk to all of them. The update speeds are typically extremely fast, so you're unlikely to experience significant latency (i.e. transmission delays) in an Arduino project.

At a low level, using I2C or SPI is substantially more complicated than a simple shift register. However, there is library code for Arduino to take care of that for you. See this question, for example: [How do I use I2C devices with Arduino?][2]

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf
  [2]: https://arduino.stackexchange.com/questions/158/how-do-i-use-i2c-devices-with-arduino


body:
You can use [Charlieplexing][1]. With this technique you can directly drive `n*(n-1)` LED's from n pins. So with 3 pins you can drive 6 LED's, 4 pins - 12 LED's, 5 pins - 20 LED's and so on.

Exemple:

Six LED's on 3 Pins

    PINS     LEDS
    0 1 2 1 2 3 4 5 6
    0 0 0 0 0 0 0 0 0
    0 1 Z 1 0 0 0 0 0
    1 0 Z 0 1 0 0 0 0
    Z 0 1 0 0 1 0 0 0
    Z 1 0 0 0 0 1 0 0
    0 Z 1 0 0 0 0 1 0
    1 Z 0 0 0 0 0 0 1
    0 0 1 0 0 1 0 1 0
    0 1 0 1 0 0 1 0 0
    0 1 1 1 0 0 0 1 0
    1 0 0 0 1 0 0 0 1
    1 0 1 0 1 1 0 0 0
    1 1 0 0 0 0 1 0 1
    1 1 1 0 0 0 0 0 0

![enter image description here][2]

You can see a better tutorial [here][3].

  [1]: http://en.wikipedia.org/wiki/Charlieplexing
  [2]: https://i.stack.imgur.com/Bq6H5.png
  [3]: http://www.pcbheaven.com/wikipages/Charlieplexing/


body:
For a [class project](https://github.com/hoosierEE/MicroPiano/blob/master/keykey/my_functions.ino#L106-L115) I used a CD4024 and two Arduino pins to drive a 7-segment display.

There are some caveats to this approach. For example, to write a `high` value to the first output of a ripple counter only requires a `reset` and toggling the clock pin twice. But if you want to write `high` to all n pins requires toggling the clock pin 2n times, and during that time all the other pins are constantly toggling on and off.

If your application can deal with these limitations and you're short on pins, it's another option.

Bonus answer: there are a lot of examples of multiplexing inputs [here](http://www.openmusiclabs.com/learning/digital/input-matrix-scanning/), many of which also apply to multiplexing outputs.


body:
If it's all about LEDs, what about WS2812B LED strips, or just the driver chips themselves? You can control a virtually unlimited number of LEDs using just one pin!

Although people are use to these in strips, they are available as standalone LEDs (known as neo pixels on Adafruit). Or if you're only driving a single colour, each WS2811 chip could control 3 LEDs by using each of the RGB outputs for a single LED each.

I recently just created created a project that uses 5 such LEDs: Door1 open/closed, Door2 open/closed, motor1 active, motor2 active and power. The "active" LEDs are dual purpose since I have red being the input from active motor and green being active flag inside the Arduino.

Point being, with 1 pin and the library installed, you can control any number of LEDs


body:
<!-- language-all: lang-C++ -->

I do not claim this method for my own, but I found this neat trick on the webpage [MUX-DEMUX: CD4051 Parlor Tricks][1]

Whatever method you choose to use to drive outputs or read inputs (shift registers, multiplexors or the straightforward direct use of the Arduino pins themselves) you can DOUBLE the number of outputs or inputs by a clever use of parallel circuit pairs (to form a dual input or output *bank*), employing diodes in opposing senses on each parallel branch, and switching the inputs/outputs to high and low.

To illustrate the method for outputs (LEDs in this case, note that the extra diodes are not required):

![LED bank][2]

> If you consider the pair of LEDs in this example to be a "bank", and
> you want to light LED_0, you need to set PIN 17 to HIGH, and PIN 18 to
> LOW. (The pin numbers are confusing, but they match the later example
> so bare with me). To light LED_1, you just reverse the PINS. The diode
> nature of LEDs keeps the current from flowing the opposite direction
> keeping the other one off.

To illustrate the method for inputs (CdSs in this case, note that the extra diodes are required):

![CdS bank][3]

> This gets a little more complicated if you want to do an analog read
> on a CdS light sensor. First, you need to add a diode to each sensor
> to control the flow. Second, since you are reading values, you need to
> pull the inputs high or low to keep them from floating. Being a lazy
> person, I'm going to pull them high using the internal pull-up
> resistors. To read CdS_0, you set PIN 17 mode to OUTPUT and set it to
> LOW. This makes it the ground. Then you set PIN 18 mode to INPUT and
> set it to HIGH to engage the pull-up resistor. Now you are set to do a
> read on PIN 18 (a.k.a. analog pin 4). To access the other sensor, just
> switch the modes and outputs.

So, if you have a CD4051 8 port multiplexor, using 5 pins on the Arduino (instead of the usual 3), you can obtain 16 inputs or outputs, or a mix of the two.

![16 outputs/inputs using a CD4051][4]

Likewise, if you have a 4067 16 port multiplexor you can obtain 32 inputs or outputs, or a mix of the two.

An example sketch would be:

    /*
     * Example of getting 16 i/o from 5 pins using a CD4051
     *
     * Based on tutorial and code by david c. and tomek n.* for k3 / malmö högskola
     * http://www.arduino.cc/playground/Learning/4051?action=sourceblock&ref=1
     */

    int selPin[] = { 14, 15, 16 }; // select pins on 4051 (analog A0, A1, A2)
    int commonPin[] = { 17, 18};   // common in/out pins (analog A3, A4)
    int led[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW };  // stores eight LED states
    int CdSVal[] = { 0, 0, 0, 0 }; // store last CdS readings
    int cnt = 0;  // main loop counter
    int persistDelay = 100; // LED ontime in microseconds

    void setup(){
      Serial.begin(9600);  // serial comms for troubleshooting (always)
      for(int pin = 0; pin < 3; pin++){ // setup select pins
        pinMode(selPin[pin], OUTPUT);
      }
    }

    void loop(){
      flashLEDs();
      if (cnt == 0){
        for(int x; x < 8; x++){
          led[x] = random(2);
        }
      }
      cnt++;
      if (cnt > 100) { cnt = 0; }
    }

    void flashLEDs() {
      for(int pin = 0; pin < 2; pin++) {  // set common pins low
        pinMode(commonPin[pin], OUTPUT);
        digitalWrite(commonPin[pin], LOW);
      }
      for (int bank = 0; bank < 4; bank++) {
        for(int pin = 0; pin < 3; pin++) { // parse out select pin bits
          int signal = (bank >> pin) & 1;  // shift  & bitwise compare
          digitalWrite(selPin[pin], signal);
        }
        if (led[bank * 2]){        // first LED
          digitalWrite(commonPin[0], HIGH);  // turn common on
          delayMicroseconds(persistDelay);   // leave led lit
          digitalWrite(commonPin[0], LOW);   // turn common off
        }
        if (led[bank * 2 + 1]){     // repeat for second LED
          digitalWrite(commonPin[1], HIGH);
          delayMicroseconds(persistDelay);
          digitalWrite(commonPin[1], LOW);
        }
      }
    }

Like I said in the first line, the full explanation can be found on [MUX-DEMUX: CD4051 Parlor Tricks][5]

  [1]: http://dawson-station.blogspot.com/2010/01/mux-demux-cd4051-parlor-tricks.html
  [2]: https://i.stack.imgur.com/nb0Mi.png
  [3]: https://i.stack.imgur.com/m11CU.png
  [4]: https://i.stack.imgur.com/H8E2F.png
  [5]: http://dawson-station.blogspot.com/2010/01/mux-demux-cd4051-parlor-tricks.html


body:
## I2C (Wire)

You can use the I2C protocol (Wire library) to connect to other devices such as port-expanders. For example, the MCP23017.

I used one of those chips to connect to an LCD board. The MCP23017 has 16 ports, which can be configured as inputs or outputs. As inputs they can raise interrupts if desired.

Example of connecting 13 of those 16 to the LCD:

![MCP23017 connected to LCD screen][1]

Now we connect to the Arduino using only 2 wires (SDA/SCL) plus power and ground:

![MCP23017 connected to Arduino][2]

---

Some third-party manufacturers have made boards with 4 x MCP23017 on them, this gives you 64 inputs/outputs:

![Centipede board][3]

---

## Multiplexers

You can use analog multiplexers like the 74HC4051 (8 ports) or the 74HC4067 (16 ports) to connect one pin to one of the 8/16 ports (but only one at a given time), like this:

![74HC4051 multiplexer][4]

These are bi-directional, so can be used as an input or output expander.

---

## SPI with 74HC595

Using SPI you can send fast serial data to a shift register, such as the 74HC595. These can be daisy chained together. In this example I am controlling 32 LEDs with only 3 I/O pins (MOSI/MISO/SCK) plus power and ground.

![74HC595 driving 32 LEDs][5]

---

I found inside a commercial LED sign that the 72 LEDs were driven by 74HC595 chips.

![Scrolling LED sign][6]

This had 9 chips driving the columns (9 x 8 = 72 LEDs) and one chip driving the rows, in a multiplexed configuration.

---

## SPI with MAX7219

If you just want to drive LEDs you can usually multiplex them. The MAX7219 simplifies that by being designed to drive LED matrixes, for example 7-segment displays:

![MAX7219 with 7-segment display][7]

Or 64-LED matrixes:

![MAX7219 with 64-LED matrix][8]

In both cases these can be daisy-chained together, for example:

![MAX7219 daisy-chain][9]

All those examples only use 3 pins of the Arduino (MOSI/MISO/SCK) plus power and ground.

---

## SPI with MCP23S17

The 16-port port expander mentioned earlier (MCP23017) also comes in an SPI variant (MCP23S17), which does virtually identical things. It uses one more wire, but would be faster.

---

## Other protocols

LED strips (like the NeoPixel ones) have their own protocols. There was a [post on Youtube by Josh Levine](https://www.youtube.com/watch?v=I-lR19_kigs) where the author drove over 1000 pixels with a Duemilanove!

---

## References

* [I2C and MCP23017](http://www.gammon.com.au/i2c)
* [MCP23017 and graphical LCD](http://www.gammon.com.au/lcd)
* [74HC4051 multiplexer / demultiplexer](http://www.gammon.com.au/forum/?id=11976)
* [SPI](http://www.gammon.com.au/spi)
* [Hacking a scrolling LED strip](http://www.gammon.com.au/forum/?id=12298)
* [Using a 74HC595 output shift register as a port-expander](http://www.gammon.com.au/forum/?id=11518)
* [Interfacing LED displays with the MAX7219 driver](http://www.gammon.com.au/forum/?id=11516)

  [1]: https://i.stack.imgur.com/a30M6.png
  [2]: https://i.stack.imgur.com/rDcCd.png
  [3]: https://i.stack.imgur.com/rDTTv.png
  [4]: https://i.stack.imgur.com/iATER.png
  [5]: https://i.stack.imgur.com/OSl67.jpg
  [6]: https://i.stack.imgur.com/StXYR.jpg
  [7]: https://i.stack.imgur.com/keI0f.jpg
  [8]: https://i.stack.imgur.com/0119t.jpg
  [9]: https://i.stack.imgur.com/WrL3k.jpg


body:
With a bit of work (installing a different bootloader) an additional seven I/O lines are available on an Uno, on the ICSP1 and JP2 headers.  The replacement bootloader is called [HoodLoader2](http://blog.atmel.com/2014/12/01/using-the-power-of-two-mcus-on-an-arduino-board/).  It allows you to install sketches on both the Atmega328 and Atmega16U2 on an Uno.  Dealing with multiple processors would be the main complication from using this method.

On an Uno, the ICSP1 and JP2 headers connect to pins PB1...PB7 of the Atmega16U2.  In addition the Atmega16U2 has about 9 I/O pins with no connection to the circuit board.  A person working under a microscope might be able to attach wires to a total of 18 I/O pins on the 16U2, while leaving three other I/O pins attached to their ordinary connections.

HoodLoader2 also works on Mega boards.


body:
There is a wealth of good answers here, but if you costed your time you'd find it cheaper to buy a Mega.

My 3/2-d worth.


message:
What are the steps involved in porting an Arduino library?

I want to use the [Adafruit CC3000][1] and its [Arduino libraries][2] on another platform. In this case it's the Arduino pin compatible [PSOC4 Pioneer Kit][3]. This is an ARM Cortex M0 based platform.

My question is: How would I go about porting a library like this? What are the steps, key files etc?

One obvious issue is that PSOC Creator does not readily support C++.

One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.

NOTE: If you think this question is off topic; please head over to [this question][4] on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.

  [1]: http://learn.adafruit.com/adafruit-cc3000-wifi
  [2]: https://github.com/adafruit/Adafruit_CC3000_Library
  [3]: http://www.cypress.com/?rID=77780
  [4]: https://arduino.meta.stackexchange.com/questions/22/is-it-ok-to-ask-questions-about-arduino-compatible-micros-not-clones

body:
I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. [I started a support thread here which can lead you through my process][1].

I tackled it the same way I do general programming:

1-» Copy over Libraries, get it so your compiler can actually SEE them.

2-» Start trying to compile and then triage errors from the "top level" down:

3-» Look for stlib functions you recognize as should be working and fix those.

4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: `ckck - bitbanging SPI`, so I can search for these later.

Repeat 3 and 4 until it works or you quit. :)

Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.

  [1]: http://forums.adafruit.com/viewtopic.php?f=47&t=42966


message:
Internet connectivity for the Arduino Due using AtmelStudio?

What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet?  I gather the [ethernet hardware](http://arduino.cc/en/Main/ArduinoBoardEthernet) is much cheaper than [WiFi hardware](http://arduino.cc/en/Main/ArduinoWiFiShield) (€29 versus €69).  In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?

body:
Well, your best bet is to import the arduino libraries in your [Atmel Studio project][1]. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.

Though, the Sam 3X features an hardware ethernet [that is not wired][2], unlike the [MBed LPC1768][3]… Sadly that's the [ethernet PHY component][4] you saw, but won't be able to actually use…

[1]:http://www.engblaze.com/tutorial-using-atmel-studio-6-with-arduino-projects/
[2]:http://forum.arduino.cc/index.php?topic=197083.0
[3]:http://mbed.org/platforms/mbed-LPC1768/
[4]:http://asf.atmel.com/docs/3.11.0/sam3x/html/group__dm9161a__ethernet__phy__group.html


message:
Washable, Wearable Tech with Arduino

**Question:** How does one prepare clothing with embedded electronics for washing?

**Background:** There are several Arduino boards/clones that are designed for "wearable tech."  (For example, the [Lilypad][1].)  Wearable tech with LED light patterns, microphones, GPS, or other circuitry is an interesting concept, but water and electricity tend not to mix.

To prepare wearable tech for washing, I would assume people make large circuitry removable.  Yet, inevitably, some electronics will be more-or-less permanently affixed to the cloth.  What, if anything, can be done to these electronics (e.g. sewn-in Arduino Lilypad) to make them washing-machine (preferred--hand wash could be done, but it's so much easier to machine wash) safe?

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

body:
I would use some sort of epoxy and cover up the exposed circuitry. The major concern would be where the wires connect to the board as flex over time can weaken it.

Some options include:

* [3M™ Scotchcast™ Wet-Niche Potting Kit][1]
* [Hysol][2]
> US1150™—For electronics, telecommunications, and automotive
> components. Provides environmental hazard protection.
>
> US1152™—For electronic assemblies. Provides environmental hazard protection.

Heat might play a factor if you cover up the boards in epoxy but you shouldn't be producing that much heat in a wearable device anyway, right?

  [1]: http://www.3m.com/product/information/Scotchcast-Wet-Niche-Potting-Kit.html
  [2]: http://www.henkelna.com/product-search-1554.htm?nodeid=8797846732801


body: I would make it so the Board has velcro on it so that it can be un attached from the clothing, and then have all the wires have snap terminals that wires from the Arduino connect to. This way you un snap all the wires and remove the arduino. As far as components, I would cover them in an epoxy to protect them.


body:
> How does one prepare clothing with embedded electronics for washing?

* Remove the battery(ies) and other power supplies, and set them far away from the water. Buzzers and speakers also.
* Gently wash clothing (including the Lilypad, LEDs, resistors, capacitors, integrated circuits, accelerometers, magnetometers, Bluetooth modules, GPS modules, etc.) by hand with a mild detergent.
* Drip dry, or manually dry with a hair-dryer.

See:

* ["LilyPad ... They're even washable!"][2]
* ["accelerometer shirt ... is washable."][3]
* ["Are LEDs and Resistors Washable?"][4] (Yes!)
* ["Remove After Washing" on Piezo Buzzer][1]

  [1]: https://electronics.stackexchange.com/questions/98556/remove-after-washing-on-piezo-buzzer
  [2]: https://www.sparkfun.com/products/9266
  [3]: http://web.media.mit.edu/~leah/LilyPad/build/accelero_shirt.html
  [4]: http://forum.arduino.cc/index.php/topic,10382.0.html


message:
Is my ATmega broken, and would replacing it with another break that one, too?

I was communicating between my computer and my Arduino Uno R3 through Bluetooth using [this Bluetooth module][1]. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.

> ![enter image description here][2]
>
>                     ↓        ↓  to Uno ↓       ↓
>                    +5V      GND       pin 0  pin 1

I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.

After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous `avrdude: stk500_getsync(): not in sync: resp=0x00` error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.

Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?

  [1]: http://www.mdfly.com/index.php?main_page=product_info&cPath=8_47&products_id=769&zenid=6f2b3946847b73b5ef2185e5e756e498
  [2]: https://i.stack.imgur.com/upJ7C.png

body:
Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.

However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.

If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...


message:
What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3?

There are some pins on the Arduino which I haven't been able to find out anything about:

 - `IOREF`
 - `AREF`
 - An unlabeled one next to `IOREF`

What are they?

body:
__AREF:__

This is the voltage reference analog-to-digital converter (ADC). It can be used instead of the standard 5V reference for the top end of the analog spectrum – for example, if you wanted to use the ADC to monitor a signal that had a 0-1.5 volt range you could get the full scale of the ADC by connect AREF to a 1.5V signal. **DO NOT CONNECT A SIGNAL OUTSIDE THE 0V TO 5V RANGE!**

Note that in order for this to work, you must run `analogReference(EXTERNAL);` before using `analogRead()`. Also:
> After changing the analog reference, the first few readings from analogRead() may not be accurate.

Fore more information, see [AnalogReference](http://www.arduino.cc/en/Reference/AnalogReference).

__IOREF:__

This is a voltage corresponding to the i/o of that board, for example an Uno would supply 5v to this pin, but a Due would supply 3.3v. Sending a signal to this pin does nothing.

__Unlabeled pin:__

This pin is unused, but is there to ensure compatibility with future products. It is not connected to anything on any R3 boards I have seen.


body:
Concerning the `AREF` pin, you have to remember that the Arduino comes with a 10bit ADC (Analog-Digital-Converter), which converts incoming voltages between 0V and 5V to integer values between 0 and 1023. This results in a resolution of roughly 4.8 mV.

If a sensor only delivers a lower maximum voltage, it is resonable to apply this voltage to the `AREF` pin, just in order to obtain a higher resolution.


message:
What is the difference between the revisions of the Arduino Uno board?

There are three different revisions of the Arduino Uno. What changed in each revision?

body:
Here is a summary from [the official site][1]:

> Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to
> ground, making it easier to put into DFU mode.
>
> Revision 3 of the board has the following new features:
>
>  - 1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that
> allow the shields to adapt to the voltage provided from the board. In
> future, shields will be compatible with both the board that uses the
> AVR, which operates with 5V and with the Arduino Due that operates
> with 3.3V. The second one is a not connected pin, that is reserved for
> future purposes.
>  - Stronger RESET circuit.
>  - Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found [here][2].

## R2:

 - The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees. ![enter image description here][3]

 - Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA." ![enter image description here][4]

 - Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP. ![enter image description here][5]

 - An LED connected to pin 13 was added. It turns on when pin 13 is `HIGH`, off when `LOW`.
 - The main microchip was changed from an ATmega168 to an ATmega328.
 - A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.
![enter image description here][8]

## R3:

 - The rotation of the ATMEGA8U2 was changed back by 45 degrees.
 - The ATMEGA8U2 was changed to an ATMEGA16U2.
 - A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.
![enter image description here][6]
 - The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.
![enter image description here][7]

  [1]: http://arduino.cc/en/Main/ArduinoBoardUno
  [2]: http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/
  [3]: https://i.stack.imgur.com/piYR2.jpg
  [4]: https://i.stack.imgur.com/mudBq.png
  [5]: https://i.stack.imgur.com/zj258.png
  [6]: https://i.stack.imgur.com/XneB4.jpg
  [7]: https://i.stack.imgur.com/ay2Zt.png
  [8]: https://i.stack.imgur.com/lzBuR.jpg


body:
### User Side Changes

- Both revision 2 and 3 boards add four solder pads (JP2) connecting to pins PB4 to PB7 of the USB ATMEGA.
- Revision 2 and 3 boards are both supplied with header pins in the USB ATMEGA ICSP header rather than just solder pads in the Arduino Uno.
- The revision 3 board changes the 8 pin connector that contains Arduino pins 8 to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. These are the two analog input pins that can be used for I2C.
- Revision 3 boards change the 6 pin connector that has the reset pin connected to it to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is reserved for future use.

### Electronics Based Changes
- The Arduino Uno and Arduino Uno revision 2 both have an ATMEGA8U2 USB microcontroller on board – this is upgraded to an ATMEGA16U2 on the revision 3 board.
- Revision 3 adds a diode across the USB ATMEGA reset pin pull-up resistor.
- Both revision 2 and 3 boards add a 1k pull-down resistor to the DTR (HWB) line coming from the USB ATMEGA microcontroller – from the PD7 pin.
- The Arduino Uno and Arduino Uno revision 2 both have a LED and resistor connected in series on Arduino pin 13. The revision 3 board buffers this LED/resistor through a unity gain op-amp. This is the spare op-amp that was unused on previous boards.

### Sources:
1. http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/


message:
How can I communicate from Arduino to MATLAB

I want to use sensors on an Arduino to control values in a [MATLAB][1] program. What are my options for communicating?

I've used [Processing][2] to receive data sent via the serial cable, and that strategy has worked pretty well. Is there something similar I can do using MATLAB? I'm somewhat new to MATLAB, so gentle guidance would be great.

I'm not really looking for something like the [ArduinoIO][3] package -- I want to have separate computation executing on the Arduino and occasionally informing my MATLAB program (which will occasionally poll the serial line, I suppose).

  [1]: http://en.wikipedia.org/wiki/MATLAB
  [2]: http://en.wikipedia.org/wiki/Processing_(programming_language)
  [3]: http://www.mathworks.com/matlabcentral/fileexchange/32374-matlab-support-package-for-arduino-aka-arduinoio-package

body:
I don't know a whole lot about MATLAB, but I found some tutorials about reading and writing from the serial port:

    s = serial('COM1');
    fopen(s)
    fprintf(s, 'Your serial data goes here')
    out = fscanf(s)

`out` is now your received data, and you can do whatever you want with it.

To close:

    fclose(s)
    delete(s)
    clear s

It is from *[Writing and Reading Data][1]* (*MATLAB*/ *Data and File Management*/ *Serial Port Devices*).

From your question I assume you know about the Arduino side of things (using `Serial`).

  [1]: http://www.mathworks.com/help/matlab/matlab_external/writing-and-reading-data.html


body:
[MATLAB Support Package for Arduino (aka ArduinoIO Package)][1] allows you to do it fairly easily.

> Sample usage:
>
> %-- connect to the board
>
> `a = arduino('COM9')`
>
> %-- specify pin mode
>
> `a.pinMode(4,'input'); `
>
> `a.pinMode(13,'output');`
>
> %-- digital i/o
>
> `a.digitalRead(4) % read pin 4 `
>
> `a.digitalWrite(13,0) % write 0 to pin 13`
>
> %-- analog i/o
>
> `a.analogRead(5) % read analog pin 5 `
>
> `a.analogWrite(9, 155) % write 155 to analog pin 9`

  [1]: http://www.mathworks.com/matlabcentral/fileexchange/32374-matlab-support-package-for-arduino-aka-arduinoio-package


body:
I've established a connection, sending numbers. By just changing Serial.write to Serial.print and fread to fscanf you can send/receive clear ASCII text instead of binary data.

Both matlab and arduino code can be found at this question:

https://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously


message:
Programming options other than C++

Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?

body:
In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).

AVR backends exist for both [LLVM](http://sourceforge.net/projects/avr-llvm/) and  [GCC](http://gcc.gnu.org/wiki/avr-gcc) -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.

Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter [1].

- [AMForth](http://amforth.sourceforge.net/TG/recipes/Arduino-HelloWorld.html), a forth dialect can be flashed onto an Arduino.
- [AVR-Ada](http://sourceforge.net/projects/avr-ada/): [Ada](http://en.wikipedia.org/wiki/Ada_(programming_language)) for AVR micro-controllers.
- [BASIC](http://www.mikroe.com/mikrobasic/avr/): Bring back the Goto!

Oh, and you could write raw [AVR Assembly](http://www.atmel.ca/Images/doc0856.pdf)!

[1]- I Haven't tried these though!


body:
Some commonly known ones:

 * [Ada](http://sourceforge.net/apps/mediawiki/avr-ada/index.php?title=AVR-Ada)
 * [Basic](http://www.mcselec.com/)
 * [Forth](http://claymore.engineer.gvsu.edu/~steriana/Python/pfavr/rationale.html), [alt](http://www.forth.com/embedded/index.html), [alt](http://www.forth.com/embedded/index.html)
 * [Java](http://www.harbaum.org/till/nanovm/index.shtml)
 * [Pascal](http://www.e-lab.de/AVRco/index_en.html)
 * [Python](http://wiki.python.org/moin/PyMite)
 * [C](http://www.ladyada.net/learn/avr/setup-mac.html) (mac) and [C](http://winavr.sourceforge.net/) (Windows)

In theory you should be able to extend avr-gcc to support other languages, though this is no small undertaking. I should also caveat that support for languages other than C typically comes with some fairly weighty restrictions on language components -- for instance, even with C++ it's discouraged to be instantiating new objects as `malloc` and `free` are extremely expensive in both memory space and cycles.

Besides using Google, the following references are applicable [Click Here.][1]

  [1]: http://www.piclist.com/techref/atmel/avr/languages.htm


body: Because avr-g++ should support all standard C / C++ constructs it is possible to code inline assembly. More info on [this](http://forum.arduino.cc/index.php/topic,40916.0.html) arduino.cc forum thread


body:
There are also some people working on **Javascript** node.js based systems. One that is already publicly available is [Espruino][1] and another is [Tessel][2] which launches in spring 2014.

  [1]: https://github.com/espruino/Espruino
  [2]: https://github.com/technicalmachine


body:
I'm surprised that nobody has mentioned [AVR Assembly][1]!

Assembly is not often thought to be the most interesting, or even an easy method of programming, but it's nonetheless, 100% possible with all AVR based arduino. SAM boards will likely not work with this flavor, but it's still possible to use assembly in their programming.

All Arduino boards (as of posting) support assembly programming via [Atmel Studio](https://www.microchip.com/mplab/avr-support/atmel-studio-7), The SDK made for Atmel based chips.

Assembly is naitively supported by all Atmel devices, and requires no boot loader in order to work, so all programs are inherently real-time.

  [1]: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html


message:
Code for one-time execution in Arduino

**Question:** Where do I put code if I want it to execute only once per Arduino startup?

**Background:** I tend to use my Arduino to perform tasks that should be executed once per power cycle.  (For example, my robot should only drive forward *once* every time I turn it on--more than that, and it might fall off the table.)

The standard Arduino IDE "template" consists of a `loop()` and a `setup()` function.  The `setup` code is run once per power cycle, and the `loop` is re-started every time it finishes.

I see two approaches to code "1 time tasks:"

Method 1: "Loop once"
--
    void setup() {
      //do setup stuff
    }

    void loop() {
      //do task

      while(1) ; //Repeat forever, preventing function from re-starting
    }

Method 2: "Setup only"
--

    void setup() {
      //do setup stuff

      //do task
    }

    void loop() {
      //do nothing
    }

**More detailed form of question:**  Is one of these methods "better" from a hardware/software sense?  (e.g. is there anything "special" about the `setup` function, like it can only run for so much time?)
And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?

body: I would strongly prefer Method 2. If you ever plan to add code to handle input, output, etc,  it's easy with Method 2 -- just fill in `loop()`, but requires reworking/refactoring in Method 1.


body: There is no time limit on the setup function. I prefer method 2 because the loop can be filled with whatever you need to later.


body: Definitely go with method two. That's what the setup function is there for. It's much easier to read as well. Anything in the `loop()` implies it will be run in a loop.


body:
I usually go with Method 2, but end up doing this:

    void setup() {
      //do setup stuff

      //do task
      init(); //Do start-up initialization steps
    }

    void init() {
      // do tasks on startup
    }

    void loop() {
      //do looping code
    }

With the above setup it allows my code to be even more organized.