martes, 8 de febrero de 2011

" Hello World!! "

.




En este primer post, vamos a explicar como comenzar a utilizar el conversor CAN. En un primer paso, integraremos la libería en el IDE de arduino, para luego conectarlo y empezar a mandar nuestros primeros mensajes por el bus. Para ello, necesitaremos:
  • 2 x (Conversor) y libería CAN, que puedes encontrar aquí.
  • ArduinoIDE 0021 o superior que puedes descargar aquí.
  • Cable rigido, tijeras, ...
Lo primero que haremos es integrar la libería CAN en el entorno de desarrollo de arduino, para que resulte más cómodo en el futuro trabajar con ella.

  1. Descomprime el fichero CAN_vX.rar en una carpeta donde te resulte luego cómodo encontrarlo.Contenido:
    • .\SECUduino-CAN\CAN\
    • .\SECUduino-CAN\CAN\can.c (Fuentes de la libería)
    • .\SECUduino-CAN\CAN\can.h (Header de la libería)
    • .\SECUduino-CAN\CAN\pinout.h (Header definiciones auxiliares)
  2. Instala el entorno Arduino 0021 o superior, siguiendo el siguiente tutorial
  3. Buscamos la carpeta en la que hemos descomprimido del archivo CAN_vX.rar.
  4. El directorio .\SECUduino-CAN\CAN lo copiamos en .\arduino0021\libraries\ De esta forma, integramos la libería en el entorno, poniendo a un simple click el uso de ejemplos y la libería.
  5. Acordemonos de seleccionar el modelo de arduino que vamos a utilizar en Tool -> Board -> Xxx y el COM adecuado.

En este punto, la libería lista para ser incluida en cualquiera de nuestros proyectos y poder usar el conversor CAN. Ahora debemos cablear nuestro arduino como se indica en la sección de [Hardware]

En mi caso he cableado los pines de la siguiente forma:







El objetivo de este ejemplo es conectar 2 arduinos a través de CAN, para que se envien entre sí el estado del switch que hemos puesto en una entrada digital de cada uno de los arduinos. Los arduinos se enviarán entre si el estado de su switch, y reflejarán a través de un led conectado a una salida digital, el estado del switch del arduino remoto.

Para ello:

  • Copie lo siguiente en el archivo PINOUT.h contenido en la libería CAN
// ----------------------------------------------
#ifndef PINOUT_H
#define PINOUT_H


//---------------------------------------------------
#define P_MOSI   B,2
#define P_MISO   B,3
#define P_SCK   B,1

#define MCP2515_CS  B,0
#define MCP2515_INT  D,2
//---------------------------------------------------




#endif // PINOUT_H
  • Conecta el primer Arduino MEGA al PC y cárgale el siguiente programa
// ----------------------------------------------
// SECUDUINO
// http://secuduino.blogspot.com/
// By Aritz Real
// 26/Feb/2011
// ----------------------------------------------
#include <can.h>
#include <pinout.h>

#define IDWAITED 100
#define OWNID 200

int ledPin = 13;
int buttonPin = 22;
byte remotePinState = 0;
int valor = 0;
//Setting up our devices and I/Os. This case just the BusCAN
//and the DigitalO
void setup()
{
  Serial.begin(115200);
  //Let's open the bus. Remember the input parameter:
  //  1: 1Mbps
  // 500: 500Kbps  <--- Most frecuently used
  // 250: 250Kbp
  // 125: 125Kbps
  CAN.begin(1);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}


//Let's receive any message here, an queue in the
//circular buffer defined by the library.
//Best practice could be use a Timer to read the 
//circular buffer, but in order to simplify
//this example let's iterate.
void loop()
{  
    if(CAN.CheckNew())
    {
      CAN.ReadFromDevice(&CAN_RxMsg);
      //Debug
      Serial.print(CAN_RxMsg.data[0],DEC);Serial.write(",");
      Serial.print(CAN_RxMsg.data[1],DEC);Serial.write(","); 
      Serial.print(CAN_RxMsg.data[2],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[3],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[4],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[5],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[6],DEC); Serial.write(",");
      Serial.println(CAN_RxMsg.data[7],DEC);
    }
    
    //Let's test the first byte
    if(CAN_RxMsg.id == IDWAITED)
    {
      if(CAN_RxMsg.data[0] == 0)
        digitalWrite(ledPin,LOW);
      else
        digitalWrite(ledPin,HIGH);
    }
      
    CAN_TxMsg.id = OWNID;
    if(digitalRead(buttonPin) == LOW)
    {
      CAN_TxMsg.data[0] = 0;
      //Serial.println("Enviado 0");
    }
    else
    {
       CAN_TxMsg.data[0] = 1;
       //Serial.println("Enviado 1");
    }
      
    CAN_TxMsg.header.length = 8;
    CAN.send(&CAN_TxMsg);
    delay(10);   
    
}
  • Copie lo siguiente en el archivo PINOUT.h contenido en la libería CAN
// ----------------------------------------------
#ifndef PINOUT_H
#define PINOUT_H


//---------------------------------------------------
#define P_MOSI   B,3
#define P_MISO   B,4
#define P_SCK   B,5

#define MCP2515_CS  B,2
#define MCP2515_INT  D,2
//---------------------------------------------------




#endif // PINOUT_H
  • Conecta el Arduino Decimilia al PC y cárgale el siguiente programa
// ----------------------------------------------
// SECUDUINO
// http://secuduino.blogspot.com/
// By Aritz Real
// 26/Feb/2011
// ----------------------------------------------
#include <can.h>
#include <pinout.h>

#define IDWAITED 200
#define OWNID 100

int ledPin = 9;
int buttonPin = 8;
byte remotePinState = 0;
int valor = 0;
//Setting up our devices and I/Os. This case just the BusCAN
//and the DigitalO
void setup()
{
  Serial.begin(115200);
  //Let's open the bus. Remember the input parameter:
  //  1: 1Mbps
  // 500: 500Kbps  <--- Most frecuently used
  // 250: 250Kbp
  // 125: 125Kbps
  CAN.begin(1);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}


//Let's receive any message here, an queue in the
//circular buffer defined by the library.
//Best practice could be use a Timer to read the 
//circular buffer, but in order to simplify
//this example let's iterate.
void loop()
{  
    if(CAN.CheckNew())
    {
      CAN.ReadFromDevice(&CAN_RxMsg);
      //Debug
      Serial.print(CAN_RxMsg.data[0],DEC);Serial.write(",");
      Serial.print(CAN_RxMsg.data[1],DEC);Serial.write(","); 
      Serial.print(CAN_RxMsg.data[2],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[3],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[4],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[5],DEC); Serial.write(",");
      Serial.print(CAN_RxMsg.data[6],DEC); Serial.write(",");
      Serial.println(CAN_RxMsg.data[7],DEC);
    }
    
    //Let's test the first byte
    if(CAN_RxMsg.id == IDWAITED)
    {
      if(CAN_RxMsg.data[0] == 0)
        digitalWrite(ledPin,LOW);
      else
        digitalWrite(ledPin,HIGH);
    }
      
    CAN_TxMsg.id = OWNID;
    if(digitalRead(buttonPin) == LOW)
    {
      CAN_TxMsg.data[0] = 0;
      //Serial.println("Enviado 0");
    }
    else
    {
       CAN_TxMsg.data[0] = 1;
       //Serial.println("Enviado 1");
    }
      
    CAN_TxMsg.header.length = 8;
    CAN.send(&CAN_TxMsg);
    delay(10);   
    
}
  • Conecta los Arduinos entre sí, usando conectores DB9 hembra, usando el PIN2(CAN_LOW) y el PIN7(CAN_HIGH). Consulta la sección FAQ si quieres aprender a cablear el bus. Esencial!


Si todo ha ido bien, al cambiar el estado del switch conectado al arduino 1, deberíamos ver como se enciende el led de la placa 2 y viceversa. Imaginemos que no es un led, sino un relé que enciende o apaga la luz de nuestro cuarto, divertido no? jeje
Para finalizar, nos gustaría mostrarte el resultado final a través de este video, esperamos que os guste!

1 comentario:

Anónimo dijo...

Thanks for that great tutorial. Really It is a good example to understand ARDUINO CANbus communication.

MEHMET YILDIZ
TURKEY,ANKARA

Publicar un comentario