1.2.- Ejemplos

 

Ejemplos Construidos en el Arduino IDE

 

SNAG- 16 06 26 22 39 24.jpg

SNAG- 16 06 26 22 36 42

 

 

  • Ejemplos de Arduino IDE

    • 1. Basics
      • 1.1. AnalogReadSerial
      • 1.2. BareMinimum
      • 1.3. Blink
      • 1.4. DigitalReadSerial
      • 1.5. Fade
      • 1.6. ReadAnaloVoltage
    • 2. Digital
      • 2.1. BlinkWithoutDelay
      • 2.2. Button
      • 2.3. Debounce
      • 2.4. DigitalInputPullup
      • 2.5. StateChangeDetection
      • 2.6. toneKeyboard
      • 2.7. toneMelody
      • 2.8. toneMultiple
      • 2.9. tonePitchFollower
    • 3. Analog
      • 3.1. AnalogInOutSerial
      • 3.2. AnalogInput
      • 3.3. AnalogWriteMega
      • 3.4. Calibration
      • 3.5. Fading
      • 3.6. Smoothing
    • 4. Communication
      • 4.1. ASCIITable
      • 4.2. Dimmer
      • 4.3. Graph
      • 4.4. Midi
      • 4.5. MultiSerial
      • 4.6. PhysicalPixel
      • 4.7. ReadASCIIString
      • 4.8. SerialCallResponseASCII
      • 4.9. SerialEvent
      • 4.10. VirtualColorMixer
    • 5. Control
      • 5.1. Arrays
      • 5.2. ForLoopIteration
      • 5.3. ifStatementConditional
      • 5.4. switchCase
      • 5.5. switchCase2
      • 5.6. WhileStatementConditional
    • 6. Sensors
      • 6.1. ADXL3xx
      • 6.2. Knock
      • 6.3. Memsic2125
      • 6.4.1. Ping – Sensor Ultrasónico HC-SR03
      • 6.4.2 Sensor Ultrasónico HC-SR04
      • 6.4.3 Sensor Ultrasónico HY-SRF05
    • 7. Display
      • 7.1. barGraph
      • 7.2. RowColumnScanning
    • 8. Strings
      • 8.1. CharacterAnalysis
      • 8.2. StringAdditionOperator
      • 8.3. StringAppendOperator
      • 8.4. StringCaseChanges
      • 8.5. StringCharacters
      • 8.6. StringComparisonOperators
      • 8.7. StringConstructors
      • 8.8. StringIndexOf
      • 8.9. StringLength
      • 8.10. StringLengthTrim
      • 8.11. StringReplace
      • 8.12. StringStartsWithEndsWith
      • 8.13. StringSubstring
      • 8.14. StringToInt
    • 9.USB – Keyboard, Mouse.
      • 9.1. KeyboardLogout
      • 9.2. KeyboardMessage
      • 9.3. KeyboardReprogram
      • 9.4. KeyboardSerial
      • 9.5. KeyboardAndMouseControl
      • 9.6. ButtonMouseControl
      • 9.7. JoystickMouseControl
    • 10. StarterKit_BasicKit
      • P02_SpaceshipInterface
      • P03_LoveOMeter
      • P04_ColorMixingLamp
      • P05_ServoMoodIndicator
      • P06_LightTeremin
      • P07_Keyboard
      • P08_DigitalHourglas
      • P09_MotorizedPinwheel
      • P10_Zoetrope
      • P11_CrystalBall
      • P12_KnockLock
      • P13_TouchSensorLamp
      • P14_TweakTheArduinoLogo
      • P15_HackingButtons
    • 11.ArduinoISP

 

 

01. Basics

SNAG- 16 06 27 00 15 25.jpg

 

1.1. AnalogReadSerial – (Herramientas > Serial Plotter)  ->  Serial.print(  );

Lectura en PIN Analógico e Impresión en Monitor Serie

AnalogReadSerial

 

/*   AnalogReadSerial - Arduino IDE
 Lee una entrada analógica en el PIN A0,
 imprime el resultado en el monitor serie.
La representación gráfica está disponible usando Serial Plotter
 (Herramientas > Serial Plotter)
Conecta le pin central de un potenciómetro (10 kohm) al PIN A0,
 y los pines exteriores a los pines: +5V  y GND.
El código de este ejemplo es de dominio público.  */

   // la rutina de instalación se ejecuta al presionar RESET:
void setup() {
   // inicializa la comunicación serial a 9600 bits por segundo:
 Serial.begin(9600);
}

   // El bucle se repite una y otra vez indefinidamente:
void loop() {
   // lee la entrada en el pin analógico A0:
 int sensorValue = analogRead(A0);
   // imprime el valor leído:
 Serial.println(sensorValue);
 delay(1); // retardo entre lecturas
}

 

SNAG- 16 07 06 21 27 12.jpg

 

SNAG- 16 07 25 23 28 20.jpg

AnalogReadSerial-Arduino IDE 6.gif

 

AnalogReadSerial-peli 6.gif

 

AnalogReadSerial-Visualino-Visualino.gif

SNAG- 16 07 25 23 48 22.jpg

/*** AnalogReadSerial - Visualino - Ángel Luis Díaz Pérez ***/
/*** Global variables ***/
     int sensorValue;
/*** Function declaration ***/
void setup()              {
    sensorValue=0;
    pinMode(A0,INPUT);
    Serial.begin(9600);   }

void loop()               {
    sensorValue=analogRead(A0);
    Serial.println(sensorValue);
    delay(1);             }
/*** Function definition ***/

AnalogReadSerail-Visualino 6.gif

SNAG- 16 08 01 01 31 50.jpg

no parp.gif

 

1.2. BareMinimum
BareMinimum

Este ejemplo contiene el mínimo código que necesita un sketch para compilarse correctamente en el Arduino IDE:

el método de setup () y el método de loop ().

/* BareMinimum */

void setup() {
   // ponga su código de configuración aquí, para ejecutar una vez:
}
void loop() {
// ponga su código principal aquí, para ejecutar repetidamente
}

 

1.3. Blink
Blink

/*  Blink - Arduino IDE
  Enciende un LED durante un segundo, luego se apaga durante un segundo,
de forma repetida.
  La mayoría de las placas Arduino tienen un LED sobre la placa que se puede
controlar.
  Sobre la placa Arduino Uno y Leonardo,  que está conectado al pin digital 13.
  Si no está seguro a que pin sobre la placa está conectado,
consulte la documentación en http://www.arduino.cc.
  Este código de ejemplo es de dominio público y ha sido modificado
el 8 de Mayo de 2014 por Scott Fitzgerald   */

    // la función de configuración se ejecuta una vez que se pulsa el reinicio
void setup() {
    // inicializa como salida el pin digital 13.
 pinMode(13, OUTPUT);
}

 // El bucle se repite una y otra vez indefinidamente:
void loop() {
 digitalWrite(13, HIGH);    // pone el the LED a nivel de voltagje ALTO
 delay(1000);               // espera un segundo
 digitalWrite(13, LOW);     // pone el the LED a nivel de voltagje BAJO
 delay(1000);               // espera un segundo
             }

Blink.gif

SNAG- 16 07 11 23 56 45

SNAG- 16 07 11 23 55 49.jpg

/*** Blink - Mixly ***/

void setup()   {
           pinMode(11, OUTPUT);
                         }

void loop()     {
          digitalWrite(11,HIGH);
          delay(1000);
           digitalWrite(11,LOW);
           delay(1000);
                           }

 

1 Intermitente 0.gif

Blink-Visualino 3.gif

SNAG- 16 07 25 05 42 33.jpg

/*** Blink - Visualino ***/
/*** Global variables ***/
     int pin=11;

/*** Function declaration ***/
void setup()    {          }

void loop()     {
     pinMode(pin,OUTPUT);
     digitalWrite(pin,HIGH);
     delay(1000);
     pinMode(pin,OUTPUT);
     digitalWrite(pin,LOW);
     delay(1000);
                 }
/*** Function definition ***/

Blink-Visualino 2.gif

 

 

1.4. DigitalReadSerial

SNAG- 16 07 07 01 08 11.jpg

/*   DigitalReadSerial - Arduino IDE
 Reads a digital input on pin 2, prints the result to the serial monitor
 This example code is in the public domain.  */

// digital pin 2 has a pushbutton attached to it. Give it a name:
    int pushButton = 2;

// the setup routine runs once when you press reset:
void setup() {
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);
 // make the pushbutton's pin an input:
 pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
 // read the input pin:
 int buttonState = digitalRead(pushButton);
 // print out the state of the button:
 Serial.println(buttonState);
 delay(1); // delay in between reads for stability
}

 

SNAG- 16 07 26 04 33 44.jpg

Digital Read Seria.gif

digitalReadSerial 3.gif

 

DigitalReadSeria-Foto.gif

 

DigitalReadSerial-Vidualino1.gif

DigitalReadSerial-Visualino 2.gif

SNAG- 16 07 26 04 26 31.jpg

/*** DigitalReadSerial - Visualino - Ángel Luis Díaz Pérez ***/ 
/*** Global variables ***/
int sensorValue;

/*** Function declaration ***/
void setup()   {
    sensorValue=0;
    pinMode(A0,INPUT);
    Serial.begin(9600);
}

void loop()   {
    sensorValue=analogRead(A0);
    Serial.println(sensorValue);
    delay(1);
}
/*** Function definition ***/

SNAG- 16 07 06 21 29 50.jpg

 

 

1.5. Fade
Fade

/*   Fade - Arduino IDE
This example shows how to fade an LED on pin 9 using the analogWrite() function.
The analogWrite() function uses PWM, so if you want to change the pin you're using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with  a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
This example code is in the public domain. 
* 220 ohm resistor   */

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

     // the setup routine runs once when you press reset:
void setup() {
     // declare pin 9 to be an output:
 pinMode(led, OUTPUT);
}

     // the loop routine runs over and over again forever:
void loop() {
      // set the brightness of pin 9:
    analogWrite(led, brightness);

      // change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

      // reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255)  {
              fadeAmount = -fadeAmount ;
                                               }
      // wait for 30 milliseconds to see the dimming effect
 delay(30);
}

 

Fade-Arduino IDE.gif

Fade-Arduino IDE-123D.gif

Fade 123D.gif

Fade 3.gif

 

Fade-Visualino.gif

SNAG- 16 07 26 05 38 25.jpg

/*** Fade - Visualino - Ángel Luis Díaz Pérez ***/
/*** Global variables ***/
int led;
int brightness;
int fadeAmount;

/*** Function declaration ***/
void setup()  {
     led=9;
     brightness=0;
     fadeAmount=5;
               }

void loop()    {
      pinMode(led,OUTPUT);
      analogWrite(led,brightness);
      brightness=brightness + fadeAmount;
      if ((brightness == 0) || (brightness == 255)) {
           fadeAmount= - fadeAmount;                }
      delay(30);
                }
/*** Function definition ***/

 

Fade-Visualino-123D.gif

 

 

1.6. ReadAnalogVoltage
ReadAnaloVoltage

SNAG- 16 08 01 01 31 50

/*   ReadAnalogVoltage
 Reads an analog input on pin 0, converts it to voltage,
 and prints the result to the serial monitor.
 Graphical representation is available using serial plotter
 (Tools > Serial Plotter menu)
 Attach the center pin of a 10kohm potentiometer to pin A0,
 and the outside pins to +5V and ground.
This example code is in the public domain.   */

    // the setup routine runs once when you press reset:
void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
             }

    // the loop routine runs over and over again forever:
void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (5.0 / 1023.0);
    // print out the value you read:
     Serial.println(voltage);
            }

SNAG- 16 07 31 02 50 18

 

AnaloReadSeria-Arduino IDE.gif

ReadAnalogVoltage-Visualino.gif

ReadAnalogVoltage-Visualino-2.gif

SNAG- 16 07 27 01 04 53.jpg

/*** ReadAnalogVoltage - Visualino - Ángel Luis Díaz Pérez ***/
/*** Global variables ***/
int sensorValue;
float voltage;

/*** Function declaration ***/
void setup()   {
    sensorValue=0;
    voltage=0;
    pinMode(A0,INPUT);
    Serial.begin(9600);
                }

void loop()     {
    sensorValue=analogRead(A0);
    voltage=sensorValue * 5 / 1023;
    Serial.println(voltage);
    delay(200);
                 }
/*** Function definition ***/

 

ReadAnalogVoltage-film.gif

 

ReadAnalogVoltage2.gif

ReadAnalogVoltage0.gif

no parp

 

 

02. Digital

SNAG- 16 06 27 00 16 36.jpg

 

2.1. BlinkWithoutDelay
BlinkWithoutDelay

/* Blink without Delay

Turns on and off a light emitting diode (LED) connected to a digital pin,
 without using the delay() function.
 This means that other code can run at the same time
 without being interrupted by the LED code.

The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

created 2005 by David A. Mellis
 modified 8 Feb 2010 by Paul Stoffregen
 modified 11 Nov 2013 by Scott Fitzgerald


 This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to set a pin number :
const int ledPin = 13; // the number of the LED pin

// Variables will change :
int ledState = LOW; // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0; // will store last time LED was updated

// constants won't change :
const long interval = 1000; // interval at which to blink (milliseconds)

void setup() {
 // set the digital pin as output:
 pinMode(ledPin, OUTPUT);
}

void loop() {
 // here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the
 // difference between the current time and last time you blinked
 // the LED is bigger than the interval at which you want to
 // blink the LED.
 unsigned long currentMillis = millis();

if (currentMillis - previousMillis >= interval) {
 // save the last time you blinked the LED
 previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:
 if (ledState == LOW) {
 ledState = HIGH;
 } else {
 ledState = LOW;
 }

// set the LED with the ledState of the variable:
 digitalWrite(ledPin, ledState);
 }
}

SNAG- 16 07 06 21 50 09.jpg

 

2.2. Button – Botón

SNAG- 16 07 07 01 15 25.jpg

SNAG- 16 07 11 19 40 03

button2.gif

 

/*   Button
 Enciende y apaga un diodo LED conectado al pin digital 13,
 cuando se presiona un pulsador conectado al pin 2.
 El circuito:
 * LED conectado desde el pin 13 a tierra (GND)
 * pulsador conectado al pin 2 desde +5V
 * resistencia de 10K conectada al pin 2 desde tierra (GND)
 * Nota: en la mayoría de las pacas arduino existe un LED conectado al pin 13.
 creado en 2005 por DojoDave <http://www.0j0.org>
 modificado el 30 Aug 2011 por Tom Igoe
El código de este ejemplo es de dominio público.
http://www.arduino.cc/en/Tutorial/Button   */

// las constantes no cambian y se usan para marcar los número de los pines:
const int buttonPin = 2;    // número del pin del pulsador
const int ledPin = 13;      // número del pin del LED

// la variables cambian:
  int buttonState = 0;      // variable para leer el estado del pulsador

void setup() {
    // inicializa el pin del LED como salida:
    pinMode(ledPin, OUTPUT);
    // inicialize el pin del pulsador como entrada:
    pinMode(buttonPin, INPUT);
              }

void loop() {
   // lee el valor del estado del pulsador:
   buttonState = digitalRead(buttonPin);
   // verifica si el pulsador está presionado.
   // de ser así, el "estado del pulsador" (buttonState) es "alto" (HIGH):
   if (buttonState == HIGH)           {
        // turn LED on:
        digitalWrite(ledPin, HIGH);    } 
    else {
         // turn LED off:
         digitalWrite(ledPin, LOW);
          }
}

 

Encender un LED progresivamente con un poteciometro 3.gif

SNAG- 16 07 17 22 05 06.jpg

 

2.3. Debounce

SNAG- 16 07 07 01 15 25.jpg

/*  Debounce - Arduino IDE
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise).
The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground
 * Note: On most Arduino boards, there is already an LED on the board
 connected to pin 13, so you don't need any extra components for this example.
 created 21 November 2006 by David A. Mellis, 
 modified 30 Aug 2011 by Limor Fried, modified 28 Dec 2012 by Mike Walters
 This example code is in the public domain.
 http://www.arduino.cc/en/Tutorial/Debounce        */

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;      // the number of the pushbutton pin
const int ledPin = 13;        // the number of the LED pin

// Variables will change:
int ledState = HIGH;          // the current state of the output pin
int buttonState;              // the current reading from the input pin
int lastButtonState = LOW;    // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;  // the debounce time; increase if the output flickers

void setup()    {
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
      // set initial LED state
      digitalWrite(ledPin, ledState);
                }

void loop()     {
      // read the state of the switch into a local variable:
      int reading = digitalRead(buttonPin);
      // check to see if you just pressed the button
      // (i.e. the input went from LOW to HIGH), and you've waited
      // long enough since the last press to ignore any noise:
      // If the switch changed, due to noise or pressing:
      if (reading != lastButtonState)    {
             // reset the debouncing timer
             lastDebounceTime = millis(); }

      if ((millis() - lastDebounceTime) > debounceDelay) {
           // whatever the reading is at, it's been there for longer
           // than the debounce delay, so take it as the actual current state:
           // if the button state has changed:
           if (reading != buttonState) {
                buttonState = reading;
                // only toggle the LED if the new button state is HIGH
                if (buttonState == HIGH)  { ledState = !ledState; }
                                        }
                                                          }
       // set the LED:
       digitalWrite(ledPin, ledState);
       // save the reading. Next time through the loop,
       // it'll be the lastButtonState:
       lastButtonState = reading;
               }

Debounce.gif

Debounce-Arduino IDE.gif

Debounce-Visualino.gif

SNAG- 16 07 29 06 50 01.jpg

Debounce-Visualino-123D.gif

 

 

 

2.4. DigitalInputPullup
DigitalInputPullup

SNAG- 16 08 01 03 04 47.jpg

/*   DigitalInputPullup - Input Pullup Serial
 This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
 digital input on pin 2 and prints the results to the serial monitor.
 The circuit:
     * Momentary switch attached from pin 2 to ground
     * Built-in LED on pin 13
 Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
 20K-ohm resistor is pulled to 5V. This configuration causes the input to
 read HIGH when the switch is open, and LOW when it is closed.
 created 14 March 2012 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/InputPullupSerial
 This example code is in the public domain   */

void setup()  {
   //start serial connection
   Serial.begin(9600);
   //configure pin2 as an input and enable the internal pull-up resistor
   pinMode(2, INPUT_PULLUP);
   pinMode(13, OUTPUT);
              }

void loop()   {
   //read the pushbutton value into a variable
   int sensorVal = digitalRead(2);
   //print out the value of the pushbutton
   Serial.println(sensorVal);
   // Keep in mind the pullup means the pushbutton's
   // logic is inverted. It goes HIGH when it's open,
   // and LOW when it's pressed. Turn on pin 13 when the
   // button's pressed, and off when it's not:
   if (sensorVal == HIGH) {
        digitalWrite(13, LOW);
   } else { digitalWrite(13, HIGH);  }
                           }

DigitalInputPullup-Aeduino IDE.gif

DigitalInputPullup-123D.gif

DigitalInputPullup.gif

SNAG- 16 08 01 03 32 19.jpg

SNAG- 16 08 01 03 31 58.jpg

/*** DigitalInputPullup - Visualino ***/
/*** Global variables ***/
    int sensorVal;
/*** Function declaration ***/
void setup()    {
     sensorVal=0;
     pinMode(2,INPUT);
     pinMode(13,OUTPUT);
                }

void loop()    {
     sensorVal=digitalRead(2);
     if (sensorVal == HIGH) { digitalWrite(13,LOW); }
     else { digitalWrite(13,HIGH); }
               }
/*** Function definition ***/

 

 

 

2.5. StateChangeDetection
StateChangeDetection

StateChangeDetection.gif

/*  State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
 but you just need to know when the input changes from one state to another.
 For example, you want to know when a button goes from OFF to ON. This is called
 state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
 and on to off.
The circuit:
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground
 * LED attached from pin 13 to ground (or use the built-in LED on
 most Arduino boards)
created 27 Sep 2005,  modified 30 Aug 2011  by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/ButtonStateChange  */

                             // this constant won't change:
const int buttonPin = 2;     // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

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

void loop()    {
     // read the pushbutton input pin:
     buttonState = digitalRead(buttonPin);
     // compare the buttonState to its previous state
     if (buttonState != lastButtonState) {
         // if the state has changed, increment the counter
         if (buttonState == HIGH)
              {
             // if the current state is HIGH then the button
             // wend from off to on:
             buttonPushCounter++;
             Serial.println("on");
             Serial.print("number of button pushes: ");
             Serial.println(buttonPushCounter);
               }
          else {
             // if the current state is LOW then the button
             // wend from on to off:
             Serial.println("off");
                }
             // Delay a little bit to avoid bouncing
           delay(50);
                                         }
     // save the current state as the last state,
     //for next time through the loop
     lastButtonState = buttonState;
     // turns on the LED every four button pushes by
     // checking the modulo of the button push counter.
     // the modulo function gives you the remainder of
     // the division of two numbers:
     if (buttonPushCounter % 4 == 0) { digitalWrite(ledPin, HIGH); }
     else { digitalWrite(ledPin, LOW); }
                  }

 

StateChangeDetection-Arduino IDE 2.gif

StateChangeDetection2.gif

 

StateChangeDetection-gif.gif

 

StateChangeDetection-Visualino.gif

SNAG- 16 08 01 06 56 56.jpg

/*** StateChangeDetection - Visualino ***/
/*** Global variables ***/
int buttonPin;
int ledPin;
int buttonPushCounter;
int buttonState;
int lastButtonState;

/*** Function declaration ***/
void setup()  {
     buttonPin=2;
     ledPin=13;
     buttonPushCounter=0;
     buttonState=0;
     lastButtonState=0;
     Serial.begin(9600);
              }

void loop()   {
     pinMode(buttonPin,INPUT);
     buttonState=digitalRead(buttonPin);
     if (buttonState != lastButtonState) {
         if (buttonState == HIGH) {
             buttonPushCounter=buttonPushCounter + 1;
             Serial.println("on");
             Serial.print("number of button pushes: ");
             Serial.println(buttonPushCounter);
         } else { Serial.println("off"); }
     delay(50);
                                          }
     lastButtonState=buttonState;
     if (buttonPushCounter%4 == 0) {
         pinMode(ledPin,OUTPUT);
         digitalWrite(ledPin,HIGH);
     } else {
         pinMode(ledPin,OUTPUT);
         digitalWrite(ledPin,LOW);
            }
               }
/*** Function definition ***/

StateChangeDetection-Visualino-123D.gif

 

 

2.6. toneKeyboard
toneKeyboard

SNAG- 16 08 02 04 32 50.jpg

/* keyboard - Plays a pitch that changes based on a changing analog input
circuit:
 * 3 force-sensing resistors from +5V to analog in 0 through 5
 * 3 10K resistors from analog in 0 through 5 to ground
 * 8-ohm speaker on digital pin 8
created 21 Jan 2010, modified 9 Apr 2012,  by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone3  */

#include "pitches.h"

const int threshold = 10; // minimum reading of the sensors that generates a note

// notes to play, corresponding to the 3 sensors:
int notes[] = {  NOTE_A4, NOTE_B4, NOTE_C3  };

void setup() {   }

void loop() {
 for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
 // get a sensor reading:
 int sensorReading = analogRead(thisSensor);

// if the sensor is pressed hard enough:
 if (sensorReading > threshold) {
 // play the note corresponding to this sensor:
 tone(8, notes[thisSensor], 20);
 }
 }
}

SNAG- 16 08 02 04 48 18.jpg

 

 

2.7. toneMelody

toneMelody

 

 

 

 

 

 

SNAG- 16 08 02 05 14 47.jpg

 

/*  toneMelody - Plays a melody
circuit:
 * 8-ohm speaker on digital pin 8
created 21 Jan 2010, modified 30 Aug 2011, by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone  */

#include "pitches.h"

// notes in the melody:
int melody[] = {
 NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {  4, 8, 8, 4, 4, 4, 4, 4 };

void setup() {
 // iterate over the notes of the melody:
 for (int thisNote = 0; thisNote < 8; thisNote++) {

 // to calculate the note duration, take one second
 // divided by the note type.
 //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
 int noteDuration = 1000 / noteDurations[thisNote];
 tone(8, melody[thisNote], noteDuration);

 // to distinguish the notes, set a minimum time between them.
 // the note's duration + 30% seems to work well:
 int pauseBetweenNotes = noteDuration * 1.30;
 delay(pauseBetweenNotes);
 // stop the tone playing:
 noTone(8);
 }
}

void loop() {     }     // no need to repeat the melody.

SNAG- 16 08 02 05 21 31.jpg

SNAG- 16 07 24 20 51 05.jpg

 

 

2.8. toneMultiple
toneMultiple

/*  Multiple tone player
Plays multiple tones on multiple pins in sequence
circuit:
 * 3x 8-ohm speaker on digital pins 6, 7, and 8
 * 3x 100 ohm resistor
created 8 March 2010, by Tom Igoe, based on a snippet from Greg Borenstein
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone4     */

void setup() {     }

void loop() {
 // turn off tone function for pin 8:
 noTone(8);
 // play a note on pin 6 for 200 ms:
 tone(6, 440, 200);
 delay(200);

// turn off tone function for pin 6:
 noTone(6);
 // play a note on pin 7 for 500 ms:
 tone(7, 494, 500);
 delay(500);

// turn off tone function for pin 7:
 noTone(7);
 // play a note on pin 8 for 500 ms:
 tone(8, 523, 300);
 delay(300);
}

 

Multiple tone player 3.gif

Multiple tone player 4.gif

 

Multiple tone player-Visualino.gif

SNAG- 16 07 24 16 13 30.jpg

/***   Multiple tone player - Visualino   ***/
/*** Global variables ***/
/*** Function declaration ***/

void setup()   {      }

void loop()    {
   tone(6,440,200);
     delay(200);
   tone(7,494,500);
     delay(500);
   tone(8,523,300);
     delay(300);
}
/*** Function definition ***/

Multiple tone player-Visualino 5.gif

 

 

2.9. tonePitchFollower
tonePitchFollower

/*  tone Pitch follower - Arduino IDE
Plays a pitch that changes based on a changing analog input
circuit:
 * 8-ohm speaker on digital pin 9
 * photoresistor on analog 0 to 5V
 * 4.7K resistor on analog 0 to ground
created 21 Jan 2010, modified 31 May 2012
 by Tom Igoe, with suggestion from Michael Flynn
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone2  */

void setup() {
 // initialize serial communications (for debugging only):
 Serial.begin(9600);
}

void loop() {
 // read the sensor:
 int sensorReading = analogRead(A0);
 // print the sensor reading so you know its range
 Serial.println(sensorReading);
 // map the analog input range (in this case, 400 - 1000 from the photoresistor)
 // to the output pitch range (120 - 1500Hz)
 // change the minimum and maximum input numbers below
 // depending on the range your sensor's giving:
 int thisPitch = map(sensorReading, 400, 1000, 120, 1500);

// play the pitch:
 tone(9, thisPitch, 10);
 delay(1); // delay in between reads for stability
}

 

tone Pitch follower.gif

tone Pitch follower 2.gif

 

Tone Pitch Follower - Visualino 2.gif

SNAG- 16 07 24 07 24 23.jpg

/***  Tone Pitch Follower - Visualino  ***/
/*** Global variables ***/
int sensorReading;
int thisPitch;

/*** Function declaration ***/
void setup() {
sensorReading=0;
thisPitch=0;
pinMode(A0,INPUT);
Serial.begin(9600);
}

void loop() {
 sensorReading=analogRead(A0);
 Serial.println(sensorReading);
 thisPitch=map(sensorReading,400,1000,120,1500);
 tone(9,thisPitch,10);
 delay(10);
}
/*** Function definition ***/

 

Tone Pitch Follower-Visualino.gif

 

 

03. Analog

SNAG- 16 06 27 00 17 40

 

3.1. AnalogInOutSerial

SNAG- 16 07 06 22 19 52.jpg

/*  AnalogInOutSerial - Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255
 and uses the result to set the pulsewidth modulation (PWM) of an output pin.
 Also prints the results to the serial monitor.
The circuit:
 * 220 ohm resistor
 * Potentiometer connected to analog pin 0.
     Center pin of the potentiometer goes to the analog pin.
     side pins of the potentiometer go to +5V and ground
 * Red LED connected from digital pin 9 to ground
created 29 Dec. 2008, modified 9 Apr 2012,  by Tom Igoe
This example code is in the public domain.  */

// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)

void setup() {
 // initialize serial communications at 9600 bps:
 Serial.begin(9600);
}

void loop() {
 // read the analog in value:
 sensorValue = analogRead(analogInPin);
 // map it to the range of the analog out:
 outputValue = map(sensorValue, 0, 1023, 0, 255);
 // change the analog out value:
 analogWrite(analogOutPin, outputValue);

 // print the results to the serial monitor:
 Serial.print("sensor = ");
 Serial.print(sensorValue);
 Serial.print("\t output = ");
 Serial.println(outputValue);

 // wait 2 milliseconds before the next loop
 // for the analog-to-digital converter to settle
 // after the last reading:
 delay(2);
}

 

AnalogInOutSerial.gif

AnalogInOutSerial 2.gif

AnalogInOutSerial-Visualino 2.gif

SNAG- 16 07 24 22 19 29.jpg

/*** AnalogInOutSerial - Visualino ***/
/*** Global variables ***/
int analogInPin;
int analogOutPin;
int sensorValue;
int outputValue;

/*** Function declaration ***/
void setup()  {
   analogInPin=(A0);
   analogOutPin=9;
   sensorValue=0;
   outputValue=0;
   Serial.begin(9600);
}

void loop()  {
 pinMode(analogInPin,INPUT);
 sensorValue=analogRead(analogInPin);
 outputValue=map(sensorValue,0,1023,0,255);
 pinMode(analogOutPin,OUTPUT);
 analogWrite(analogOutPin,outputValue);
 Serial.print("sensor = ");
 Serial.print(sensorValue);
 Serial.print("/t output = ");
 Serial.print(outputValue);
 delay(2);
}
/*** Function definition ***/

AnalogInOutSerial-Visualino 3.gif

 

 

3.2. AnalogInput
AnalogInput

/*  Analog Input - Arduino IDE
 Demonstrates analog input by reading an analog sensor on analog pin 0 and
 turning on and off a light emitting diode(LED) connected to digital pin 13.
 The amount of time the LED will be on and off depends on
 the value obtained by analogRead().

The circuit:
 * Potentiometer attached to analog input A0
 * center pin of the potentiometer to the analog pin A0
 * one side pin (either one) to ground
 * the other side pin to +5V
 * LED anode (long leg) attached to digital output 13
 * LED cathode (short leg) attached to ground

* Note: because most Arduinos have a built-in LED attached
  to pin 13 on the board, the LED is optional.
  Created by David Cuartielles, modified 30 Aug 2011, By Tom Igoe
  This example code is in the public domain.
  http://www.arduino.cc/en/Tutorial/AnalogInput    */

int sensorPin = A0;      // select the input pin for the potentiometer
int ledPin = 13;         // select the pin for the LED
int sensorValue = 0;     // variable to store the value coming from the sensor

void setup()  {
         // declare the ledPin as an OUTPUT:
      pinMode(ledPin, OUTPUT);
              }

void loop()  {
          // read the value from the sensor:
      sensorValue = analogRead(sensorPin);
          // turn the ledPin on
      digitalWrite(ledPin, HIGH);
          // stop the program for <sensorValue> milliseconds:
      delay(sensorValue);
          // turn the ledPin off:
      digitalWrite(ledPin, LOW);
          // stop the program for for <sensorValue> milliseconds:
      delay(sensorValue);
             }

 

AnalogInput 03.gif

AnalogInput-Arduino IDE.gif

AnalogInput.gif

AnalogInput-Visualino 2.gif

SNAG- 16 07 28 00 03 05.jpg

/*** AnalogInput - Visualino ***/
/*** Global variables ***/
int sensorPin;
int ledPin;
int sensorValue;

/*** Function declaration ***/
void setup()   {
     sensorPin=(A0);
     ledPin=13;
     sensorValue=0;
               }
void loop()    {
     pinMode(sensorPin,INPUT);
     sensorValue=analogRead(sensorPin);
     pinMode(ledPin,OUTPUT);
     digitalWrite(ledPin,HIGH);
     delay(sensorValue);
     pinMode(ledPin,OUTPUT);
     digitalWrite(ledPin,LOW);
     delay(sensorValue);
               }
/*** Function definition ***/

AnalogInput-Visualino

AnalogInput.gif

 

 

3.3. AnalogWriteMega
AnalogWriteMega

/*   Mega analogWrite() test
This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
 This sketch was written for the Arduino Mega, and will not work on previous boards.
The circuit:
 * LEDs attached from pins 2 through 13 to ground.
created 8 Feb 2009,  by Tom Igoe
This example code is in the public domain.  */
// These constants won't change. They're used to give names
// to the pins used:
const int lowestPin = 2;
const int highestPin = 13;

void setup() {
 // set pins 2 through 13 as outputs:
 for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
 pinMode(thisPin, OUTPUT);
 }
}

void loop() {
 // iterate over the pins:
 for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
 // fade the LED on thisPin from off to brightest:
 for (int brightness = 0; brightness < 255; brightness++) {
 analogWrite(thisPin, brightness);
 delay(2);
 }
 // fade the LED on thisPin from brithstest to off:
 for (int brightness = 255; brightness >= 0; brightness--) {
 analogWrite(thisPin, brightness);
 delay(2);
 }
 // pause between LEDs:
 delay(100);
 }
}

 

Mega analogWrite() test-Arduino IDE.gif

/*** Mega analogWrite() test-Arduino IDE ***/
/*** modificado por Angel Luis Díaz Përez en 2016 ***/
const int pinIN = 2;
const int pinFIN = 13;

void setup()
 {
   for (int i = pinIN; i <= pinFIN; i++)
        {
          pinMode(i, OUTPUT);
        }
  }

void loop()
{
   for (int i = pinIN; i <= pinFIN; i++)      {
           for (int brillo = 0; brillo < 255; brillo++)   {
                analogWrite(i, brillo);
                delay(2);
           }
           for (int brillo = 255; brillo >= 0; brillo--)   {
                analogWrite(i, brillo);
                delay(2);
           }
           delay(100);
        }
}

Mega analogWrite() test2.gif

Mega analogWrite() test-Mixly.gif

SNAG- 16 07 22 06 40 07.jpg

/*** AnalogWriteMega - Visualino ***!
/*** Global variables ***/
int i;
int brillo;

/*** Function declaration ***/
void setup()  {
 i=0;
 brillo=0;    }

void loop()   {
   for (i = 2; i <= 13; i++) {
       for (brillo = 0; brillo <= 255; brillo++)   {
           pinMode(i,OUTPUT);
           analogWrite(i,brillo);
           delay(2);
                                                    }
        for (brillo = 255; brillo >= 0; brillo--)   {
            pinMode(i,OUTPUT);
            analogWrite(i,brillo);
            delay(2);
                                                    }
         delay(200);
          }
}

Mega AnalogWrite-Visualiino.gif

 

3.4. Calibration
Calibration

/*  Calibration - Arduino IDE
 Demonstrates one technique for calibrating sensor input. The
 sensor readings during the first five seconds of the sketch
 execution define the minimum and maximum of expected values
 attached to the sensor pin.
 The sensor minimum and maximum initial values may seem backwards.
 Initially, you set the minimum high and listen for anything
 lower, saving it as the new minimum. Likewise, you set the
 maximum low and listen for anything higher as the new maximum.
 The circuit:
   * Analog sensor (LDR, potentiometer will do) attached to analog input 0
   * LED attached from digital pin 9 to ground
   * 10k ohm resistor or  10k potenciometer
   * 220 ohm resistor
created 29 Oct 2008,  By David A Mellis, modified 30 Aug 2011,  By Tom Igoe
http://www.arduino.cc/en/Tutorial/Calibration
This example code is in the public domain.     */

    // These constants won't change:
const int sensorPin = A0; // pin that the sensor is attached to
const int ledPin = 9; // pin that the LED is attached to
    // variables:
int sensorValue = 0; // the sensor value
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value

void setup() {
     // turn on LED to signal the start of the calibration period:
     pinMode(13, OUTPUT);
     digitalWrite(13, HIGH);
    // calibrate during the first five seconds
     while (millis() < 5000) {
           sensorValue = analogRead(sensorPin);
           // record the maximum sensor value
           if (sensorValue > sensorMax)   { sensorMax = sensorValue; }
           // record the minimum sensor value
           if (sensorValue < sensorMin)   { sensorMin = sensorValue; }
                              }
     // signal the end of the calibration period
     digitalWrite(13, LOW);
           }

void loop()   {
     // read the sensor:
     sensorValue = analogRead(sensorPin);
     // apply the calibration to the sensor reading
     sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
     // in case the sensor value is outside the range seen during calibration
     sensorValue = constrain(sensorValue, 0, 255);
     // fade the LED using the calibrated value:
     analogWrite(ledPin, sensorValue);
               }

Calibration 1.gif

Si sustituimos la resistencia de 10k por un potenciómetro de 10k tenemos un mejor control sobre el umbral de detección del sensor LDR (fotoresistor).

Calibration-Sensor-Potenciometro.gif

 

SNAG- 16 07 28 06 01 38.jpg

 

/*** Calibration-Sensor-Visualino ***/
/*** Global variables ***/
int sensorPin;
int ledPin;
int sensorValue;
int sensorMin;
int sensorMax;

/*** Function declaration ***/
void setup()   {
       sensorPin=(A0);
       ledPin=9;
       sensorValue=0;
       sensorMin=1023;
       sensorMax=0;
       pinMode(13,OUTPUT);
               }
void loop()    {
       digitalWrite(13,HIGH);
       while (millis() < 5000) {
            sensorValue=analogRead(sensorPin);
            if (sensorValue > sensorMax) { sensorMax=sensorValue; }
            if (sensorValue < sensorMin) { sensorMin=sensorValue; }
            digitalWrite(13,LOW);
                               }
       pinMode(sensorPin,INPUT);
       sensorValue=analogRead(sensorPin);
       sensorValue=map(sensorValue,sensorMin,sensorMax,0,255);
       sensorValue=map(sensorValue,0,1023,0,255);
       pinMode(ledPin,OUTPUT);
       analogWrite(ledPin,sensorValue);
              }
/*** Function definition ***/

 

Caliabration-Visualino 4.gif

SNAG- 16 07 28 06 09 47.jpg

NOTA:

Tanto

SNAG- 16 07 28 03 19 33

como

SNAG- 16 07 28 03 19 45

nos dan el mismo resultado:

sensorValue=analogRead(sensorPin);

 

/*** Calibration-Sensor-Visualino-Ángel Luis Díaz Pérez ***/
/*** Global variables ***/
     int sensorPin;
     int ledPin;
     int sensorValue;
     int sensorMin;
     int sensorMax;

/*** Function declaration ***/
void setup()   {
     sensorPin=(A0);
     ledPin=9;
     sensorValue=0;
     sensorMin=1023;
     sensorMax=0;
     pinMode(13,OUTPUT);
                }

void loop()     {
     digitalWrite(13,HIGH);
     while (millis() < 5000) {
            sensorValue=analogRead(sensorPin);
            if (sensorValue > sensorMax) { sensorMax=sensorValue;  }
            if (sensorValue < sensorMin) { sensorMin=sensorValue;  }
            digitalWrite(13,LOW);
                              }
      while ((sensorValue < 0) || (sensorValue > 255)) {
            pinMode(sensorPin,INPUT);
            sensorValue=analogRead(sensorPin);
            sensorValue=map(sensorValue,sensorMin,sensorMax,0,255);
            pinMode(ledPin,OUTPUT);
            analogWrite(ledPin,sensorValue);
                                                         }
                  }
/*** Function definition ***/

 

 

Calibration-Sensor-Visualino.gif

 

 

3.5. Fading
SNAG- 16 07 06 22 36 13.jpg

/*   Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
 * LED attached from digital pin 9 to ground.
 * 220 ohm resistor
Created 1 Nov 2008. By David A. Mellis, modified 30 Aug 2011. By Tom Igoe
http://www.arduino.cc/en/Tutorial/Fading
This example code is in the public domain.   */

int ledPin = 9;   // LED connected to digital pin 9

void setup() {    // nothing happens in setup
             }

void loop()  {
      // fade in from min to max in increments of 5 points:
      for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5)     {
              // sets the value (range from 0 to 255):
              analogWrite(ledPin, fadeValue);
              // wait for 30 milliseconds to see the dimming effect
              delay(30);                                             }
      // fade out from max to min in increments of 5 points:
      for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5)     {
              // sets the value (range from 0 to 255):
              analogWrite(ledPin, fadeValue);
              // wait for 30 milliseconds to see the dimming effect
              delay(30);                                              }
            }

Fade 123D.gif

Fading-Arduino IDE.gif

 

Fading-Visualino2.gif

SNAG- 16 07 28 10 16 50.jpg

/*** Fading - Visualino - Ángel Luis Díaz Pérez ***/
/*** Global variables ***/
int ledPin;
int fadeValue;

/*** Function declaration ***/
void setup()       {
     ledPin=9;
     fadeValue=0;  }

void loop()        {
     for (fadeValue = 0; fadeValue <= 255; fadeValue++) {
           pinMode(ledPin,OUTPUT);
           analogWrite(ledPin,fadeValue);
           delay(30);                                    }
     for (fadeValue = 255; fadeValue >= 0; fadeValue--)  {
           pinMode(ledPin,OUTPUT);
           analogWrite(ledPin,fadeValue);
           delay(30);                                    }
                   }

 

Visualino tiene solamente la opción:

SNAG- 16 07 28 10 26 46.jpg

es decir:

for (fadeValue = 0; fadeValue <= 255; fadeValue++)

pero no tiene la opción de saltar de 5 en 5

for (fadeValue = 0; fadeValue <= 255; fadeValue +=  5)

por lo tanto la ejecución será 5 veces mas lenta.

Fading-Visualino 3.gif

FAding-Visualino 5.gif

 

 

3.6. Smoothing
Smoothing

SNAG- 16 08 01 01 31 50

SNAG- 16 07 31 02 50 18

/*   Smoothing
 Reads repeatedly from an analog input, calculating a running average
 and printing it to the computer. Keeps ten readings in an array and
 continually averages them.
The circuit:
 * Analog sensor (10k potentiometer will do) attached to analog input 0
Created 22 April 2007 by David A. Mellis <dam@mellis.org>
 modified 9 Apr 2012 by Tom Igoe
 http://www.arduino.cc/en/Tutorial/Smoothing
 This example code is in the public domain.   */

// Define the number of samples to keep track of. The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input. Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
const int numReadings = 10;

int readings[numReadings];  // the readings from the analog input
int readIndex = 0;          // the index of the current reading
int total = 0;              // the running total
int average = 0;            // the average
int inputPin = A0;

void setup()  {
         // initialize serial communication with computer:
         Serial.begin(9600);
         // initialize all the readings to 0:
         for (int thisReading = 0; thisReading < numReadings; thisReading++) {
         readings[thisReading] = 0;                                         }
              }

void loop()   {
         // subtract the last reading:
         total = total - readings[readIndex];
         // read from the sensor:
         readings[readIndex] = analogRead(inputPin);
         // add the reading to the total:
         total = total + readings[readIndex];
         // advance to the next position in the array:
         readIndex = readIndex + 1;

         // if we're at the end of the array...
         if (readIndex >= numReadings) {
              // ...wrap around to the beginning:
              readIndex = 0;            }
         // calculate the average:
         average = total / numReadings;
         // send it to the computer as ASCII digits
         Serial.println(average);
         delay(1); // delay in between reads for stability
              }

 

Smoothing-Arduino IDE-01.gif

Smoothing-Arduino IDE-123D.gif

no parp

 

 

04. Communication

SNAG- 16 07 06 11 39 40

 

4.1. ASCIITable
ASCIITableSNAG- 16 07 06 22 39 36.jpg

/* Dimmer - Arduino IDE
 Demonstrates the sending data from the computer to the Arduino board,
 in this case to control the brightness of an LED. The data is sent
 in individual bytes, each of which ranges from 0 to 255. Arduino
 reads these bytes and uses them to set the brightness of the LED.
The circuit:
 LED attached from digital pin 9 to ground.
 Serial connection to Processing, Max/MSP, or another serial application
 Created 2006 by David A. Mellis, modified 30 Aug 2011,
 by Tom Igoe and Scott Fitzgerald
 This example code is in the public domain.
 http://www.arduino.cc/en/Tutorial/Dimmer */

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+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC
ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP
xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK
rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W
sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui
FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv
AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK
z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu
xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2
uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj
jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA
4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr
TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS
xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6
WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9
FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7
3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc
cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ
+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x
D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8
ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS
xqZqbd3ZLdera1iPqYxOm++v7SUSz
-----------end_max5_patcher-----------
 */

ASCIITable.gif

 

 

4.2. Dimmer
DimmerSNAG- 16 07 06 22 36 13.jpg

 

/* Dimmer - Arduino IDE
Demonstrates the sending data from the computer to the Arduino board,
 in this case to control the brightness of an LED. The data is sent
 in individual bytes, each of which ranges from 0 to 255. Arduino
 reads these bytes and uses them to set the brightness of the LED.
 The circuit:
   LED attached from digital pin 9 to ground.
   Serial connection to Processing, Max/MSP, or another serial application
   created 2006 by David A. Mellis, modified 30 Aug 2011
 by Tom Igoe and Scott Fitzgerald
 This example code is in the public domain.
 http://www.arduino.cc/en/Tutorial/Dimmer  */

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+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC
ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP
xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK
rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W
sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui
FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv
AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK
z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu
xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2
uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj
jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA
4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr
TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS
xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6
WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9
FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7
3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc
cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ
+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x
D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8
ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS
xqZqbd3ZLdera1iPqYxOm++v7SUSz
-----------end_max5_patcher-----------
 */

SNAG- 16 08 02 06 55 51.jpg

 

No funciona

 

SNAG- 16 08 02 06 47 20.jpg

El Sketch usa 2.280 bytes (7%) del espacio de almacenamiento de programa. El máximo es 32.256 bytes.
Las variables Globales usan 182 bytes (8%) de la memoria dinámica, dejando 1.866 bytes para las variables locales. El máximo es 2.048 bytes.
avrdude: ser_open(): can’t open device “\\.\COM11”: El sistema no puede encontrar el archivo especificado.

Problema subiendo a la placa. Visita:

http://www.arduino.cc/en/Guide/Troubleshooting#upload

para sugerencias.

 

 

 

4.3. Graph

Graph

/* Graph - Arduino IDE
 A simple example of communication from the Arduino board to the computer:
 the value of analog input 0 is sent out the serial port. We call this "serial"
 communication because the connection appears to both the Arduino and the
 computer as a serial port, even though it may actually use
 a USB cable. Bytes are sent one after another (serially) from the Arduino
 to the computer.
 You can use the Arduino serial monitor to view the sent data, or it can
 be read by Processing, PD, Max/MSP, or any other program capable of reading
 data from a serial port. The Processing code below graphs the data received
 so you can see the value of the analog input changing over time.
The circuit:
 Any analog input sensor is attached to analog in pin 0.
 Analog Sensor (potentiometer, photocell, FSR, etc.)
 Created 2006 by David A. Mellis,
 modified 9 Apr 2012 by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Graph  */

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
// Created 20 Apr 2005
// Updated 24 Nov 2015
// by Tom Igoe
// This example code is in the public domain.

     /* import processing.serial.*/
     Serial myPort; // The serial port
     int xPos = 1; // horizontal position of the graph
     float inByte = 0;

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 () {
     // 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++;
            }
}

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:
     inByte = float(inString);
     println(inByte);
     inByte = map(inByte, 0, 1023, 0, height);
                      }
                                 }
*/
/* Max/MSP v5 patch for this example
 ----------begin_max5_patcher----------
1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT
RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6
Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy
dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL
vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz
1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT
YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S
crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc
sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1
nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ
jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv
HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ
DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82
LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F
G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs
vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL
hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER
bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY
aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k
Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG
YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H
hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ
q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV
XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI
pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg
M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu
mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1
tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X
zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV
9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m
eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl
c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a
53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM
RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
HJ5hhnng3h9HPj4lud02.1bxGw.
-----------end_max5_patcher-----------

*/

 

SNAG- 16 07 31 02 50 18.jpg

Graph-Arduino IDE.gif

no parp

 

 

 

4.4. Midi

Midi

 

4.5. MultiSerialMega

SNAG- 16 07 06 22 49 09.jpg

 

4.6. ReadASCIIString

ReadASCIIString

RGB led foto1.gif

/*  ReadASCIIString - Arduino IDE
 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-Cathode RGB LED wired like so:
 * Red anode: digital pin 3
 * Green anode: digital pin 5
 * Blue anode: digital pin 6
 * Cathode : GND
 created 13 Apr 2012 by Tom Igoe, modified 14 Mar 2016 by Arturo Guadalupi
 This example code is in the public domain. */

// 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);
                               }
                                     }
        }

SNAG- 16 08 02 08 22 08.jpg

no funciona.

como alternativa tenemos el siguiente sketch.

RGB led

/***  RGB led  ***/
void setup()
   { pinMode(3, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT); }

void Color(int R, int G, int B)
   { analogWrite(3 , R);    // Red  -Rojo
     analogWrite(5, G) ;    // Green-Verde
     analogWrite(6, B) ; }  // Blue -Azul

void loop()
   { Color(255, 0 , 0 );    delay(500); 
     Color( 0 ,255, 0 );    delay(500);
     Color( 0 , 0 ,255);    delay(500);
     Color( 0 , 0 , 0 );    delay(1000); }

RGB Led -3.gif

RGB led-1.gif

REG -ed-Arduino IDE.gif

RGB led foto2.gif

RGB led foto1.gif

 

 

4.7. SerialCallResponseASCII
SerialCallResponseASCII

/*
 Serial Call and Response in ASCII
 Language: Wiring/Arduino

This program sends an ASCII A (byte of value 65) on startup
 and repeats that until it gets some data in.
 Then it waits for a byte in the serial port, and
 sends three ASCII-encoded, comma-separated sensor values,
 truncated by a linefeed and carriage return,
 whenever it gets a byte in.

Thanks to Greg Shakar and Scott Fitzgerald for the improvements

The circuit:
 * potentiometers attached to analog inputs 0 and 1
 * pushbutton attached to digital I/O 2

Created 26 Sept. 2005
 by Tom Igoe
 modified 24 Apr 2012
 by Tom Igoe and Scott Fitzgerald

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII

*/

int firstSensor = 0; // first analog sensor
int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte

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

 pinMode(2, INPUT); // digital sensor is on digital pin 2
 establishContact(); // send a byte to establish contact until receiver responds
}

void loop() {
 // if we get a valid byte, read analog ins:
 if (Serial.available() > 0) {
 // get incoming byte:
 inByte = Serial.read();
 // read first analog input:
 firstSensor = analogRead(A0);
 // read second analog input:
 secondSensor = analogRead(A1);
 // read switch, map it to 0 or 255L
 thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
 // send sensor values:
 Serial.print(firstSensor);
 Serial.print(",");
 Serial.print(secondSensor);
 Serial.print(",");
 Serial.println(thirdSensor);
 }
}

void establishContact() {
 while (Serial.available() <= 0) {
 Serial.println("0,0,0"); // send an initial string
 delay(300);
 }
}

/* Processing code to run with this example:

// This example code is in the public domain.

import processing.serial.*; // import the Processing serial library
Serial myPort; // The serial port

float bgcolor; // Background color
float fgcolor; // Fill color
float xpos, ypos; // Starting position of the ball

void setup() {
 size(640,480);

// 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 module, so I open Serial.list()[0].
 // Change the 0 to the appropriate number of the serial port
 // that your microcontroller is attached to.
 myPort = new Serial(this, Serial.list()[0], 9600);

// read bytes into a buffer until you get a linefeed (ASCII 10):
 myPort.bufferUntil('\n');

// draw with smooth edges:
 smooth();
}

void draw() {
 background(bgcolor);
 fill(fgcolor);
 // Draw the shape
 ellipse(xpos, ypos, 20, 20);
}

// serialEvent method is run automatically by the Processing applet
// whenever the buffer reaches the byte value set in the bufferUntil()
// method in the setup():

void serialEvent(Serial myPort) {
 // read the serial buffer:
 String myString = myPort.readStringUntil('\n');
 // if you got any bytes other than the linefeed:
 myString = trim(myString);

// split the string at the commas
 // and convert the sections into integers:
 int sensors[] = int(split(myString, ','));

// print out the values you got:
 for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
 print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
 }
 // add a linefeed after all the sensor values are printed:
 println();
 if (sensors.length > 1) {
 xpos = map(sensors[0], 0,1023,0,width);
 ypos = map(sensors[1], 0,1023,0,height);
 fgcolor = sensors[2];
 }
 // send a byte to ask for more data:
 myPort.write("A");
 }

*/

/*
Max/MSP version 5 patch to run with this example:
----------begin_max5_patcher----------
3640.3oc6cs0jZajE94Y9UzKkeHoVloTeSHkm1II0VkeHIthSs6C1obIjZ.E
KjHRhY7jT4+9d5KBj.jTCAXfoV6x.sj5VmyWet127ed6MCFm8EQw.z2f9.5l
a9yau4F0kjW3FS4aFLO3KgIAEpGaPX174hzxAC02qT7kR80mkkUHPAnBQdbP
BZQVdIZRd1bT4r3BDTmkU0YQPY3r3zoeJWDVpe2ttr6cFhvXt7KhyH8W26f9
USkhiTulrw+1czQUszjrzxzf4B0sdP9dqtS5x4woIhREQiWewrkkUW0oViTD
+GpFASt2Qd0+51akeLzRPIU7DPXagIFnH.4653f9WAKKyxVHRQNcfDXlih2w
puvbdWHAlcTPBRKHg4x5mr74EBMINHV1+iFL.8qG.VMWTTDLUrs.TBH+zAvP
nTEhvvxun9pBd6FWH38DWH6DWv6ItbX.RKBOJ7XbP5ztvDesvhBLb6VTwcOg
DmiBjnXfiIrjjED0CpP490PEmtPExwQA5EGUVjK.CKQJqtcYl0nCMRAJi76D
Z7dQflCCVV1i+ENiTy3AwYaghEA4.KVJx+jHMXbhntJPceO3iBpPOPKtZqtU
jUoXtw28fkEimmEIlOI.3Q4iMT9wO+iLxc9O7sN28928t6Ve8uMYo.7EUN6t
ePVoUW+6E4hOW7CAgeaV1meWd1cuWnYLy8mKhhClGDd25F3ce+C2si1Ud42+
bZ3IQJOXg7q96t80e50YvDjqHw7VvkRTXhHHuKEerRwmqfBFsS.g9h.HZN3X
hJf5Qd+xHZHgzc.mrqeYjbn4E84evfIDUjDtjNwD2iRHV6anmGdbmsfKxTTJ
dd93rjtBJ2U42foCwZDqKfYzKkrh4VgYIY4FxVRmN2646f8ck+xw7KrjzOlZ
ZYAVfdZgKlaWn29FzA8nfdR2quj.3ejflBJnKr.Dwpf13cZBm85P0rPj.rOB
6fvztPFGkVI0SAPi5NKHmih7E8Ph2e35uOtYN6x6JEQtJVWpV7gRtm2dZy9W
+YMCxLHrEvAknQktDVdY7v82SFosgmSGHO56BRRt6mEEKxRKDnGd+2812h9X
5GSeODOcAJ.M9YHHAfjPkyD0GIugn.Ht6bQ.7TTS8DoPtCQCQxWobX+jYPUJ
hPn3zgnx7kogphieFZ2j3TwDgH5dzaUscJ77kEnIY4hoYKglVYzcH5KKxJzu
qmgegxl.0MLNGBNDsr.5IUz0iAPZFE.0TtLOEdClQYrAAeORwW+XVo3aP+hb
DHUBCH.mfbEKfGOPyjQhGiCAdNUUBRcQjij4X.u5MZRDzHSyTDQFbcYdHHIM
AzlF1lnoLjKG8UZH5guV1vEkA4kKWbOPGPC9YgjNdJHVy+ZJQ1.Cq.FUWQpA
ke.8DbUwi.YEWBUCDhPyAXCEETFbuhICg9EIRiYnGVjKyt0+io.r+9vrxRz+
Nt7OlJxCRhT35u.X0amlI9X5xEQppQwneJrLarPVU7JkGYWVHz2njevz1UoX
XkoEWOkxDWO9kXYocoTwuzF611zXJyimB3F5qf9nOT9qesryJTJ1EOcV4cIh
IPVWYoOBUMFTl.4sGRRzRT4AOIkRjn8h7LnNJI2mhg6OSk5JZrPJ4i9gfu.R
w+NHLCcpfAMij88n+qTPPMt4UTwj3bAnY.h.aIe.RiAEeF8Pdzx3zLkLUs1Z
mcmczah0FH4ZmpLcp.rVbX3d0zalKhSiKAxBZ9BU2zTP3uPobgL1Q.U0.kl+
jcBZj1AMOpzsJYjdz0n53QXsfYrqELKblH7yUFoDfPVXbrwDGXqCjwjviT7a
rXZbpxOvxzXvpOnPH0GlTJMZog8l2UZJcdPjxjG7ywIYgeFULaInFDk8jpxZ
apvMA4cv9X.7.vaRRGFAcPYHMR0dF2BZC7wEJ2TOKeZnCRD+HzJo.OLWSW6r
qk2wfI6pGf.pdjC4rpfL2YeK8JYloVf93.ocJEvocv9wAcEiMQgBtl.lb0y9
heKnvtGRs+iHOJHM3uaZbN1jDrhED4FfwfLPCEmH8jV.BB0Z+aF.Vkqc4apU
EIb9a5zAcGt5Rf3WdsNJ3R4PXDU0mouHzIca0MWO.KpQjT8oq1SIyqV3mP24
ToxfHpdyOPNqgwoK.W.fxfRNtwsiDSBVlT9ociSMu+jfPQqUtk9paFLMONJK
URFMpq7xUuvOXF1HBuN6ndhzfE6nxPXQkKKFGjKQNyHtSptYYVVRyaspyBD3
CRiA0YQYrlbgHdptY77E4wZk5UWSOf9yJByyRRZzT5673NtiNrvmhiJmoZq5
fI73wKp5DFrBihhmBNxadsxfoEMuRiIbutfVcM4FWuyr.2bvrlNF5.3U+q9C
sKaa5jkMt70iSd8bC2ZbEFUuAa0DWqYF0tJ91p43649br2nZ2usLGuoxrnQq
6TArNx+1CjRLPpVWf62Kj59ZFRa38Y6D0kRo8AnT8b0g0e4p8+f6.P4sBnaX
TqMmPsOdOcjG+dMtOmdzcgLdIGqjX0J+FAVrmSu.L8fAX19Ky1C.e1.z+IB2
qpeCIUV+.I4fARxQGH0i.9ECVZrhZMTheMCkc4XRMsoCgbef2ZFjaF5MXzaH
n2PQugYmhe0WjdcU47Z1Ukhb6CwFISy2HNtcvtaNRWdshHNVgHcNMUlopRm4
tJByyLXfI0UN6GM7eUiFTm8BMbctZQC8atOegDu6oveXrgpeaGnfaETvsBJN
6AKuNsT4n+zRVXJtQd+ciEEYKyCq.8ptRTSdBRQrLNcUd5eXcjoa7fyhihZl
UrNQxBYZo5g.vpdt8klkJi1QyPvdH7UFMStbvYu8Amu1nY7ECMKGXBqnY2KH
Z18Jjl4aYNnEYiQWVzrUxytWNzL0VZ14xglI6isN5kAMi2GZlbYPyNma6FqC
aJRs9qEogO+ovfvYFxxjGV07cLnH3QQzm.R.BG7SAkk4wiWVpC2p9jwX23ka
0zSz4M6e1QZY.8mljMNHwLURqZ9FuzslMk8ZJXtcMPeblVut1XYDhdMCpmjZ
8BAqsU9DezKxJAa8Hmbbfi+wccuVv7c0qELrEHB+UAhHWzCfCbKPEyBki24Z
clythVwfkYSmlHrPdX8tC5v1iPb5ArPuOWc8NVrRZspq24UxhE0wBcAsMyt2
2LLuqvkKZRXjEq5CM6S3tq9Zm6HD+8Prm0F+jDWn1paUe+2ZuF259kxkiR5W
Qf6vzKBtMm+gFrMeuWsKW.6B61VyWOFjz0Zsmwza+.ikxQcAL3iDtbLWMTKm
OtyMEFcjWM9iu0rMa81D8kUl3v2ewcHWP5B2HX6kK7t7DL5fs6JVIrO0Z1l3
bEpOP3zih9.gbspPzKDYbRVAQ7CFhtZsYzhW1ko0WEJcG3oAC0aRIyxKsUEI
+iDPwOLfp0uNA68MmtSUSmRuNb8d1ttWya7sVWf5Iwf.1LQtZUnqNvT1bS6z
E5o2vfqNSH5bufQbuZV09M.E04Mj8XBUiBqNGl5FSt3NGlZaGRpV6wc4kiWi
q0twaaORhul1jjsIi7cMjQlJJUaQuhR495nlfRQWRJXkrgmMGXWjKM4jdGJH
yovkl4HUetutzWuY5tjFHneGn77rtG3iJ92whCVJxKhBwgGtRaFIzabfNrRn
WThd9q24vsZjf9JvHwOKBhprFDmtXYIZ7xISjaO1GE4OK2V9yiS.qFhvrznh
8cKyMZs7EVepT01FlCe0rIC0lUk6NX4N9syCyAE660+ovE9hyGqjaGurrLak
G0YwoMlFO4YMSZjd9DcWucsjUr1Yqgy8TluCY3N9Q8.+k0JCD3ZTS0CW8Qyb
s19nOxrgjw7VFU+3ooYviK66pCfimt8AAxHOOBkK+EajC2yayWtciMzgdvpM
NKORj29YyGcS4wFVlql0wcZTg1yw5wvMNiTpuUzpu.Y0miRlgO0w7wpZI2Em
SUBGayVM5eqU4C+rV4ZSPkvXqLJbAHlR3mKwT5ISL8+Kv0k.GWEKwpP3ewk3
7omKIN7EtDmp4ZtHk0BfatXgLhgasHgZrVYaY8AIO7fq8Pas1fFzjd4ibwpd
XO4GXOeOG+lcyasNh1R+wVx2yBxeTOT+wiZFYA0P48PNyiiVjAhJlNT4Qvpb
uj3aN2qYqJcBfSWhMbf+YCPcsfbNeTC2l9WNc+5eIlkST0RJgupzIn+kysgC
X6GGXnYpdYfP0GP6MKQXM3N1Ih6XVvcLuym7B0B5w8v.ahqBI49qJcJ.TaX.
N+xBP4NGHhhqYfkRNM9q1f3ZweqyYCQYdGCSZGQ5wBx47o.Ssw+CkcgQOmud
KZic4QKzCw+7ROm8nY2LfMsEDtdfeMKSn5Ev95IQhorcqJcBrzPsQUhRNe8M
1X6lhOezC4Bidv1nKcFs8YimJ9n8RWZXiO7aSCxDRLdjd91qU5TnmXCeRvmR
9jnm7b15RmJ9rO4Kr+IgO04BfczyOpqx9npzofOsIlaR8Mo0IUMR48i0mYly
lVMwlw6gbloGRezy4yKEw6BHBBWik.eRi3DNM5KDahS.SOE1EjmXl7Uyqo9T
AtQAO8fG3oLX3cZFxKh0FLNSRfDaoG74gdvW.ZDU9FMGSdFMBt+IQh.6eIvw
FujTkJREGKKcJ3X2WtXf7Ub1HywEqxh2tJnE.FcZhMByrcXQw1x+bOWJYjpy
lv8oq55aEHLcwD8hJjxbVU5EigcNtL7Ql76KVVp69Huhcb87vpoCkRYT+96v
Hd5Ay1rofMqm+FkLYvv0+GL3FkL6bLp21kL6QFNV8BNM48foWBV4zt1wXm5V
4jkNEbL45dtNw13Iltmi9sAyY0S0l8BR+3yWjVXax7eOmKrp4m0QKIal6VYo
SAf5XQxSrCa5l0qk45k5kAzqEgMNgzkz9FmL5abpnu4IhNzZ+0s+OKCSg0.
-----------end_max5_patcher-----------

*/

 

SNAG- 16 07 06 22 54 51.jpg

 

4.8. SerialEvent
SerialEvent

/*
 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.
Created 9 May 2011, by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent
*/

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() {
 // 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;
 }
 }
}

 

 

4.9. VirtualColorMixer

SNAG- 16 07 06 23 08 49.jpg

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

http://www.arduino.cc/en/Tutorial/VirtualColorMixer

created 2 Dec 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe and Scott Fitzgerald

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
S4zORQtgIdDbRHrObRzSMNofUVZVcbKbhQZrSOo934TqRHIN2ncr7BF8TKR1
tHDqL.PejLRRPKMR.pKFAkbtDa+UOvsYsIFH0DYsTCjqZ66T1CmGeDILLpSm
myk0SdkOKh5LUr4GbWwRYdW7fm.BvDmzHnSdH3biGpSbxxDNJoGDAD1ChH7L
I0DaloOTBLvkO7zPs5HJnKNoGAXbol5eytUhfyiSfnjE1uAq+Fp0a+wygGwR
q3ZI8.psJpkpJnyPzwmXBj7Sh.+bNvVZxlcKAm0OYHIxcIjzEKdRChgO5UMf
LkMPNN0MfiS7Ev6TYQct.F5IWcCZ4504rGsiVswGWWSYyma01QcZgmL+f+sf
oU18Hn6o6dXkMkFF14TL9rIAWE+6wvGV.p.TPqz3HK5L+VxYxl4UmBKEjr.B
6zinuKI3C+D2Y7azIM6N7QL6t+jQyZxymK1ToAKqVsxjlGyjz2c1kTK3180h
kJEYkacWpv6lyp2VJTjWK47wHA6fyBOWxH9pUf6jUtZkLpNKW.9EeUBH3ymY
XSQlaqGrkQMGzp20adYSmIOGjIABo1xZyAWJtCX9tg6+HMuhMCPyx76ao+Us
UxmzUE79H8d2ZB1m1ztbnOa1mGeAq0awyK8a9UqBUc6pZolpzurTK232e5gp
aInVw8QIIcpaiNSJfY4Z+92Cs+Mc+mgg2cEsvGlLY6V+1kMuioxnB5VM+fsY
9vSu4WI1PMBGXye6KXvNuzmZTh7U9h5j6vvASdngPdgOFxycNL6ia1axUMmT
JIzebXcQCn3SKMf+4QCMmOZung+6xBCPLfwO8ngcEI52YJ1y7mx3CN9xKUYU
bg7Y1yXjlKW6SrZnguQdsSfOSSDItqv2jwJFjavc1vO7OigyBr2+gDYorRk1
HXZpVFfu2FxXkZtfp4RQqNkX5y2sya3YYL2iavWAOaizH+pw.Ibg8f1I9h3Z
2B79sNeOHvBOtfEalWsvyu0KMf015.AaROvZ7vv5AhnndfHLbTgjcCK1KlHv
gOk5B26OqrXjcJ005.QqCHn8fVTxnxfj93SfQiJlv8YV0VT9fVUwOOhSV3uD
eeqCUClbBPa.j3vWDoMZssNTzRNEnE6gYPXazZaMF921syaLWyAeBXvCESA8
ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc
iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq
-----------end_max5_patcher-----------


 */

 

SNAG- 16 07 06 23 06 28.jpg

SNAG- 16 07 06 23 08 01.jpg

05. Control

SNAG- 16 06 27 00 19 25.jpg

 

5.1. Arrays
Arrays

/*   Arrays - Arduino IDE
   Demonstrates the use of an array to hold pin numbers
 in order to iterate over the pins in a sequence.
 Lights multiple LEDs in sequence, then in reverse.
   Unlike the For Loop tutorial, where the pins have to be
 contiguous, here the pins can be in any random order.

The circuit:
 * 6x LEDs from pins 2 through 7 to ground
 * 6x 220 ohm resistors

created 2006 by David A. Mellis, modified 30 Aug 2011 by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Array    */

int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = { 2, 7, 4, 6, 5, 3 };
 // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)

void setup() {
 // the array elements are numbered from 0 to (pinCount - 1).
 // use a for loop to initialize each pin as an output:
 for (int thisPin = 0; thisPin < pinCount; thisPin++)
    {  pinMode(ledPins[thisPin], OUTPUT);   }
}

void loop() {
 // loop from the lowest pin to the highest:
 for (int thisPin = 0; thisPin < pinCount; thisPin++) {
 // turn the pin on:
 digitalWrite(ledPins[thisPin], HIGH);
 delay(timer);
 // turn the pin off:
 digitalWrite(ledPins[thisPin], LOW);
}

// loop from the highest pin to the lowest:
 for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
 // turn the pin on:
 digitalWrite(ledPins[thisPin], HIGH);
 delay(timer);
 // turn the pin off:
 digitalWrite(ledPins[thisPin], LOW);
 }
}

 

Arrays-Arduino IDE 0.gif

Arrays-Arduino IDE.gif

 

Arrays-Mixly 2.gif

SNAG- 16 07 25 02 52 40.jpg

/*** Array - Mixly - Ángel Luis Díaz Pérez ***/
float timer;
float pintCount;
float thisPin;
long ledPins[6]={2,7,4,6,5,3};

void setup() {
 timer = 100;
 pintCount = 6;
 thisPin = 0; }

void loop() {
 for (thisPin = (0); thisPin <= (pintCount); thisPin = thisPin + (1)) {
    pinMode(ledPins[(int)(thisPin - 1)], OUTPUT);
    digitalWrite(ledPins[(int)(thisPin - 1)],HIGH);
    delay(timer);
    pinMode(ledPins[(int)(thisPin - 1)], OUTPUT);
    digitalWrite(ledPins[(int)(thisPin - 1)],LOW);
 } for (thisPin = (pintCount - 1); thisPin >= (0); thisPin = thisPin + (-1)) {
    pinMode(ledPins[(int)(thisPin - 1)], OUTPUT);
    digitalWrite(ledPins[(int)(thisPin - 1)],HIGH);
    delay(timer);
    pinMode(ledPins[(int)(thisPin - 1)], OUTPUT);
    digitalWrite(ledPins[(int)(thisPin - 1)],LOW);
 }
}

Arrays-Mixly.gif

Arrays - Visualino 3.gif

Visualino no tiene la opción de crear una Lista 6 elementos,

SNAG- 16 07 25 01 37 18.jpg

SNAG- 16 07 25 01 38 01.jpgNo nos permite crea una lista distinta de esta.

Por lo tanto hemos optado por poner los elementos por extensión en lugar de crear un loop

SNAG- 16 07 25 00 35 43.jpg

SNAG- 16 07 25 00 36 12.jpg

 

/*** Arrays - Visualino ***/
/*** Global variables ***/
int timer;
int ledPin1;
int ledPin2;
int ledPin3;
int ledPin4;
int ledPin5;
int ledPin6;

/*** Function declaration ***/
void setup()  {
 timer=100;
 ledPin1=2;
 ledPin2=7;
 ledPin3=4;
 ledPin4=6;
 ledPin5=5;
 ledPin6=3;   }

void loop()  {
 pinMode(ledPin1,OUTPUT);
 digitalWrite(ledPin1,HIGH);
 delay(timer);
 pinMode(ledPin1,OUTPUT);
 digitalWrite(ledPin1,LOW);
 pinMode(ledPin2,OUTPUT);
 digitalWrite(ledPin2,HIGH);
 delay(timer);
 pinMode(ledPin2,OUTPUT);
 digitalWrite(ledPin2,LOW);
 pinMode(ledPin3,OUTPUT);
 digitalWrite(ledPin3,HIGH);
 delay(timer);
 pinMode(ledPin3,OUTPUT);
 digitalWrite(ledPin3,LOW);
 pinMode(ledPin4,OUTPUT);
 digitalWrite(ledPin4,HIGH);
 delay(timer);
 pinMode(ledPin4,OUTPUT);
 digitalWrite(ledPin4,LOW);
 pinMode(ledPin5,OUTPUT);
 digitalWrite(ledPin5,HIGH);
 delay(timer);
 pinMode(ledPin5,OUTPUT);
 digitalWrite(ledPin5,LOW);
 pinMode(ledPin6,OUTPUT);
 digitalWrite(ledPin6,HIGH);
 delay(timer);
 pinMode(ledPin6,OUTPUT);
 digitalWrite(ledPin6,LOW);
 pinMode(ledPin5,OUTPUT);
 digitalWrite(ledPin5,HIGH);
 delay(timer);
 pinMode(ledPin5,OUTPUT);
 digitalWrite(ledPin5,LOW);
 pinMode(ledPin4,OUTPUT);
 digitalWrite(ledPin4,HIGH);
 delay(timer);
 pinMode(ledPin4,OUTPUT);
 digitalWrite(ledPin4,LOW);
 pinMode(ledPin3,OUTPUT);
 digitalWrite(ledPin3,HIGH);
 delay(timer);
 pinMode(ledPin3,OUTPUT);
 digitalWrite(ledPin3,LOW);
 pinMode(ledPin2,OUTPUT);
 digitalWrite(ledPin2,HIGH);
 delay(timer);
 pinMode(ledPin2,OUTPUT);
 digitalWrite(ledPin2,LOW);
 pinMode(ledPin1,OUTPUT);
 digitalWrite(ledPin1,HIGH);
 delay(timer);
 pinMode(ledPin1,OUTPUT);
 digitalWrite(ledPin1,LOW);
}
/*** Function definition ***/

 

Arrays-Visualino 4.gif

 

 

5.2. ForLoopIteration
ForLoopIteration

/*
 For Loop Iteration

Demonstrates the use of a for() loop.
 Lights multiple LEDs in sequence, then in reverse.

The circuit:
 * LEDs from pins 2 through 7 to ground

created 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ForLoop
 */

int timer = 100; // The higher the number, the slower the timing.

void setup() {
 // use a for loop to initialize each pin as an output:
 for (int thisPin = 2; thisPin < 8; thisPin++) {
 pinMode(thisPin, OUTPUT);
 }
}

void loop() {
 // loop from the lowest pin to the highest:
 for (int thisPin = 2; thisPin < 8; thisPin++) {
 // turn the pin on:
 digitalWrite(thisPin, HIGH);
 delay(timer);
 // turn the pin off:
 digitalWrite(thisPin, LOW);
 }

// loop from the highest pin to the lowest:
 for (int thisPin = 7; thisPin >= 2; thisPin--) {
 // turn the pin on:
 digitalWrite(thisPin, HIGH);
 delay(timer);
 // turn the pin off:
 digitalWrite(thisPin, LOW);
 }
}

SNAG- 16 07 06 23 11 08.jpg

 

5.3. ifStatementConditional
ifStatementConditional

SNAG- 16 08 01 01 31 50

SNAG- 16 07 31 02 49 59.jpg

/* Conditionals - If statement - Arduino IDE

This example demonstrates the use of if() statements.
 It reads the state of a potentiometer (an analog input) and turns on an LED
 only if the potentiometer goes above a certain threshold level. It prints the analog value
 regardless of the level.
The circuit:
  * potentiometer connected to analog pin 0.
  Center pin of the potentiometer goes to the analog pin.
  side pins of the potentiometer go to +5V and ground
  * LED connected from digital pin 13 to ground
  * Note: On most Arduino boards, there is already an LED on the board
  connected to pin 13, so you don't need any extra components for this example.
created 17 Jan 2009, modified 9 Apr 2012  by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/IfStatement  */

// These constants won't change:
const int analogPin = A0;     // pin that the sensor is attached to
const int ledPin = 13;        // pin that the LED is attached to
const int threshold = 400; 
     // an arbitrary threshold level that's in the range of the analog input

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

void loop()    {
     // read the value of the potentiometer:
     int analogValue = analogRead(analogPin);
     // if the analog value is high enough, turn on the LED:
     if (analogValue > threshold) {
           digitalWrite(ledPin, HIGH);
      } else {
           digitalWrite(ledPin, LOW);
              }
     // print the analog value:
     Serial.println(analogValue);
     delay(1);      // delay in between reads for stability
               }

 

ifStatementConditional-Arduino IDE.gif

ifStatementConditional-123D.gif

si parpadea.gif

ifStatementConditional-Visualino.gif

ifStatementConditional.jpg

/*** ifStatementConditional - Visualino ***/
/*** Global variables ***/
int analogPin;
int ledPin;
int threshold;
int analogValue;

/*** Function declaration ***/
void setup()  {
     analogPin=(A0);
     ledPin=13;
     threshold=400;
     analogValue=0;
     Serial.begin(9600);
              }

void loop()   {
     pinMode(analogPin,INPUT);
     analogValue=analogRead(analogPin);
     if (analogValue > threshold) {
           pinMode(ledPin,OUTPUT);
           digitalWrite(ledPin,HIGH);
     } else {
           pinMode(ledPin,OUTPUT);
           digitalWrite(ledPin,LOW);
            }
     Serial.print(analogValue);
     delay(1);
}
/*** Function definition ***/

ifStatementConditional-123D 2.gif

 

5.4. switchCase
switchCase

/*
 Switch statement

Demonstrates the use of a switch statement. The switch
 statement allows you to choose from among a set of discrete values
 of a variable. It's like a series of if statements.

To see this sketch in action, but the board and sensor in a well-lit
 room, open the serial monitor, and and move your hand gradually
 down over the sensor.

The circuit:
 * photoresistor from analog in 0 to +5V
 * 10K resistor from analog in 0 to ground

created 1 Jul 2009
 modified 9 Apr 2012
 by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SwitchCase
 */

// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 600; // sensor maximum, discovered through experiment

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

void loop() {
 // read the sensor:
 int sensorReading = analogRead(A0);
 // map the sensor range to a range of four options:
 int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

// do something different depending on the
 // range value:
 switch (range) {
 case 0: // your hand is on the sensor
 Serial.println("dark");
 break;
 case 1: // your hand is close to the sensor
 Serial.println("dim");
 break;
 case 2: // your hand is a few inches from the sensor
 Serial.println("medium");
 break;
 case 3: // your hand is nowhere near the sensor
 Serial.println("bright");
 break;
 }
 delay(1); // delay in between reads for stability
}

SNAG- 16 07 06 23 16 02.jpg

5.5. switchCase2
switchCase2

/*
 Switch statement with serial input

Demonstrates the use of a switch statement. The switch
 statement allows you to choose from among a set of discrete values
 of a variable. It's like a series of if statements.

To see this sketch in action, open the Serial monitor and send any character.
 The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn
 the LEDs off.

The circuit:
 * 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors

created 1 Jul 2009
 by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SwitchCase2
 */

void setup() {
 // initialize serial communication:
 Serial.begin(9600);
 // initialize the LED pins:
 for (int thisPin = 2; thisPin < 7; thisPin++) {
 pinMode(thisPin, OUTPUT);
 }
}

void loop() {
 // read the sensor:
 if (Serial.available() > 0) {
 int inByte = Serial.read();
 // do something different depending on the character received.
 // The switch statement expects single number values for each case;
 // in this exmaple, though, you're using single quotes to tell
 // the controller to get the ASCII value for the character. For
 // example 'a' = 97, 'b' = 98, and so forth:

switch (inByte) {
 case 'a':
 digitalWrite(2, HIGH);
 break;
 case 'b':
 digitalWrite(3, HIGH);
 break;
 case 'c':
 digitalWrite(4, HIGH);
 break;
 case 'd':
 digitalWrite(5, HIGH);
 break;
 case 'e':
 digitalWrite(6, HIGH);
 break;
 default:
 // turn all the LEDs off:
 for (int thisPin = 2; thisPin < 7; thisPin++) {
 digitalWrite(thisPin, LOW);
 }
 }
 }
}

SNAG- 16 07 06 23 19 34.jpg

 

5.6. WhileStatementConditional
WhileStatementConditional

/*
 Conditionals - while statement

This example demonstrates the use of while() statements.

While the pushbutton is pressed, the sketch runs the calibration routine.
 The sensor readings during the while loop define the minimum and maximum
 of expected values from the photo resistor.

This is a variation on the calibrate example.

The circuit:
 * photo resistor connected from +5V to analog in pin 0
 * 10K resistor connected from ground to analog in pin 0
 * LED connected from digital pin 9 to ground through 220 ohm resistor
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground

created 17 Jan 2009
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/WhileLoop
*/

// These constants won't change:
const int sensorPin = A2; // pin that the sensor is attached to
const int ledPin = 9; // pin that the LED is attached to
const int indicatorLedPin = 13; // pin that the built-in LED is attached to
const int buttonPin = 2; // pin that the button is attached to

// These variables will change:
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
int sensorValue = 0; // the sensor value


void setup() {
 // set the LED pins as outputs and the switch pin as input:
 pinMode(indicatorLedPin, OUTPUT);
 pinMode(ledPin, OUTPUT);
 pinMode(buttonPin, INPUT);
}

void loop() {
 // while the button is pressed, take calibration readings:
 while (digitalRead(buttonPin) == HIGH) {
 calibrate();
 }
 // signal the end of the calibration period
 digitalWrite(indicatorLedPin, LOW);

// read the sensor:
 sensorValue = analogRead(sensorPin);

// apply the calibration to the sensor reading
 sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

// in case the sensor value is outside the range seen during calibration
 sensorValue = constrain(sensorValue, 0, 255);

// fade the LED using the calibrated value:
 analogWrite(ledPin, sensorValue);
}

void calibrate() {
 // turn on the indicator LED to indicate that calibration is happening:
 digitalWrite(indicatorLedPin, HIGH);
 // read the sensor:
 sensorValue = analogRead(sensorPin);

// record the maximum sensor value
 if (sensorValue > sensorMax) {
 sensorMax = sensorValue;
 }

// record the minimum sensor value
 if (sensorValue < sensorMin) {
 sensorMin = sensorValue;
 }
}

 

 

06. Sensors

SNAG- 16 06 27 00 20 01.jpg

 

 

6.1. ADXL3xx
ADXL3xx

 

 

6.2. Knock
Knock

/* Knock Sensor

This sketch reads a piezo element to detect a knocking sound.
 It reads an analog pin and compares the result to a set threshold.
 If the result is greater than the threshold, it writes
 "knock" to the serial port, and toggles the LED on pin 13.

The circuit:
 * + connection of the piezo attached to analog in 0
 * - connection of the piezo attached to ground
 * 1-megohm resistor attached from analog in 0 to ground

http://www.arduino.cc/en/Tutorial/Knock

created 25 Mar 2007
 by David Cuartielles <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

*/


// these constants won't change:
const int ledPin = 13; // led connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 100; // threshold value to decide when the detected sound is a knock or not


// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light

void setup() {
 pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
 Serial.begin(9600); // use the serial port
}

void loop() {
 // read the sensor and store it in the variable sensorReading:
 sensorReading = analogRead(knockSensor);

// if the sensor reading is greater than the threshold:
 if (sensorReading >= threshold) {
 // toggle the status of the ledPin:
 ledState = !ledState;
 // update the LED pin itself:
 digitalWrite(ledPin, ledState);
 // send the string "Knock!" back to the computer, followed by newline
 Serial.println("Knock!");
 }
 delay(100); // delay to avoid overloading the serial port buffer
}

 

SNAG- 16 07 06 23 24 42.jpg

 

6.3. Memsic2125
Memsic2125

/*
 Memsic2125

Read the Memsic 2125 two-axis accelerometer. Converts the
 pulses output by the 2125 into milli-g's (1/1000 of earth's
 gravity) and prints them over the serial connection to the
 computer.

The circuit:
 * X output of accelerometer to digital pin 2
 * Y output of accelerometer to digital pin 3
 * +V of accelerometer to +5V
 * GND of accelerometer to ground

http://www.arduino.cc/en/Tutorial/Memsic2125

created 6 Nov 2008
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

*/

// these constants won't change:
const int xPin = 2; // X output of the accelerometer
const int yPin = 3; // Y output of the accelerometer

void setup() {
 // initialize serial communications:
 Serial.begin(9600);
 // initialize the pins connected to the accelerometer
 // as inputs:
 pinMode(xPin, INPUT);
 pinMode(yPin, INPUT);
}

void loop() {
 // variables to read the pulse widths:
 int pulseX, pulseY;
 // variables to contain the resulting accelerations
 int accelerationX, accelerationY;

// read pulse from x- and y-axes:
 pulseX = pulseIn(xPin, HIGH);
 pulseY = pulseIn(yPin, HIGH);

// convert the pulse width into acceleration
 // accelerationX and accelerationY are in milli-g's:
 // earth's gravity is 1000 milli-g's, or 1g.
 accelerationX = ((pulseX / 10) - 500) * 8;
 accelerationY = ((pulseY / 10) - 500) * 8;

// print the acceleration
 Serial.print(accelerationX);
 // print a tab character:
 Serial.print("\t");
 Serial.print(accelerationY);
 Serial.println();

delay(100);
}

 

 

6.4.1.  Ping))) – Sensor Ultrasónico HC-SR03

Ping

6.4.1.1  Descripción del HC-SR03

  • Es un sensor de distancias por ultrasonidos capaz de detectar objetos y calcular la distancia a la que se encuentra en un rango de 2 a 300 cm.
  • Funciona por ultrasonidos
  • Contiene toda la electrónica encargada de hacer la medición
  • Su uso es tan sencillo como enviar el pulso de arranque y medir la anchura del pulso de retorno
  • De muy pequeño tamaño
  • Se destaca por su bajo consumo, gran precisión
  • El HC-SR03 es un sensor ultrasónico de bajo costo que no sólo puede detectar si un objeto se presenta, como un sensor PIR (Passive Infrared Sensor)
  • También puede sentir y transmitir la distancia al objeto.
  • Tienen dos transductores, básicamente, un altavoz y un micrófono.
  • Ofrece una excelente detección sin contacto (remoto) con elevada precisión y lecturas estables en un formato fácil de usar.
  • El funcionamiento no se ve afectado por la luz solar o el material negro como telémetros ópticos.
  • Aunque acústicamente materiales suaves como telas pueden ser difíciles de detectar.
  • La velocidad del sonido en el aire (a una temperatura de 20 °C) es de 343 m/s.
  • Por cada grado centígrado que sube la temperatura, la velocidad del sonido aumenta en 0,6 m/s.

SNAG- 16 08 04 07 28 26.jpg

6.4.1.2 Características del HC-SR03

  • Los módulos incluyen transmisores ultrasónicos, el receptor y el circuito de control.
  • Número de pines:
    • VCC: Tensión de alimentación +5V (4.5V min – 5.5V max)
    • SG: (Señal)
    • GND: Tierra (Ground)
  • Corriente de reposo: < 2mA
  • Corriente de trabajo: 15mA
  • Ángulo de medición: 30º
  • Ángulo de medición efectivo: < 15º
  • Rango mínimo de detección: 2 cm
  • Rango máximo de detección de 3 m
  • Frecuencia de trabajo: 40KHz para 200 µs
  • Duración mínima del pulso de disparo (nivel TTL): 2 μS
  • Pulso echo: Pulso TTL positivo, 115 µs a 18.5 ms
  • Señal de salida de alto nivel: 5V
  • Señal de salida de bajo nivel: 0V

SNAG- 16 08 06 05 48 01.jpg

https://www.pololu.com/file/0J212/Distance_with_PING.pdf

 

 

La velocidad del sonido en el aire (a una temperatura de 20 °C) es de 343 m/s.
Por cada grado centígrado que sube la temperatura, la velocidad del sonido aumenta en 0,6 m/s.
Es decir a 25ºC es de v=343m/s+5×0.6m/s=346 m/s
La duración del pulso viene dado en microsegundos.
1 seg=1000000 microseg.
La distancia recorrida por el pulso es la suma del recorrido ida y el de regreso
Por lo que la distancia a la que se encuentra el objeto es la mitad de lo recorrido por el pulso.

SNAG-0007 2016 08 25 01 38 07.png   distancia = velocidad * tiempo / 2
d=v.t/2
t=pulso en microsegundos
1 m = 100 cm
d=346 m/seg pulso /2
d=34600 cm/1000000 /microseg pulso /2
d=pulso 34600/1000000/2
d=0.0173 pulso en cm

SNAG- 16 08 04 07 35 57.jpg

SNAG- 16 08 04 02 11 50

/* Ping))) - Sensor Ultrasónico HC-SR03 - Arduino IDE
 Este sketch lee un PING))) sensor de ultrasonidos y devuelve la
 distancia a objeto mas cercano. Para hacer eso, envía un pulso
 al sensor para iniciar una lectura, luego se dispone a recibir
 un pulso de respuesta. La longitud del pulso recibido es
 proporcional a la distancia entre objeto y sensor.
El circuito:
 * +V  conección del PING)))  a +5V
 * GND conección del PING)))  a tierra
 * SIG conección del PING)))  al pin digital 7
http://www.arduino.cc/en/Tutorial/Ping
Creada el 3 Nov 2008 por David A. Mellis, modificada el 30 Aug 2011 por Tom Igoe
El código de este ejemplo es de dominio público.   */

// esta constante no cambiará. It's the pin number
// Es el número de PIN de la salida del sensor:
const int pingPin = 7;

void setup() {
 // inicializa la comunicación serial:
 Serial.begin(9600);
}

void loop() {
 // establece las variables para la duración del ping,
 // y la distancia resultante en pulgadas y centímetros:
 long duration, inches, cm;

// El PING))) es desencadenado por un pulso ALTO de 2 o mas milisegundos.
// De antemano da un corto pulso BAJO para asegurar un pulso ALTO limpioe:
 pinMode(pingPin, OUTPUT);
 digitalWrite(pingPin, LOW);
 delayMicroseconds(2);
 digitalWrite(pingPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(pingPin, LOW);
// se usa el mismo pin para leer la señal desde PING))):
// un pulso ALTO cuya duración es el tiempo en (en milisegundos)
// desde el envío del ping hasta la recepción de su eco desde un objeto.
 pinMode(pingPin, INPUT);
 duration = pulseIn(pingPin, HIGH);
// convierte el tiempo en una distancia
 inches = microsecondsToInches(duration);
 cm = microsecondsToCentimeters(duration);
 Serial.print(inches);
 Serial.print("in, ");
 Serial.print(cm);
 Serial.print("cm");
 Serial.println();
 delay(100);   }

 // De acuerdo a la hoja de datos de Paralla para el PING))),
 // hay 73.746 milisegundos por pulgada.
 // (p.e. el sonido viaja a 1130 pies por segundo).
 // Esto dá la distancia viajada por el ping, entre ida y regreso,
 // por lo que debemos dividir entre 2 para obtener la distancia
 // hasta el obstáculo
 // Ver: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;    }
 // La velocidad del sonido es de 340 m/s o 29 microsegundos por centimetro.
 // El ping viaja tanto de ida como de regreso, de forma tal que para encontrar
 // la distancia al objeto debemos tomar la mitad de la distancia viajada
 // por el ping.
long microsecondsToCentimeters(long microseconds) { 
return microseconds / 29 / 2;  }

 

Ping-123D.gif

Ping.gif

Podemos observar en el GIF anterior que la distancia de corte mínima es de 20 cm y la distancia de corte máxima es de 300 cm y se define automáticamente sin necesidad de darles valores previamente.

 

Visualino carece de pulseIn

pinMode(pingPin, INPUT);
 duration = pulseIn(pingPin, HIGH);              /* en Ping)))-Mixly */

pero Mixly si la tiene en:   SNAG- 16 08 04 02 33 12

SNAG- 16 08 04 02 34 13.jpg     SNAG- 16 08 04 02 34 44

También definimos en Mixly las funciones:

long microsecondsToInches(long microseconds) {
        return microseconds / 74 / 2;    }        /* en Ping)))-Aduino IDE */

SNAG- 16 08 04 06 47 27.jpg

long microsecondsToInches(float microseconds) { 
        return microseconds / 148; }             /* en Ping)))-Mixly */

y

long microsecondsToCentimeters(long microseconds) { 
return microseconds / 29 / 2;  }                 /* en Ping)))-Aduino IDE */

SNAG- 16 08 04 06 50 55.jpg

long microsecondsToCentimeters(float microseconds) { 
        return microseconds / 58; }               /* en Ping)))-Mixly */

 

SNAG- 16 08 04 05 16 19.jpg

SNAG- 16 08 04 05 13 41

SNAG- 16 08 04 05 06 51.jpg

/***  Ping))) - Sensor Ultrasónico HC-SR03 - Mixly  ***/
long pingPin; 
long duration; 
long microseconds; 
long inches; 
long cm; 
long microsecondsToInches(float microseconds) { 
        return microseconds / 148; } 
long microsecondsToCentimeters(float microseconds) { 
        return microseconds / 58; } 
 
void setup()           { 
 pingPin = 7; 
 duration = 0; 
 inches = 0; 
 cm = 0; 
 microseconds = 0; 
 pinMode(pingPin, INPUT); 
 Serial.begin(9600);    } 
 
 void loop()            { 
 pinMode(pingPin, OUTPUT); 
 digitalWrite(pingPin,LOW); 
 delay(2); 
 pinMode(pingPin, OUTPUT); 
 digitalWrite(pingPin,HIGH); 
 delay(5); 
 pinMode(pingPin, OUTPUT); 
 digitalWrite(pingPin,LOW); 
 duration = pulseIn(pingPin, HIGH); 
 inches = microsecondsToInches(duration); 
 cm = microsecondsToCentimeters(duration); 
 Serial.print(inches); 
 Serial.print(String("in ")); 
 Serial.print(cm); 
 Serial.print(String("cm")); 
 Serial.println(String(" ")); 
 delay(100);               }

Ping-Mixly-123D.gif

 

6.4.2  Sensor Ultrasónico HC-SR04

SNAG- 16 08 04 08 09 46.jpg

6.4.2.1  Descripción del HC-SR04

  • Es un sensor de distancias por ultrasonidos capaz de detectar objetos y calcular la distancia a la que se encuentra en un rango de 2 a 450 cm.
  • Funciona por ultrasonidos
  • Contiene toda la electrónica encargada de hacer la medición
  • Su uso es tan sencillo como enviar el pulso de arranque y medir la anchura del pulso de retorno
  • De muy pequeño tamaño
  • Se destaca por su bajo consumo, gran precisión
  • El HC-SR04 es un sensor ultrasónico de bajo costo que no sólo puede detectar si un objeto se presenta, como un sensor PIR (Passive Infrared Sensor)
  • También puede sentir y transmitir la distancia al objeto.
  • Tienen dos transductores, básicamente, un altavoz y un micrófono.
  • Ofrece una excelente detección sin contacto (remoto) con elevada precisión y lecturas estables en un formato fácil de usar.
  • El funcionamiento no se ve afectado por la luz solar o el material negro como telémetros ópticos.
  • Aunque acústicamente materiales suaves como telas pueden ser difíciles de detectar.
  • La velocidad del sonido en el aire (a una temperatura de 20 °C) es de 343 m/s.
  • Por cada grado centígrado que sube la temperatura, la velocidad del sonido aumenta en 0,6 m/s.

SNAG- 16 08 06 05 08 32.jpg

6.4.2.2 Características del HC-SR04

  • Los módulos incluyen transmisores ultrasónicos, el receptor y el circuito de control.
  • Número de pines:
    • VCC: Tensión de alimentación +5V (4.5V min – 5.5V max)
    • TRIG: (Disparo del ultrasonido) Trigger entrada (input) del sensor (TTL)
    • ECHO: (Recepción del ultrasonido) Echo salida (output) del Sensor (TTL)
    • GND: Tierra (Ground)
  • Corriente de reposo: < 2mA
  • Corriente de trabajo: 15mA
  • Ángulo de medición: 30º
  • Ángulo de medición efectivo: < 15º
  • Rango mínimo de detección: 1.7 cm
  • Rango máximo de detección de 4 m
  • Sirve a más de 4m, pero el fabricante no garantiza una buena medición
  • La precisión puede variar entre los 3mm
  • Frecuencia de trabajo: 40KHz
  • Duración mínima del pulso de disparo (nivel TTL): 10 μS
  • Duración del pulso eco de salida (nivel TTL): 100-25000 μS
  • Tiempo mínimo de espera entre una medida y el inicio de otra 20 mS
  • Señal de salida de alto nivel: 5V
  • Señal de salida de bajo nivel: 0V

 

SNAG- 16 08 04 08 00 24.jpg

6.4.2.3  HC-SR04

 

SNAG- 16 08 15 20 35 08.jpg

/*** Sensor ultrasónico HC-SR04 - Arduino IDE ***/ 
/*** Imprime la distancia en el Monitor Serie ***/
int Trig = 12;
int Echo = 11;
float v=331.5+0.6*20;                        // m/s

void setup()                {
     Serial.begin(9600);
     pinMode(Trig, OUTPUT);
     pinMode(Echo, INPUT);   }
float FuncionDistancia()     {
     // send sound pulse
     digitalWrite(Trig, LOW);
     delayMicroseconds(3);
     digitalWrite(Trig, HIGH);
     delayMicroseconds(5);
     digitalWrite(Trig, LOW);
     // listen for echo
     float pulso = pulseIn(Echo, HIGH);        // microseconds
     float t = pulso / 1000.0 / 1000.0 / 2;    // s
     float d = t*v;                            // m
     return d*100;           }                 // cm

void loop()                  {
     int distancia=FuncionDistancia();
     Serial.println(distancia);
     delay(200);              }                // ms

Sensor ultrasónico HC-SR04 - Arduino IDE.gif

SNAG- 16 08 15 20 34 38.jpg

SNAG- 16 08 15 15 13 14.jpg

 

Sensor ultrasonico HC-SR04-Mixly.gif

SNAG- 16 08 15 19 24 02.jpg

/*** Sensor Ultrasónico HC-SR04 - Mixly ***/
/*** Imprime la distancia en el Monitor Serie ***/
long Trig; 
float distancia; 
long Echo; 
float v; 
float d; 
float pulso; 
float t; 
 
float FuncionDistancia()   { 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     delay(3); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,HIGH); 
     delay(5); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     pulso = pulseIn(Echo, HIGH); 
     t = ((pulso / 1000) / 1000) / 2;
     d = t * v; 
     return d * 100;       } 
 
void setup()               { 
     Trig = 12; 
     Echo = 11; 
     v = 331.5 + 0.6 * 20; 
     pulso = 0; 
     t = 0; 
     d = 0; 
     distancia = 0; 
     pinMode(Echo, INPUT); 
     Serial.begin(9600);    } 
 
void loop()                 { 
     distancia = FuncionDistancia(); 
     Serial.println(distancia); 
     delay(200);            }

Sensor Ultrasónico HC-SR04 - Mixly.gif

sensor ultrasonico gif.gif

 Simplificamos el código del sketch usando los cálculos siguientes

v = velocidad a la que viaja el pulso en el aire.
La velocidad del sonido en el aire (a una temperatura de 20 °C) es de 343 m/s.
Por cada grado centigrado que sube la temperatura, la velocidad del sonido aumenta en 0,6 m/s.
Es decir a 25ºC es de:
v = 343+5x0.6
v = 346 m/s

1 seg = 1000000 microseg.
1 m = 100 cm

t = pulso = tiempo de duración del pulso en microsegundos (ida y regreso)

v.t = distancia recorrida por el pulso es la suma de la de ida y regreso.

d = distancia a la que se encuentra el objeto es la mitad
    de lo recorrido por el pulso.

SNAG-0007 2016 08 25 01 38 07.png   distancia = velocidad * tiempo / 2
d = v.t/2
d = 346 m/seg pulso /2
d = 34600 cm/1000000 /microseg pulso /2
d = pulso 34600/1000000/2
d = 0.0173 pulso (en cm)

 

/*** Sensor ultrasónico HC-SR04 - Arduino IDE - Simplificado ***/ 
/*** Imprime la distancia en el Monitor Serie ***/
int Trig = 12;
int Echo = 11;
float pulso=0;
float d=0;

void setup()                {
     Serial.begin(9600);
     pinMode(Trig, OUTPUT);
     pinMode(Echo, INPUT);   }
     // envia el pulso ultrasónico
     digitalWrite(Trig, LOW);
     delayMicroseconds(3);
     digitalWrite(Trig, HIGH);
     delayMicroseconds(5);
     digitalWrite(Trig, LOW);
     // recibe el eco del pulso ultrasónico
     pulso= pulseIn(Echo, HIGH);     // mms

void loop()                  {
     d = 0.0173 pulso;                // cm
     Serial.println(d);
     delay(200);              }       // mms

SNAG- 16 08 15 15 13 14.jpg

 

Sensor ultrasónico HC-SR04 - Mixly - Simplificado2.gif

SNAG-0000 2016 08 21 10 41 30

/*** Sensor ultrasónico HC-SR04 - Mixly - Simplificado ***/ 
/*** Imprime la distancia en el Monitor Serie ***/
long Trig; 
long Echo; 
float pulso; 
float d; 
 
void setup()  { 
     Trig = 12; 
     Echo = 11; 
     pulso = 0; 
     d = 0; 
     pinMode(Echo, INPUT); 
     Serial.begin(9600);    } 
 
void loop()   { 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     delayMicroseconds(3); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,HIGH); 
     delayMicroseconds(5); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     pulso = pulseIn(Echo, HIGH); 
     d = 0.0173 * pulso; 
     Serial.println(d); 
     delayMicroseconds(200);   }

 

Visualino no posee soporte para la función

pulseIn(Echo, HIGH);   como en Mixly  SNAG-0007 2016 08 21 16 43 38.png

Sin embargo Visualino tiene un bloque operadores Zum, entre ellos un sensor de ultrasonidos en

SNAG-0006 2016 08 21 16 32 48

SNAG-0005 2016 08 21 16 31 18.png

Vamos a usarlo para hacer un sketch de Arduino.

SNAG-0003 2016 08 21 16 17 23.png

SNAG-0004 2016 08 21 16 17 50.png

/***  Sensor ultrasónico HC-SR04 - Visualino - Simplificado   ***/
/*** Global variables ***/
long Trig;
long Echo;
float d;

/*** Function declaration ***/
//bqBAT
long TP_init(int trigger_pin, int echo_pin);
long Distance(int trigger_pin, int echo_pin);

void setup() {
     Trig=12;
     Echo=11;
     d=0;
     Serial.begin(9600); }

void loop()    {
     pinMode( Echo , INPUT );
     pinMode( Trig , OUTPUT );
     d=Distance(Trig,Echo);
     Serial.println(d);
     delay(200); }

/*** Function definition ***/
     //bqBAT
long TP_init(int trigger_pin, int echo_pin)  {
     digitalWrite(trigger_pin, LOW);
     delayMicroseconds(2);
     digitalWrite(trigger_pin, HIGH);
     delayMicroseconds(10);
     digitalWrite(trigger_pin, LOW);
     long microseconds = pulseIn(echo_pin ,HIGH);
     return microseconds;           }
long Distance(int trigger_pin, int echo_pin)  {
     long microseconds = TP_init(trigger_pin, echo_pin);
     long distance;
     distance = microseconds/29/2;
     if (distance == 0){ distance = 999; }
     return distance; }

HC-SR04-Visualino-Monitor.gif

 

podemos observar que

microseconds = pulseIn(echo_pin ,HIGH);
     distance = microseconds/29/2;
     distance = 0.01724 microseconds;

muy cercano al valor de

     distance = 0.0173 microseconds;

que hemos propuesto previamente, para una temperatura de 25ºC.

 

 La añadimos al código del sketch simplificado anterior, LEDs que  parpadean y advertencia de lejanía por el puerto serial.

SNAG-0003 2016 08 22 18 48 50.png

int dMIN = 15;
int dMAX = 200;
int ledMIN = 7;      // led verde
int ledMAX = 13;     // led amarillo

pinMode(ledMIN, OUTPUT); 
pinMode(ledMAX, OUTPUT);
Serial.begin(9600);

if (d < dMIN)   { digitalWrite(ledMIN,HIGH); }
else            { digitalWrite(ledMIN,LOW);  }

if (d >= dMAX || d <= 0) 
      { Serial.println("sensor fuera del rango MÁXimo");
        digitalWrite(ledMAX,HIGH); }
else  { Serial.print(d);  Serial.println(" cm");
        digitalWrite(ledMAX,LOW); }

 

en Mixly

SNAG-0010 2016 08 22 00 06 23.png

en Visualino

SNAG-0014 2016 08 22 02 07 31.png

SNAG-0001 2016 08 22 18 47 45.png

 

SNAG-0008 2016 08 21 22 09 21.png

SNAG-0006 2016 08 22 18 49 38.png

/*** Sensor ultrasónico HC-SR04 - Arduino IDE - Simplificado ***/ 
/*** Con LEDs que avisan y advertencias por el puerto serial ***/
/*** Imprime la distancia en el Monitor Serie ***/
int Trig = 12;
int Echo = 11;
int ledMIN = 7;      // led verde
int ledMAX = 13;     // led amarillo
float pulso=0;
float d=0;
int dMIN = 15;
int dMAX = 200;

void setup()                {
     Serial.begin(9600);
     pinMode(Trig, OUTPUT);
     pinMode(Echo, INPUT);
     pinMode(ledMIN, OUTPUT); 
     pinMode(ledMAX, OUTPUT); 
     // envia el pulso ultrasónico
     digitalWrite(Trig, LOW);
     delayMicroseconds(3);
     digitalWrite(Trig, HIGH);
     delayMicroseconds(5);
     digitalWrite(Trig, LOW);
     // recibe el eco del pulso ultrasónico
     pulso= pulseIn(Echo, HIGH);     // mms
                           }

void loop()     {
     d = 0.0173 pulso;               // cm
     if (d < dMIN) { digitalWrite(ledMIN,HIGH); }
     else { digitalWrite(ledMIN,LOW); }
     if (d >= dMAX || d <= 0) 
         { Serial.println("sensor fuera del rango MÁXimo");
          digitalWrite(ledMAX,HIGH); }
     else { Serial.print(d); Serial.println(" cm");
            digitalWrite(ledMAX,LOW); }
     delay(200);  }                  // mms

 

SNAG-0004 2016 08 22 18 49 04.png

Sensor Ultrasonico HC-SR04 b 2.gif

SNAG-0009 2016 08 21 23 50 57.png

/*** Sensor ultrasónico HC-SR04 - Mixly - Simplificado ***/ 
/*** Con LEDs que avisan y advertencias por el puerto serial ***/
/*** Imprime la distancia en el Monitor Serie ***/
long Trig; 
long Echo; 
long ledMIN; 
long ledMAX; 
float pulso; 
float d; 
long dMIN; 
long dMAX; 
 
void setup() { 
     Trig = 12; 
     Echo = 11; 
     ledMIN = 7; 
     ledMAX = 13; 
     pulso = 0; 
     d = 0; 
     dMIN = 15; 
     dMAX = 200; 
     pinMode(Echo, INPUT); 
     Serial.begin(9600); 
            } 
  
void loop() { 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     delayMicroseconds(3); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,HIGH); 
     delayMicroseconds(5); 
     pinMode(Trig, OUTPUT); 
     digitalWrite(Trig,LOW); 
     pulso = pulseIn(Echo, HIGH); 
     d = 0.0173 * pulso; 
     if (d < dMIN) { 
              pinMode(ledMIN, OUTPUT); 
              digitalWrite(ledMIN,HIGH); 
     } else { pinMode(ledMIN, OUTPUT); 
              digitalWrite(ledMIN,LOW);  } 
     if (d >= dMAX || d <= 0) { 
              Serial.println(String("sensor fuera del rango MAXimo")); 
              pinMode(ledMAX, OUTPUT); 
              digitalWrite(ledMAX,HIGH); 
     } else { Serial.print(d); 
              Serial.println(String(" cm")); 
     pinMode(ledMAX, OUTPUT); 
     digitalWrite(ledMAX,LOW);  } 
     delayMicroseconds(500); 
           }

 

SNAG-0005 2016 08 22 18 49 25

Sensor Ultrasonico HC-SR04 Visualino-Simplificado b.gif

SNAG-0012 2016 08 22 01 50 42.png

/*** Sensor ultrasónico HC-SR04 - Visualino - Simplificado ***/ 
/*** Con LEDs que avisan y advertencias por el puerto serial ***/
/*** Imprime la distancia en el Monitor Serie ***/
/*** Global variables ***/
long Trig;
long Echo;
long ledMIN;
long ledMAX;
float d;
long dMIN;
long dMAX;

/*** Function declaration ***/
//bqBAT
long TP_init(int trigger_pin, int echo_pin);
long Distance(int trigger_pin, int echo_pin);

void setup() {
     Trig=12;
     Echo=11;
     ledMIN=7;
     ledMAX=13;
     d=0;
     dMIN=15;
     dMAX=200;
     Serial.begin(9600);
              }

void loop()     {
     pinMode( Echo , INPUT );
     pinMode( Trig , OUTPUT );
     d=Distance(Trig,Echo);
     if (d < dMIN) {
         pinMode(ledMIN,OUTPUT);
         digitalWrite(ledMIN,HIGH);
     } else {
         pinMode(ledMIN,OUTPUT);
         digitalWrite(ledMIN,LOW);
             }
      if ((d >= dMAX) || (d <= 0)) {
         Serial.println("sensor fuera del rango MAXimo");
         pinMode(ledMAX,OUTPUT);
         digitalWrite(ledMAX,HIGH);
      } else {
         Serial.print(d);
         Serial.println(" cm");
         pinMode(ledMAX,OUTPUT);
         digitalWrite(ledMAX,LOW);
              }
 delay(500);
                 }

/*** Function definition ***/
//bqBAT
long TP_init(int trigger_pin, int echo_pin)
     { digitalWrite(trigger_pin, LOW);
       delayMicroseconds(2);
       digitalWrite(trigger_pin, HIGH);
       delayMicroseconds(10);
       digitalWrite(trigger_pin, LOW);
       long microseconds = pulseIn(echo_pin ,HIGH);
       return microseconds;
      }
long Distance(int trigger_pin, int echo_pin)
      { long microseconds = TP_init(trigger_pin, echo_pin);
        long distance;
        distance = microseconds/29/2;
        if (distance == 0)  { distance = 999; }
        return distance;
       }

 

Sensorultrasonico HC-SR04 b.gif

 

 

6.4.2.4  Inconvenientes del HC-SR04

El sensor ultrasónico HC-SR04 tiene el problema de que cuando mide una “distancia infinita” (fuera de rango) queda bloqueado.

El dispositivo, una vez disparado (TRIGGER), espera un pulso por el pin ECHO. Si no tiene o no funciona un timeout que lo saque de la espera, se quedará bloqueado al no recibir el
eco.

Tenemos las soluciones a continuación:

  1. Desbloqueo con Arduino IDE:
    • Detectar un bloqueo
    • Realizar la siguiente secuencia en ARDUINO:
      • Definir el pin ECHO como salida, ponerlo en estado bajo
      • hacer un pequeño delay (empezar con 100ms)
      • volverlo a definir como entrada. Eso debe sacarlo de su bloqueo.
  2. Desbloqueo con Visualino:
    • Apagar/encender el sensor.
    • Vamos, reinicializarlo (no el programa, el sensor). Se puede conseguir
      alimentando el sensor (Vcc) a través de un transistor que se active por otro pin de ARDUINO que cuando detecte un bloqueo lo apague momentáneamente.

 

6.4.2.5   Sensor Ultrasónico HC-SR04

Desbloqueo con Arduino IDE del problema de falta de tiempo de espera
(lack of timeout problem) usando la librería NewPing.h

 

SNAG- 16 08 06 05 00 03.jpg

SNAG- 16 08 05 03 57 16.jpg

/*** Sensor Ultrasónico HC-SR04 - solution to lack of timeout problem) ***/
/* Modificamos le parpadeo de un LED de acuerdo a la distancia
 del HC-SR04 a un obstáculo */
/* Umbral a 14 cm
Si no regresa la señal al pin ECHO (lack of timeout)
muestra 0,0,0... cm reiteradamente
Solución al timeout  0,0,0,0,0,0,... */
/* When I detect the sensor is stuck, I simply switch echo pin to OUTPUT,
put it into LOW state, and after a while re-set it to INPUT, then cycle
again. */
/* Componentes del circuito:
   * sensor ultrasónico HC-SR04
   * diodo LED
   * resistencia de 220 ohmios   */
/* conexiones del sensor HC-SR04:
     trigger 12
     echo 11
     Gnd tierra (GND)
     Vcc 5V
     LED 8    */
 
#include <NewPing.h>   //libreria que maneja el sensor HC-SR04
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11   // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200
int x;                //distancia hasta el obstaculo
int intentos = 0;     //num de veces que pone 0 cm
int led = 8;
           // NewPing configura los pines y la distancia max detectada
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
void setup()  {
 Serial.begin(115200);      // Abre el monitor serie a 115200 baudios
 pinMode (led, OUTPUT);
              }
 
void loop()    {
    delay(50);
           // Send ping, get ping time in microseconds (uS)
    unsigned int uS = sonar.ping();
    Serial.print("Ping: ");
    x = uS / US_ROUNDTRIP_CM;      // distancia en cm
    Serial.print(x);
    Serial.println("cm");
        //Solucion do{} ... while()
        //para cuando el pin ECHO no recibe rebote de señal
        //el timer no se detiene y aparecen 0,0,0,... cm constantemente.
    do {
        delay(100);
        pinMode(ECHO_PIN, OUTPUT);
        digitalWrite(ECHO_PIN, LOW);
        delay(100);
        pinMode(ECHO_PIN, INPUT);
      } 
   while (x == 0 && ++intentos < 3);
   if (x < 14 && x!=0)   {   //si X < 14 cm y distinto de 0, cambia el parpadeo
       digitalWrite ( led , HIGH) ;
       delay(50);
       digitalWrite( led , LOW) ;
       delay(50);      }    //fin del if
   else {
       digitalWrite ( led , HIGH) ;
       delay(250);
       digitalWrite( led , LOW) ;
       delay(250);
        }        //fin del else
              }      //fin del loop()

 

SNAG- 16 08 05 03 58 11.jpg

 

Para manejar el sensor de ultrasonidos usaremos la libreria NewPing explicada en http://www.arduino.cc y que podemos descargar a partir del siguiente enlace:

https://bitbucket.org/teckel12/arduino-new-ping/downloads

 

SNAG- 16 08 06 05 00 15

SNAG- 16 08 05 03 58 56.jpg
Para instalar la librería en el IDE de Arduino usaremos el enlace:

http://www.prometec.net/librerias/

Donde nos indica como instalar y desinstalar librerías en el IDE de Arduino.

 

SNAG- 16 08 05 03 59 57.jpg
Referencia inicial:

https://forum.arduino.cc/index.php?topic=55119.15

 

Referencia secundaria:

 

http://www.picuino.com/es/uno-doc/ultrasonic.html

 

https://tecnoclara.wikispaces.com/Arduino+UNO

 

 

 

6.4.2.6  Sensor Ultrasónico HC-SR04

Desbloqueo con Visualino del problema de falta de tiempo de espera
(lack of timeout problem) usando un transistor como interruptor.

 

SNAG- 16 08 06 03 52 07

https://www.youtube.com/watch?v=uXVSfRF6IS0

 

 

SNAG-0006 2016 08 25 00 33 34.png

Disposición de los electrodos de distintos encapsulados de transistores.

SNAG-0000 2016 08 25 20 32 07_edited

Lack of timeout problem solved

https://forum.arduino.cc/index.php?topic=55119.0

https://forum.arduino.cc/index.php?topic=55119.15

 

SNAG- 16 08 06 03 06 39.jpg

SNAG- 16 08 05 07 52 56.jpg

SNAG- 16 08 05 07 37 59.jpg

SNAG- 16 08 05 07 53 44.jpg

 

SNAG- 16 08 05 07 37 51.jpg

SNAG- 16 08 05 07 54 25.jpg

/*** Sensor Ultrasónico HC-SR04 - Visualino  ***/
/*** Lack of timeout problem solved 
Componentes del circuito:
* Sensor ultrasónico HC-SR04
* Transistor NPN BC109
* resistencia de 440 ohmios ***/

/*** Global variables ***/
int distancia;

/*** Function declaration ***/
     //bqBAT
long TP_init(int trigger_pin, int echo_pin);
long Distance(int trigger_pin, int echo_pin);

void setup()  {
     distancia=0;
     pinMode(5,OUTPUT);
     pinMode(13,OUTPUT);
     pinMode( 12 , INPUT );
     pinMode( 11 , OUTPUT );
     Serial.begin(9600);
              }

void loop()   {
     digitalWrite(5,HIGH);
     digitalWrite(13,LOW);
     distancia=Distance(11,12);
     if (distancia > 990)  {
        digitalWrite(5,LOW);
        digitalWrite(13,HIGH);
        delay(50);         }
      if ((distancia > 5) && (distancia < 100))
       { Serial.println(distancia);
         tone(8,261,5);
         delay(5);
         delay(distancia * 3);  }
             }

/*** Function definition ***/
     //bqBAT
long TP_init(int trigger_pin, int echo_pin)
{     digitalWrite(trigger_pin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigger_pin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger_pin, LOW);
      long microseconds = pulseIn(echo_pin ,HIGH);
      return microseconds;
}
long Distance(int trigger_pin, int echo_pin)
{     long microseconds = TP_init(trigger_pin, echo_pin);
      long distance;
      distance = microseconds/29/2;
      if (distance == 0){  distance = 999;  }
      return distance;
}

 

SNAG- 16 08 05 07 25 19.jpg

Activa el Pin digital 5 y enciende el sensor ultrasónico HC-SR04

 

SNAG- 16 08 05 07 26 06.jpg

Almacena la distancia detectada por el sensor

 

SNAG- 16 08 05 07 36 49.jpg

Si la distancia es mayor que 990 y  el pin digital 5 está bajo entonces enciende el led en la placa conectado al pin digital 13

 

SNAG- 16 08 05 07 28 04.jpg

En un rango de distancias entre 5 y 100, imprime la distancia por el puerto serie y toca un tono variable según la distancia.

 

 

Otro esquema encontrado en  #66

https://forum.arduino.cc/index.php?topic=55119.60

SNAG- 16 08 06 01 18 40.jpg

En

https://www.youtube.com/watch?v=5zCrG6opB4Q

encontramos

SNAG-0001 2016 08 25 16 51 15.png   SNAG-0001 2016 08 25 20 32 24_edited

donde se usa el transistor NPN BC547

SNAG-0002 2016 08 25 16 51 43.png

SNAG-0003 2016 08 25 16 52 17.png

 

 

 

 

6.4.3  Sensor Ultrasónico HY-SRF05

 

SNAG- 16 08 04 07 53 33.jpg

6.4.3.1  Descripción del HY-SRF05

  • Es un sensor de distancias por ultrasonidos capaz de detectar objetos y calcular la distancia a la que se encuentra en un rango de 1.7 a 400 cm.
  • Funciona por ultrasonidos
  • Contiene toda la electrónica encargada de hacer la medición
  • Su uso es tan sencillo como enviar el pulso de arranque y medir la anchura del pulso de retorno
  • De muy pequeño tamaño
  • Se destaca por su bajo consumo, gran precisión
  • El HY-SRF05 es un sensor ultrasónico de bajo costo que no sólo puede detectar si un objeto se presenta, como un sensor PIR (Passive Infrared Sensor)
  • También puede sentir y transmitir la distancia al objeto.
  • Tienen dos transductores, básicamente, un altavoz y un micrófono.
  • Ofrece una excelente detección sin contacto (remoto) con elevada precisión y lecturas estables en un formato fácil de usar.
  • El funcionamiento no se ve afectado por la luz solar o el material negro como telémetros ópticos.
  • Aunque acústicamente materiales suaves como telas pueden ser difíciles de detectar.
  • La velocidad del sonido en el aire (a una temperatura de 20 °C) es de 343 m/s.
  • Por cada grado centígrado que sube la temperatura, la velocidad del sonido aumenta en 0,6 m/s.

 

SNAG- 16 08 04 07 52 40

6.4.3.2 Características del HY-SRF05

  • Los módulos incluyen transmisores ultrasónicos, el receptor y el circuito de control.
  • Número de pines:
    • VCC: Tensión de alimentación +5V (4.5V min – 5.5V max)
    • TRIG: (Disparo del ultrasonido) Trigger entrada (input) del sensor (TTL)
    • ECHO: (Recepción del ultrasonido) Echo salida (output) del Sensor (TTL)
    • OUT:
    • GND: Tierra (Ground)
  • Corriente de reposo: < 2mA
  • Corriente de trabajo: 15mA
  • Ángulo de medición: 30º
  • Ángulo de medición efectivo: < 15º
  • Rango mínimo de detección: 1.7 cm
  • Rango máximo de detección de 4 m
  • Sirve a más de 4m, pero el fabricante no garantiza una buena medición
  • La precisión puede variar entre los 2mm
  • Frecuencia de trabajo: 40KHz
  • Duración mínima del pulso de disparo (nivel TTL): 10 μS
  • Duración del pulso eco de salida (nivel TTL): 100-25000 μS
  • Tiempo mínimo de espera entre una medida y el inicio de otra 20 mS
  • Señal de salida de alto nivel: 5V
  • Señal de salida de bajo nivel: 0V
  • El SRF05 es mecánicamente igual al SR04, por lo que puede ser un sustituto de este.
    Incluye un breve retardo después del pulso de eco para dar a los controladores más lentos como Basic Stamp y Picaxe el tiempo necesario para ejecutar sus pulsos en los comandos.
  • El sensor SRF05 tiene dos modos de funcionamiento, según se realicen las conexiones.

 

 

 

http://www.iesluisdelucena.es/dpp/docs/presentaciones/El_sensor_de_ultrasonidos_sfr05_rev091210.pdf

 

http://www.muchotrasto.com/srf05.php

 

6.4.3.3  Ventajas del HY-SRF05 con respecto al HC-SR04

El sensor ultrasónico HY-SRF05 no se queda bloqueado cuando mide una “distancia infinita” (fuera de rango) que deja bloqueado al HC-SR04

 

 

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

 

 

 

 

07. Display

SNAG- 16 06 27 00 20 55

 

7.1. LED barGraph
barGraph

/*   LED bar graph
  Turns on a series of LEDs based on the value of an analog sensor.
 This is a simple way to make a bar graph display. Though this graph
 uses 10 LEDs, you can use any number by changing the LED count
 and the pins in the array.
  This method can be used to control any series of digital outputs that
 depends on an analog input.
  The circuit:
 * LEDs from pins 2 through 11 to ground
  created 4 Sep 2010  by Tom Igoe
 This example code is in the public domain.
  http://www.arduino.cc/en/Tutorial/BarGraph   */

// these constants won't change:
const int analogPin = A0;  // the pin that the potentiometer is attached to
const int ledCount = 10;   // the number of LEDs in the bar graph

int ledPins[] = {  2, 3, 4, 5, 6, 7,8,9,10,11 };
 // an array of pin numbers to which LEDs are attached

void setup() {
 // loop over the pin array and set them all to output:
 for (int thisLed = 0; thisLed < ledCount; thisLed++) {
 pinMode(ledPins[thisLed], OUTPUT); 
 }
}

void loop() {
 // read the potentiometer:
 int sensorReading = analogRead(analogPin);
 // map the result to a range from 0 to the number of LEDs:
 int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

 // loop over the LED array:
 for (int thisLed = 0; thisLed < ledCount; thisLed++) {
 // if the array element's index is less than ledLevel,
 // turn the pin for this element on:
 if (thisLed < ledLevel) {
 digitalWrite(ledPins[thisLed], HIGH);
 } 
 // turn off all pins higher than the ledLevel:
 else {
 digitalWrite(ledPins[thisLed], LOW); 
 }
 }
}

 

LED bar graph-aldp.gif

/*** barGraph LED 2-13 controlada con potenciometro-Arduino IDE ***/
/*** Autodesk Circuits.io ***/
 const int analogPin = A0; 
 const int ledCount = 13;
 int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

void setup()     {
     for (int i = 0; i < ledCount; thisLed++)
     { pinMode(ledPins[i], OUTPUT); }
                  }

void loop()      {
     int sensorReading = analogRead(analogPin);
     int ledLevel = map(sensorReading, 0, 1023, 2, ledCount);
     for (int i = 0; i < ledCount; i++)    { 
          if (i < ledLevel) { digitalWrite(ledPins[i], HIGH); }
          else { digitalWrite(ledPins[i], LOW); }
                                           }
}

LED barGraph LED 2-13 controlada con potenciometro-Arduino IDE.gif

 

barGraph LED 2-13 controlado por potenciometro-Visualino.gif

SNAG- 16 07 19 12 57 21.jpg

/*** barGraph LED 2-13 controlada con potenciómetro-Visualino ***/
/*** Global variables ***/
int i=0;
int LED=0;
int variable=0;

/*** Function declaration ***/
void setup()            {
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(7,OUTPUT);
    pinMode(8,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(10,OUTPUT);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    pinMode(13,OUTPUT);

    digitalWrite(2,LOW);
    digitalWrite(3,LOW);
    digitalWrite(4,LOW);
    digitalWrite(5,LOW);
    digitalWrite(6,LOW);
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
 
    Serial.begin(9600);       }

void loop()          { 
    variable=analogRead(A0);
    LED=map(variable,0,1023,2,13);
    for (i = 2; i <= 13; i++) {
       if (i == LED) {
           pinMode(i,OUTPUT);
           digitalWrite(i,HIGH);
       } else {
           pinMode(i,OUTPUT);
           digitalWrite(i,LOW); }
               }
}
/*** Function definition ***/

Mega AnalogWrite-Visualiino.gif

 

 

7.2. RowColumnScanning
RowColumnScanning

/*
 Row-Column Scanning an 8x8 LED matrix with X-Y input

This example controls an 8x8 LED matrix using two analog inputs

created 27 May 2009, modified 30 Aug 2011 by Tom Igoe

This example works for the Lumex LDM-24488NI Matrix. See
 http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
 for the pin connections

For other LED cathode column matrixes, you should only need to change
 the pin numbers in the row[] and column[] arrays

rows are the anodes
cols are the cathodes
 ---------

Pin numbers:
 Matrix:
 * Digital pins 2 through 13,
 * analog pins 2 through 5 used as digital 16 through 19
 Potentiometers:
 * center pins are attached to analog pins 0 and 1, respectively
 * side pins attached to +5V and ground, respectively.

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/RowColumnScanning

see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more
 */

// 2-dimensional array of row pin numbers:
const int row[8] = {
 2, 7, 19, 5, 13, 18, 12, 16
};

// 2-dimensional array of column pin numbers:
const int col[8] = {
 6, 11, 10, 3, 17, 4, 8, 9
};

// 2-dimensional array of pixels:
int pixels[8][8];

// cursor position:
int x = 5;
int y = 5;

void setup() {
 // initialize the I/O pins as outputs
 // iterate over the pins:
 for (int thisPin = 0; thisPin < 8; thisPin++) {
 // initialize the output pins:
 pinMode(col[thisPin], OUTPUT);
 pinMode(row[thisPin], OUTPUT);
 // take the col pins (i.e. the cathodes) high to ensure that
 // the LEDS are off:
 digitalWrite(col[thisPin], HIGH);
 }

// initialize the pixel matrix:
 for (int x = 0; x < 8; x++) {
 for (int y = 0; y < 8; y++) {
 pixels[x][y] = HIGH;
 }
 }
}

void loop() {
 // read input:
 readSensors();

// draw the screen:
 refreshScreen();
}

void readSensors() {
 // turn off the last position:
 pixels[x][y] = HIGH;
 // read the sensors for X and Y values:
 x = 7 - map(analogRead(A0), 0, 1023, 0, 7);
 y = map(analogRead(A1), 0, 1023, 0, 7);
 // set the new pixel position low so that the LED will turn on
 // in the next screen refresh:
 pixels[x][y] = LOW;

}

void refreshScreen() {
 // iterate over the rows (anodes):
 for (int thisRow = 0; thisRow < 8; thisRow++) {
 // take the row pin (anode) high:
 digitalWrite(row[thisRow], HIGH);
 // iterate over the cols (cathodes):
 for (int thisCol = 0; thisCol < 8; thisCol++) {
 // get the state of the current pixel;
 int thisPixel = pixels[thisRow][thisCol];
 // when the row is HIGH and the col is LOW,
 // the LED where they meet turns on:
 digitalWrite(col[thisCol], thisPixel);
 // turn the pixel off:
 if (thisPixel == LOW) {
 digitalWrite(col[thisCol], HIGH);
 }
 }
 // take the row pin low to turn off the whole row:
 digitalWrite(row[thisRow], LOW);
 }
}

 

08. Strings

SNAG- 16 06 27 00 21 47.jpg

 

8.1. CharacterAnalysis
CharacterAnalysisSNAG- 16 08 09 03 20 20.jpg

/*** Character analysis operators -Arduino IDE ***/
 /* Examples using the character analysis operators.
 Send any byte and the sketch will tell you about it.
created 29 Nov 2010, modified 2 Apr 2012, by Tom Igoe
This example code is in the public domain.   */

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

// send an intro:
 Serial.println("send any byte and I'll tell you everything I can about it");
 Serial.println();
}

void loop() {
 // get any incoming bytes:
 if (Serial.available() > 0) {
 int thisChar = Serial.read();

// say what was sent:
 Serial.print("You sent me: \'");
 Serial.write(thisChar);
 Serial.print("\' ASCII Value: ");
 Serial.println(thisChar);

// analyze what was sent:
 if (isAlphaNumeric(thisChar)) {
 Serial.println("it's alphanumeric");
 }
 if (isAlpha(thisChar)) {
 Serial.println("it's alphabetic");
 }
 if (isAscii(thisChar)) {
 Serial.println("it's ASCII");
 }
 if (isWhitespace(thisChar)) {
 Serial.println("it's whitespace");
 }
 if (isControl(thisChar)) {
 Serial.println("it's a control character");
 }
 if (isDigit(thisChar)) {
 Serial.println("it's a numeric digit");
 }
 if (isGraph(thisChar)) {
 Serial.println("it's a printable character that's not whitespace");
 }
 if (isLowerCase(thisChar)) {
 Serial.println("it's lower case");
 }
 if (isPrintable(thisChar)) {
 Serial.println("it's printable");
 }
 if (isPunct(thisChar)) {
 Serial.println("it's punctuation");
 }
 if (isSpace(thisChar)) {
 Serial.println("it's a space character");
 }
 if (isUpperCase(thisChar)) {
 Serial.println("it's upper case");
 }
 if (isHexadecimalDigit(thisChar)) {
 Serial.println("it's a valid hexadecimaldigit (i.e. 0 - 9, a - F, or A - F)");
 }

// add some space and ask for another byte:
 Serial.println();
 Serial.println("Give me another byte:");
 Serial.println();
 }
}

CharacterAnalysis-Arduiino IDE.gif



send any byte and I'll tell you everything I can about it

CharacterAnalysis-123D.gif

 

 

8.2. StringAdditionOperator

StringStartsWithEndsWithSNAG- 16 08 09 03 20 20.jpg

/*** StringAdditionOperator-Arduino IDE ***/
/*  Adding Strings together
Examples of how to add strings together
 You can also add several different data types to string, as shown here:
created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
http://www.arduino.cc/en/Tutorial/StringAdditionOperator
This example code is in the public domain.    */

// declare three strings:
String stringOne, stringTwo, stringThree;

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
 }

 stringOne = String("stringThree = ");
 stringTwo = String("this string");
 stringThree = String();
 // send an intro:
 Serial.println("\n\nAdding strings together (concatenation):");
 Serial.println();
}

void loop() {
 // adding a constant integer to a string:
 stringThree = stringOne + 123;
 Serial.println(stringThree); // prints "stringThree = 123"

// adding a constant long interger to a string:
 stringThree = stringOne + 123456789;
 Serial.println(stringThree); // prints " You added 123456789"

// adding a constant character to a string:
 stringThree = stringOne + 'A';
 Serial.println(stringThree); // prints "You added A"

// adding a constant string to a string:
 stringThree = stringOne + "abc";
 Serial.println(stringThree); // prints "You added abc"

stringThree = stringOne + stringTwo;
 Serial.println(stringThree); // prints "You added this string"

// adding a variable integer to a string:
 int sensorValue = analogRead(A0);
 stringOne = "Sensor value: ";
 stringThree = stringOne + sensorValue;
 Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0) has

// adding a variable long integer to a string:
 long currentTime = millis();
 stringOne = "millis() value: ";
 stringThree = stringOne + millis();
 Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has

// do nothing while true:
 while (true);
}

StringAdditionOperator-Arduino IDE.gif


Adding strings together (concatenation):

stringThree = 123
stringThree = 123456789
stringThree = A
stringThree = abc
stringThree = this string
Sensor value: 405
millis() value: 110

StringAdditionOperator-123D.gif

 

 

8.3. StringAppendOperator
StringAppendOperatorSNAG- 16 08 09 03 20 20.jpg

/*** StringAppendOperator - Arduino IDE ***/
/* Appending to Strings using the += operator and concat()
 Examples of how to append different data types to strings
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringAppendOperator
 This example code is in the public domain. */

String stringOne, stringTwo;

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

stringOne = String("Sensor ");
 stringTwo = String("value");
 // send an intro:
 Serial.println("\n\nAppending to a string:");
 Serial.println();
}

void loop() {
 Serial.println(stringOne); // prints "Sensor "

// adding a string to a string:
 stringOne += stringTwo;
 Serial.println(stringOne); // prints "Sensor value"

// adding a constant string to a string:
 stringOne += " for input ";
 Serial.println(stringOne); // prints "Sensor value for input"

// adding a constant character to a string:
 stringOne += 'A';
 Serial.println(stringOne); // prints "Sensor value for input A"

// adding a constant integer to a string:
 stringOne += 0;
 Serial.println(stringOne); // prints "Sensor value for input A0"

// adding a constant string to a string:
 stringOne += ": ";
 Serial.println(stringOne); // prints "Sensor value for input"

// adding a variable integer to a string:
 stringOne += analogRead(A0);
 Serial.println(stringOne); // prints "Sensor value for input A0: 456" or whatever analogRead(A0) is

Serial.println("\n\nchanging the Strings' values");
 stringOne = "A long integer: ";
 stringTwo = "The millis(): ";

// adding a constant long integer to a string:
 stringOne += 123456789;
 Serial.println(stringOne); // prints "A long integer: 123456789"

// using concat() to add a long variable to a string:
 stringTwo.concat(millis());
 Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is

// do nothing while true:
 while (true);
}

StringAppendOperator - Arduino IDE.gif


Appending to a string:

Sensor 
Sensor value
Sensor value for input 
Sensor value for input A
Sensor value for input A0
Sensor value for input A0: 
Sensor value for input A0: 419


changing the Strings' values
A long integer: 123456789
The millis(): 191

 

StringAppendOperator-123D.gif

 

 

8.4. StringCaseChanges
StringCaseChangesSNAG- 16 08 09 03 20 20.jpg

/*** StringCaseChanges - Arduino IDE ***/
/* String Case changes
 Examples of how to change the case of a string
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringCaseChanges
 This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString case changes:");
 Serial.println();
}

void loop() {
 // toUpperCase() changes all letters to upper case:
 String stringOne = "<html><head><body>";
 Serial.println(stringOne);
 stringOne.toUpperCase();
 Serial.println(stringOne);

// toLowerCase() changes all letters to lower case:
 String stringTwo = "</BODY></HTML>";
 Serial.println(stringTwo);
 stringTwo.toLowerCase();
 Serial.println(stringTwo);

 // do nothing while true:
 while (true);
}

StringCaseChanges.gif



String case changes:

<html><head><body>
<HTML><HEAD><BODY>
</BODY></HTML>
</body></html>

StringCaseChanges-123D.gif

 

 

8.5. StringCharacters
StringCharactersSNAG- 16 08 09 03 20 20.jpg

/*** StringCharacters - Arduino IDE ***/
/* String charAt() and setCharAt()
 Examples of how to get and set characters of a String
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringCharacters
 This example code is in the public domain. */

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

Serial.println("\n\nString charAt() and setCharAt():");
}

void loop() {
 // make a string to report a sensor reading:
 String reportString = "SensorReading: 456";
 Serial.println(reportString);

// the reading's most significant digit is at position 15 in the reportString:
 char mostSignificantDigit = reportString.charAt(15);

String message = "Most significant digit of the sensor reading is: ";
 Serial.println(message + mostSignificantDigit);

// add blank space:
 Serial.println();

// you can alo set the character of a string. Change the : to a = character
 reportString.setCharAt(13, '=');
 Serial.println(reportString);

// do nothing while true:
 while (true);
}

StringCharacters - Arduino IDE.gif



String charAt() and setCharAt():
SensorReading: 456
Most significant digit of the sensor reading is: 4

SensorReading= 456

StringCharacters-123D.gif

 

8.6. StringComparisonOperator
StringComparisonOperatorSNAG- 16 08 09 03 20 20.jpg

/*** StringComparisonOperator - Arduino IDE ***/
/* Comparing Strings
 Examples of how to compare strings using the comparison operators
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringComparisonOperators
 This example code is in the public domain. */

String stringOne, stringTwo;

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

 stringOne = String("this");
 stringTwo = String("that");
 // send an intro:
 Serial.println("\n\nComparing Strings:");
 Serial.println();
}

void loop() {
 // two strings equal:
 if (stringOne == "this") {
 Serial.println("StringOne == \"this\"");
 }
 // two strings not equal:
 if (stringOne != stringTwo) {
 Serial.println(stringOne + " =! " + stringTwo);
 }

// two strings not equal (case sensitivity matters):
 stringOne = "This";
 stringTwo = "this";
 if (stringOne != stringTwo) {
 Serial.println(stringOne + " =! " + stringTwo);
 }
 // you can also use equals() to see if two strings are the same:
 if (stringOne.equals(stringTwo)) {
 Serial.println(stringOne + " equals " + stringTwo);
 } else {
 Serial.println(stringOne + " does not equal " + stringTwo);
 }

// or perhaps you want to ignore case:
 if (stringOne.equalsIgnoreCase(stringTwo)) {
 Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
 } else {
 Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);
 }

// a numeric string compared to the number it represents:
 stringOne = "1";
 int numberOne = 1;
 if (stringOne.toInt() == numberOne) {
 Serial.println(stringOne + " = " + numberOne);
 }

// two numeric strings compared:
 stringOne = "2";
 stringTwo = "1";
 if (stringOne >= stringTwo) {
 Serial.println(stringOne + " >= " + stringTwo);
 }

// comparison operators can be used to compare strings for alphabetic sorting too:
 stringOne = String("Brown");
 if (stringOne < "Charles") {
 Serial.println(stringOne + " < Charles");
 }

if (stringOne > "Adams") {
 Serial.println(stringOne + " > Adams");
 }

if (stringOne <= "Browne") {
 Serial.println(stringOne + " <= Browne");
 }

 if (stringOne >= "Brow") {
 Serial.println(stringOne + " >= Brow");
 }

// the compareTo() operator also allows you to compare strings
 // it evaluates on the first character that's different.
 // if the first character of the string you're comparing to
 // comes first in alphanumeric order, then compareTo() is greater than 0:
 stringOne = "Cucumber";
 stringTwo = "Cucuracha";
 if (stringOne.compareTo(stringTwo) < 0) {
 Serial.println(stringOne + " comes before " + stringTwo);
 } else {
 Serial.println(stringOne + " comes after " + stringTwo);
 }

delay(10000); // because the next part is a loop:

// compareTo() is handy when you've got strings with numbers in them too:

while (true) {
 stringOne = "Sensor: ";
 stringTwo = "Sensor: ";

stringOne += analogRead(A0);
 stringTwo += analogRead(A5);

if (stringOne.compareTo(stringTwo) < 0) {
 Serial.println(stringOne + " comes before " + stringTwo);
 } else {
 Serial.println(stringOne + " comes after " + stringTwo);
}
 }
}

StringComparisonOperator - Arduino IDE.gif




before Sensor: 279
Sensor: 276 com

Comparing Strings:

StringOne == "this"
this =! that
This =! this
This does not equal this
This equals (ignoring case) this
1 = 1
2 >= 1
Brown < Charles
Brown > Adams
Brown <= Browne
Brown >= Brow
Cucumber comes before Cucuracha
Sensor: 489 comes after Sensor: 388
Sensor: 418 comes after Sensor: 396
Sensor: 396 comes after Sensor: 391
Sensor: 370 comes before Sensor: 372
Sensor: 357 comes before Sensor: 363
Sensor: 349 comes before Sensor: 352
Sensor: 342 comes before Sensor: 345
Sensor: 337 comes before Sensor: 340
Sensor: 332 comes before Sensor: 334
Sensor: 327 comes before Sensor: 330
Sensor: 323 comes before Sensor: 325
Sensor: 320 comes before Sensor: 321
Sensor: 317 comes before Sensor: 318
Sensor: 314 comes before Sensor: 315
Sensor: 311 comes before Sensor: 312
Sensor: 309 comes after Sensor: 309
Sensor: 305 comes before Sensor: 306
Sensor: 303 comes before Sensor: 304
Sensor: 301 comes before Sensor: 302
Sensor: 300 comes after Sensor: 300
Sensor: 298 comes after Sensor: 298
Sensor: 297 comes after Sensor: 297
Sensor: 298 comes after Sensor: 298
Sensor: 298 comes before Sensor: 299
Sensor: 298 comes after Sensor: 298
Sensor: 298 comes before Sensor: 299
Sensor: 298 comes after Sensor: 298
Sensor: 299 comes after Sensor: 299
Sensor: 298 comes before Sensor: 299
Sensor: 298 comes after Sensor: 298
Sensor: 297 comes after Sensor: 297
Sensor: 294 comes before Sensor: 295
Sensor: 293 comes before Sensor: 297
Sensor: 292 comes before Sensor: 293
Sensor: 291 comes before Sensor: 292
Sensor: 291 comes after Sensor: 291
...
...
...

StringComparisonOperator-123D.gif

 

 

8.7. StringConstructors
StringConstructorsSNAG- 16 08 09 03 20 20.jpg

/*** StringConstructors - Arduino IDE ***/
/* String constructors
 Examples of how to create strings from other data types
 created 27 July 2010, modified 30 Aug 2011, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringConstructors
 This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString Constructors:");
 Serial.println();
}

void loop() {
 // using a constant String:
 String stringOne = "Hello String";
 Serial.println(stringOne); // prints "Hello String"

// converting a constant char into a String:
 stringOne = String('a');
 Serial.println(stringOne); // prints "a"

// converting a constant string into a String object:
 String stringTwo = String("This is a string");
 Serial.println(stringTwo); // prints "This is a string"

// concatenating two strings:
 stringOne = String(stringTwo + " with more");
 // prints "This is a string with more":
 Serial.println(stringOne);

// using a constant integer:
 stringOne = String(13);
 Serial.println(stringOne); // prints "13"

// using an int and a base:
 stringOne = String(analogRead(A0), DEC);
 // prints "453" or whatever the value of analogRead(A0) is
 Serial.println(stringOne);

// using an int and a base (hexadecimal):
 stringOne = String(45, HEX);
 // prints "2d", which is the hexadecimal version of decimal 45:
 Serial.println(stringOne);

// using an int and a base (binary)
 stringOne = String(255, BIN);
 // prints "11111111" which is the binary value of 255
 Serial.println(stringOne);

// using a long and a base:
 stringOne = String(millis(), DEC);
 // prints "123456" or whatever the value of millis() is:
 Serial.println(stringOne);

//using a float and the right decimal places:
 stringOne = String(5.698, 3);
 Serial.println(stringOne);

//using a float and less decimal places to use rounding:
 stringOne = String(5.698, 2);
 Serial.println(stringOne);

// do nothing while true:
 while (true);
}

StringConstructors-Arduino IDE.gif



String Constructors:

Hello String
a
This is a string
This is a string with more
13
406
2d
11111111
48
5.698
5.70

StringConstructor-123D.gif

 

 

 

8.8. StringIndexOf
StringIndexOfSNAG- 16 08 09 03 20 20.jpg

/*** StringIndexOf - Arduino IDE ***/
 /* String indexOf() and lastIndexOf() functions
 Examples of how to evaluate, look for, and replace characters in a String
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringIndexOf
 This example code is in the public domain. 
 */

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

// send an intro:
 Serial.println("\n\nString indexOf() and lastIndexOf() functions:");
 Serial.println();
}

void loop() {
 // indexOf() returns the position (i.e. index) of a particular character
 // in a string. For example, if you were parsing HTML tags, you could use it:
 String stringOne = "<HTML><HEAD><BODY>";
 int firstClosingBracket = stringOne.indexOf('>');
 Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);

stringOne = "<HTML><HEAD><BODY>";
 int secondOpeningBracket = firstClosingBracket + 1;
 int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
 Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);

// you can also use indexOf() to search for Strings:
 stringOne = "<HTML><HEAD><BODY>";
 int bodyTag = stringOne.indexOf("<BODY>");
 Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);

stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
 int firstListItem = stringOne.indexOf("<LI>");
 int secondListItem = stringOne.indexOf("<LI>", firstListItem + 1);
 Serial.println("The index of the second list tag in the string " + stringOne + " is " + secondListItem);

// lastIndexOf() gives you the last occurrence of a character or string:
 int lastOpeningBracket = stringOne.lastIndexOf('<');
 Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);

int lastListItem = stringOne.lastIndexOf("<LI>");
 Serial.println("The index of the last list tag in the string " + stringOne + " is " + lastListItem);

 // lastIndexOf() can also search for a string:
 stringOne = "<p>Lorem ipsum dolor sit amet</p><p>Ipsem</p><p>Quod</p>";
 int lastParagraph = stringOne.lastIndexOf("<p");
 int secondLastGraf = stringOne.lastIndexOf("<p", lastParagraph - 1);
 Serial.println("The index of the second to last paragraph tag " + stringOne + " is " + secondLastGraf);

// do nothing while true:
 while (true);
}

StringIndexOf - Arduino IDE.gif




String indexOf() and lastIndexOf() functions:

The index of > in the string <HTML><HEAD><BODY> is 5
The index of the second > in the string <HTML><HEAD><BODY> is 11
The index of the body tag in the string <HTML><HEAD><BODY> is 12
The index of the second list tag in the string <UL><LI>item<LI>item<LI>item</UL>
 is 12
The index of the last < in the string <UL><LI>item<LI>item<LI>item</UL> is 28
The index of the last list tag in the string <UL><LI>item<LI>item<LI>item</UL>
 is 20
The index of the second to last paragraph tag <p>Lorem ipsum dolor sit amet</p>
<p>Ipsem</p><p>Quod</p> is 33

StringIndexOf-123D.gif

 

 

 

8.9. StringLength
StringLengthSNAG- 16 08 09 03 20 20.jpg

/*** StringLength - Arduino IDE ***/ 
/* String length()
Examples of how to use length() in a String.
 Open the Serial Monitor and start sending characters to see the results.
created 1 Aug 2010, by Tom Igoe
http://www.arduino.cc/en/Tutorial/StringLengthTrim
This example code is in the public domain. */

String txtMsg = ""; // a string for incoming text
int lastStringLength = txtMsg.length(); // previous length of the String

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

 // send an intro:
 Serial.println("\n\nString length():");
 Serial.println();
}

void loop() {
 // add any incoming characters to the String:
 while (Serial.available() > 0) {
 char inChar = Serial.read();
 txtMsg += inChar;
 }

// print the message and a notice if it's changed:
 if (txtMsg.length() != lastStringLength) {
 Serial.println(txtMsg);
 Serial.println(txtMsg.length());
 // if the String's longer than 140 characters, complain:
 if (txtMsg.length() < 140) {
 Serial.println("That's a perfectly acceptable text message");
 } else {
 Serial.println("That's too long for a text message.");
 }
 // note the length for next time through the loop:
 lastStringLength = txtMsg.length();
 }
}

StringLength - Arduino IDE.gif




String length():

StringLength-123D.gif

 

 

 

8.10. StringLengthTrim
StringLengthTrimSNAG- 16 08 09 03 20 20.jpg

/*** StringLengthTrim - Arduino IDE ***/
/* String length() and trim()
 Examples of how to use length() and trim() in a String
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringLengthTrim
 This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString length() and trim():");
 Serial.println();
}

void loop() {
 // here's a String with empty spaces at the end (called white space):
 String stringOne = "Hello! ";
 Serial.print(stringOne);
 Serial.print("<--- end of string. Length: ");
 Serial.println(stringOne.length());

// trim the white space off the string:
 stringOne.trim();
 Serial.print(stringOne);
 Serial.print("<--- end of trimmed string. Length: ");
 Serial.println(stringOne.length());

// do nothing while true:
 while (true);
}

StringLengthTrim-Arduino IDE




String length() and trim():

Hello! <--- end of string. Length: 13
Hello!<--- end of trimmed string. Length: 6

 

StringLengthTrim-123D.gif

 

 

8.11. StringReplace
StringReplaceSNAG- 16 08 09 03 20 20.jpg

/*** StringReplace - Arduino IDE ***/
/* String replace()
 Examples of how to replace characters or substrings of a string
 created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringReplace
 This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString replace:\n");
 Serial.println();
}

void loop() {
 String stringOne = "<html><head><body>";
 Serial.println(stringOne);
 // replace() changes all instances of one substring with another:
 // first, make a copy of th original string:
 String stringTwo = stringOne;
 // then perform the replacements:
 stringTwo.replace("<", "</");
 // print the original:
 Serial.println("Original string: " + stringOne);
 // and print the modified string:
 Serial.println("Modified string: " + stringTwo);

// you can also use replace() on single characters:
 String normalString = "bookkeeper";
 Serial.println("normal: " + normalString);
 String leetString = normalString;
 leetString.replace('o', '0');
 leetString.replace('e', '3');
 Serial.println("l33tspeak: " + leetString);

// do nothing while true:
 while (true);
}

StringReplace - Arduino IDE.gif




String replace:


<html><head><body>
Original string: <html><head><body>
Modified string: </html></head></body>
normal: bookkeeper
l33tspeak: b00kk33p3r

StringReplace-123D.gif

 

 

 

8.12. StringStartsWithEndsWith
StringStartsWithEndsWithSNAG- 16 08 09 03 20 20.jpg

/*** StringStartsWithEndsWith - Arduino IDE ***/
/* String startWith() and endsWith()
Examples of how to use startsWith() and endsWith() in a String
created 27 July 2010, modified 2 Apr 2012, by Tom Igoe
http://www.arduino.cc/en/Tutorial/StringStartsWithEndsWith
This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString startsWith() and endsWith():");
 Serial.println();
}

void loop() {
 // startsWith() checks to see if a String starts with a particular substring:
 String stringOne = "HTTP/1.1 200 OK";
 Serial.println(stringOne);
 if (stringOne.startsWith("HTTP/1.1")) {
 Serial.println("Server's using http version 1.1");
 }

// you can also look for startsWith() at an offset position in the string:
 stringOne = "HTTP/1.1 200 OK";
 if (stringOne.startsWith("200 OK", 9)) {
 Serial.println("Got an OK from the server");
 }

// endsWith() checks to see if a String ends with a particular character:
 String sensorReading = "sensor = ";
 sensorReading += analogRead(A0);
 Serial.print(sensorReading);
 if (sensorReading.endsWith("0")) {
 Serial.println(". This reading is divisible by ten");
 } else {
 Serial.println(". This reading is not divisible by ten");
 }

// do nothing while true:
 while (true);
}

StringStartsWithEndsWith - Arduino IDE.gif




String startsWith() and endsWith():

HTTP/1.1 200 OK
Server's using http version 1.1
Got an OK from the server
sensor = 410. This reading is divisible by ten

StringStartsWithEndsWith-123D.gif

 

8.13. StringSubstring
StringSubstringSNAG- 16 08 09 03 20 20.jpg

/*** StringSubstring - Arduino IDE ***/
/* String substring()
 Examples of how to use substring in a String
 created 27 July 2010, modified 2 Apr 2012, by Zach Eveland
 http://www.arduino.cc/en/Tutorial/StringSubstring
 This example code is in the public domain. */

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

// send an intro:
 Serial.println("\n\nString substring():");
 Serial.println();
}

void loop() {
 // Set up a String:
 String stringOne = "Content-Type: text/html";
 Serial.println(stringOne);

// substring(index) looks for the substring from the index position to the end:
 if (stringOne.substring(19) == "html") {
 Serial.println("It's an html file");
 }
 // you can also look for a substring in the middle of a string:
 if (stringOne.substring(14, 18) == "text") {
 Serial.println("It's a text-based file");
 }

// do nothing while true:
 while (true);
}

 

StringSubstring - Arduino IDE.gif




String substring():

Content-Type: text/html
It's an html file
It's a text-based file

StringSubstring-123D.gif

 

 

8.14. StringToInt
StringToIntSNAG- 16 08 09 03 20 20.jpg

/*** StringToInt - Arduino IDE ***/
/* String to Integer conversion
 Reads a serial input string until it sees a newline, then converts
 the string to a number if the characters are digits.
 The circuit: No external components needed.
 created 29 Nov 2010, by Tom Igoe
 This example code is in the public domain. */

String inString = ""; // string to hold input

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

// send an intro:
 Serial.println("\n\nString toInt():");
 Serial.println();
}

void loop() {
 // Read serial input:
 while (Serial.available() > 0) {
 int inChar = Serial.read();
 if (isDigit(inChar)) {
 // convert the incoming byte to a char
 // and add it to the string:
 inString += (char)inChar;
 }
 // if you get a newline, print the string,
 // then the string's value:
 if (inChar == '\n') {
 Serial.print("Value:");
 Serial.println(inString.toInt());
 Serial.print("String: ");
 Serial.println(inString);
 // clear the string for new input:
 inString = "";
 }
 }
}

 

StringToInt - Arduino IDE.gif




String toInt():

StringToInt-123D.gif

 

 

 

09. USB – Keyboard, Mouse.

SNAG- 16 06 27 00 22 32.jpg

 

9.1. KeyboardLogout
KeyboardLogout

 

/*** KeyboardLogout ***/
/* Keyboard logout
This sketch demonstrates the Keyboard library.
When you connect pin 2 to ground, it performs a logout.
 It uses keyboard combinations to do this, as follows:
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.
 * Arduino Leonardo, Micro, or Due board
 * pushbutton
 * breadboard
created 6 Mar 2012, modified 27 Mar 2012  by Tom Igoe
This example is in the public domain
http://www.arduino.cc/en/Tutorial/KeyboardLogout */
#define OSX 0
#define WINDOWS 1
#define UBUNTU 2
#include "Keyboard.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);
}

 

 

9.2. KeyboardMessage
KeyboardMessage

 

9.3. KeyboardReprogram
KeyboardReprogram

 

9.4. KeyboardSerial
KeyboardSerial

 

9.5. KeyboardAndMouseControl
KeyboardAndMouseControl

 

9.6. ButtonMouseControl
ButtonMouseControl

 

9.7. JoystickMouseControl
JoystickMouseControl

 

10. StarterKit_BasicKit

SNAG- 16 06 27 00 23 47.jpg

SNAG- 16 06 26 22 22 41.jpg

Arduino Basic Kit

SNAG- 16 06 26 22 24 30.jpg

Arduino Starter Kit Gallery

SNAG- 16 06 26 22 24 47.jpg

 

11. ArduinoISP

SNAG- 16 06 27 00 24 38

JoystickMouseControl

JoystickMouseControl

 

Ping Pong

Ping Pong.gif

 

#include <Servo.h> 
Servo myservoR;
Servo myservoL;


int val;
int pinArray[] = {12, 11, 10, 9, 8, 7, 6, 5};
int count = 0;
int timer = 25;

void setup(){
 
myservoR.attach(3); 
myservoL.attach(13);
 
for (count=0;count<8;count++) {
pinMode(pinArray[count], OUTPUT);
}
}

void loop() {
for (count=0;count<8;count++) {
digitalWrite(pinArray[count], HIGH);
 
delay(timer);
digitalWrite(pinArray[count + 1], HIGH);
 val= (count*22.5);
 myservoR.write(val);
 myservoL.write(val); 
 
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer*2);
}
for (count=7;count>0;count--) {
digitalWrite(pinArray[count], HIGH);
 digitalWrite(pinArray[count], HIGH);
 
delay(timer);
digitalWrite(pinArray[count - 1], HIGH);
 val=(count*22.5);
 myservoR.write(val);
 myservoL.write(val);
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer*2);
}
}

 

 

tira LED mas buzzer.gif

 

int potenciometro = 5;
int buzzer = A0;
int tensao = 0;
int i;

void volume(int potenciometro, int buzzer){
 for (i = 2; i <= 13; i++){
 tensao = analogRead(potenciometro);
 analogWrite(buzzer, tensao / 4);
 Serial.println(tensao);
 if ((i <= (tensao/78)) or (i <= (tensao/85))){
 digitalWrite(i, HIGH);
 }
 else {
 digitalWrite(i, LOW);
 }
 }
}

// the setup routine runs once when you press reset:
void setup() {
 // initialize the digital pin as an output.
 Serial.begin(9600);
 pinMode(buzzer, OUTPUT);
 pinMode(2, OUTPUT);
 pinMode(3, OUTPUT);
 pinMode(4, OUTPUT);
 pinMode(5, OUTPUT);
 pinMode(6, OUTPUT);
 pinMode(7, OUTPUT);
 pinMode(8, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(12, OUTPUT);
 pinMode(13, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
 volume(potenciometro, buzzer);
}

 

 

 

Anuncios