Vous êtes sur la page 1sur 70

FACULTAD DE INGENIERIA Y CIENCIAS AGROINDUSTRIALES

GUIA DE LABORATORIO DE ELECTRONICA

PROGRAMA: TECNOLOGIA EN AUTOMATIZACION INDUSTRIAL

AREA: FUNDAMENTACION ESPECIFICA TECNICA

PRACTICA No.

TEMA: ARDUINO ANDROID ,INDUSTRIAL MONTAR EN FISICO 04

1.Keyboard Logout
En este ejemplo se utiliza la biblioteca teclado realice la desconexión
de la sesión de usuario en el equipo cuando el pin 2 en el Leonardo,
Micro o Debido se tira al suelo. El boceto simula la pulsación de tecla
en secuencia de dos o tres teclas al mismo tiempo y después de un breve
retraso que los libera .
Nota: Cuando se utiliza el comando Keyboard.print (), el Arduino se hace
cargo el teclado de su computadora! Para asegurarse de no perder el
control de su ordenador mientras se ejecuta un boceto con esta función ,
asegúrese de establecer un sistema de control fiable antes de llamar
Keyboard.print (). Este bosquejo está diseñado únicamente para enviar un
comando de teclado después de un alfiler se ha tirado al suelo.

Hardware Required

 Arduino Leonardo, Micro, or Due board


 pushbutton
 hook-up wires
 breadboard

Circuit
Schematic
Code
Antes de cargar el programa en el tablero, asegúrese de asignar el
sistema operativo correcto está utilizando actualmente para la variable
de plataforma.
Mientras que el boceto está en ejecución, pulsando el botón conectará el
pin 2 al suelo y la junta enviará la secuencia de cierre de sesión a la
PC USB conectado .
/*
Keyboard logout
Este bosquejo demuestra la biblioteca del teclado .

Cuando se conecta el pin 2 al suelo, se lleva a cabo un cierre de sesión


Utiliza combinaciones de teclado para hacer esto , de la siguiente
manera :

On Windows, CTRL-ALT-DEL followed by ALT-l


On Ubuntu, CTRL-ALT-DEL, and ENTER
On OSX, CMD-SHIFT-q

To wake: Spacebar.

Circuit:
* Arduino Leonardo or Micro
* wire to connect D2 to ground.

*/

#define OSX 0
#define WINDOWS 1
#define UBUNTU 2

#include "Keyboard.h"
#include "HID.h"

// change this to match your platform:


int platform = OSX;

void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);

switch (platform) {
case OSX:
Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q');
delay(100);
Keyboard.releaseAll();
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-l:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}

// do nothing:
while (true);
}
Keyboard Message
2.

Cuando se pulsa el botón en este ejemplo, una cadena de texto se envía a


la computadora como entrada de teclado. La cadena informa del número de
veces que el botón ha sido presionado. Una vez que tienen el Leonardo
programado y cableada , abre tu editor de texto favorito para ver los
resultados.
Nota: Cuando se utiliza el comando Keyboard.print (), el Arduino se hace
cargo el teclado de su computadora! Para asegurarse de no perder el
control de su ordenador mientras se ejecuta un boceto con esta función ,
asegúrese de establecer un sistema de control fiable antes de llamar
Keyboard.print (). Este bosquejo incluye un pulsador para cambiar el
teclado, de modo que sólo se ejecuta después de pulsar el botón.

Hardware Required

 Arduino Leonardo, Micro, or Due board


 momentary pushbutton
 10k ohm resistor

Circuito
Conecte un pin del pulsador al pin 4 en el Arduino . Conecte el otro pin
de 5V . Utilice la resistencia como un desplegable , proporcionando una
referencia a tierra, uniendo desde la patilla 4 a tierra.
Una vez que haya programado su tablero , desconecte el cable USB , abra
un editor de texto y poner el cursor de texto en en el área de escritura.
Conecte la tarjeta al ordenador a través de USB de nuevo y pulse el botón
para escribir en el documento.
Code

/*
Keyboard Message test

Sends a text string when a button is pressed.


The circuit:
* pushbutton attached from pin 4 to +5V
* 10-kilohm resistor attached from pin 4 to ground

*/

#include "Keyboard.h"
#include "HID.h"

const int buttonPin = 4; // input pin for pushbutton


int previousButtonState = HIGH; // for checking the state of a pushButton
int counter = 0; // button push counter

void setup() {
// make the pushButton pin an input:
pinMode(buttonPin, INPUT);
// initialize control over the keyboard:
Keyboard.begin();
}

void loop() {
// read the pushbutton:
int buttonState = digitalRead(buttonPin);
// if the button state has changed,
if ((buttonState != previousButtonState)
// and it's currently pressed:
&& (buttonState == HIGH)) {
// increment the button counter
counter++;
// type out a message
Keyboard.print("You pressed the button ");
Keyboard.print(counter);
Keyboard.println(" times.");
}
// save the current button state for comparison next time:
previousButtonState = buttonState;
}
Keyboard Reprogram
3.

En este ejemplo se utiliza la biblioteca de teclado para abrir un nuevo


Arduino Software ( IDE) de ventana de boceto , enviar comandos de teclado
de ese tipo en el ejemplo Blink , y reprograma el tablero. Después de
ejecutar este bosquejo y la conexión de la clavija 2 a tierra utilizando
el pulsador , la junta tendrá un nuevo programa , Blink .
Nota: Cuando se utiliza el comando Keyboard.print (), el Arduino se hace
cargo el teclado de su computadora! Para asegurarse de no perder el
control de su ordenador mientras se ejecuta un boceto con esta función ,
asegúrese de establecer un sistema de control fiable antes de llamar
Keyboard.print (). Este bosquejo está diseñado sólo para enviar comandos
de teclado después de pin digital 2 se tira al suelo.

Hardware Required

 Arduino Leonardo, Micro, or Due board


 pushbutton
 hook-up wires
 breadboard

Software Required

 Arduino IDE running

Circuit
Schematic

Code
Conecte su tablero para el puerto USB , a continuación, pulse el botón
para conectar D2 con GND e iniciar el boceto de emulación de pulsación
del teclado. Recuerde que debe tener la ventana Arduino Software ( IDE )
ha seleccionado antes de pulsar el botón.
/*
Arduino Programs Blink

This sketch demonstrates the Keyboard library.

When you connect pin 2 to ground, it creates a new


window with a key combination (CTRL-N),
then types in the Blink sketch, then auto-formats the text
using another key combination (CTRL-T), then
uploads the sketch to the currently selected Arduino using
a final key combination (CTRL-U).

Circuit:
* Arduino Leonardo, Micro, Due, LilyPad USB, or Yún
* wire to connect D2 to ground.

*/

#include "Keyboard.h"
#include "HID.h"

// use this option for OSX.


// Comment it out if using Windows or Linux:
char ctrlKey = KEY_LEFT_GUI;
// use this option for Windows and Linux.
// leave commented out if using OSX:
// char ctrlKey = KEY_LEFT_CTRL;

void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
// initialize control over the keyboard:
Keyboard.begin();
}

void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
// new document:
Keyboard.press(ctrlKey);
Keyboard.press('n');
delay(100);
Keyboard.releaseAll();
// wait for new window to open:
delay(1000);

// versions of the Arduino IDE after 1.5 pre-populate


// new sketches with setup() and loop() functions
// let's clear the window before typing anything new
// select all
Keyboard.press(ctrlKey);
Keyboard.press('a');
delay(500);
Keyboard.releaseAll();
// delete the selected text
Keyboard.write(KEY_BACKSPACE);
delay(500);

// Type out "blink":


Keyboard.println("void setup() {");
Keyboard.println("pinMode(13, OUTPUT);");
Keyboard.println("}");
Keyboard.println();
Keyboard.println("void loop() {");
Keyboard.println("digitalWrite(13, HIGH);");
Keyboard.print("delay(3000);");
// 3000 ms is too long. Delete it:
for (int keystrokes = 0; keystrokes < 6; keystrokes++) {
delay(500);
Keyboard.write(KEY_BACKSPACE);
}
// make it 1000 instead:
Keyboard.println("1000);");
Keyboard.println("digitalWrite(13, LOW);");
Keyboard.println("delay(1000);");
Keyboard.println("}");
// tidy up:
Keyboard.press(ctrlKey);
Keyboard.press('t');
delay(100);
Keyboard.releaseAll();
delay(3000);
// upload code:
Keyboard.press(ctrlKey);
Keyboard.press('u');
delay(100);
Keyboard.releaseAll();

// wait for the sweet oblivion of reprogramming:


while (true);
}

4. Keyboard Serial
En este ejemplo se escucha por un byte que viene del puerto serie. Cuando
se reciban, la Junta envía una pulsación de tecla de nuevo al equipo . El
golpe de teclado enviado es uno más alto que lo que se recibe , por lo
que si usted envía una "a " en el monitor serie , recibirá una "b" de la
placa conectada a la computadora. Un " 1 " devolverá un " 2 " y así
sucesivamente .
Nota: Cuando se utiliza el comando Keyboard.print (), el Leonardo, Micro
o Debido a bordo se hace cargo el teclado de su computadora! Para
asegurarse de no perder el control de su ordenador mientras se ejecuta un
boceto con esta función , asegúrese de establecer un sistema de control
fiable antes de llamar Keyboard.print (). Este bosquejo está diseñado
únicamente para enviar un comando de teclado después de que la junta ha
recibido un byte a través del puerto serie.

Hardware Required

 Arduino Leonardo, Micro, or Due board

Circuit
Conecte su tablero al ordenador con un cable micro-USB .
Una vez programada , abra su monitor de serie y enviar un byte . La junta
le responderá con un golpe de teclado que es un número más alto.
Code

/*
Keyboard test

For the Arduino Leonardo, Micro or Due

*/

#include "Keyboard.h"
#include "HID.h"

void setup() {
// open the serial port:
Serial.begin(9600);
// initialize control over the keyboard:
Keyboard.begin();
}

void loop() {
// check for incoming serial data:
if (Serial.available() > 0) {
// read incoming serial data:
char inChar = Serial.read();
// Type the next ASCII value from what you received:
Keyboard.write(inChar + 1);
}
}

Keyboard and Mouse Control


5.

Este ejemplo ilustra el uso del ratón y el teclado bibliotecas juntos.


Cinco interruptores momentáneos actúan como botones direccionales para el
cursor . Cuando se pulsa un botón , el cursor de la pantalla se moverá ,
y pulsar una tecla , que corresponde a la letra asociada con la dirección
, será enviado a la computadora. Una vez que tenga el Leonardo, Micro o
Debido programado y cableado , abra su editor de texto favorito para ver
los resultados.
Nota: Cuando utilice las funciones de mouse y teclado de la biblioteca ,
el Arduino se hace cargo del cursor de su computadora ! Para asegurarse
de no perder el control de su ordenador mientras se ejecuta un boceto con
esta función , asegúrese de configurar un controlador antes de llamar
Mouse.move ().

Hardware Required

 Arduino Leonardo, Micro or Arduino Due board


 5 pushbuttons
 5 10k ohm resistors
 hook-up wires
 breadboard

Software Required

 Any text editor


Circuit
Conecte un extremo de los pulsadores a los pines 2 , 3, 4 , 5 y 6 en el
tablero. Conecte el otro extremo a + 5V . Utilice las resistencias como
pull-downs , proporcionando una referencia a tierra para los
interruptores. Adjuntar desde el pasador de conexión a la placa a tierra.
Una vez que haya programado su tablero , desconecte el cable USB y abra
un editor de texto . Conecte su tablero a su ordenador y pulse los
botones para escribir en el documento como se mueve el cursor.

Schematic
Code

/*
KeyboardAndMouseControl

Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due.

Hardware:
* 5 pushbuttons attached to D2, D3, D4, D5, D6

The mouse movement is always relative. This sketch reads


four pushbuttons, and uses them to set the movement of the mouse.

WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the mouse commands.

*/
#include "Keyboard.h"
#include "Mouse.h"
#include "HID.h"

// set pin numbers for the five buttons:


const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;

void setup() { // initialize the buttons' inputs:


pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);

Serial.begin(9600);
// initialize mouse control:
Mouse.begin();
Keyboard.begin();
}

void loop() {
// use serial input to control the mouse:
if (Serial.available() > 0) {
char inChar = Serial.read();

switch (inChar) {
case 'u':
// move mouse up
Mouse.move(0, -40);
break;
case 'd':
// move mouse down
Mouse.move(0, 40);
break;
case 'l':
// move mouse left
Mouse.move(-40, 0);
break;
case 'r':
// move mouse right
Mouse.move(40, 0);
break;
case 'm':
// perform mouse left click
Mouse.click(MOUSE_LEFT);
break;
}
}

// use the pushbuttons to control the keyboard:


if (digitalRead(upButton) == HIGH) {
Keyboard.write('u');
}
if (digitalRead(downButton) == HIGH) {
Keyboard.write('d');
}
if (digitalRead(leftButton) == HIGH) {
Keyboard.write('l');
}
if (digitalRead(rightButton) == HIGH) {
Keyboard.write('r');
}
if (digitalRead(mouseButton) == HIGH) {
Keyboard.write('m');
}

}
Button Mouse Control
6.

El uso de la biblioteca del ratón, se puede controla el cursor en la


pantalla de un ordenador con un Arduino Leonardo, Micro o Due. Este
ejemplo particular utiliza cinco botones para mover el cursor en
pantalla. Cuatro de los botones son direccionales (arriba, abajo,
izquierda, derecha) y la otra es por un clic izquierdo del ratón
El movimiento del cursor del Arduino es siempre relativa. Cada vez que se
lee una entrada, la posición del cursor se actualiza con respecto a su
posición actual.
Cada vez que se pulsa uno de los botones de dirección, el Arduino se
moverá el ratón, la asignación de un ALTO entrada a un rango de 5 en la
dirección apropiada.
El quinto botón es para el control de un clic izquierdo de un ratón.
Cuando se pulsa, la Junta envía una prensa a la computadora. Cuando se
suelta el botón, el ordenador reconocerá el evento.
Nota: Cuando se utiliza el comando Mouse.move (), el Arduino se hace
cargo del cursor de su computadora! Para asegurarse de no perder el
control de su ordenador mientras se ejecuta un boceto con esta función,
asegúrese de configurar un controlador antes de llamar Mouse.move ().
Este bosquejo sólo actualiza la posición del cursor cuando se pulsa un
botón.

Hardware Required

 Arduino Leonardo, Micro or Due board


 5 momentary pushbuttons
 5 10k ohm resistors
 hook-up wires
 breadboard

Circuit
Conecte su tablero al ordenador con un cable micro-USB . Los botones
están conectados a las entradas digitales de 2 a 6. Asegúrese de que
utiliza 10k ohm resistencias desplegables .
Code

/*
ButtonMouseControl

Hardware:
* 5 pushbuttons attached to D2, D3, D4, D5, D6

The mouse movement is always relative. This sketch reads


four pushbuttons, and uses them to set the movement of the mouse.

WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the mouse commands.

*/

#include "Mouse.h"
#include "HID.h"

// set pin numbers for the five buttons:


const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;

int range = 5; // output range of X or Y movement; affects movement speed


int responseDelay = 10; // response delay of the mouse, in ms

void setup() {
// initialize the buttons' inputs:
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);
// initialize mouse control:
Mouse.begin();
}

void loop() {
// read the buttons:
int upState = digitalRead(upButton);
int downState = digitalRead(downButton);
int rightState = digitalRead(rightButton);
int leftState = digitalRead(leftButton);
int clickState = digitalRead(mouseButton);

// calculate the movement distance based on the button states:


int xDistance = (leftState - rightState) * range;
int yDistance = (upState - downState) * range;

// if X or Y is non-zero, move:
if ((xDistance != 0) || (yDistance != 0)) {
Mouse.move(xDistance, yDistance, 0);
}

// if the mouse button is pressed:


if (clickState == HIGH) {
// if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
}
}
// else the mouse button is not pressed:
else {
// if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
}
}

// a delay so the mouse doesn't move too fast:


delay(responseDelay);
}

7. Joystick Mouse Control


El uso de la biblioteca del ratón, se puede controla el cursor en la
pantalla de un ordenador con un Arduino Leonardo, Micro o Due. Este
ejemplo particular utiliza un pulsador para activar y desactivar el
control del ratón con un joystick.
El movimiento del cursor del Arduino es siempre relativa. Así que cada
vez que la entrada analógica se lee, la posición del cursor se actualiza
con respecto a su posición actual.
Dos entradas analógicas que van desde 0 a 1,023 mil se convierten a
rangos de -12 a 12. El dibujo asume que los valores de la palanca de
mando de reposo son alrededor de la mitad de la gama, pero que varían
dentro de un umbral.
El pulsador le permite alternar el control del ratón y se apaga. Como
opción es posible conectar un LED al pin 5 que ilumina hipertiempo el
Arduino es controlar el ratón de estado. Un segundo pulsador puede
conectarse con otro desplegable 10k ohmios (a GND) resistencia a D3 para
actuar como el botón izquierdo del ratón.
Nota: Cuando se utiliza el comando Mouse.move (), el Arduino se hace
cargo del cursor de su computadora! Para asegurarse de no perder el
control de su ordenador mientras se ejecuta un boceto con esta función,
asegúrese de configurar un controlador antes de llamar Mouse.move ().
Este bosquejo incluye un pulsador para cambiar el estado de control del
ratón, por lo que se puede activar y desactivar el control del ratón.

Hardware Required

 Arduino Leonardo, Micro, or Due board


 2 axis joystick
 momentary pushbutton (possibly integrated in the joystick)
 LED
 220 ohm resistor
 10k ohm resistor (if needed as pulldown)

Circuit
Conecte su tablero Leonardo al ordenador con un cable micro-USB . El
pulsador está conectado al pin 6. Si está utilizando una parte como el
escudo Joystick foto de abajo , puede que no necesite una resistencia
desplegable. El eje x en el joystick está conectado a analógico en 0 , el
eje y está en analógica en 1 .

Schematic
Code

/*
JoystickMouseControl

Controla el ratón de una palanca de mando en un Arduino Leonardo, Micro o


Due.
Utiliza un pulsador para activar y desactivar el control del ratón , y
un segundo pulsador para hacer clic en el botón izquierdo del ratón

Hardware:
* Joystick de 2 ejes conectados a los pines A0 y A1
* Pulsadores conectada al pin D2 y D3

El movimiento del ratón es siempre relativa . Este bosquejo lee


dos entradas analógicas que van de 0 a 1023 ( o menos en cada extremo )
y las traduce en rangos de -6-6 .
El dibujo asume que los valores de la palanca de mando de descanso son
alrededor de la
medio de la gama , pero que varían dentro de un umbral .

ADVERTENCIA : Cuando se utiliza el comando Mouse.move (), el Arduino


toma
su ratón ! Asegúrese de que usted tiene el control antes de utilizar el
comando.
Este bosquejo incluye un pulsador para cambiar el estado de control del
ratón , por lo que
se puede activar y desactivar el control del ratón .

*/

#include "Mouse.h"
#include "HID.h"

// set pin numbers for switch, joystick axes, and LED:


const int switchPin = 2; // switch to turn on and off mouse control
const int mouseButton = 3; // input pin for the mouse pushButton
const int xAxis = A0; // joystick X axis
const int yAxis = A1; // joystick Y axis
const int ledPin = 5; // Mouse control LED

// parameters for reading the joystick:


int range = 12; // output range of X or Y movement
int responseDelay = 5; // response delay of the mouse, in ms
int threshold = range / 4; // resting threshold
int center = range / 2; // resting position value

boolean mouseIsActive = false; // whether or not to control the mouse


int lastSwitchState = LOW; // previous switch state

void setup() {
pinMode(switchPin, INPUT); // the switch pin
pinMode(ledPin, OUTPUT); // the LED pin
// take control of the mouse:
Mouse.begin();
}

void loop() {
// read the switch:
int switchState = digitalRead(switchPin);
// if it's changed and it's high, toggle the mouse state:
if (switchState != lastSwitchState) {
if (switchState == HIGH) {
mouseIsActive = !mouseIsActive;
// turn on LED to indicate mouse state:
digitalWrite(ledPin, mouseIsActive);
}
}
// save switch state for next comparison:
lastSwitchState = switchState;
// read and scale the two axes:
int xReading = readAxis(A0);
int yReading = readAxis(A1);

// if the mouse control state is active, move the mouse:


if (mouseIsActive) {
Mouse.move(xReading, yReading, 0);
}

// read the mouse button and click or not click:


// if the mouse button is pressed:
if (digitalRead(mouseButton) == HIGH) {
// if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
}
}
// else the mouse button is not pressed:
else {
// if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
}
}

delay(responseDelay);
}

/*
reads an axis (0 or 1 for x or y) and scales the
analog input range to a range from 0 to <range>
*/

int readAxis(int thisAxis) {


// read the analog input:
int reading = analogRead(thisAxis);

// map the reading from the analog input range to the output range:
reading = map(reading, 0, 1023, 0, range);

// if the output reading is outside from the


// rest position threshold, use it:
int distance = reading - center;

if (abs(distance) < threshold) {


distance = 0;
}
// return the distance for this axis:
return distance;
}
Communication

8. ASCII Table
Este ejemplo demuestra las funciones de impresión de serie avanzada
generando en el monitor de serie del software de Arduino ( IDE) de una
tabla de caracteres y sus valores ASCII en decimal , hexadecimal , octal
y binario. Para más en ASCII , consulte asciitable.com

Hardware Required

 Arduino or Genuino Board

Circuit

Ninguno , pero la junta tiene que estar conectado al ordenador a través


del puerto serie o el puerto USB .

Code
Las esperas de boceto para una conexión en serie en el setup () y luego
imprime línea por línea la tabla ASCII hasta el último carácter
imprimible. Cuando esto se logra , entra en un bucle sin fin en una
estructura de tiempo y no pasa nada más . Cerrando y abriendo la ventana
del monitor de serie de la Arduino Software ( IDE ) debe restablecer el
tablero y reinicie el boceto .
/*
ASCII table

Prints out byte values in all possible formats:


* as raw binary values
* as ASCII-encoded decimal, hex, octal, and binary values

For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII

The circuit: No external hardware needed.

*/
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// prints title with ending line break


Serial.println("ASCII Table ~ Character Map");
}

// first visible ASCIIcharacter '!' is number 33:


int thisByte = 33;
// you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!';

void loop() {
// prints value unaltered, i.e. the raw binary version of the
// byte. The serial monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!'
Serial.write(thisByte);

Serial.print(", dec: ");


// prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed:
Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it:

// Serial.print(thisByte, DEC);
Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX);

Serial.print(", oct: ");


// prints value as string in octal (base 8);
Serial.print(thisByte, OCT);

Serial.print(", bin: ");


// prints value as string in binary (base 2)
// also prints ending line break:
Serial.println(thisByte, BIN);

// if printed last visible character '~' or 126, stop:


if (thisByte == 126) { // you could also use if (thisByte == '~') {
// This loop loops forever and does nothing
while (true) {
continue;
}
}
// go on to the next character
thisByte++;
}

Output
ASCII Table ~ Character Map
!, dec: 33, hex: 21, oct: 41, bin: 100001
", dec: 34, hex: 22, oct: 42, bin: 100010
#, dec: 35, hex: 23, oct: 43, bin: 100011
$, dec: 36, hex: 24, oct: 44, bin: 100100
%, dec: 37, hex: 25, oct: 45, bin: 100101
&, dec: 38, hex: 26, oct: 46, bin: 100110
', dec: 39, hex: 27, oct: 47, bin: 100111
(, dec: 40, hex: 28, oct: 50, bin: 101000
), dec: 41, hex: 29, oct: 51, bin: 101001
*, dec: 42, hex: 2A, oct: 52, bin: 101010
+, dec: 43, hex: 2B, oct: 53, bin: 101011
,, dec: 44, hex: 2C, oct: 54, bin: 101100
-, dec: 45, hex: 2D, oct: 55, bin: 101101
., dec: 46, hex: 2E, oct: 56, bin: 101110
/, dec: 47, hex: 2F, oct: 57, bin: 101111
0, dec: 48, hex: 30, oct: 60, bin: 110000
1, dec: 49, hex: 31, oct: 61, bin: 110001
2, dec: 50, hex: 32, oct: 62, bin: 110010
3, dec: 51, hex: 33, oct: 63, bin: 110011
4, dec: 52, hex: 34, oct: 64, bin: 110100
5, dec: 53, hex: 35, oct: 65, bin: 110101
6, dec: 54, hex: 36, oct: 66, bin: 110110
7, dec: 55, hex: 37, oct: 67, bin: 110111
8, dec: 56, hex: 38, oct: 70, bin: 111000
9, dec: 57, hex: 39, oct: 71, bin: 111001
:, dec: 58, hex: 3A, oct: 72, bin: 111010
;, dec: 59, hex: 3B, oct: 73, bin: 111011
<, dec: 60, hex: 3C, oct: 74, bin: 111100
=, dec: 61, hex: 3D, oct: 75, bin: 111101
>, dec: 62, hex: 3E, oct: 76, bin: 111110
?, dec: 63, hex: 3F, oct: 77, bin: 111111
@, dec: 64, hex: 40, oct: 100, bin: 1000000
A, dec: 65, hex: 41, oct: 101, bin: 1000001
B, dec: 66, hex: 42, oct: 102, bin: 1000010
C, dec: 67, hex: 43, oct: 103, bin: 1000011
D, dec: 68, hex: 44, oct: 104, bin: 1000100
E, dec: 69, hex: 45, oct: 105, bin: 1000101

...

Dimmer en este ejercicio necesitan processing


9.

Este ejemplo muestra cómo enviar datos desde un ordenador personal a una
placa Arduino o Genuino para controlar el brillo de un LED. Los datos se
envían en bytes individuales, cada uno de ellos oscila en el valor de 0 a
255. El boceto lee estos bytes y los utiliza para ajustar el brillo de
los LED .
Puede enviar bytes al tablero de cualquier software que se puede acceder
al puerto serie del ordenador . Ejemplos de Procesamiento y Max / MSP
versión 5 se muestran a continuación .

Hardware Required

 Arduino or Genuino Board


 LED
 220 ohm resistor

Software Required

 Processing or
 Max/MSP version 5

Circuit
Conecte el actual 220 ohm resistencia limitadora de pin digital 9 , con
un LED en serie. La pata larga , positivo ( el ánodo ) del LED debe ser
conectado a la salida de la resistencia , con el , pierna más corta
negativo ( el cátodo ) conectado a tierra.
Schematic
Code

/*
Regulador de intensidad

Demuestra el envío de datos desde el ordenador a la placa Arduino ,


en este caso para controlar el brillo de un LED. Se envían los datos
en bytes individuales, cada uno de los cuales varía de 0 a 255. Arduino
lee estos bytes y los utiliza para ajustar el brillo de los LED .

El circuito:
LED adjunto de pin digital 9 a tierra.
Conexión en serie al tratamiento , Max / MSP , u otra aplicación en
serie

*/

const int ledPin = 9; // the pin that the LED is attached to


void setup() {
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}

void loop() {
byte brightness;

// check if data has been sent from the computer:


if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}

/* Processing code for this example


// Dimmer - sends bytes over a serial port
// by David A. Mellis
//This example code is in the public domain.

import processing.serial.*;
Serial port;

void setup() {
size(256, 150);

println("Available serial ports:");


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// Uses the first port in this list (number 0). Change this to
// select the port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your
// Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you
// can specify it directly like this.
//port = new Serial(this, "COM1", 9600);
}

void draw() {
// draw a gradient from black to white
for (int i = 0; i < 256; i++) {
stroke(i);
line(i, 0, i, 150);
}

// write the current X-position of the mouse to the serial port as


// a single byte
port.write(mouseX);
}
*/

/* Max/MSP v5 patch for this example

----------begin_max5_patcher----------
1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M
YWr+2KeX4vjnjXKKkKhhiGQ9M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HtcwJ
+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x
D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8
ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS
xqZqbd3ZLdera1iPqYxOm++v7SUSz
-----------end_max5_patcher-----------
*/
Graph
10.

Este ejemplo muestra cómo enviar un byte de datos de la Arduino o Genuino


a un ordenador personal y representar gráficamente el resultado. Esto se
llama comunicación serie porque la conexión parece tanto a la junta
directiva y el equipo como un puerto serie, a pesar de que en realidad
puede utilizar un cable USB, una serie a USB y un convertidor de USB a
serie.
Usted puede utilizar el monitor de serie del software de Arduino ( IDE )
para ver los datos enviados , o puede ser leído por Procesamiento (ver
código de abajo ) , Flash , PD , Max / MSP , etc.

Hardware Required

 Arduino or Genuino Board


 Analog Sensor (potentiometer, photocell, FSR, etc.)

Software Required

 Processing or
 Max/MSP version 5

Circuit

Connect a potentiometer or other analog sensor to analog input 0.


Schematic
Code

/*
Graph

Un ejemplo simple de comunicación de la placa Arduino al ordenador :


el valor de la entrada analógica 0 se envía al puerto serie. A esto le
llamamos " serie "
la comunicación debido a que la conexión aparece tanto a la Arduino y la
ordenador como un puerto serie, a pesar de que puede utilizar realmente
un cable USB. Bytes se envían uno tras otro ( en serie ) de la Arduino
a la computadora.
Puede utilizar el monitor serie Arduino para ver los datos enviados , o
puede ser leído por procesamiento , PD , Max / MSP , o cualquier otro
programa capaz de leer datos de un puerto serie . El código de
procesamiento a continuación representa gráficamente los datos recibidos
para que pueda ver el valor de la entrada analógica cambiando con el
tiempo.

El circuito:
Cualquier sensor de entrada analógica se adjunta a analógica en el pin 0
.

*/

void setup() {
// initialize the serial communication:
Serial.begin(9600);
}

void loop() {
// send the value of analog input 0:
Serial.println(analogRead(A0));
// wait a bit for the analog-to-digital converter
// to stabilize after the last reading:
delay(2);
}

/* Processing code for this example

// Graphing sketch

// This program takes ASCII-encoded strings


// from the serial port at 9600 baud and graphs them. It expects values in the
// range 0 to 1023, followed by a newline, or newline and carriage return

import processing.serial.*;

Serial myPort; // The serial port


int xPos = 1; // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// I know that the first port in the serial list on my mac


// is always my Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);

// don't generate a serialEvent() unless you get a newline character:


myPort.bufferUntil('\n');

// set inital background:


background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {


// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:


stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:


if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}

*/
/*
*/

11. MIDI Note Player


Este tutorial muestra cómo enviar notas MIDI desde una placa Arduino o
Genuino a un instrumento MIDI conectado a través de los 5 polos estándar
DIN cable.
MIDI, la Interfaz Digital de Instrumentos Musicales, es un protocolo útil
para sintetizadores, secuenciadores de control y otros dispositivos
musicales. Dispositivos MIDI generalmente se agrupan en dos grandes
clases: los controladores (es decir, dispositivos que generan señales
MIDI basado en las acciones humanas) y sintetizadores (incluyendo
samplers, secuenciadores, y así sucesivamente). Estos últimos toman datos
MIDI en y crea el sonido, la luz, o algún otro efecto.
MIDI es un protocolo serie que opera a 31.250 bits por segundo. La junta
incorporada puerto serie (todos ellos en los Mega así) puede enviar datos
a esa velocidad.
Bytes MIDI se dividen en dos tipos: bytes de comando y bytes de datos.
Bytes de comando son siempre 128 o mayor, o 0x80 a 0xFF en hexadecimal.
Bytes de datos son siempre menor que 127, o 0x00 a 0x7F en hexadecimal.
Comandos incluyen cosas como la nota sobre, tenga apagado, pitch bend, y
así sucesivamente. Bytes de datos incluyen cosas como el tono de la nota
para jugar, la velocidad, o el volumen de la nota, la cantidad de pitch
bend y así sucesivamente. Para más detalles, consulte la especificación
MIDI o una de las muchas MIDI guías de protocolo en la Web.
Los datos MIDI se suele anotada en hexadecimal porque los bancos e
instrumentos MIDI se agrupan en grupos de 16.
Para más vea esta introducción a MIDI o este ejemplo.

Hardware Required

 Arduino or Genuino Uno


 Female MIDI jack
 220 ohm resistor
 hook-up wires
 MIDI enabled device (optional, for testing)

Circuit

All MIDI connectors are female, by definition of the MIDI spec. Here's how to wire the
connector to the board:

 Digital pin 1 connected to MIDI jack pin 5


 MIDI jack pin 2 connected to ground
 MIDI jack pin 4 connected to +5V through a 220 ohm resistor
Schematic
Code

Attention If you're using a board with ATmega32U4 like DUE or Leonardo, please replace
Serial with Serial1 in the sketch below.

/*
MIDI note player

This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data.
If this circuit is connected to a MIDI synth, it will play
the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence.

The circuit:
* digital in 1 connected to MIDI jack pin 5
* MIDI jack pin 2 connected to ground
* MIDI jack pin 4 connected to +5V through 220-ohm resistor
Attach a MIDI cable to the jack, then to a MIDI synth, and play music.
*/

void setup() {
// Set MIDI baud rate:
Serial.begin(31250);
}

void loop() {
// play notes from F#-0 (0x1E) to F#-5 (0x5A):
for (int note = 0x1E; note < 0x5A; note ++) {
//Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
noteOn(0x90, note, 0x45);
delay(100);
//Note on channel 1 (0x90), some note value (note), silent velocity (0x00):
noteOn(0x90, note, 0x00);
delay(100);
}
}

// plays a MIDI note. Doesn't check to see that


// cmd is greater than 127, or that data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}

12. MultiSerialMega
A veces , un puerto serie no es suficiente ! Al tratar de comunicarse con
múltiples dispositivos serie activada, al mismo tiempo que el envío de
información de nuevo a la ventana de serie principal, a pocos puertos
adicionales RX / TX pueden ser algo bienvenido. En este ejemplo se hace
uso de una de Arduino y 3 puertos serie auxiliares de Genuino Mega , el
encaminamiento de los datos entrantes leídos en esa conexión directa a la
línea principal TX , y , a su vez , a la ventana principal de serie para
que las veas .

Hardware Required

 Arduino or Genuino Mega Board


 Serial enabled device (a Xbee Radio, a Bluetooth module, or RFID reader, or
another board, for instance).
Circuit
Después de comprobar la ficha de datos de cualquier serie dispositivo
activado para usted elige utilizar para este ejemplo, asegúrese de que es
a la vez correctamente conectado y alimentado. Conecte el pin RX y TX
pasadores de su dispositivo a los pines TX1 RX1 y de su Mega , como se
muestra en el esquema de abajo .
Asegúrese de que su Mega está conectado al ordenador, a través de USB ,
para permitir la comunicación en serie.

Schematic
Code

This sketch assumes that you connect your serial enabled device is attached to TX1 and
RX1.

/*
Mega multple serial test

Receives from the main serial port, sends to the others.


Receives from serial port 1, sends to the main serial (Serial 0).
This example works only on the Arduino Mega

The circuit:
* Any serial device attached to Serial port 1
* Serial monitor open on Serial port 0:

*/

void setup() {
// initialize both serial ports:
Serial.begin(9600);
Serial1.begin(9600);
}

void loop() {
// read from port 1, send to port 0:
if (Serial1.available()) {
int inByte = Serial1.read();
Serial.write(inByte);
}

// read from port 0, send to port 1:


if (Serial.available()) {
int inByte = Serial.read();
Serial1.write(inByte);
}
}

13. Physical Pixel


Este ejemplo ejemplo se utiliza la placa Arduino o Genuino para recibir
datos desde el ordenador . El tablero se enciende un LED cuando recibe el
carácter ' H' , y se apaga el LED cuando recibe el carácter "L" .
Los datos se pueden enviar desde el Arduino Software ( IDE ) monitor
serie , u otro programa como el procesamiento (ver código de abajo ) ,
Flash (a través de un proxy de serie -net) , PD , o Max / MSP .

Hardware Required

 Arduino or Genuino Board


 LED (optional)
 220 ohm resistor (optional)
Software Required

 Processing or
 Max/MSP version 5

Circuit
Muchas placas Arduino y Genuino tienen incorporado un LED conectado al
pin 13 ; si la placa no tiene LED incorporado , conecte un LED externo al
pin 13. La pierna de largo, o ánodo , va a la patilla 13 a través de una
resistencia de 220 . La pata corta , o cátodo , va al suelo .

Schematic
Code

/*
Physical Pixel

Un ejemplo del uso de la placa Arduino para recibir datos de la


computadora. En este caso, las placas Arduino se enciende un LED cuando
recibe el carácter ' H' , y se apaga el LED cuando se
recibe el carácter "L" .

Los datos pueden ser enviados desde el monitor de serie Arduino, u otro
programa como Procesamiento (ver código de abajo ) , Flash ( a través de
una serie -net
apoderado) , PD , o Max / MSP .

El circuito:
* LED conectado desde pin digital 13 a tierra
*/

const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into

void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}

void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}

/* Processing code for this example

// mouseover serial

// Demonstrates how to send data to the Arduino I/O board, in order to


// turn ON a light if the mouse is over a square and turn it off
// if the mouse is not.

import processing.serial.*;

float boxX;
float boxY;
int boxSize = 20;
boolean mouseOverBox = false;
Serial port;

void setup() {
size(200, 200);
boxX = width/2.0;
boxY = height/2.0;
rectMode(RADIUS);

// List all the available serial ports in the output pane.


// You will need to choose the port that the Arduino board is
// connected to from this list. The first port in the list is
// port #0 and the third port in the list is port #2.
// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// Open the port that the Arduino board is connected to (in this case #0)
// Make sure to open the port at the same speed Arduino is using (9600bps)
port = new Serial(this, Serial.list()[0], 9600);

void draw()
{
background(0);

// Test if the cursor is over the box


if (mouseX > boxX-boxSize && mouseX < boxX+boxSize &&
mouseY > boxY-boxSize && mouseY < boxY+boxSize) {
mouseOverBox = true;
// draw a line around the box and change its color:
stroke(255);
fill(153);
// send an 'H' to indicate mouse is over square:
port.write('H');
}
else {
// return the box to it's inactive state:
stroke(153);
fill(153);
// send an 'L' to turn the LED off:
port.write('L');
mouseOverBox = false;
}

// Draw the box


rect(boxX, boxY, boxSize, boxSize);
}
*/

/*
Max/MSP version 5 patch to run with this example:

----------begin_max5_patcher----------
1672.3oc2ZszaaiCD9ryuBBebQVCQRYao8xhf1cQCPVfBzh8RRQ.sDsM2HSZ
HQmlzh9eu7gjsjsEk7y0oWjiHoHm4aluYHGlueUmtiDuPy5B9Cv8fNc99Uc5
XZR2Pm726zcF4knDRlYXciDylQ4xtWa6SReQZZ+iSeMiEQR.ej8BM4A9C7OO
kkAlSjQSAYTdbFfvA27o2c6sfO.Doqd6NfXgDHmRUCKkolg4hT06BfbQJGH3
5Qd2e8d.QJIQSow5tzebZ7BFW.FIHow8.2JAQpVIIYByxo9KIMkSjL9D0BRT
sbGHZJIkDoZOSMuQT.8YZ5qpgGI3locF4IpQRzq2nDF+odZMIJkRjpEF44M3
A9nWAum7LKFbSOv+PSRXYOvmIhYiYpg.8A2LOUOxPyH+TjPJA+MS9sIzTRRr
QP9rXF31IBZAHpVHkHrfaPRHLuUCzoj9GSoQRqIB52y6Z.tu8o4EX+fddfuj
+MrXiwPL5+9cXwrOVvkbxLpomazHbQO7EyX7DpzXYgkFdF6algCQpkX4XUlo
hA6oa7GWck9w0Gnmy6RXQOoQeCfWwlzsdnHLTq8n9PCHLv7Cxa6PAN3RCKjh
ISRVZ+sSl704Tqt0kocE9R8J+P+RJOZ4ysp6gN0vppBbOTEN8qp0YCq5bq47
PUwfA5e766z7NbGMuncw7VgNRSyQhbnPMGrDsGaFSvKM5NcWoIVdZn44.eOi
9DTRUT.7jDQzSTiF4UzXLc7tLGh4T9pwaFQkGUGIiOOkpBSJUwGsBd40krHQ
9XEvwq2V6eLIhV6GuzP7uzzXBmzsXPSRY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udDtjw0t+xZ85wWZd80tMCiiMADNX4UzrcSeK23su87IANqmA7j
tiRzoXi2YRh67ldAk79gPmTe3YKuoY0qdEDV3X8xylCJMTN45JIakB7uY8XW
uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp
942acPvx2NPocMC1wQZ8glRn3myTykVaEUNLoEeJjVaAevA4EAZnsNgkeyO+
3rEZB7f0DTazDcQTNmdt8aACGi1QOWnMmd+.6YjMHH19OB5gKsMF877x8wsJ
hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2
.P0K+3peBt3NskC
-----------end_max5_patcher-----------
*/

Processing Code

Copy the Processing code from the code sample above. As you mouse over the center
square, the LED on pin 13 should turn on and off. The Processing applet looks like this:

Pase el ratón sobre la plaza para encender el LED de encendido y apagado.


parche Max
El parche Max / MSP se parece a la imagen de abajo . Copiar desde el
ejemplo de código anterior y péguelo en una nueva ventana del parche.
14.Read ASCII String
Este bosquejo utiliza la función Serial.parseInt () para localizar
valores separados por un carácter no alfanumérico . A menudo, las
personas utilizan una coma para indicar diferentes piezas de información
( este formato se conoce comúnmente como separados por comas valores o
CSV ) , pero otros personajes como un espacio o un período trabajarán
también. Los valores se analizan en números enteros y se utilizan para
determinar el color de un LED RGB . Vamos a usar el software de Arduino (
IDE ) monitor serie para enviar cadenas como " 5,220,70 " a la junta para
cambiar el color de la luz .

Hardware Required

 Arduino or Genuino Board


 common anode RGB LED
 3 220 ohm resistors
 hook-up wires
 breadboard

Circuit
Schematic
Tendrá cuatro cables para hacer el circuito anterior. Un cable conecta el
5V del conector de alimentación de la placa a la patilla más larga del
LED RGB. Usted debe girar el LED de manera que el pasador más largo es el
segundo por la izquierda ..
Coloque el RGB LED en el tablero con el pasador más largo que el segundo
de la parte superior. Compruebe la ficha técnica para su específica LED
para verificar los pines, pero deben ser R, V +, G y B. El cable de 5V
por lo tanto debe conectar ese segundo pasador de arriba, como en el
esquema de conexión anterior.
Con los cables restantes, conecte el cátodo rojo al pin 3, cátodo verde
al pin 5, y el azul del cátodo al pin 6 en serie con las resistencias.
LEDs RGB con una cuota de ánodo común un pin de alimentación común. En
lugar de convertir una ALTA pin para iluminar el LED, es necesario girar
el LOW pin, para crear una diferencia de voltaje a través del diodo. Así
que el envío de 255 a través analogWrite () convierte el LED apagado,
mientras que un valor de 0 lo enciende en el brillo completo. En el
código de abajo, vamos a usar un poco de matemáticas en el lado boceto,
para que puedas enviar valores que se corresponden con el brillo
esperado. Esencialmente, en lugar de utilizar analogWrite (pin, brillo),
se le llama analogWrite (pin, 255-brillo).

Code
Usted primero configurar algunas variables globales para los pasadores su
LED conectarse. Esto hará que sea más fácil de diferenciar cuál es el
rojo , verde y azul en la parte principal de su programa:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

En su configuración () , comenzará la comunicación serial a 9600 bits de


datos por segundo entre la tarjeta y el ordenador con la línea:
Serial.begin(9600);

Also in the setup, you'll want to configure the pins as outputs:

pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

En el bucle () , compruebe si hay algún dato en el buffer de serie. Al


hacer esta declaración un tiempo ( ) , pondrá en funcionamiento , siempre
y cuando se dispone de información a la espera de ser leído :
while (Serial.available() > 0) {

A continuación, declarar algunas variables locales para almacenar la


información de serie. Este será el brillo de los LEDs. Usando
Serial.parseInt ( ) para separar los datos por comas , lee la información
en sus variables :
int red = Serial.parseInt();
int green = Serial.parseInt();
int blue = Serial.parseInt();

Una vez que haya leído los datos en las variables, compruebe si el
carácter de nueva línea de proceder :
if (Serial.read() == '\n') {

El uso de restricción () , puede mantener los valores en un rango


aceptable para el control PWM . De esta manera , si el valor estaba fuera
del rango de lo PWM puede enviar , se limita a un número válido. Restando
este valor de 255 se le formateando el valor de usar con un ánodo común
LED. Como se explicó anteriormente , estos LEDs se iluminan cuando hay
una diferencia de voltaje entre el ánodo y el pin conectado a la placa :
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);

Ahora que ha formateado los valores de PWM , utilice analogWrite () para


cambiar el color del LED . Porque restado el valor de 255 en el paso
anterior :
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

Enviar el valor de cada LED de nuevo a la pantalla de serie en una cadena


como valores HEX :

Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);

Por último , cierre de seguridad de sus soportes de la sentencia if,


while y bucle principal :
}
}
}

Una vez que haya programado el tablero , abra el software de Arduino (


IDE ) monitor serie . Asegúrese de que ha elegido para enviar un carácter
de nueva línea al enviar un mensaje. Introduzca valores entre 0-255 para
las luces en el siguiente formato : Rojo, Verde, Azul . Una vez que haya
enviado los valores a la junta , el LED conectado se convertirá en el
color que ha especificado y recibirá de vuelta los valores HEX en el
monitor serie .
/*
Reading a serial ASCII-encoded string.

This sketch demonstrates the Serial parseInt() function.


It looks for an ASCII string of comma-separated values.
It parses them into ints, and uses those to fade an RGB LED.

Circuit: Common-anode RGB LED wired like so:


* Red cathode: digital pin 3
* Green cathode: digital pin 5
* blue cathode: digital pin 6
* anode: +5V

*/

// pins for the LEDs:


const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
void setup() {
// initialize serial:
Serial.begin(9600);
// make the pins outputs:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

void loop() {
// if there's any serial available, read it:
while (Serial.available() > 0) {

// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();

// look for the newline. That's the end of your


// sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);

// fade the red, green, and blue legs of the LED:


analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

// print the three numbers in one string as hexadecimal:


Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
}
}
}
Processing Code
Copiar el boceto de procesamiento de la muestra de código de seguridad. A
medida que cambia el valor del sensor analógico , usted obtendrá una
pelota en movimiento en pantalla algo como esto. El balón sólo aparecerá
cuando se presiona el botón :

Max Code

The max patch looks like this. Copy the text from the code sample above and paste it into a
new Max window
SerialEvent
15.

Este ejemplo demuestra el uso de la función serialEvent (). Esta función


se denomina dentro del bucle (). Si hay datos en serie en el tampón de
cada carácter encontrado se añade a una cadena hasta que se encuentra una
nueva línea. En este caso la cadena hecha por los caracteres recibidos
hasta la fecha se imprime y se vuelve a establecer en nulo.

Hardware Required

 Arduino or Genuino Board


Circuit

Ninguno , pero la junta tiene que ser conectado a la computadora ;


Arduino Software ( IDE ) monitor serie puede utilizarse para comunicar
los caracteres simples o múltiples y recibir la cadena hacia atrás.

Code

/*
Serial Event example

When new serial data arrives, this sketch adds it to a String.


When a newline is received, the loop prints the string and
clears it.

A good test for this is to try it with a GPS receiver


that sends out NMEA 0183 sentences.

*/

String inputString = ""; // a string to hold incoming data


boolean stringComplete = false; // whether the string is complete

void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}

void loop() {
serialEvent(); //call the function
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}

/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}

16. Virtual Color Mixer


Este ejemplo muestra cómo enviar múltiples valores de la placa Arduino al
ordenador. Las lecturas de los tres potenciómetros se utilizan para
establecer los componentes rojo, verde y azul del color de fondo de un
boceto de procesamiento o parche Max / MSP .

Hardware Required

 Arduino or Genuino Board


 3 Analog Sensors (potentiometer, photocell, FSR, etc.)
 3 10K ohm resistors
 hook-up wires
 breadboard
Software Required

 Processing or
 Max/MSP version 5

Circuit
Conecte los sensores analógicos a analógico pines de entrada 0, 1 , y 2.
Este circuito utiliza tres subcircuitos divisor de tensión para generar
tensiones analógicas de las resistencias de la fuerza de detección. un
divisor de tensión tiene dos resistencias en serie , dividiendo el
voltaje proporcional a sus valores .

Schematic
Code
Conecte los sensores analógicos a analógico pines de entrada 0, 1 , y 2.
Este circuito utiliza tres subcircuitos divisor de tensión para generar
tensiones analógicas de las resistencias de la fuerza de detección. un
divisor de tensión tiene dos resistencias en serie , dividiendo el
voltaje proporcional a sus valores .
/*
This example reads three analog sensors (potentiometers are easiest)
and sends their values serially. The Processing and Max/MSP programs at the bottom
take those three values and use them to change the background color of the screen.

The circuit:
* potentiometers attached to analog inputs 0, 1, and 2

This example code is in the public domain.


*/

const int redPin = A0; // sensor to control red color


const int greenPin = A1; // sensor to control green color
const int bluePin = A2; // sensor to control blue color

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

void loop() {
Serial.print(analogRead(redPin));
Serial.print(",");
Serial.print(analogRead(greenPin));
Serial.print(",");
Serial.println(analogRead(bluePin));
}

/* Processing code for this example

// This example code is in the public domain.

import processing.serial.*;

float redValue = 0; // red value


float greenValue = 0; // green value
float blueValue = 0; // blue value

Serial myPort;

void setup() {
size(200, 200);

// List all the available serial ports


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// I know that the first port in the serial list on my mac


// is always my Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
}

void draw() {
// set the background color with the color values:
background(redValue, greenValue, blueValue);
}

void serialEvent(Serial myPort) {


// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// split the string on the commas and convert the
// resulting substrings into an integer array:
float[] colors = float(split(inString, ","));
// if the array has at least three elements, you know
// you got the whole thing. Put the numbers in the
// color variables:
if (colors.length >=3) {
// map them to the range 0-255:
redValue = map(colors[0], 0, 1023, 0, 255);
greenValue = map(colors[1], 0, 1023, 0, 255);
blueValue = map(colors[2], 0, 1023, 0, 255);
}
}
}
*/

/* Max/MSP patch for this example

----------begin_max5_patcher----------
1512.3oc4Z00aaaCE8YmeED9ktB35xOjrj1aAsXX4g8xZQeYoXfVh1gqRjdT
TsIsn+2K+PJUovVVJ1VMdCAvxThV7bO7b48dIyWtXxzkxaYkSA+J3u.Sl7kK
lLwcK6MlT2dxzB5so4zRW2lJXeRt7elNy+HM6Vs61uDDzbOYkNmo02sg4euS
4BSede8S2P0o2vEq+aEKU66PPP7b3LPHDauPvyCmAvv4v6+M7L2XXF2WfCaF
lURgVPKbCxzKUbZdySDUEbgABN.ia08R9mccGYGn66qGutNir27qWbg8iY+7
HDRx.Hjf+OPHCQgPdpQHoxhBlwB+QF4cbkthlCRk4REnfeKScs3ZwaugWBbj
.PS+.qDPAkZkgPlY5oPS4By2A5aTLFv9pounjsgpnZVF3x27pqtBrRpJnZaa
C3WxTkfUJYA.BzR.BhIy.ehquw7dSoJCsrlATLckR.nhLPNWvVwL+Vp1LHL.
SjMG.tRaG7OxT5R2c8Hx9B8.wLCxVaGI6qnpj45Ug84kL+6YIM8CqUxJyycF
7bqsBRULGvwfWyRMyovElat7NvqoejaLm4f+fkmyKuVTHy3q3ldhB.WtQY6Z
x0BSOeSpTqA+FW+Yy3SyybH3sFy8p0RVCmaMpTyX6HdDZ2JsPbfSogbBMueH
JLd6RMBdfRMzPjZvimuWIK2XgFA.ZmtfKoh0Sm88qc6OF4bDQ3P6kEtF6xej
.OkjD4H5OllyS+.3FlhY0so4xRlWqyrXErQpt+2rsnXgQNZHZgmMVzEofW7T
S4zORQtgIdDbRH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OhSV3uD
eeqCUClbBPa.j3vWDoMZssNTzRNEnE6gYPXazZaMF921syaLWyAeBXvCESA8
ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc
iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq
-----------end_max5_patcher-----------

*/

Processing Code

Copy the Processing sketch from the code sample above. As you change the value of the
analog sensors, the background color will change:
Max Code

The max patch looks like this. Copy the text of it from the code sample above and paste
into a new Max window.

Vous aimerez peut-être aussi