Color mixing lamp

Versione italiana (english version below)

Rieccomi qui, per mostrarvi come realizzare una “color mixing lamp”: una lampadina che cambia colore.

Il progetto è molto semplice, così come il materiale necessario:

  • un LED RGB;
  • tre resistenze da 220Ω;
  • cavi di connessione

Basta collegare il LED al GND e all’Arduino tramite le resistenze. Questo lo schema del circuito:

ColorMixingLamp Circuit Scheme

LED RGBRGB LED

Questo particolare LED è dotato di 4 pin: tre per i rispettivi colori primari rosso, verde e blu, e il quarto è il catodo. Creando una differenza di voltaggio sui pin (connessi all’Arduino tramite resistenze da 220Ω), il LED oscillerà tra i tre colori. Il piede più lungo è l’anodo.

Pulse Width Modulation

Il LED RGB ovviamente può mostrare più dei tre colori primari: basta modificare il voltaggio applicato ai pin (il valore dei colori varia da 0 a 255).

Per far ciò, viene utilizzata la tecnica Pulse Width Modulation, o PWM. E’ un procedimento che consiste nel cambiare molto rapidamente l’output sul pin da HIGH a LOW, per un certo periodo di tempo. E’ molto simile al funzionamento dei film: una serie di immagine scorre molto rapidamente, creando l’illusione del movimento.

La percentuale di tempo in cui il pin è su valore HIGH si chiama duty cicle. Più è alto il valore del duty cicle, più è alto il voltaggio applicato sul pin, e, di conseguenza, il valore del colore corrispondente.

Pulse Width Modulation

La scheda che utilizzo, Arduino Uno, è dotata di sei pin predisposti al PWM (pin digitali 3, 5, 6, 9, 10 e 11), che possono essere identificati dalla tilde ~ posta vicino al numero del pin sulla scheda.

Software

Utilizzeremo due programmi:

  • lo sketch Arduino, che legge terne di valori nel formato (r;g;b) dalla porta seriale e illumina il led del colore inviato (ad esempio la stringa “255;0;0″ per il rosso);
  • lo sketch Processing che invia tramite porta seriale la stringa con i valori rgb del colore selezionato dall’utente.

Clicca qui per scaricare il pacchetto completo.

Questo è il risultato finale:

ColorMixingLamp - Finished

Stay tuned!


English version

Hello guys, today we are going to learn how to build up a “color mixing lamp”: a lamp that is able to change its color.

The project is really simple, as well as the required components:

  • a RGB LED;
  • three 220Ω resistances;
  • cables

You just have to connect the LED to GND and to Arduino, through the resistances. This is the circuit:

ColorMixingLamp Circuit Scheme

RGBRGB LED LED

This particular kind of LED has 4 pins: three for the primary colors red, green and blue, and the fourth is the cathode. By creating a voltage difference between the cathode and the voltage coming out of the Arduino’s PWM pins, the LED will fade between the three colors. The longer leg is the anode.

Pulse Width Modulation

RGB LED obviously can show more than the three primary colors: you just have to modify the voltage on its pins (color value vary from 0 to 255).

For this reason, you will need the technique called Pulse Width Modulation, or PWM. It consists of rapidly turning the output pin HIGH and LOW over a fixed period of time. The change happens faster than the human eye can see. It’s similar to the way movies work, quickly flashing a number of still images to create the illusion of motion.

When you are rapidly turning the pin HIGH and LOW, it is as if you were changing the voltage. The percentage of time a pin is HIGH in a period is called duty cicle. When the pin is HIGH half of the period, the duty cicle is 50%. The higher is the duty cicle, the higher the voltage on the pin, and so is the value for the color.

Pulse Width Modulation

The board I use, Arduino Uno, provides six set aside for PWM (digital pins 3, 5, 6, 9, 10 e 11), that can be identified by the tilde ~ next to their number on the board.

Software

This project need two programs:

  • the Arduino sketch, that reads terns of value in the format (r;g;b) from the serial and lights up the led of the right color (for example, “255;0;0″ means red);
  • the Processing sketch, that catch the user input and send via serial the string for the chosen color.

Click here to download the complete package.

This is the final result:

ColorMixingLamp - Finished

Stay tuned!

How to – piezo as knock sensor

Versione italiana

Salve a tutti, oggi vedremo come utilizzare un piezo, un dispositivo che vibra quando riceve energia elettrica: vibrando, smuove l’aria intorno a sé, creando onde sonore. Tuttavia, è ancor più interessante vedere come sia possibile utilizzare lo stesso strumento per rilevare, ad esempio, un colpo di nocche – per questo motivo, esso viene anche chiamato knock sensor.

Piezo

Tale strumento utilizza il cosiddetto effetto piezoelettrico: è capace, cioè, di generare una differenza di potenziale quando è soggetto ad una deformazione meccanica.

Piezoelectric effect

Creare onde sonore

Per prima cosa, vediamo in che modo sia possibile emettere onde sonore. Modificando il voltaggio applicato al piezo, possiamo controllare la frequenza delle onde emesse.

Il circuito è semplicissimo: basta collegare il piezo al ground e ad un pin digitale dell’Arduino.

Questo è lo sketch: utilizza la funzione tone() per emettere onde sonore di data frequenza (nel nostro caso 1500) per un certo periodo di tempo (nel nostro caso 2 secondi). Il piezo è stato collegato al pin digitale 8; se si cambia pin, va modificato il valore della costante piezoPin con il valore corretto.

Knock sensor

Ma come già detto, il piezo può essere utilizzato anche come sensore. Il circuito è stato leggermente modificato:

Knock sensor scheme

L’unica differenza è la presenza della resistenza da 1 MegaOhm. Attenzione: adesso il sensore è collegato ad un pin analogico (A0).

Questo lo sketch: ogni volta che il sensore riceve un colpo, appare la scritta “Knock!”. Vengono presi in considerazione i valori maggiori della soglia 100 in modo da evitare che piccoli spostamenti siano interpretati come un colpo. Consiglio di non colpire direttamente il sensore ma di appoggiarvici un’altra superficie.

Stay tuned!


English version

Hello everyone, in this post we are going to learn how to work with a piezo, that is a device that virbates when it receives electricity: when it moves, it displaces air around it, creating sound waves. However, it is even more interesting to learn how it is possibile to use the same device as a sensor to catch, for example, a knock. For this reason, it is also called knock sensor.

Piezo

This device exploit the so-called piezoeletctric effect: it means that it is able to create a variable voltage when it is deformed.

Piezoelectric effect

Emitting sound waves

First of all, let me explain how it is possible to emit sound waves. Modifying the voltage on the piezo, we can control sound waves’s frequency.

The circuit is really simply: you have just to link the piezo to the ground and to a digital pin on the Arduino.

This is the sketch: it uses the function  tone() in order to emit sound waves of fixed frequency (in this particular case 1500) for a certain period (in this case 2 seconds). The piezo has been linked to the digital pin 8: if you want to change pin, you also have to modify the value of piezoPin constant with the correct value.

Knock sensor

But, as I said, the piezo can be used also as a sensor. The circuit is a bit different:

Knock sensor scheme

The only difference is the presence of a 1 MegaOhm resistence. Pay attention: now the sensor is connected to an analogic pin (A0).

This is the sketch: every time that the sensor catch a knock, the string “Knock!” is sent through the serial port. In order to avoid to take little movement as knocks, it only considers values greater than the treshold of 100. Just a tip: do not knock directly on the sensor: cover it with an other surface.

Stay tuned!

How to – LCD custom characters

Versione italiana

Nell’ultimo post abbiamo imparato come interfacciare l’Arduino con un LCD. Adesso vedremo come sia possibile creare caratteri personalizzati da mostrare sullo schermo.

Ogni cella in cui è diviso il display è composta da una griglia di 5×8 pixel (5 colonne e 8 righe). Tramite codice, è possibile creare nuovi caratteri, operando direttamente sui pixel. Ad esempio, il carattere “omega” (Ω), può essere suddiviso in pixel come in figura:

LCD custom character

Come potete notare, il carattere è descritto da un’array di 8 byte, che rappresentano le righe: ogni byte contiene invece le informazioni per le colonne. “1″ è il pixel acceso, “0″ il pixel spento.

Per caratteri molto grandi, che non rientrano nella griglia 5×8, è possibile utilizzare una combinazione di due o più caratteri.

Questo è un semplice sketch con l’utilizzo di caratteri personalizzati. Utilizza la funzione createChar() della libreria LiquidCrystal.

LCD display custom character

Stay tuned!


English version

In the last post we have learnt how to interface Arduino with a LCD. Now, we are going to learn how it is possibile to create custom characters, and to show them on the display.

Every cell in which the display is divided is formed by a grid of 5×8 pixels (5 columns and 8 rows). Through code, you can create new custom characters, working directly on these pixels. For example, the “omega” character (Ω) can be divided in pixels like this:

LCD custom character

As you can see, the character is described by an array of 8 byte, that represent rows: every byte contains the information about columns. “1″ means pixel is on, “0″ pixel is off.

For bigger characters, that do not fit in the 5×8 grid, you can use two or more custom character together.

This is a simple sketch that shows how to create and print custom characters. It uses  createChar() function in LiquidCrystal library.

LCD display custom character

Stay tuned!

How to – LCD Interfacing

Versione italiana

Salve a tutti, oggi vedremo come utilizzare un display a cristalli liquidi. Io utilizzo un LCD Hitachi HD44780, un display 16×2 (16 colonne e 2 righe, per un totale di 32 caratteri) economico e facile da reperire.

Il display è dotato di 16 pin in totale: 2 per l’alimentazione, 2 per la retroilluminazione, 1 per la regolazione del contrasto, 3 linee di controllo e 8 per l’effettiva scrittura di dati. Tuttavia, in questo post trasferiremo i dati a 4bit, e quindi di questi ultimi ne utilizzero soltanto 4. Analizziamo i pin nel dettaglio.

Funzioni pin

Di seguito la tabella con nome e funzione di ogni pin:

Pin number Symbol Function
 1  Vss  GND
 2  Vdd  +5V
 3  V0  Controllo contrasto
 4  RS  Selezione registro
 5  R/W  Modalità read/write
 6  E  Abilitazione scrittura registri
 7  D0  Data bus line
 8  D1  Data bus line
 9  D2  Data bus line
10  D3  Data bus line
11  D4  Data bus line
12  D5  Data bus line
13  D6  Data bus line
14  D7  Data bus line
15  BL+  +5V per retroilluminazione
16  BL-  GND per retroilluminazione

Di seguito una più accurata descrizione di alcuni pin:

  • Il pin 3 (V0) viene di solito collegato ad un potenziometro in modo che l’utente possa applicare una variazione di tensione (da 0 a +5V) in modo da far variare il contrasto.
  • Il pin 4 (RS) è utilizzato per controllare in quale memoria dell’LCD si intende scrivere. Si possono selezionare il registro dati, che mantiene ciò che andrà sullo schermo, o il registro delle istruzioni, che è dove l’LCD guarda per sapere cosa fare.
  • Il pin dal 7 al 14 (D0-D7) sono le linee dati che inviano o ricevono informazioni dai registri dell’LCD.

Per maggiori informazioni consultare il datasheet.

I collegamenti

Dato il numero di pin, avremo un bel po’ di cavi da gestire, ma non fatevi spaventare. Ecco lo schema:

LCD scheme

Questo è il codice di prova, ricavato dal tutorial sul sito ufficiale di Arduino. Utilizza la libreria LiquidCrystal.

LCD - Hello world

Stay tuned!


English version

Hello everyone, today we are going to learn how to use a liquid crystal display. I use a Hitachi HD44780 LCD, a 16×2 display (16 columns and 2 rows, 32 characters in total), that is cheap and easy to get.

The display has 16 pins: 2 for the power, 2 for the backlight, 1 for contrast adjustement, 3 control lines and 8 for writing data. However, in this post I am going to transfer data in 4bit: so I only use 4 of these last pins. Let’s analyze the pins in detail.

Pin functions

Below, a table with every pin’s name and function:

Pin number Symbol Function
 1  Vss  GND
 2  Vdd  +5V
 3  V0  Contrast adjustement
 4  RS  Register select signal
 5  R/W  Read/write signal
 6  E  Enable signal
 7  D0  Data bus line
 8  D1  Data bus line
 9  D2  Data bus line
10  D3  Data bus line
11  D4  Data bus line
12  D5  Data bus line
13  D6  Data bus line
14  D7  Data bus line
15  BL+  +5V for blacklight
16  BL-  GND for blacklight

Here a more accurated descriptions of certain pins:

  • Pin 3 (V0) is usually connected to a potentiometer, so that the user can apply a voltage variation (from 0 to +5V): in this way, he can adjust the LCD contrast.
  • Pin 4 (RS) is used to control in which lcd memory you want to write. You can select the data register, that hold data which will be printed on the screen, or the instructions register, that is where the LCD look for istructions on what to do.
  • Pin 7 to 14 (D0-D7) are control lines that send or receive data to or from LCD’s registers.

For further information, look up the datasheet.

Links

Because of the number of used pins, there will be a lot of wires, but don’t worry, it’s quite simple. Here’s the scheme:

LCD scheme

This is a test sketch from the tutorial on Arduino official website. It uses LiquidCrystal library.

LCD - Hello world

Stay tuned!

How to – Ultrasonic sensor HC-SR04

Versione italiana

Salve a tutti, oggi vedremo come utilizzare un sensore ad ultrasuoni HC-SR04. Si tratta di uno strumento che misura il tempo impiegato dalle onde sonore emesse da una sorgente a tornare indietro, dopo aver incontrato un ostacolo che le riflette; da questa informazione è possibile misurare la distanza dell’ostacolo dal sensore. Il fascio di onde sonore emesso ha forma conica e lo stesso vale per le onde riflesse da un ostacolo; di conseguenza, il sensore riceve riflessioni da diversi oggetti, ed è dunque incapace di distinguere un oggetto dall’altro.

Il sensore HC-SR04 è in grado di misurare correttamente distanze comprese tra 2 centimetri e 4 metri, con un errore di pochi millimetri. Per maggiori informazioni, è possibile consultare il datasheet.

HC-SR04 sensor

Calcolo della distanza

La velocità del suono varia in base alla temperatura dell’ambiente. Ipotizziamo di trovarci a temperatura 20°C: la velocità v del suono è 343,4 m/s. Il sensore restituisce il tempo misurato in microsecondi (µs); tuttavia, è utile calcolare la distanza in cm. Calcoliamo quindi la velocità del suono in cm/µs: 1 m/s = 10^2 cm / 10^6 µs = 10^-4 cm/µs => V = 343,5 m/s * 10^-4 = 3,4*10^-2 cm/µs. Adesso, calcoliamo lo spazio percorso dall’onda sonora: s = v*t = 3,4*10^-4 * t. Tuttavia, bisogna tenere conto che l’onda sonora percorre lo spazio s due volte, andata e ritorno. Quindi, la formula finale per il calcolo della distanza è:

S = 1,7 * 10^-2 * t

Il sensore HC-SR04

Il sensore HC-SR04 dispone di 4 pin: Vcc (+5V), Trigger, Echo, GND. Si invia un impulso alto sul pin Trigger per almeno 10 microsecondi, in modo che il sensore invii il ping sonoro e aspetti il ritorno delle onde riflesse. Il sensore risponderà sul pin Echo con un impulso alto di durata corrispondente a quella di viaggio delle onde sonore. Per sicurezza, si aspettano in genere 60 millisec per far si che non vi siano interferenze con la misura successiva.

HC-SR04 sensor schema

Bisogna collegare il pin Vcc e GND rispettivamente all’alimentazione da 5V e al ground, e i pin Trigger ed Echo a due pin digitali dell’Arduino.

Questo lo sketch che calcola e mostra la distanza misurata dal sensore: utilizza i pin 7 per il Trigger e 8 per l’Echo.

Stay tuned!


English version

Hi everyone, today we are going to learn how to use a HC-SR04 ultrasonic sensor. It is a useful device that measure the time spent by a beam of sound waves, emitted from a source, to come back again, after they had been reflected by an obstacle. Starting from this information, we are able to calculate the distance from the sensor to the object. The beam of sound waves has a conical shape, as well as the reflected beam; therefore, it’s impossible for the sensor to distinguish an object from another.

The HC-SR04 sensor can measure correctly distance for values between 2 centimeters and 4 meters, with an error of few millimeters. For further information, consult the datasheet.

HC-SR04 sensor

Distance calculation

The speed of sound vary according to the temperature of the environment. Let’s assume the temperature of the environment is 20°C: the speed v of sound is 343,3 m/s. The sensor returns the measured time in microseconds (µs); however, may be useful to calculate the distance in centimeters. So, we calculate the speed of sound in cm/µs: 1 m/s = 10^2 cm / 10^6 µs = 10^-4 cm/µs => V = 343,5 m/s * 10^-4 = 3,4*10^-2 cm/µs. Now, we calculate the distance traveled by the sound wave: s = v*t = 3,4*10^-4 * t. Pay attention: the wave travel the same distance twice, going and return. In conclusion, the final formula for calculating the distance is:

S = 1,7 * 10^-2 * t

The HC-SR04 sensor

The HC-SR04 has 4 pins: Vcc (+5V), Trigger, Echo and GND. You send a high impulse on the Trigger pin for 10 microseconds. In this way, the sensor send the sound waves and waits for its return. Then, the sensor will respond on the Echo pin, with an high impulse of duration directly proportional to the duration of the sound waves’ travel. You need to wait at least 60 milliseconds from an impulse to another one, in order to avoid interferences with the next measurement.

HC-SR04 sensor schema

You just have to connect the Vcc and GND pins respectively to 5V power and ground, and Trigger and Echo pins to two digital pins on the Arduino.

This is the sketch that calculate and show the distance measured with the sensor. It uses digital pin 7 for Trigger and 8 for Echo.

Stay tuned!

Hacking the Wii Nunchuk

Versione italiana

Salve a tutti, in questo articolo vedremo come collegare il controller Nunchuk della Nintendo Wii all’Arduino e utilizzarlo come dispositivo di input, per utilizzarlo al posto del mouse.

Nunchuk and Arduino

Per interfacciarci con il Nunchuk, utilizzerò la libreria ArduinoNunchuk scritta da Gabriel Bianconi.

Il Nunchuk va collegato all’Arduino in questo modo:

Nunchuk Connection scheme

Utilizzerò quindi i pin analogici 4 e 5, oltre che l’alimentazione a 3.3 volt e il ground.

Anche questa volta, i software sono due: lo sketch, che comunica tramite porta seriale l’input ricevuto dal Nunchuk, nel formato “analogX analogY cBtn zBtn”: ovvero, la coordinata x ed y del joystick analogico, e i valori della pressione dei tasti C e Z (1 per tasto premuto, 0 per tasto rilasciato); tutti i valori sono separati da uno spazio.

Il programma che verrà eseguito sul computer, anche questa volta scritto in Python, si occupa di analizzare l’input dalla porta seriale, e simulare il movimento o la pressione di tasti del mouse, tramite la libreria pymouse.

Manca tuttavia la possibilità di poter tenere premuto il tasto destro, ad esempio per trascinare delle icone.

Nel prossimo post vedremo come utilizzare il Nunchuk per interagire con un’applicazione più complessa.

Stay tuned!


English version

Hello everyone, in this post we are going to learn how to connect the Nintendo Wii Nunchuk controller to the Arduino, and use it as an input device, to control the mouse.

Nunchuk and Arduino

In order to interface with the Nunchuk, we are going to use the ArduinoNunchuk library, written by Gabriel Bianconi.

The Nunchuk must be connected to the Arduino in this way:

Nunchuk Connection scheme

So, we will use analog pin 4 and 5, besides 3.3V power and ground.

The required softwares are two also this time: the sketch, that communicates through the serial port the input data received from the Nunchuk, in the format “analogX analogY cBtn zBtn”: x and y coordinates of the analog joystick, and the value of C and Z button (1 for pressed, 0 for released); every value is separated from the other with a white space.

The software that run on the computer is written in Python again, and it analyzes the input from the serial port and simulate mouse movement and clicks, using the pymouse library.

However, you can’t hold the left button pressed, for example to drag icons.

In the next post, we will see how to use Nunchuk to interact with a more complex application.

Stay tuned!

Facebook Notifier – Final

Versione italiana

Finalmente, la versione finale del “Facebook Notifier”, discusso nel post precedente, è pronta. Ho colorato la scatola di blu con una bomboletta spray, e incollato alla parte fronale della scatola “f”, ricavata da un foglio di carta; la bandierina invece è formata da un pezzo di cartoncino rosso incollato ad una cannuccia bianca e blu.

Di seguito alcune foto scattate durante la lavorazione:

FbNotifier - Painted box FbNotifier - F logo FbNotifier - F box

FbNotifier - Final 1 FbNotifier - Final 2

Stay tuned!


English version

Finally, the final version of the “Facebook Notifier”, discussed in the previous post, is done. I’ve painted the box in blue with a spray can, and glued an “f” (cut from a sheet of paper) on the front. The flag consists of a little sheed of red cardboard, glued on a white and blue straw.

Here, some photos of the box:

FbNotifier - Painted box FbNotifier - F logo FbNotifier - F box

FbNotifier - Final 1 FbNotifier - Final 2

Stay tuned!