Mostrando entradas con la etiqueta Slider. Mostrar todas las entradas
Mostrando entradas con la etiqueta Slider. Mostrar todas las entradas

miércoles, 8 de enero de 2014

How to start creating and programming robots

 

Introduction


Create robots requires a lot of different skills and, depending on how sophisticated is the behavior or the tasks that must be performed, can be really complex and extremely difficult.

The three pillars of robotics are electronics, mechanics and programming; there are others, but only with these three you can already start experimenting.

In addition to applicable knowledge you also need some others items such as motors (or other actuators), sensors, a small computer to avoid weight and power consumption (typically a SBC or microcontroller ) and a power source (battery to be autonomous) and some parts that sustain and hold together all these elements and their movements.

These elements can be acquired (some even manufactured) separately, or more easily, and probably cheaper as a kit.

.

What do I need to start?


Mainly, you need wish to enjoy creating and learning.

* Acquire a minimum and basic knowledge of:

+ Electronics or electricity (if only to distinguish voltage and current),

+ Mechanics (the minimum would be screwing and unscrewing or connect Lego type pieces)

+ Computer (at least to run a program on a computer)

* Get at least a microcontroller (Arduino, for example), a pair of motors, a distance sensor, a battery, cables, and a structure to support it. The basic set or kit.

A kit, the best option


A clear advantage of starting with a kit is that you start NOW, spending your time on where is your interest (electronic, mechanical or computer) , because the others areas are already solved, but anytime you can get to work in any of them. When you buy the kit with all the necessary set of elements together, the price is also often cheaper.

From the more expensive and complex to the cheapest and easiest

bioloid_bio_img01Bioloid : 18 powerful servo motors, 4 sensors. Ideal for humanoid, quadrupeds, hexapods and even vehicles; software to create them and behave like living beings. Includes programming software RoboPlus Tasks, you can also program in C, and create motion sequences with RoboPlus Motion.  Using other controller, like Raspberry Pi you can use any language and programming tools which generate code to it.

It costs about 1000 euros. Yes, it is somewhat expensive, but if you have enough money and programming skills or willingness to learn, I think it deserves the price.

Mindstorms_EV3Mindstorm EV3: 2 servo motors, 1 motor, 4 sensors. Ideal for mechanisms and vehicles. Very easy to use, but it also allows you to create complex robots. Includes programming software NXT-G, NXT is also possible to program in Java with Far and C / C + + with Osek, not yet available for EV3 or very early versions.

It costs about 300 euros, although it may seem expensive compared to other options, its enormous potential and flexibility in all aspects (construction, programming and electronics) make it tremendously interesting.

Mindstorms EV3 is the latest version, released in August 2013.

[caption id="attachment_2226" align="alignleft" width="240"]Arduino robot Robot Arduino[/caption]

Vehicle based on Arduino: at least 2 servomotors and all the sensors  you want to start. Is easy and cheap, for about 40€/50$ - 70€/97$ you can have the a robot. Ideal for deepening in electronics.

It can be programmed with the friendly Arduino programming environment .

Is the cheapest option and you can go further by buying more components as you go. It not offers as much flexibility and ability to build as Mindstorms vehicles or Bioloid articulated robots, but you can really learn a lot more than it may seem.

.

.

.

And with less money or no money?


For less money, for starters, you can get an Arduino microcontroller or its clones, which cost just over 20 euros/dollars.

Or, completely free of charge, you can start learning to program in C or C + +, which will come very handy to program robots.

Free resources for learning C programming:

C introduction (pdf)

But there are a lot…

C Language Tutorial (html)
How C Programming Works (html)
Several C programming tutorials (html)
... and more from Google


And here you can find free resources for learning C++ programming.

In the next post I will write about a fast comparative between Bioloid, Mindstorms and Arduino based robots and about Arduino programming.

jueves, 12 de diciembre de 2013

(III) ¿Cómo empezar a construir y programar robots?

Herramientas de programación de Arduino, Mindstorms y Bioloid


Tanto Lego Mindstorms como Bioloid de Robotis incluyen herramientas de programación gráfica (se utilizan iconos en lugar de únicamente escribir texto) y Arduino utiliza un editor de texto para los programas. Todos ellos permiten crear el ejecutable y enviarlo al controlador.

Entorno Arduino:

Además del entorno de programación donde editar los programas Arduino ofrece un conjunto de librerías que facilitan mucho la utilización de sensores, servos y otros dispositivos. Muchas de estas librerías para modelos de sensores concretos o servos  ya vienen incorporadas, otras se han de incluir manualmente.

En el editor se escribe el programa utilizando C o C++ (dos potentes, flexibles y muy utilizados lenguajes estándares, especialmente en robótica). El entorno de Arduino, tras unas pequeñas transformaciones, lo compila utilizando el compilador avr-gcc o avr-g++, generando el ejecutable que enviaremos al microcontrolador.

Todo lo que aprendemos de C y/o C++ nos será muy útil, pues se puede utilizar con todos los kits, robots, sistemas operativos y computadores. Y estaresmos, además, aprendiendo la forma de trabajar y herramientas habituales en programación.
ArduinoIDE

Lego Mindstorms NXT-G:

Es ideal para familiarizarse con Mindstorms y para pequeños programas, así como para las primeras pruebas que realicemos con un sensor u otro dispositivo nuevo.

Pero es exclusiva para Mindstorms, bastante fácil de utilizar para programas sencillos, pero, a medida que queramos desarrollar programas con un poco de complejidad, iremos descubriendo problemas y limitaciones (búsquedas en el programa, organizar modularmente, depuración de errores, guardar versiones y poderlas comparar)
NXT-G_EV3

Robotis Roboplus Tasks: (la ayuda, de momento, sólo está en inglés)

Se puede decir exactamente lo mismo que para Mindstorms NXT-G: Fácil de utilizar e ideal para empezar o para programas pequeños y pruebas, pero exclusiva para robots de (en este caso) Robotis. Adoleciendo de los mismos defectos, si queremos realizar programas con un mínimo de complejidad nos encontraremos con los mismos problemas.

Sólo añadiría que mi impresión es que está pensada para escribir pequeños programas que recojan los comandos mandados por el telemando y ejecuten las secuencias de movimiento creadas con Roboplus Motion (la otra utilidad básica de Robotis).
RoboplusTaks

¿A qué me refiero con un poco más de complejidad?


Retomando la propuesta de comportamiento del primer artículo de la serie podemos ver una progresión de menos a más complejidad, de forma progresiva.

El típico vehículo que hacemos que evite obstáculos mediante dos sensores de contacto (ultrasonidos o infrarojos), uno a la derecha y otro a la izquierda.

1.- El programa más sencillo simplemente evita los obstáculos girando unos pocos grados a la izquierda cuando detecte una "colisión" en el sensor derecho, y a la izquierda cuando la detecte en el sensor derecho.

2.- Intentar evitar el obstáculo con las mínimas maniobras posibles, dando el mínimo rodeo,  para seguir el rumbo previo.

Pero si el robot se nos acaba situando en un rincón o en un "callejón sin salida" (ha de girar 180 grados o salir marcha atrás) lo más probable es que nunca logre salir por sus propios medios de ahí, ya que irá de "rebotando" del lado izquierdo al derecho y viceversa hasta que se le agoten las baterías...

3.- Añadimos un poco de "inteligencia" y complejidad. En lugar de girar siempre unos determinados grados fijos vamos a hacer que cuando detecte cierta cantidad de colisiones seguidas (en determinada cantidad de milisegundos o segundos) aumente el número de grados que girará, para así acabar consiguiendo que salga del rincón o del "callejón".

4.- Ahora el problema es que tras salir del rincón o del "callejón" cuando detecte un obstáculo va a girar mucho más de lo necesario. Pues igual que se lo dimos, grados de más a girar, se lo quitamos; a medida que pasan determinados milisegundos o segundos sin detectar colisiones iremos disminuyendo los grados a girar hasta que lleguen al valor inicial.

Realmente sólo estamos utilizando dos sensores de contacto, medición del tiempo y contador de colisiones, pero ya no es ese sencillo programa inicial.

5.- Otro grado de complejidad, o probablemente más de un grado, sería añadir un sensor de luz que hiciera al robot tender hacia la fuente de luz más intensa, evitando los obtáculos del camino, claro.

A partir de este nivel de complejidad creo que utilizar la herramientas NXT-G o Roboplus Tasks requiere más esfuerzo y nos aparecerán más problemas que utilizando lenguajes estándares como Java, C o C++, así como sus herramientas asociadas.

Creo que una buena continuación serían estos artículos de introducción a la programación

martes, 10 de diciembre de 2013

(II) ¿Cómo empezar a construir y programar robots?

Resumen del anterior artículo


Antes de empezar con la programación resumamos las conclusiones del anterior artículo:

1.- Los conocimientos mínimos para empezar a construir un robot los tiene prácticamente todo el mundo o se pueden conseguir muy fácilmente:

+ electrónica o electricidad (aunque sólo sea saber distinguir voltaje e intensidad),

+mecánica (lo mínimo sería atornillar y destornillar o conectar piezas tipo Lego)

+informática (saber ejecutar un programa en un ordenador)

2.- Un kit basado en Arduino, Lego Mindstorms o Bioloid de Robotis es la forma más fácil, divertida y educativa de empezar.

¿Arduino, Mindstorms o Bioloid?


¿Por dónde queremos empezar y qué kit nos lo ofrece?

- Si queremos construir robots articulados que caminen con dos, cuatro o seis patas Bioloid es ideal, especialmente si además queremos centrarnos en programación.


- Si lo que queremos es construir distintos vehículos con ruedas o cadenas, utilizando distintos sensores para percibir el mundo, Lego Mindstorms es la mejor opción.


- Y si queremos centrarnos en la electrónica y/o programación sin gastar demasiado dinero Arduino o un kit basado en Arduino es nuestra mejor opción.

Empecemos por el kit más barato, kit Arduino. Porque, además, lo que aprenderemos con él nos servirá también para otros kits, especial, aunque no únicamente, respecto programación en C y C++.

Kit con base Arduino


[caption id="attachment_2229" align="alignleft" width="90"]Controlador Arduino Controlador Arduino[/caption]

Arduino, explicado de forma sencilla, es un controlador programable de sensores y motores, que

[caption id="attachment_2226" align="alignright" width="150"]Arduino robot Robot Arduino 66€[/caption]

podemos utilizar como "cerebro" de un robot. Podemos empezar consiguiendo un controlador Arduino y posteriormente el resto de elementos.

O bien, conseguir el controlador con un kit que incluya ya todos los elementos necesarios para construir un vehículo robot. Con el kit nos aseguramos que motores, sensores y piezas de la

[caption id="attachment_2242" align="alignleft" width="90"]Robot arduino 40€ Robot arduino 40€[/caption]

estructura encajarán y se conectarán correctamente, probablemente también nos resulte más barato. En cualquiera de ambos casos terminaremos programando el microcontrolador que incorpora Arduino. Pero Arduino no es sólo hardware, es también un conjunto de utilidades que nos facilitarán muchísimo el trabajo de programar. Y existe además una comunidad muy activa de usuarios donde podremos participar recibiendo y dando ayuda a otras personas.

Guía, ejemplos y manual


Existe bastante documentación en castellano, aquí la referencia a las principales sentencias y funciones y este fantástico manual en castellano creado por Ardumanía. Pero aún hay más:

- Conceptos básicos y ejemplos

- Guía de instalación y ejecución de primer ejemplo para Windows

Bien, ¿y cómo es en programa sencillo con el lenguaje de programación C?, así se hace parpaderar un LED:

[sourcecode language="c"]
/*
Parpadeo
Enciende durante un segundo un LED,y lo apaga durante otro segundo, así continuamente
 */

// Pin 13 está conectado a un LED en la mayoría de Arduinos
// asignamos en número de conector pin a la variable led:
int led = 13;

// la función setup se ejecuta una sola vez cuando pulsas reset
void setup() {
  // inicializ el conector pin digital como salida.
  pinMode(led, OUTPUT);
}

// la función loop (bucle) se ejecuta una vez tras otra contínuamente
void loop() {
  digitalWrite(led, HIGH);   // enciende LED (HIGH es nivel alto de voltaje)
  delay(1000);               // espera un segundo
  digitalWrite(led, LOW);    // apaga el LED bajando el voltaje; LOW, significa bajo
  delay(1000);               // espera un segundo
}

[/sourcecode]

¿Y C++? ¿Y las herramientas de programación que incluyen Robotis, RoboPlus Taks, y Lego Mindstorms, NXT-G? También, pero ya será en el siguiente artículo...

lunes, 25 de noviembre de 2013

¿Cómo empezar a construir y programar robots?

[caption id="attachment_2192" align="alignleft" width="213"]Honda Asimo Honda Asimo[/caption]

Introducción


Crear robots requiere una gran cantidad de conocimientos distintos y, dependiendo de lo sofisticado que sea el comportamiento o tareas que ha de realizar, puede ser realmente complejo y extremadamente difícil.

Los tres pilares fundamentales de la robótica son la electrónica, la mecánica y la informática; tiene otros, pero con estos tres ya podemos empezar a experimentar.

Además de conocimiento aplicable también necesitamos algunos elementos de los que partir, como motores (u otros actuadores), sensores, una computadora de pequeño tamaño, para evitar peso y consumo eléctrico, (habitualmente una SBC o microcontrolador) y una fuente de energía (batería para que sea autónomo) y algunas piezas que sustenten y mantengan unidos a todos estos elementos en sus movimientos y desplazamientos.

Estos elementos los podemos adquirir (algunos incluso fabricar)  por separado o, para facilitar la entrada a la róbótica, también los podemos adquirir de forma conjunta, como un kit.

Comparte en este foro tus dudas y comentarios

¿Qué necesito para empezar?


Sobre todo, ganas de disfrutar creando y aprendiendo.

* Adquirir unos mínimos y básicos conocimientos de:

+ electrónica o electricidad (aunque sólo sea saber distinguir voltaje e intensidad),

+mecánica (lo mínimo sería atornillar y destornillar o conectar piezas tipo Lego)

+informática (saber ejecutar un programa en un ordenador)

* Conseguir, al menos, microcontrolador (Arduino, por ejemplo), un par de motores, un sensor de distancias, unas pilas, cables y una estructura que lo soporte. El conjunto o kit básico.

Un kit, la mejor opción


Una clara ventaja de empezar con un kit es que puedes empezar YA y dedicarte a la parte fundamental (electrónica, mecánica o informática) que más te interese, porque las demás las tienes ya solucionadas; aunque en cualquier momento puedes ponerte a trabajar en cualquiera de las otras partes. Al comprar el kit, con todo el conjunto de elementos necesarios juntos, el precio además suele ser más barato.

Del más caro y complejo al más barato y sencillo

bioloid_bio_img01Bioloid: 18 potentes servomotores, 4 sensores. Ideal para humanoides, cuadrúpedos, hexápodos e incluso vehículos, y crearles software para que se comporten como seres vivos. Incluye software de programación Roboplus Tasks, también se puede programar en C, y de creación de movimientos Roboplus Motion.

Tiene un precio de unos 1000 euros. Sí, resulta algo caro, pero si dispones del dinero y de suficientes conocimientos de programación o ganas de aprender, creo que lo merece.

[caption id="attachment_76" align="alignleft" width="90"]NXT Acer Explorer con Acer NXT Acer Explorer con Acer[/caption]

Mindstorms: 2 servomotores, 1 motor, 4 sensores. Ideal para mecanismos y vehículos. Muy fácil de utilizar, pero también permite crear robots complejos. Incluye software de programacion NXT-G y, NXT es posible programarlo también en Java con Lejos y C/C++ con Osek, aún no disponible para EV3 o versiones muy preliminares.

Tiene un precio de unos 300 euros, aunque pueda parecer caro frente a otras opciones, su enorme potencial y flexibilidad en todos los aspectos (de construcción, programación y de ampliar su electrónica) lo hacen enormemente interesante.

 

[caption id="attachment_2226" align="alignleft" width="90"]Arduino robot Robot Arduino[/caption]

Vehículo basado en Arduino: 2 servomotores y los sensores con los que desees empezar. Es el más sencillo y barato, por unos 40-60 euros puedes tener lo mínimo. Ideal para profundizar en electrónica.

Se puede programar con el amigable entorno de programación Arduino.

Es el que tiene un precio más barato y que además lo puedes ir comprando por partes, a medida que vayas necesitándolas. No ofrece tanta flexibilidad como Mindstorms ni capacidad para crear robots articulados como Bioloid, pero realmente se puede aprender mucho más de lo que pueda parecer.

.

¿Y con menos dinero o sin dinero?

Por menos dinero puedes conseguir un microcontrolador tipo Arduino o sus clones, que cuestan poco más de 20 euros.

O, de forma totalmente gratuita, puedes empezar a aprender a programar en C o C++, que será muy útil para luego darle vida al robot.

¿Con qué robot empezar?


Un sencillo vehículo de dos ruedas tractoras y una libre es un buen punto de partida con el que empezar a divertirse aprendiendo.

A modo de sugerencia de un programa sencillo y cómo ir añadiéndole una mínima complejidad de comportamiento. Se puede hacer de muchísimas formas:

El típico vehículo que hacemos que evite obstáculos mediante dos sensores de contacto, uno a la derecha y otro a la izquierda.

1.- El programa más sencillo simplemente evita los obstáculos girando unos pocos grados a la izquierda cuando detecte una "colisión" en el sensor derecho, y a la izquierda cuando la detecte en el sensor derecho.

2.- Se intenta evitar el obstáculo con las mínimas maniobras posibles para seguir el rumbo establecido.

Pero si el robot se nos acaba situando en un rincón o en un "callejón sin salida" (ha de girar 180 grados o salir marcha atrás) lo más probable es que nunca logre salir por sus propios medios de ahí, ya que irá de "rebotando" del lado izquierdo al derecho y viceversa hasta que se le agoten las baterías...

3.- Añadimos un poco de "inteligencia" y complejidad. En lugar de girar siempre unos determinados grados fijos vamos a hacer que cuando detecte cierta cantidad de colisiones seguidas (en determinada cantidad de milisegundos o segundos) aumente el número de grados que girará, para así acabar consiguiendo que salga del rincón o del "callejón".

4.- Ahora el problema es que tras salir del rincón o del "callejón" cuando detecte un obstáculo va a girar mucho más de lo necesario. Pues igual que se lo dimos, grados de más a girar, se lo quitamos; a medida que pasan determinados milisegundos o segundos sin detectar colisiones iremos disminuyendo los grados a girar hasta que lleguen al valor inicial.

Realmente sólo estamos utilizando dos sensores de contacto, medición del tiempo y contador de colisiones, pero ya no es ese sencillo programa inicial.

Otro paso sería añadir un sensor de luz que hiciera al robot tender hacia la fuente de luz más intensa, evitando los obtáculos del camino, claro.

Y en el siguiente artículo...

Empezando a programar


Aprendiendo a programar con Bioloid, Mindstorms o robot basado en Arduino.

miércoles, 20 de noviembre de 2013

(I) Reading sensors connected to Robotis CM-510

cm-510 sensorsUsing the Dynamixel SDK instead of RoboPlus Tasks is not possible to query sensors connected to the CM-5xx controller. But, of course, using standard programming languages, like C++, and tools, line QT Creator or Eclipse, with its full featured IDEs and debuggers is a hugue gain.

So I created a firmware for the CM-510 which can be queried and receive commands to itself, including its sensors, or to Dynamyxel devices.

The idea is very simple:

This program running in the CM-510 receives:

- commands or queries to IDs of Dynamixel devices. These are not processed, only redirected to the Dynamixel bus only if it was received by serial port ( serial cable or zigbee). If it was received from the Dynamixel bus nothing is done.

- commands or queries to the CM-510 ID (I chose ID=200), like beep, or to the sensors connected to it. This commands and queries are processed in the CM-510, basically querying the sensors.

In both cases the answer is sent to the connection from which the query or command was received.

After power on the CM-510, you can select the mode with the 4 cursor keys as showed in a terminal connected to its serial port:

"For 'Toss mode' press (Up), for 'Device mode' (Down), for 'Device debug mode' (Left),to start press (Right)"

In the Device mode:

all the receptions and sends are through the Dynamixel bus, the CM-510 is simply another device.

In the Toss mode:

- what is received from the serial connection is sent to the Dynamixel bus or processed in the CM-510 (If sent to its ID)

-what is received from the Dynamixel bus is sent to the serial connection

Finally, the Debug mode:

is like the Device mode, but all the debug messages included in the CM-510 are sent to the serial connection.

A complete sequence with code snippets from the CM-510 program and from the code running in the other computer:

Some C++ code snippets from this example: (C# in the next post)


[sourcecode language="cpp"]
enum AX12Address //and functions implemented in the CM-510 program, like
{
ReadCM510SensorRaw = 1,
Beep = 8,
ReadCM510SensorFiltered = 4,
SetSensorValuesToFilter = 5,
...
}
[/sourcecode]

[sourcecode language="cpp"]
void doBeep()
{
cout << "Beep" << endl;
mySystem.dynamixelCommunication.sendOrder(100, AXS1_Buzzer, (byte) DO, (short) 500);
usleep (200000);
mySystem.dynamixelCommunication.sendOrder(200,MyCommunications::Beep short)5);
}
[/sourcecode]

Querying sensor:

[sourcecode language="cpp"]
void doQuerySensor()
{
int sensorPort=getSensorPort();
int value=mySystem.dynamixelCommunication.readSensorValue (200,ReadCM510SensorRaw, sensorPort);
cout << "the sensor reads: [" << value << "] " << endl << endl << endl;
}
[/sourcecode]

These command and query are processed in the CM-510:

Getting the sensor value:

[sourcecode language="c"]

int executeCM510Function()
{
...
case F_GET_SENSOR_VALUE_RAW:
values[1] = getSensorValueRaw(parameters[1]);
break;

case F_GET_SENSOR_VALUE_FILTERED:
values[1] = getSensorValueFiltered(parameters[1], sensorValuesToFilterDefined);
break;

case F_GET_TWO_DMS_SENSOR_VALUES:
parametersReceived=3;
getTwoDMSSensorsValues();
break;

case F_GET_MULTIPLE_SENSOR_VALUE:
getMultipleSensorsValues();
break;

case F_DO_SENSOR_SCAN:
values[1]= sensorScan(parameters[1]);
break;

case F_SET_VALUE_DMS1 : //set default value DMS1
DMS1=parameters[1];
break;

case F_SET_VALUE_DMS2 : //set default value DMS1
DMS2=parameters[1];
break;

case F_BEEP:
if (debugMode)
printf("executeCM510Function beep\n");
beep();
break;

case F_SET_SENSOR_VALUES_TO_FILTER:
sensorValuesToFilterDefined=parameters[1];
break;
}

return function;
}

}
...
int getSensorValueRaw(unsigned char portId)
{
ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1);

setPort(portId);
//PORTA &= ~0x80;
//PORTA &= ~0x20;

//_delay_us(12); // Short Delay for rising sensor signal
_delay_us(24);
ADCSRA |= (1 << ADIF); // AD-Conversion Interrupt Flag Clear
ADCSRA |= (1 << ADSC); // AD-Conversion Start

while( !(ADCSRA & (1 << ADIF)) ); // Wait until AD-Conversion complete

PORTA = 0xFC; // IR-LED Off

//printf( "%d\r\n", ADC); // Print Value on USART

//_delay_ms(50);
_delay_ms(ReadSensorDelayMS);

return ADC;
}

[/sourcecode]

 

[sourcecode language="c"]

void beep()
{
buzzOn(100);
buzzOff();
}
[/sourcecode]

But we can do a little more with the CM-510 processor, we can do some filtering to the sensor values.

The readings from the DMS are usually somewhat erratic, so we can simply:

- discard the minimum and maximum values:

- if we take 5 more than measures, then return the average if the are more than 3, if 3 or less it

Previously we should set how many readings should be done, if not, the default number of readings are 5:

[sourcecode language="c"]
int getSensorValueFiltered(unsigned char portId, int times)
{
...
switch(function)
{
case F_GET_SENSOR_VALUE_RAW:
values[1] = getSensorValueRaw(parameters[1]);
break;

case F_GET_SENSOR_VALUE_FILTERED:
values[1] = getSensorValueFiltered(parameters[1], sensorValuesToFilterDefined);
break;

case F_GET_TWO_DMS_SENSOR_VALUES:
parametersReceived=3;
getTwoDMSSensorsValues();
break;

case F_GET_MULTIPLE_SENSOR_VALUE:
getMultipleSensorsValues();
break;

case F_DO_SENSOR_SCAN:
values[1]= sensorScan(parameters[1]);
break;

case F_SET_VALUE_DMS1 : //set default value DMS1
DMS1=parameters[1];
break;

case F_SET_VALUE_DMS2 : //set default value DMS1
DMS2=parameters[1];
break;

case F_BEEP:
if (debugMode)
printf("executeCM510Function beep\n");
beep();
break;

case F_SET_SENSOR_VALUES_TO_FILTER:
sensorValuesToFilterDefined=parameters[1];
break;
}
...
[/sourcecode]

We also can take values from multiple sensors with one query, but It will be explained in the next post...

Forums opened

As l wrote in this previous post I would like to improve your participation in this site, and, in general, the interactions between all the people who visit this forum.

So I have opened some forums to post doubts, questions, comments, suggestions or opinions about the publushed posts.

Already there are some questions and answers!

miércoles, 13 de noviembre de 2013

Creating behaviors (I)

As you may guess from the domain of this site, software souls, one of my principal interests in robotics is creating behaviors, to make robots act as if they were alive. And here comes software. But I separate two aspects, because I think that to create the behavior just coding is too much complex, even for seasoned developers, and, worse, is too much rigid and difficult to change:

- The software to create, define or configure the behavior (the same way animations are created with specific software, and even hardware, tools)

- The software embedded in the robot to control it "executing" the behavior

In addition, if we can create a really easy to use tool to define and configure behaviors, not only developers could create behaviors, but anyone that could use a computer.

This post is focused in the software embedded in the robot and the two inputs that it will receive from the behavior creator: the behavior specification. The next diagram try to show the main parts:

[caption id="attachment_2136" align="alignleft" width="300"]Creating behaviors Creating behaviors[/caption]

The embedded robot software have four main components and two interfaces:

- A configurable  behavior event generator that will be arising, internally or externally triggered, needs, wishes, and other action driving "behavior events"

- The sensor perception component that receive and process the information from the robot environment

- The motion component that control the robot motion.

- The coordination component that organize all the information to generate the movements showing its behavior.

The two interfaces uncouple the event generator from the perception and motion.

The user could use the default configuration or adjust it  to change different aspects related to its behavior, perception or motion. Just using this configuration it will act stand-alone, based on the configuration and its environment. If we want it to do any specific tasks or tasks we should supply a DSL based specification of the tasks, that will be executed but conditioned by the configured behavior.

lunes, 29 de julio de 2013

(I) Programming serial port communications

250px-Serial_portConnections and operating system symbolic names

A serial port is a communication physical interface through which information  transfers in or out one bit at a time (in contrast to a parallel port) being, more or less compliant, with the RS-232 standard.

But serial port communications aren't only useful for wired DE-9 connectors. it also allows us to use it with USB (ftdi), Bluetooth (serial profile) and Zigbee using virtual serial ports.

·

Types-usbSerial and virtual serial ports appear as  COMx in Windows operating systems (COM1, COM2, ...) andin UNIX/Linux as ttySx or ttyUSBx or even ttyACMx (ttyS0, ttyS1, ttyUSB0, ttyUSB1, ttyACM0, ttyACM1,...).

For programming purposes we usually want to communicate computers with others computers, microcontrollers or other devices like GPS, LED or LCD displays.

·

Serial port programming in C/C++, Windows and Linux

Using the serial port is a lot  easier, but sometimes tricky. The basic commands are to open a connection, read and write over this connection and, finally, tom close it, better if using the C++ RAII idiom.

winWindows commands:
Here you can find a complete C++ for Windows example.

With these next two definitions (among others needed):

HANDLE
serialPortHandle
wchar_t* device

serialPortHandle = CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);


if (serialPortHandle!=INVALID_HANDLE_VALUE)
ReadFile(serialPortHandle, buffer, len, &read_nbr, NULL);

...
if (serialPortHandle!=INVALID_HANDLE_VALUE)
WriteFile(serialPortHandle, buffer, len, &result, NULL);


CloseHandle(serialPortHandle);

linuxUnix/Linux commands:
Here you can find a complete C++ for Linux example.

With these two definitions:
·

int fileDescriptor;

char *device;


·

·


  • Opening a connection, open


struct termios terminalAttributes;

fileDescriptor = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_FSYNC );

// clear terminalAttributes data
memset(&terminalAttributes, 0, sizeof(struct termios));

terminalAttributes.c_cflag = B57600 | CS8 | CLOCAL | CREAD;
terminalAttributes.c_iflag = IGNPAR |  ONLCR;
terminalAttributes.c_oflag = OPOST;
terminalAttributes.c_cc[VTIME] = 0;
terminalAttributes.c_cc[VMIN] = 1;

tcsetattr(fileDescriptor, TCSANOW, &terminalAttributes);


int n=read(fileDescriptor, buffer, len);

...
int n=write(fileDescriptor, buffer, len);


  • Closing the connection, close


close(fileDescriptor);

More information:


https://en.wikipedia.org/wiki/Serial_communication
http://en.wikipedia.org/wiki/Serial_port

http://www.lvr.com/serport.htm
http://digilander.libero.it/robang/rubrica/serial.htm
http://en.wikibooks.org/wiki/Serial_Programming

http://msdn.microsoft.com/en-us/library/ff802693.aspx

domingo, 23 de junio de 2013

Arduino C++ crash examples tutorial using Duemilanove (I)

This is the first example in a serie of cheap (absolutely free and cheap) articles to get some basic and practical C++ knowledge. It will references the great explanations provided at www.cplusplus.com C++ tutorial. Using Arduino Duemilanove (well, really it's a Funduino).

Here you can download The file with the code, and you can find links to a lot of free tutorials, courses and books to learn C++ here.


[sourcecode language="cpp"]
// C++ crash tutorial with Arduino Duemilanove.

// First example: http://softwaresouls.com/softwaresouls/2013/06/23/c-crash-tutorial-using-robotis-cm-900-board-and-ide-i/

/*
Hello World shows messages on construction and destruction
Also it lets you to salute.
Showing always its assigned identifiction number MyId
*/
class HelloWorld
{
private:
int myId; //Object identification num ber

public:

// class constructor http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld(char *message, byte id)
{
myId=id;
Serial.print(message);
printId();
}

// class destructor http://www.cplusplus.com/doc/tutorial/classes/
~HelloWorld()
{
Serial.print ("Destructing object: ");
printId();
}

void printId()
{
Serial.print(" ID:");
Serial.println(myId);
Serial.println(" ");
}

void Salute(char *name)
{
Serial.print("Hi!, ");
Serial.println(name);
Serial.print("Regards from object: ");
printId();
}
};

/*
void setup() function it's only executed one time at the start of the execution.
It is called from a hidden main() function in the Ronbotis CM-900 IDE core.

\ROBOTIS-v0.9.9\hardware\robotis\cores\robotis\main.cpp
Note: "while (1)" is a forevr loop ( http://www.cplusplus.com/doc/tutorial/control ):

(Basic structure http://www.cplusplus.com/doc/tutorial/program_structure/)

int main(void) {
setup();

while (1) {
loop();
}
return 0;
}
*/
void setup()
{
Serial.begin(57600); //initialize serial USB connection
delay(3000); //We will wait 3 seconds, let the user open (Control+Shift+M) the Monitor serial console
}

//We will not see neither the construction nor the destruction of this global object because serial port it's not still initiated
HelloWorld hw0("construction object", 0); //Object construction http://www.cplusplus.com/doc/tutorial/classes/

// A counter to see progress and launch events
int iterationCounter=0; //An integer variable to count iterations http://www.cplusplus.com/doc/tutorial/variables

// void loop() will be executing the sentences it contains while CM-900 is on.
void loop()
{
// Lets's show only the first 5 iterations http://www.cplusplus.com/doc/tutorial/control/
if (iterationCounter<5)
{
Serial.print("starting iteration #");
Serial.println(++iterationCounter); // firts, iterationCounter is incremented and then printed

// We will see the consttructiona and destruction messages from this local (inside the loop function) object. Object construction http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld hw1("constructing object", 1);
hw1.Salute("Joe");

if (iterationCounter==3)
{
// We will see the consttruction and destruction messages from this local (inside the "if" block inside the "loop" function) object. Objet construction http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld hw2("constructing object", 2);
hw2.Salute("Jones");
} // Objet hw2 destruction http://www.cplusplus.com/doc/tutorial/classes/

//Let's show that object hw0 is alive
hw0.Salute("Pepe");

Serial.print("ending iteration #");
Serial.println(iterationCounter++); // first cpunter is printed, then incremented.
} // Objet hw1 destruction http://www.cplusplus.com/doc/tutorial/classes/
} // Program end. Objet hw0 destruction http://www.cplusplus.com/doc/tutorial/classes/
[/sourcecode]

(I) Robotis CM-900 C++ crash examples tutorial

This is the first example in a serie of cheap (absolutely free and cheap) articles to get some basic and practical C++ knowledge. It will references the great explanations provided at www.cplusplus.com C++ tutorial. And using the very cheap and opensource (about 20$/€) Robotis 32 bits microcontroller board CM-900 (STM32 based) and Arduino based IDE.

Here you can download the file with the code, and you can find links to a lot of free tutorials, courses and books to learn C++ here.


[sourcecode language="cpp"]
// C++ crash tutorial with Robotis CM-900.

// First example: http://softwaresouls.com/softwaresouls/2013/06/23/c-crash-tutorial-using-robotis-cm-900-board-and-ide-i/

/*
Hello World shows messages on construction and destruction
Also it lets you to salute.
Showing always its assigned identifiction number MyId
*/
class HelloWorld
{
private:
int myId; //Object identification num ber

public:

// class constructor http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld(char *message, byte id)
{
myId=id;
SerialUSB.print(message);
printId();
}

// class destructor http://www.cplusplus.com/doc/tutorial/classes/
~HelloWorld()
{
SerialUSB.print ("Destructing object: ");
printId();
}

void printId()
{
SerialUSB.print(" ID:");
SerialUSB.println(myId);
SerialUSB.println(" ");
}

void Salute(char *name)
{
SerialUSB.print("Hi!, ");
SerialUSB.println(name);
SerialUSB.print("Regards from object: ");
printId();
}
};

/*
void setup() function it's only executed one time at the start of the execution.
It is called from a hidden main() function in the Ronbotis CM-900 IDE core.

\ROBOTIS-v0.9.9\hardware\robotis\cores\robotis\main.cpp
Note: "while (1)" is a forevr loop ( http://www.cplusplus.com/doc/tutorial/control ):

(Basic structure http://www.cplusplus.com/doc/tutorial/program_structure/)

int main(void) {
setup();

while (1) {
loop();
}
return 0;
}
*/
void setup()
{
SerialUSB.begin(); //initialize serial USB connection
delay(3000); //We will wait 3 seconds, let the user open (Control+Shift+M) the Monitor serial console
}

//We will not see neither the construction nor the destruction of this global object because serial port it's not still initiated
HelloWorld hw0("construction object", 0); //Object construction http://www.cplusplus.com/doc/tutorial/classes/

// A counter to see progress and launch events
int iterationCounter=0; //An integer variable to count iterations http://www.cplusplus.com/doc/tutorial/variables

// void loop() will be executing the sentences it contains while CM-900 is on.
void loop()
{
// Lets's show only the first 5 iterations http://www.cplusplus.com/doc/tutorial/control/
if (iterationCounter<5)
{
SerialUSB.print("starting iteration #");
SerialUSB.println(++iterationCounter); // firts, iterationCounter is incremented and then printed

// We will see the consttruction and destruction messages from this local (inside the loop function) object. Object construction http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld hw1("constructing object", 1);
hw1.Salute("Joe");

if (iterationCounter==3)
{
// We will see the consttructiona and destruction messages from this local (inside the "if" block inside the "loop" function) object. Objet construction http://www.cplusplus.com/doc/tutorial/classes/
HelloWorld hw2("constructing object", 2);
hw2.Salute("Jones");
} // Objet hw2 destruction http://www.cplusplus.com/doc/tutorial/classes/

//Let's show that object hw0 is alive
hw0.Salute("Pepe");

SerialUSB.print("ending iteration #");
SerialUSB.println(iterationCounter++); // first cpunter is printed, then incremented.
} // Objet hw1 destruction http://www.cplusplus.com/doc/tutorial/classes/
} // Program end. Objet hw0 destruction http://www.cplusplus.com/doc/tutorial/classes/
[/sourcecode]

domingo, 16 de junio de 2013

Robotis CM-900 in Toss Mode and querying connected sensors

CM-900 is a very cheap and tiny Robotis Dynamixel controller based in the STM32 ARM 32 bits microcontroller. Here you can find several links to documents.

CM-900_Size

I think it's ideal as a controller managed with, for example, a Raspberry Pi or a Pandaboard, so I have created a program which can be managed externally to control Dynamixel items (AX-12, AX-S1), Toss Mode, and sensors connected to the CM-900 with a simple protocol similar but simpler than the Dynamixel protocol:

[Headers] [ID] [Command code] [Nº Params] [Param1] [Param2] [ParamN]

Toss Mode works like USB2Dynamixel, but with this program in addition you can get sensor vales.

Toss Mode was a software feature, at least since CM-5, which allows you to use the elements connected to the controller from another device, usually a more powerful computer. What it receives from the USB or serial is sent to the Dynamixel bus, and whatever it receives from Dynamyxel bus is sent to the serial or USB connection.

Example for blinking twice: { 0xFF, 0xFF, 90, 1, 1, 2 }

Headers: 0xFF 0xFF

ID: 90

Command code: 1

Number of parameters: 1

Parameter 1: 2

Example for reading ultrasonic sensor (HC-SR04) : { 0xFF, 0xFF, 90, 2, 0 }

[sourcecode language="CPP"]

void MainWindow::testCM900_Sensor_US()
{
const int size=5;
byte buffer2[size] = { 0xFF, 0xFF, 90, 2, 0 };
pDynComm->rawWrite(buffer2, size);
}
[/sourcecode]

[caption id="attachment_1753" align="alignleft" width="320"]Ultrasonic sensor hc-sr04 Ultrasonic sensor hc-sr04[/caption]

And here the file with the code for Robotis CM-9 IDE version 0.9.9. You also need to copy Prof. Mason library for ultrasonic sensor to CM 900 IDE libraries folder. Althought it i still a beta version, I think it works ok. Asigning true to these variables, the messages for debugging are sent either to USB connection o Serial2 (connecting Zigbee is the easy option):

[sourcecode language="CPP"]
bool debugOutputSerial2On=true;
bool debugOutputOn=false;
[/sourcecode]

Arduino LCD 1602 (16x2) display

Another little pearl from www.dx.com is the Arduino compatible LCD 1602 (16 characters each of the 2 rows) display:

20130616_091530

It's really cheap, 6$/4.5€, works very fine and it's easy to use! I will use as a handy debug display and little dashboard (it has 6 buttons at the bottom) while on field robots debugging, but this wioll be a near post with the sourcecode (that also will be a order receiver to program a Rapsberry Pi to control a robot using and Arduino Funduino Duemilanove.)

Arduino LCD text

Two easy examples from the Arduino IDE wondeful examples, it's important that you notice that the initialization sentence should be:

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

The hello world
[sourcecode language="C"]
/*
LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The LiquidCrystal
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.

This sketch prints "Hello World!" to the LCD
and shows the time.

The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe

This example code is in the public domain.

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

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Te, amo, Nuriitaa!");
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}
[/sourcecode]

Testing buttons
[sourcecode language="C"]
//Sample using LiquidCrystal library
#include <LiquidCrystal.h>

/*******************************************************

This program will test the LCD panel and the buttons
Mark Bramwell, July 2010

********************************************************/

// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key = 0;
int adc_key_in = 0;
#define btnRIGHT 0
#define btnUP 1
#define btnDOWN 2
#define btnLEFT 3
#define btnSELECT 4
#define btnNONE 5

// read the buttons
int read_LCD_buttons()
{
adc_key_in = analogRead(0); // read the value from the sensor
// my buttons when read are centered at these valies: 0, 144, 329, 504, 741
// we add approx 50 to those values and check to see if we are close
if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
if (adc_key_in < 50) return btnRIGHT;
if (adc_key_in < 195) return btnUP;
if (adc_key_in < 380) return btnDOWN;
if (adc_key_in < 555) return btnLEFT;
if (adc_key_in < 790) return btnSELECT;
return btnNONE; // when all others fail, return this...
}

void setup()
{
lcd.begin(16, 2); // start the library
lcd.setCursor(0,0);
lcd.print("Push the buttons"); // print a simple message
}

void loop()
{
lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over
lcd.print(millis()/1000); // display seconds elapsed since power-up


lcd.setCursor(0,1); // move to the begining of the second line
lcd_key = read_LCD_buttons(); // read the buttons

switch (lcd_key) // depending on which button was pushed, we perform an action
{
case btnRIGHT:
{
lcd.print("RIGHT ");
break;
}
case btnLEFT:
{
lcd.print("LEFT ");
break;
}
case btnUP:
{
lcd.print("UP ");
break;
}
case btnDOWN:
{
lcd.print("DOWN ");
break;
}
case btnSELECT:
{
lcd.print("SELECT");
break;
}
case btnNONE:
{
lcd.print("NONE ");
break;
}
}
}
[/sourcecode]

lunes, 15 de abril de 2013

Cheapest Smart Car Robot: parts, examples of use and documentation

[caption id="attachment_1552" align="aligncenter" width="600"]Ultrasonic Smart Car Kit Ultrasonic Smart Car Kit[/caption]

[caption id="attachment_1746" align="alignleft" width="150"]Funduino Arduino DuemilaNove clon Funduino Arduino DuemilaNove clon[/caption]

It's really cheap but it does not include any documentation; but don't panic, all you will need can be found on Internet. And now, the main electronic components: the microcontroller, the dual motor driver, the ultrasonic sensor and the servo:

The microcontroller brain is a Funduino (Arduino Duemilanove clone), and as far I've used it (and as other buyer said is fully, at least for software, compatible). Here we will not have any problem because there are a lot of documentation about Arduino and Duemilanove.

A simple hello world example (here the file)

[sourcecode language="c"]

// Blinking LED

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

void setup()
{
Serial.begin(57600);
printf (&amp;amp;quot;Setup/n/l&amp;amp;quot;);
Serial.println(&amp;amp;quot;Hello world!&amp;amp;quot;);
pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
printf (&amp;amp;quot;2009&amp;amp;quot;);
Serial.println(&amp;amp;quot;2009&amp;amp;quot;);
digitalWrite(ledPin, HIGH);   // sets the LED on
delay(1000);                  // waits for a second
digitalWrite(ledPin, LOW);    // sets the LED off
delay(1000);                  // waits for a second
}

[/sourcecode]

[caption id="attachment_1748" align="alignleft" width="150"]Dual_H-Bridge_Motor_Driver Dual_H-Bridge_Motor_Driver[/caption]

But to control the two motors this kit use an Dual H-Bridge motor driver (L298). Here (read the Drive Two DC Motors section) you can find a lot of useful documentation and examples,  and  here you can find also more information, specially about electronics.

Here the file with the example

[sourcecode language="c"]
int ENA=5;//connected to Arduino's port 5(output pwm)
int IN1=2;//connected to Arduino's port 2
int IN2=3;//connected to Arduino's port 3
int ENB=6;//connected to Arduino's port 6(output pwm)
int IN3=4;//connected to Arduino's port 4
int IN4=7;//connected to Arduino's port 7
void setup()
{
Serial.begin(57600);
Serial.println(&amp;amp;quot;Two motors&amp;amp;quot;);
pinMode(ENA,OUTPUT);//output
pinMode(ENB,OUTPUT);
pinMode(IN1,OUTPUT);
pinMode(IN2,OUTPUT);
pinMode(IN3,OUTPUT);
pinMode(IN4,OUTPUT);
digitalWrite(ENA,LOW);
digitalWrite(ENB,LOW);//stop driving
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);//setting motorA's directon
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);//setting motorB's directon
}
void loop()
{
analogWrite(ENA,255);//start driving motorA
analogWrite(ENB,255);//start driving motorB
delay(3000);
analogWrite (IN1,0);//stop driving motorA
analogWrite (IN2,0);//stop driving motorB

analogWrite (IN3,0);//stop driving motorA
analogWrite (IN4,0);//stop driving motorB

delay (3000);

int ledPin = 13;
while (1)
{
digitalWrite(ledPin, HIGH);   // sets the LED on
delay(1000);                  // waits for a second
digitalWrite(ledPin, LOW);    // sets the LED off
delay(000);
}
&amp;amp;lt;pre&amp;amp;gt;[/sourcecode]

[caption id="attachment_1753" align="alignleft" width="150"]Ultrasonic sensor hc-sr04 Ultrasonic sensor hc-sr04[/caption]

The HC-SR04 ultrasonic distance sensor, example of use (here the file):

[sourcecode language="c"]

#define trigPin 9
#define echoPin 11

void setup() {
Serial.begin (115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance &amp;amp;gt; 400 || distance &amp;amp;lt; 0){
Serial.println(&amp;amp;quot;Out of range&amp;amp;quot;);
}
else {
Serial.print(distance);
Serial.println(&amp;amp;quot; cm&amp;amp;quot;);
}
delay(500);
}

[/sourcecode]


[caption id="attachment_1755" align="alignleft" width="150"]TowerPro micro servo SG90 TowerPro micro servo SG90[/caption]

And the Tower PRO SG-90 micro servo (and here the file with the example):

[sourcecode language="c"]
// Sweep
// by BARRAGAN &amp;amp;lt;http://barraganstudio.com&amp;amp;gt;
// This example code is in the public domain.

#include &amp;amp;lt;Servo.h&amp;amp;gt;

Servo myservo;  // create servo object to control a servo
// a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
myservo.attach(3);  // attaches the servo on pin 3 to the servo object
}

void loop()
{
for(pos = 0; pos &amp;amp;lt; 180; pos += 1)  // goes from 0 degrees to 180 degrees
{                                  // in steps of 1 degree
myservo.write(pos);              // tell servo to go to position in variable 'pos'
delay(15);                       // waits 15ms for the servo to reach the position
}
for(pos = 180; pos&amp;amp;gt;=1; pos-=1)     // goes from 180 degrees to 0 degrees
{
myservo.write(pos);              // tell servo to go to position in variable 'pos'
delay(15);                       // waits 15ms for the servo to reach the position
}
}
[/sourcecode]

Soon I will add an LCD display with 6 buttons

domingo, 17 de marzo de 2013

C. C++, C# robotics programming Workshop/tutorial with the cheapest robotic platform

[caption id="" align="alignleft" width="108"]My Smart Car construction My Smart Car construction[/caption]

[Update March 30, 2013: Added photo gallery]

I will start a C. C++, C# robotics programming Workshop/tutorial with the cheapest robotic platform I have found at dealextreme.com: (Arduino based) plus a Raspberry Pi (like this that use Bioloid as the hardware platform):

Ultrasonic Smart Car Kit

I have not still received the kit, but I will review the kit and start the workshop as soon as I receive it.

lunes, 29 de octubre de 2012

Robotizando un coche teledirigido con Arduino

Esta es la primera entrega de una serie (espero) de ellas sobre cómo hackear un coche teledirigido y ponerle todos los sensores y cacharros que se nos ocurran.

Por supuesto, empezaremos por el principio: cómo hacer que el coche sea autónomo a través de un Arduino. El elegido en este caso es el Arduino Leonardo, pero vale  casi cualquier otro.

Materiales necesarios:

  • Un coche teledirigido baratillo, de los chinos mismo

  • Una placa Arduino

  • Cuatro resistencias (yo usé de 1K, pero valen de un valor +-50%)

  • Estaño

  • Funda termoretráctil

  • Varios cables de colores (a poder ser) de unos 20cm

  • Una batería de 9V


Herramientas necesarias:

  • Estañador

  • Destornillador

  • Pelacables (o una navaja, en su defecto)

  • Alicates de corte diagonal

  • Desoldador de estaño (no imprescindible, pero sí recomendable)


Pasos a seguir:

1. Desmonta el coche

Photobucket

Photobucket

Photobucket

2. Desatornilla la placa

Photobucket

3. Elimina el circuito integrado, ya que no lo necesitaremos para nada. Para ello tienes dos opciones:

a) Consigues calentar el estaño de sus patitas y lo sacas como Dios manda o...
b) Con los alicates le cortas las patitas por la parte de arriba y lo sacas con unas pinzas. Yo me he decidido por esta segunda opción. ;)

Photobucket

Éste es el aspecto que mostrará cuando las hayas cortado todas:

Photobucket

Photobucket

4. Prepara las resistencias

Lo que vamos a hacer ahora es proteger nuestra placa, por lo que vamos a coger las cuatro resistencias que tenemos (en mi caso de 1K, pero ya digo que el valor no es crítico, pueden ir desde 0,5K a 1,5K) y cuatro cables de colores de unos 10cm de largo, y los vamos a unir formando binomios resistencia-cable:

Photobucket

Cuando ya tengas las parejas hechas, consolida la unión con estaño.

Photobucket

Las cuatro parejas tendrán este aspecto:

Photobucket

Elimina el trozo sobrante con los alicates de corte.

5. Estudia el circuito integrado que desechaste

Fíjate en las letras impresas que tiene encima para poder Googlearlo. Si has comprado un coche en un chino o en algún sitio por el estilo, seguramente tendrás un integrado como este:

http://jumpjack.altervista.org/digitalrome/progetti/macchinina/TX-2C%28RX-2C%29AY.pdf

Lo que se trata es de buscar a qué corresponde cada pata del integrado para poder controlar nosotros a voluntad el coche. Fïjate que en este pdf aparecen tanto las especificaciones del transmisor (el que está en el mando), como del receptor (que es el que nos interesa). Los pines que estamos buscando son los correspondientes a:

  • Tierra (GND)

  • Derecha (RIGHT)

  • Izquierda (LEFT)

  • Marcha atrás (BACKWARD)

  • Hacia delante (FORWARD)


En mi caso, se trata de los pines 2, 6, 7, 10 y 11.

6. Introduce las parejas que preparaste y el quinto cable en los pines que has identificado

Lo que tienes que hacer ahora es, con ayuda del estañador y el desoldador, eliminar las patitas correspondientes a esos pines para poder introducir las resistencias por los agujeros. Procura limpiar bien la zona con el desoldador para que sea más fácil introducir la pata de la resistencia, aunque ya te digo que yo no tenía y no me costó excesivo trabajo dejar la zona presentable).

A continuación, introduce las cuatro resistencias por los pines correspondientes a las dos marchas y a los lados izquierdo y derecho de la siguiente manera:

Photobucket

Puedes observar que la resistencia queda hacia el lado de arriba, y cómo están limpios y preparados el resto de agujeros. Éste es el aspecto que tiene por debajo:

Photobucket

Una vez introduzcas las cuatro resistencias y el quinto cable que tenías apartado, pero aun no habías usado (es el que va en la patilla de GND, efectivamente), estaña los cinco pines y corta el sobrante tanto de las resistencias como del cable de tierra que te sobrará.

Photobucket

Photobucket

Éste es el aspecto que tendrá tu placa entonces:

Photobucket

7. Protegiendo tu placa

Lo que vas a hacer ahora es proteger esas parejas que hemos introducido con la funda termoretráctil. Para ello corta en varios trozos la funda de tal manera que cada trozo cubra totalmente la resistencia, el trozo estañado y un poco del cable. Unos 10-15 cm, vamos. Y como bien dice su nombre, aplícale calor para que se retraiga y se moldee según la resistencia y el cable. Puedes usar desde un mechero o una cerilla a un secador de pelo. Tú mismo. El objetivo es darle un mejor acabado a las conexiones eléctricas y dotar de protección mecánica y anti-abrasiva a los cables y demás componentes eléctricos.

Photobucket

Photobucket

Éste será el aspecto que tendrá finalmente tu placa.

8. Preparando el Arduino

Si no lo has hecho antes, ahora es el momento de anotar a qué color corresponde cada pin. Puedes hacer una tabla como la siguiente (la que resultó en mi caso):

PIN                  COLOR                  FUNCIÓN

2                               Verde                             GND

6                               Gris                                 Derecha

7                               Azul                                Izquierda

10                            Blanco                           Marcha atrás

11                            Amarillo                       Adelante

El código que vamos a preparar es muy sencillo, ya que únicamente se trata de verificar las cuatro funciones: las dos direcciones marcha atrás y adelante, y los dos lados izquierda y derecha. Se trata del siguiente:

[sourcecode language="c"]
/*
Probando las cuatro órdenes del coche
*/

int forward = 12;  // Forward pin
int reverse = 11;  // Reverse pin
int left = 10;     // Left pin
int right = 9;     // Right pin

void setup()       // Configuración de los pines como salidas
{
pinMode(forward, OUTPUT);
pinMode(reverse, OUTPUT);
pinMode(left, OUTPUT);
pinMode(right, OUTPUT);
}

void go_forward()
{
digitalWrite(forward,HIGH);  // Da la orden de adelante
digitalWrite(reverse,LOW);   // Apaga la orden de marcha atrás
}
void go_reverse()
{
digitalWrite(reverse,HIGH);  // Da la orden de marcha atrás
digitalWrite(forward,LOW);   // Apaga la orden de adelante
}
void stop_car()
{
digitalWrite(reverse,LOW);   // Apaga todas las órdenes
digitalWrite(forward,LOW);
digitalWrite(left,LOW);
digitalWrite(right,LOW);
}
void go_left()
{
digitalWrite(left,HIGH);     // Da la orden de izquierda
digitalWrite(right,LOW);     // Quita la orden de derecha
}
void go_right()
{
digitalWrite(right,HIGH);    // Da la orden de derecha
digitalWrite(left,LOW);      // Quita la orden de izquierda
}

void loop()
{

go_forward();
go_left();
delay(500);

stop_car();
delay(500);

go_reverse();
go_left();
delay(500);

stop_car();
delay(500);

go_forward();
go_right();
delay(500);

stop_car();
delay(500);

go_reverse();
go_right();
delay(500);

stop_car();
delay(500);

}
[/sourcecode]

9. Conectando y probando el Arduino

Y por fin llega el último paso: donde por fin pruebas si todo esto funciona. Elimina la antena del coche si no lo has hecho ya (obviamente, no nos hará falta) y atornilla la placa con los tornillos que quitaste en el paso 2.

Conecta los cables según los pines que has declarado en el programa (en mi caso del 9 al 12) y los colores que anotaste antes. El color de tierra lo llevarás al GND de la placa, que como ves en la foto, está junto a los otros cuatro cables (en mi caso, repito):

Photobucket

Para realizar las pruebas de código, o variaciones, te recomiendo que aun no alimentes la placa con una batería, de tal manera que tendrás que tener la placa accesible al USB. Puedes volver a montar el coche y sujetar la placa con una goma elástica, como en mi caso, o dejarlo ya desmontado para introducir la placa y la batería dentro. Ahí según tu elección.

10. Alimentando la placa

Tan sólo falta el toque final: hacer el coche totalmente autónomo. Con el código ya probado ya sabes que se mueve solo, así que sólo falta el tema de la alimentación. Para ello puedes usar una batería normal de 9V, como esta:

Photobucket

Puedes fijarla tanto en el propio chasis del coche (si tienes sitio), como en la carrocería (algo como esto):

Photobucket

La conexión la puedes realizar con un enchufe centro-positivo en el conector de alimentación de la placa, o con unos simples cables como los ya empleados, insertándolos en los pines GND y Vin del conector POWER de la placa. Según tengas el adaptador o no.

El resultado será algo como esto:

[youtube http://www.youtube.com/watch?v=ulftGvqm1LU]

Espero que te haya resultado divertido. Si tienes cualquier pregunta o duda, estamos aquí para ayudarte.

Un saludo y nos vemos en la siguiente entrega! :D