Mostrando entradas con la etiqueta Arduino Nano. Mostrar todas las entradas
Mostrando entradas con la etiqueta Arduino Nano. Mostrar todas las entradas

jueves, 7 de febrero de 2013

Arduino by Davis: “Controlling Big, Mean, Devices"


Arduino by Davis: “Re: Controlling an animatronics bust” plus 19 more

Link to Arduino by Davis

  • Controlling Big, Mean, Devices


Controlling Big, Mean, Devices


Microcontrollers are a ton of fun. Once I got hooked, there was no
turning back. Initially playing with sensors and LCDs, I quickly discovered the limits to what a microcontroller could control. A microcontroller’s GPIO (general purpose input/output) pins cannot handle higher power requirements. An LED was easy enough, but large power items such as light bulbs, toaster ovens, and blenders required more sneaky circuitry. Something sneaky called a relay:
http://www.sparkfun.com/tutorial/Outlet/Outlet-1.jpg
In this tutorial we will discuss a small relay board to control the power to a normal AC outlet using 5VDC control.

All the usual warnings apply: Main voltage (120VAC or 220VAC) can kill you. This project, done incorrectly, could certainly burn down your house. Have your pet spayed or neutered. Shampoo is better. Do not work on or solder to any part of a project while it is plugged into the wall – just unplug it!

You can get the Eagle files for the control board here. The control board is composed of a relay along with a NPN transistor and LED.



What’s a relay?
I admit, I really just wanted to build my own Blender Defender (I don’t even have a cat!). However, building a 5V controllable outlet can be handy for many applications. For these power hogs, a relay is the perfect fit.

A relay is a large mechanical switch. That switch is toggled on or off by energizing a coil.

Image:Relay.jpg
From wikipedia

In this example we are going to talk about the simplest version of a relay. Inside the relay are two paddles made of metal. One paddle is made of a ferrous material like steel and is free to move. The other paddle is made of copper and stationary. When these paddles touch (the closed switch state), they are capable of allowing a large amount of power to flow – like 30A@120VAC (huge!).

The other half the relay is called the coil. This is basically a small electro-magnet. If you send current through the coil, a magnetic force is created, which pulls on the steel paddle causing it to move (flip) and touch the copper paddle – as if you flipped a light switch. The coil requires a small amount of power (5VDC @ 80mA). So you see, controlling the low-power coil allows us to actually control quite a lot of power!

It is important to note the coil is physically isolated from the paddles. If you have 120VAC running through the paddles, you don’t have to worry about that 120VAC sneaking back into and vaporizing your microcontroller (connected to the coil).

The paddles are capable of carrying very large currents. Both AC or DC – the paddles don’t care. A relay can be used to control a DC motor, or an AC lamp.

The relay that we will be working with, in this tutorial, is a beefcake in my opinion. It can handle a lot of power – 30A at 220VAC. What happens if you violate this limit? I have thankfully never been in that situation. I have heard reports that the relay will begin to heat up. When the voltage/current becomes large enough, there will be sparks inside the relay as you switch the paddles. If these sparks get large enough, you can actually spot weld the movable paddle to stationary paddle causing the relay to fail, potentially in the ‘on’ position. Obviously this would be very bad on many levels.

Like we do with capacitors, we under-rate the relay so that we mitigate the risk of relay failure. If you need 10A@120VAC, don’t use a relay rated for 10A@120VAC, instead use a bigger one (such as 30A@120VAC). Remember, power = current * voltage so a 30A@220V relay can handle up to a 6,000W device (two hair dryers).



The Outlet

http://www.sparkfun.com/tutorial/Outlet/Outlet-0.jpg

The goal is the get a GFCI outlet into some sort of a housing, with a power cord, the relay, and control circuitry.

Materials:
  • GFCI Outlet ($10)
  • Nail mount housing ($1)
  • Thick 3-wire type extension cord, 8 feet (2-wire cords will not work) ($7)
  • Relay ($4)
  • Control board and parts ($5)
Please notice that we are using a Ground Fault Circuit Interrupter (GFCI) Outlet and not a normal outlet. A normal outlet costs $0.59 – but I went for the $10 GFCI. Why? The GFCI may save your life. It’s the type of outlet you’ll find near anything that outputs water (kitchen sinks, batchroom tubs, etc). When the outlet detects an abnormal amount of current, it assumes that a large amount of potentially fatal current is flowing through your body, and therefore switches off – saving you and your project.

Truthfully, the GFCI may only shut off when there is a current leak across a connection to ground – and not an over-current condition. What this means is if your ‘project’ suddenly pulls 50A because the microwave turned on, the GFCI will not trip off. But it you accidentally touch the wrong exposed wire, the GFCI will trip because it will detect a fault to ground (saving your heart from cardiac arrest). We repeat – when working on any part of an AC project, unplug the thing from the wall.



The Inline Power Control Board
The first thing you need to do is build up the Power Control board.

http://www.sparkfun.com/tutorial/Outlet/Outlet-1.jpg

This board contains the relay, transistor, and activation LED. The board requires 5V and GND to operate. A control pin controls whether the relay is ‘closed’ (allows high power to flow) or ‘open’ (paddle’s default state of disconnected).


The control board is fairly straight forward. The coil within the relay requires up to 80mA. This is more than a GPIO pin can handle (20mA by default) so we use NPN transistor as a controllable connection to ground. The NPN transistor can handle up to a 200mA which is more than the coil (80mA) and the LED (20mA) combined.

When the ‘RELAY’ pin (aka CTRL) goes high, the NPN transistor connects to ground sending current through the coil (activating the relay) and through the LED (turning the activation LED on). R1 pulls the ‘RELAY’ pin to ground so if anything goes haywire the relay will remain in the safe, off position.

Note: The 1N4148 diode is connected in a odd fashion for a reason. This is placed between power and ground in a reverse fashion. When the coil of the relay is de-activated, it acts like an inductor, trying to suppress current change. This can cause some havoc on the 5V power rail. When this happens, the 1N4148 will forward bias causing the current stored in the coil to flow happily back to the 5V rail protecting the power supply and the near-by parts.



The Build

Take that beautiful extension cord and cut off the female connector about 6" from the female end.

http://www.sparkfun.com/tutorial/Outlet/Outlet-2.jpg
A male US power plug next to the cut off end of the extension cord

This should leave leave a few feet of extension cord between the part that plugs into the wall (male end) and the bare, exposed, recently cut-off end of the extension cord. Don’t plug it in!

Note: A two-wire extension cord will not work correctly. Notice we are using thick, three-wire circular extension cord. This extra wire is the ground return and allows the GFCI to operate correctly.

Using a meter set to continuity, check that the ground pin (the round one) is indeed connected to the green ground wire.  I’ve seen a few extension cords with non-standard colors.


http://www.sparkfun.com/tutorial/Outlet/Outlet-3.jpg

Use a wire stripper or an exacto-knife to remove about 6" of the sheath from the extension cord. You should find three wires - black, white and green.

http://www.sparkfun.com/tutorial/Outlet/Outlet-4.jpg

Use wire strippers to strip the three wires individually about 1". I twist the ends of the wires to combine the strands of the wires together in preparation for soldering.

http://www.sparkfun.com/tutorial/Outlet/Outlet-5.jpg

Sometimes the roll of solder can be used as a third hand.

http://www.sparkfun.com/tutorial/Outlet/Outlet-6.jpg

The goal here is to 'tin' the three wires. Adding solder to each of the stranded wires will hold all the wires together and allow for easier manipulation later.

http://www.sparkfun.com/tutorial/Outlet/Outlet-9.jpg

Be sure to thread the extension cord through the housing (shown above) before soldering to the control board. It's a huge pain to have to cut and remove the wires from the control board.
http://www.sparkfun.com/tutorial/Outlet/Outlet-8.jpg

Be sure the extension is threaded through the housing before you do this step.

With a good 6" of wire exposed, cut the black wire about 5" down from the end. The is where the relay will live.

http://www.sparkfun.com/tutorial/Outlet/Outlet-10.jpg
Notice the hooks on the three wires. I wrapped the tinned ends of wire around a small jewelers screw driver to create a half circle within the wire. This will aid connection to the screws on the GFCI.

Here we have the black wire cut and soldered to the control board. The relay is a NO (Normally Open) type relay. When power is off, there is no connection between the two thick black strands that you just cut and soldered. This is a safety feature - if all things go wrong and the power goes out of the coil, the relay will kick off and the outlet will shut down.

Conversely, when you send 5V to the coil, the paddle flips from the 'off' state to the 'on' state, connecting the two pieces of black wire (on the left side of the picture above), power is delivered to the outlet and your project is powered.

http://www.sparkfun.com/tutorial/Outlet/Outlet-11.jpg

Now we connect the wires from the extension cord to the outlet. The Black and white wires connect to the two side terminals of the GFCI - the green wire (ground) connects to the end of the outlet.

Advanced trick: Notice how the hooks of the tinned wires are arranged so that they are clock-wise. If you align the hooks of the wires under the screws correctly, as you tighten the screws, the hook of the wire will be 'sucked' into the tightening screw. This creates a very compact connection.

http://www.sparkfun.com/tutorial/Outlet/Outlet-7.jpg

Now lower the relay into the enclosure and feed the control wires (red, yellow, and black) out one corner of the housing. (You're right, the extension cord wires are not soldered to the relay board in this picture - please make believe). 

http://www.sparkfun.com/tutorial/Outlet/Outlet-12.jpg

You can double-stick tape the control board to the bottom of the housing or just let it float - the wires from the extension cord will tend to hold it in place. Once you have everything lowered into place, screw the outlet onto the enclosure, and the face plate onto the enclosure.

http://www.sparkfun.com/tutorial/Outlet/Outlet-13.jpg
Here we test the controllable outlet against the Boxing Timer

DO NOT plug the extension cord into the wall yet.

Now for the moment of truth. Attach the three control wires (5V, GND, and CTRL) to some sort of system. In the above picture, I have a fairly dirty breadboard. All that I am actually using on the bread board is 5V and GND - ignore all the other parts as they are not doing anything. I then manually toggled the control wire from GND (off) to 5V (on). You can do the same thing by plugging into the 5V and GND pins on an Arduino board.

Tying the CTRL line to 5V I heard a very friendly click as the relay kicked over. This indicated (along with the LED on the control board) that the relay was actuated to the 'on' position. Removing CTRL from the 5V rail (called floating because the CTRL line is neither connected to 5V or GND), the relay released. This is good! If CTRL is left floating or tied to ground, the outlet is turned off.

You can also use a meter in continuity mode to check that the relay is working properly before youconnect to 120VAC.  When the relay’s open, one of the fins of the plug and one of the rectangular holes of the outlet will not have continuity, and when it’s closed, they will.  The other fin and rectangular hole will always have continuity, as will the ground pin and the funny hole.  I always do this check before plugging into the 120VAC, because I am, you know, paranoid.

The next step is to plug the extension cord into the wall and test again. If anything goes wrong the GFCI should activate and cut off. Be sure to unplug the outlet anytime you are working on it. Please don’t get zapped!



You should now have an outlet that is fully controllable over 5V logic. When you plug a device into the outlet, it will by default be off. When you expose 5V to the CTRL line, the relay will activate turning on power to the device plugged into the outlet.

martes, 20 de noviembre de 2012

Arduino - Arduino Board Nano


Arduino Nano

Descripción General

El Arduino Nano es una pequeña y completa placa basada en el ATmega328 (Arduino Nano 3.0) o ATmega168 (Arduino Nano 2.x) que se usa conectándola a una protoboard. Tiene más o menos la misma funcionalidad que el Arduino Duemilanove, pero con una presentación diferente. No posee conector para alimentación externa, y funciona con un cable USB Mini-B en vez de el cable estandar. El nano fue diseñado y está siendo producido por Gravitech.

Esquemático y Diseño

Arduino Nano 3.0 (ATmega328): Esquemático, Archivos Eagle.
Arduino Nano 2.3 (ATmega168): manual (pdf), Archivos Eagle. Nota: debido a que la versión gratuita de Eagle no permite trabajar con más de dos capas, y esta versión del Nano posee 4 capas, se ha publicado aquí sin ser enrutado, así los usuarios pueden abrirlo y usarlo en la versión gratuita de Eagle.

Especificaciones:

MicrocontroladorAtmel ATmega168 o ATmega328
Tensión de Operación (nivel lógico)5 V
Tensión de Entrada (recomendado)7-12 V
Tensión de Entrada (límites)6-20 V
Pines E/S Digitales14 (de los cuales 6 proveen de salida PWM
Entradas Analógicas8
Corriente máx por cada PIN de E/S40 mA
Memoria Flash16 KB (ATmega168) o 32 KB (ATmega328) de los cuales 2KB son usados por el bootloader
SRAM1 KB (ATmega168) o 2 KB (ATmega328)
EEPROM512 bytes (ATmega168) o 1 KB (ATmega328)
Frecuencia de reloj16 MHz
Dimensiones18,5mm x 43.2mm

Alimentación:

El Arduino Nano puede ser alimentado usando el cable USB Mini-B , con una fuente externa no regulada de 6-20V (pin 30), o con una fuente externa regulada de 5V (pin 27). La fuente de alimentación es seleccionada automáticamente a aquella con mayor tensión.
El chip FTDI FT232RL que posee el Nano solo es alimentado si la placa esta siendo alimentada usando el cable USB. como resultado, cuando se utiliza una fuente externa (no USB), la salida de 3.3V (la cual es proporcionada por el chip FTDI) no está disponible y los pines 1 y 0 parpadearán si los pines digitales 0 o 1 están a nivel alto.

Memoria

El ATmega168 posee 16KB de memoria flash para almacenar el codigo (de los cuales 2KB son usados por el bootloader); elATmega 328 posee 32KB, (también con 2 KB usados por el bootloader). El Atmega168 posee 1KB de SRAM y 512 bytes de EEPROM (la cual puede ser leida y escrita con la librería EEPROM); el ATmega328 posee 2 KB de SRAM y 1KB de EEPROM.

Entrada y Salida

Cada uno de los 14 pines digitales del Nano puede ser usado como entrada o salida, usando las funciones pinMode(),digitalWrite(), y digitalRead(). Operan a 5 voltios. Cada pin puede proveer o recibir un máximo de 40mA y poseen una resistencia de pull-up (desconectada por defecto) de 20 a 50 kOhms. Además algunos pines poseen funciones especializadas:
  • Serial: 0 (RX) y 1 (TX). (RX) usado para recibir y (TX)usado para transmitir datos TTL vía serie. Estos pines están conectados a los pines correspondientes del chip USB-a-TTL de FTDI.
  • Interrupciones Externas: pines 2 y 3. Estos pines pueden ser configurados para activar una interrupción por paso a nivel bajo, por flanco de bajada o flanco de subida, o por un cambio de valor. Mira la función attachInterrupt()para más detalles.
  • PWM: pines 3, 5, 6, 9, 10, y 11. Proveen de una salida PWM de 8-bits cuando se usa la función analogWrite().
  • SPI: pines 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). Estos pines soportan la comunicación SPI, la cual, a pesar de poseer el hardware, no está actualmente soportada en el lenguaje Arduino.
  • LED: Pin 13. Existe un LED conectado al pin digital 13. Cuando el pin se encuentra en nivel alto, el LED está encendido, cuando el pin está a nivel bajo, el LED estará apagado.
El Nano posee 8 entradas analógicas, cada unas de ellas provee de 10 bits de resolución (1024 valores diferentes). Por defecto miden entre 5 voltios y masa, sin embargo es posible cambiar el rango superior usando la funciónanalogReference(). También, algunos de estos pines poseen funciones especiales:
  • I2C: Pines 4 (SDA) y 5 (SCL). Soporta comunicación I2C (TWI) usando la librería Wire (documentación en la web Wiring).
Hay algunos otros pines en la placa:
  • AREF. Tensión de referencia por las entradas analógicas. Se configura con la función analogReference().
  • Reset. Pon esta linea a nivel bajo para resetear el microcontrolador. Normalmente se usa para añadir un botón de reset que mantiene a nivel alto el pin reset mientras no es pulsado.

Comunicación

El Arduino Nao tiene algunos métodos para la comunicación con un PC, otro Arduino, u otros microcontroladores. ElATmega168 y el ATmega328 poseen un módulo UART que funciona con TTL (5V)el cual permite una comunicación vía serie, la cual está disponible usando los pines 0 (RX) y 1 (TX). El chip FTDI FT232RL en la placa hace de puente a través de USB para la comunicación serial y los controladores FTDI (incluidos con el software de Arduino) provee al PC de un puerto com vitual para el software en el PC. El software Arduino incluye un monitor serial que permite visualizar en forma de texto los datos enviados desde y hacia la placa Arduino. Los LEDs RX y TX en la placa parpadearán cuando los datos se estén enviando a través del chip FTDI y la conexión USB con el PC (Pero no para la comunicación directa a través de los pines 0 y 1)
La librería SoftwareSerial permite llevar a cabo una comunicación serie usando cualquiera de los pines digitales del Nano.
El ATmega168 y el ATmega328 también soporta comunicación I2C (TWI) y SPI. El software Arduino incluye la librería Wire para simplificar el uso del bus I2C; mira la documentación para más detalles. Para usar la comunicación SPI, por favor mira la hoja de datos del ATmega168 o el ATmega328.

Programación

El Arduino Nano puede ser programado con el software de Arduino (descarga). Selecciona "Arduino Diecimila, Duemilanove, o Nano w/ ATmega168" o "Arduino Duemilanove or Nano w/ ATmega328" de el menú Tools > Board(seleccionando el modelo del microcontrolador en tu placa). Para más detalles, mira la referencia y los tutoriales.
El ATmega168 o ATmega328 del Arduino Nano vienen preprogramados con un bootloader que te permite subir tu código al Arduino sin la necesidad de un programador externo. Se comunica usando el protocolo STK500 original (referencia,Archivos cabecera C).
También puedes programar el microcontrolador usando un programador ICSP (In-Circuit Serial Programming, Pogramación Serie En-Circuito); visita estasinstrucciones para más detalles.

Reset Automático (Software)

En vez de necesitar pulsar un botón físico de reset, el Arduino Nano ha sido diseñado de tal manera que permite ser reseteado por el software del PC al que está conectado. Una de las líneas de control de flujo por hardware (DTR) del chipFT232RL está conectada a la línea de reset del ATmega168 o ATmega328 a través de un condensador de 100 nanofaradios. Cuando esta línea se pone a nivel bajo, la linea de reset se mantiene a nivel bajo el suficiente tiempo para causar el reset del chip. El software de Arduino usa esta capacidad para permitir cargar código en el Arduino pulsando simplemente el botón "upload" en el entorno software de Arduino. Esto significa que el tiempo de espera del bootloader es más pequeño, ya que el tiempo en el que se encuentra a nivel bajo el DTR puede ser cordinado bien con el inicio de la carga del código.
Esta configuración tiene otras implicaciones. Cuando el Nano se conecta a un PC que funciona con Mac OS X o Linux, se resetea cada vez que se hace la conexión con el software (a través del USB). Durante el siguiente medio segundo más o menos, el bootloader está corriendo en el Nano. Como el bootloader ha sido para programado para ignorar cualquier dato erróneo (cualquier dato que no sea la carga de nuevo código), por lo tanto ignorará los primeros bytes que se reciban justo después de hacer la conexión. Si un sketch cargado en la placa recibe algún tipo de configuración o algún otro tipo de dato importante nada más iniciarse, asegúrate de que el software con el que se comunique, espere al menos un segundo antes de enviar datos para que no sean ignorados por el bootloader.