sábado, 17 de noviembre de 2012

ARDUINO COMPUTER (Parte II)

En esta segunda parte mostraré el código utilizado para el primer Microcontrolador Arduino que usaremos como controladora gráfica utilizando la librería TVout.

#include <SoftwareSerial.h>
SoftwareSerial puertoUno(13, 12);
#include <TVout.h>
#include <fontALL.h>
TVout TV;
byte i;
byte k;
void setup(){
  Serial.begin(9600);
  puertoUno.begin(4800);
  TV.begin(NTSC,120,96);
    TV.select_font(font6x8);
}
void loop(){
  if(Serial.available()){
    i=Serial.read();
 TV.print(i);
}
  if(puertoUno.available()){
    k=puertoUno.read();
 TV.print(k);

}
}

Arduino Computer

ORDENADOR ARDUINO

En este tutorial explicaré como  hacer un ordenador con menos de 20 euros utilizando solo 3 microcontroladores Atmega328, para hacer un ordenador con un interprete de Arduino que nos permita hacer programas simples como lo haríamos con nuestro arduino desde un ordenador convencional.





Solo tenemos que conectar nuestro dispositivo a un televisor y a un teclado PS2 y tendremos un ordenador completo que nos permitirá programar las entradas y salidas (imput/output)  de uno de nuestros microcontroladores que hará las veces de CPU y del cual podremos utilizar sus pines digitales y análogos para hacer proyectos simples al estilo ARDUINO, como por ejemplo encender y apagar leds, manipular servos, conectar a un zumbador piezoelectrico (piezo Sounder) y añadir botones para hacer un piano, etc,...


Lo único que hay que tener en cuenta que el microcontrolador que hace las veces de CPU al estar cargado con el interprete de Arduino(Simulador de Lenguaje Arduino) tiene poca capacidad para almacenar programas; pero por lo demás funciona perfectamente.

Para esto solo necesitaremos:

- Un televisor con entrada de video (video in) RCA (ojo la entrada de video es la de color amarillo)
- Un teclado PS2 (si tienes uno viejo o puedes comprarlo en tiendas de ordenadores o electrónicas suelen costar unos 6 euros)
- 3 Atmega328 con el bootloader Arduino instalado ( yo solo tenía 2 cuando hice el proyecto, mientras tanto utilice mi placa Arduino Uno.)
      1 Atmega328 para que haga las veces de la controladora gráfica del ordenador, usando la librería       TVout.
         1 Atmega328 para utilizar el teclado PS2, usando la librería PS2Keyboard.
      1 Atmega328 (o por el momento tu placa arduino, yo utilicé una Arduino UNO smd) en la cual cargaremos el interprete de Arduino desarrollado por N. Mitsunaga n.mtng.org/ele/arduino/iarduino.html 
al que haremos algunas pequeñas modificaciones)
- 6 condensadores cerámicos de 22 pf
- 3 cristales de 16Mhz
- 3 resitencias de 12 Khm
(estos ultimos componentes lo necesitan nuestros microcontroladores para poder trabajar)
- 1 resistencia de 1 kOhm
- 1 resistencia de 470Ohm
(estas resistencias las utilizaremos para la salida a TV (TVout)
- una fuente de alimentación de 5v DC, (yo utilicé un transformador que tenía de juguete, aunque al principio utilice la alimentación de mi placa arduino UNO; o puedes utilizar un regulador IC2 7805, 2 condensadores electrolíticos de 100Mf y un diodo 1n 4007)

Ustedes se preguntarán ¿Porqué no he utilizado una sola placa arduino o un solo microcontrolador? 

La respuesta es que cuando junté las librerías TVout y PS2Keyboard en la misma placa me daba errores y titilaba como si hubiera interferencia entre ellas, además de que el Interprete de Arduino usa mucha memoria  de nuestro Atmega328, memoria en la cual también guardaremos nuestros sketches o programas.

Para que se comuniquen entre los 3 Microcontroladores usaremos los puertos seriales RX y TX estandares de cada uno de ellos y además untilizaremos la librería SoftwareSerial para crear nuevos puertos seriales utilizando 2 de los demás pines de nuestros Micros.


domingo, 11 de noviembre de 2012

ARDUINO Y PROCESSING MEDIDOR DE DISTANCIA SRF05

ARDUINO Y PROCESSING MEDIDOR DE DISTANCIAUSANDO SRF05



En este tutorial expliacaré como realizar un medidor de distancia utilizando un sensor de ultrasonidos SRF-05 y visualizar los datos en processing.

El código que utilicé en ARDUINO es el siguiente:


const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int index = 0;                  // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int echoPin = 2;             // the SRF05's echo pin
int initPin = 3;             // the SRF05's init pin
unsigned long pulseTime = 0;  // variable for reading the pulse
unsigned long distance = 0;  // variable for storing the distance

void setup() {


  // make the init pin an output:

  pinMode(initPin, OUTPUT);
  // make the echo pin an input:
  pinMode(echoPin, INPUT);
  // initialize the serial port:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
     readings[thisReading] = 0;
  }
  // set the serial port to begin logging values which Processing will later read.
  Serial.begin(9600);
}

void loop() {

  // send the sensor a 10microsecond pulse:
  digitalWrite(initPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(initPin, LOW);

  // wait for the pulse to return. The pulse

  // goes from low to HIGH to low, so we specify
  // that we want a HIGH-going pulse below:

  // converts the microsecond time to distance in CM

  pulseTime = pulseIn(echoPin, HIGH);
  distance = pulseTime/58;

  // subtract the last reading:

  total= total - readings[index];
  // read from the sensor:
  readings[index] = distance;
  // add the reading to the total:
  total= total + readings[index];
  // advance to the next position in the array:
  index = index + 1;                    

  // if we're at the end of the array...

  if (index >= numReadings)  {
    // ...wrap around to the beginning:
    index = 0;
  }
  // calculate the average:
  average = total / numReadings;  

  // print out an A character to set the start of the value and help us

  // cast this value to a string and integer later on in Processing.
  Serial.print('A');

  // now write out our value from the sensor.

  Serial.print(average);
  // delay must be the same as the delay in the processing code
  delay(100);
}

No hay que olvidar conectar bien el Srf-05 usando solo el pin  ECO "echo pin"de este (conectar al Pin 2 de Arduino) y el pin de INICIO "init pin" (conectar al Pin 3 de Arduino) . Además de conectar a tierra y a fuente de 5v.(usar los pines de arduino GND y 5v).
NOTA: en este caso NO usaremos el Trigger imput Pin.


Luego en Processing incluiremos el siguiente código:


// import the serial libary for Processing

import processing.serial.*; 


// define a new port object

Serial port;

// setup the port, this referes to the port object above

// COM8 is my USB port that I use, your's maybe anythign like COM1, etc..
// 9600 is the baud rating (how much data is transferred over a set time)
// it is important to make sure your Arduino is outputting to the same baud rating!!

void setup(){

  size (1200,700);
  fill(0, 255,255);
  smooth();
strokeWeight(1);
stroke(60,255,0);

textSize(20);

textAlign(LEFT);
  
     port = new Serial(this, "COM4", 9600);
}

// begin our output for Processing

void draw(){

  

  // delay 100 milliseconds - this must be the same delay used in the Arduino sketch.
  delay(100);

  // create a string to store the value from reading the serial port

  String serialBuffer = port.readString();

  // check if the value is not null, that the value is greater that 2 and no more than 4 characters

  if (serialBuffer != null && serialBuffer.length() >= 2 && serialBuffer.length() <= 4) {

    // check that the first character in the string is A

    // we add A to our output to cast the serial value to a string type.
    // Its also handy as the A is doubled up as a marker for a new value in the serial log
    if (serialBuffer.indexOf("A") == 0) {
      // if this is true then remove A
      serialBuffer =  serialBuffer.substring(1,serialBuffer.length());
    }
    // double check to make sure there are no more A's in our string - otherwise we can't convert to a number
    if (serialBuffer.indexOf("A") == -1) {
      // convert the string to an integer
      int i = Integer.parseInt(serialBuffer);
      // print our integer
      println(i);
      
      background(10,0,0);
      
      ellipse(0, 0, 200, 200); // Red circle
      fill(0, 80, 0,100); // Green color
      
      ellipse(0, 0, 500, 500); // Red circle
      fill(0, 80, 0,100); // Green color
      
      ellipse(0, 0, 900, 900); // Red circle
      fill(0, 80, 0,100); // Green color
      
      ellipse(0, 0, 1400, 1400); // Red circle
      fill(0, 80, 0,100); // Green color
      
      ellipse(0, 0, 2000, 2000); // Red circle
      fill(0, 80, 0,255); // Green col
      for (int x = 5; x>=5 && x<700;x+=5) {
      line (800,x,820,x);
      }
      for (int x = 20; x>=20 && x<700;x+=20) {
      line (800,x,840,x);
      }
      for (int x = 0; x>=0 && x<700;x+=100) {
      line (840,x,860,x);
      }
      for (int x = 0; x>=0 && x<700;x+=200) {
      line (860,x,880,x);
      }
      text("50 cm.", 880, 100);
      text("1 mt.", 880, 200);
      text("150 cm.", 880, 300);
      text("2 mt.", 880, 400);
      text("250 cm.", 880, 500);
      text("3 mt.", 880, 600);
      text("350 cm.", 880, 700);
      text("4 mt.", 880, 800);

      

      fill(0,0,0,90);
      
      rect(397,270,73,50);
      fill(255,255,255,100);
      text(i, 400, 300);
      text("cm", 440, 300);
      
      
      
      line (800,i*2, 0,0);

      

    }
  }

}