Mostrando entradas con la etiqueta Bioloid. Mostrar todas las entradas
Mostrando entradas con la etiqueta Bioloid. 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.

martes, 25 de junio de 2013

Bioloid Workbench Windows C++ examples

This post presents the Windows version of two examples/utilities built, this time, with MS Visual C++ and QT Creator, a great open source IDE and framework.

The first utility has a comand line user interface, being an easy example with only two DLL dependencies to the Visual C++ runtimes.

Screenshot-Terminal

The second example utility has a graphic user interface created with QT Creator.

QTWorkbench

Here you can find the bin executables and the projects with the source code.

This is the main function of the first example, the command line:

[sourcecode language="cpp"]
int _tmain(int argc, _TCHAR* argv[])
{
cout << "AXControl_v2_VS_CPP test v0" << endl;

bool quit=false;
MyBasicSystem::BasicSystem mySystem;
UI ui(mySystem);
do
{
ui.showMenu();
int selected=ui.selectOption();
if (selected==ui.OptionQuit)
quit=true;
ui.executeSelectedOption(selected);
}while (!quit);

mySystem.dynamixelCommunication.close();

return 0;
}
[/sourcecode]

[Update] Yesterday I discovered a subtle but ugly bug. Can you spot it? Send an email to if you can't find it but you want to know the danger bug.

It use two classes, the "BasicSystem" (in the library "VS_CPP_AXControl_lib.lib") and a simple "UI" class that receives the input from the user and use the operations offered by the "BasicSystem" class.

For example:

[sourcecode language="cpp"]
int UI::getPosition()
{
int position=0;

do
{
cout << "Type a value between 0 and 1023 to set the AX-12 in that position" << endl; cin>>position;

}while(!validRange(position, 0, 1023));

cout << "Position:" << position << endl;

return position;
}
...
void UI::doSetPosition()
{
int ax12Id=getId();
int position=getPosition();

mySystem.dynamixelCommunication.sendOrder(ax12Id, MyCommunications::GoalPosition,(short) position);
}
[/sourcecode]

And all the cource code:

[sourcecode language="cpp"]
/*------------------------------------------------------------------------------*\
* This source file is subject to the GPLv3 license that is bundled with this *
* package in the file COPYING. *
* It is also available through the world-wide-web at this URL: *
* http://www.gnu.org/licenses/gpl-3.0.txt *
* If you did not receive a copy of the license and are unable to obtain it *
* through the world-wide-web, please send an email to *
* siempre.aprendiendo@gmail.com so we can send you a copy immediately. *
* *
* @category Robotics *
* @copyright Copyright (c) 2011 Jose Cortes (http://www.siempreaprendiendo.es) *
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU v3 Licence *
* *
\*------------------------------------------------------------------------------*/

#include "stdafx.h"
#include
#include "BasicSystem.h"
#include "Util.h"

using namespace std;

class UI
{
public:
static const int OptionQuit=8;

UI(MyBasicSystem::BasicSystem& aMySystem) : mySystem(aMySystem) {}

void showMenu();
int selectOption();
bool executeSelectedOption(int selected);
void doBeep();

private:
MyBasicSystem::BasicSystem mySystem;

static const int OptionSetLEDOnOff=1;
static const int OptionQueryAX12=2;
static const int OptionMoveAX12=3;
static const int OptionTorqueAX12=4;
static const int OptionQuerySensor=5;
static const int OptionShowMenu=6;
static const int OptionBeep=7;

static const int MinOption=OptionSetLEDOnOff;
static const int MaxOption=OptionQuit;

bool validRange(int value, int MinValue, int MaxValue);
bool nonValidOption(int option);
int getPosition();
int getId();
int getSensorPort();
void doGetPosition();
void doSetPosition();
void doQuerySensor();
void doSetLEDOnOff();
void doSetTorqueOnOff();

};

void UI::showMenu()
{
cout << "V02" << endl;

cout << OptionSetLEDOnOff << ".- Toggle AX-12 LED" << endl;
cout << OptionQueryAX12 << ".- Query AX-12" << endl;
cout << OptionMoveAX12 << ".- Move AX-12" << endl;
cout << OptionTorqueAX12 << ".- Torque AX-12" << endl;
cout << OptionQuerySensor << ".- Query CM-510 sensor" << endl;
cout << OptionShowMenu << ".- Show menu" << endl;
cout << OptionBeep << ".- Beep" << endl;
cout << OptionQuit << ".- Quit" << endl;
}

bool UI::nonValidOption(int option)
{
return (optionMaxOption);
}

int UI::selectOption()
{
int option=-1;

while (nonValidOption(option))
{
cout << "Select option (" << MinOption << "-" << MaxOption << ")" << endl; cin >> option;
if (nonValidOption(option))
{
cout << endl;
cout << endl;
cout << "(" << option << ") is NOT a valid option" << endl; } } return option; } bool UI::validRange(int value, int MinValue, int MaxValue) { return (value>=MinValue && value<=MaxValue);
}

int UI::getPosition()
{
int position=0;

do
{
cout << "Type a value between 0 and 1023 to set the AX-12 in that position" << endl; cin>>position;

}while(!validRange(position, 0, 1023));

cout << "Position:" << position << endl; return position; } int UI::getId() { int ax12Id=1; do { puts ("Type the ID of the AX-12 to use, a value between 1 and 18, "); cin >> ax12Id;

}while(!validRange(ax12Id, 1, 18));

cout << "AX12 Id:" << ax12Id << endl; return ax12Id; } int UI::getSensorPort() { int sensorPort=1; do { puts ("Type the sensor Port to read, a value between 1 and 6, "); cin >> sensorPort;

}while(!validRange(sensorPort, 1, 6));

cout << "Sensor Port number:" << sensorPort << endl;

return sensorPort;
}

void UI::doBeep()
{
cout << "Beep" << endl;
mySystem.dynamixelCommunication.sendOrder(100, AXS1_Buzzer, (byte) DO, (short) 500);
Sleep (2);
mySystem.dynamixelCommunication.sendOrder(200, MyCommunications::Beep, (byte) 5);
}

void UI::doGetPosition()
{
int ax12Id=getId();

int position = mySystem.dynamixelCommunication.readValue(ax12Id, MyCommunications::PresentPosition);
cout << "the position is: [" << position << "] " << endl << endl << endl;
}

void UI::doSetPosition()
{
int ax12Id=getId();
int position=getPosition();

mySystem.dynamixelCommunication.sendOrder(ax12Id, MyCommunications::GoalPosition,(short) position);
}

void UI::doQuerySensor()
{
int sensorPort=getSensorPort();

int value=mySystem.dynamixelCommunication.readSensorValue (200, ReadCM510SensorRaw, sensorPort);
cout << "the sensor reads: [" << value << "] " << endl << endl << endl;
}

void UI::doSetLEDOnOff()
{
byte lByte=0, hByte=0;
int ledValue;

int ax12Id=getId();

ledValue=mySystem.dynamixelCommunication.readValue(ax12Id, MyCommunications::LED);
Hex::toHexHLConversion(ledValue, hByte, lByte);

bool onOff=false;
if (lByte!=0)
onOff=true;

cout << "The LED is: [" << (onOff?"on":"off") << "], putting it: [" << (onOff?"Off":"on") << "] " << endl << endl << endl;
mySystem.dynamixelCommunication.sendOrder(ax12Id, MyCommunications::LED, byte(onOff?0:1));
}

void UI::doSetTorqueOnOff()
{
byte lByte=0, hByte=0;
int ax12Id=getId();

int torque=mySystem.dynamixelCommunication.readValue(ax12Id, MyCommunications::Torque);
Hex::toHexHLConversion(torque, hByte, lByte);
bool onOff=(lByte!=0?true:false);

cout << "The Torque is: [" << (onOff?"on":"off") << "], putting it: [" << (onOff?"Off":"on") << "] " << endl << endl << endl;

mySystem.dynamixelCommunication.sendOrder(ax12Id, MyCommunications::Torque,(byte) (onOff?0:1));
}

bool UI::executeSelectedOption(int option)
{
bool isOk=true;
cout << endl;
cout << endl;

cout << "Selected option: [" << option << "] " << endl; switch(option) { case OptionSetLEDOnOff: doSetLEDOnOff(); break; case OptionQueryAX12: doGetPosition(); break; case OptionMoveAX12: doSetPosition(); break; case OptionTorqueAX12: doSetTorqueOnOff(); break; case OptionQuerySensor: doQuerySensor(); break; case OptionShowMenu: showMenu(); break; case OptionBeep: doBeep(); break; } return isOk; } [/sourcecode]

The code for the Qt version is more complex, but as an example, the same operation that the example for the command line:

[sourcecode language="cpp"] int MainWindow::getAX12_1_Id() { // Get the value from the edit control for the first AX-12 QString qStr=ui->SB_AX12_1_ID->text();
int id=Util::convertToInt(qStr.toStdString());

return id;
}
...
void MainWindow::on_B_AX12_1_SET_POS_clicked()
{
int id = getAX12_1_Id();

// Get the target position from the UI edit control as string and a convert it to int
short position= ui->SB_AX12_1_POS->text().toInt();

// Send the order to the AX-12 with the "id" to go to "position"
pDynComm->sendOrder(id, MyCommunications::GoalPosition,position);
}
[/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]

miércoles, 12 de junio de 2013

Robotis CM-900 as a tosser for Dynamixel commands

CM-900 is really tiny and cheap, so is perfect to use as communication bridge between any computer (Raspberry Pi, Pandaboard, etc. included, of course) and the Dynamixel bus. Whatever it receives from the Serial USB (usually commands and queries) is sent to the Dynamixel bus, and what it receives from the Dynamixel bus is sent to the SerialUSB (usually answers)

Here is the source code of the little program for CM-900 IDE:

[sourcecode language="C"]
int counter;
bool onlyOnceHappened;

void blinkOnce()
{
digitalWrite(BOARD_LED_PIN, LOW);
delay_us(100);
digitalWrite(BOARD_LED_PIN, HIGH);
}

void setup()
{
pinMode(BOARD_LED_PIN, OUTPUT);

onlyOnceHappened=false;
counter=0;

//USB Serial initialize
SerialUSB.begin();
// SerialUSB.attachInterrupt(USBDataReceived);
//DXL initialize
Dxl.begin(1);
}

byte aByte=0;
uint8 aUint8;

void loop()
{
// SerialUSB.println (counter++);

if (onlyOnceHappened==false)
{
blinkOnce();
onlyOnceHappened=true;
delay (3000); //Some time to the user to activate the monitor/console
SerialUSB.println ("v1.1.1 Orders receiver started");
}

if (SerialUSB.available())
{
aUint8=SerialUSB.read();
blinkOnce();
Dxl.writeRaw(aUint8);
// delay(20);
}

if (Dxl.available())
{
aByte=Dxl.readRaw();
blinkOnce();
SerialUSB.write(aByte);
// delay(20);
}
}

[/sourcecode]

Here the file.

In the next post I will include an improved version that could read sensors connected to the CM-900, "expanding" the Dynamixel protocol.

lunes, 15 de abril de 2013

CM-900 Robotis IDE more programming examples

I've started to program CM-900 "translating" the example from the C programming tutorial for CM-510

CM900_with_its parts_names

You can get more information at robotsource.org CM-900 community circle and the CM-900 e-manual. There you can find:

- Quick start guide

- Presentation Workshop

- Arduino based IDE to program it very easily (examples included)

- Source code and instructions

- Using other servos

- Interfacing sensors

I already have "translated" two examples: a simple "hello world" like where a servo is move to 2 different positions and another where the servo id and position is asked and after entered the data the servo is positionated in the typed position, validating that id and position are in range.

The "hello World " example (here the zipped file):

[sourcecode language="c"]
#define P_GOAL_POSITION_L     30
#define P_MOVING              46

int counter;
int onlyOnceHappened;

void setup()
{
//USB Serial initialize

onlyOnceHappened=0;
counter=0;

SerialUSB.begin();
Dxl.begin(1);
delay (5000);
SerialUSB.println("Setup");
}

void loop()
{

delay (3000);
SerialUSB.print("loop");
SerialUSB.println(counter);
counter++;
delay(1000);

if (onlyOnceHappened==0)
{
onlyOnceHappened=1;
SerialUSB.println("Hello, World");
}

int id=8;

SerialUSB.println ("Simple example #0");

SerialUSB.print ("Perform movement 1 with the AX-12:");
SerialUSB.println (id);
byte bMoving = Dxl.readByte( id, P_MOVING);
byte CommStatus = Dxl.getResult();
if( CommStatus == COMM_RXSUCCESS )
Dxl.writeWord( id, P_GOAL_POSITION_L, 511 );
else
SerialUSB.println ("CommStatus IS NOT COMM_RXSUCCESS");

SerialUSB.println ("Pause half a second");
delay (500); // half-second pause

SerialUSB.println ("Beep!");
//buzzOn (100); // beep

SerialUSB.println ("Pause for a second");
delay (1000); // pause for 1 second

SerialUSB.print ("Perform movement 2 with the AX-12: ");
SerialUSB.println (id);

Dxl.writeWord( id, P_GOAL_POSITION_L, 611 );

SerialUSB.println ("End");

}
[/sourcecode]

Asking Id and Position example, (here the zipped file)

[sourcecode language="c"]

int counter;
bool onlyOnceHappened;

int id;
int position;

bool debugOutputOn;
char charReaded;

void debugOutputUSB(char *buffer, bool newlineAfterMessage)
{
if (debugOutputOn)
{
if (newlineAfterMessage)
SerialUSB.println(buffer);
else
SerialUSB.print(buffer);
}
}

void debugOutputUSB(int value, bool newlineAfterMessage)
{
if (debugOutputOn)
{
if (newlineAfterMessage)
SerialUSB.println(value);
else
SerialUSB.print(value);
}
}

void debugOutputPairUSB(char *buffer, int value)
{
if (debugOutputOn)
{
SerialUSB.println ("");
SerialUSB.print(buffer);
SerialUSB.println(value);
}
}

void debugOutputPairUSB(char *buffer1, char *buffer2)
{
if (debugOutputOn)
{
SerialUSB.println ("");
SerialUSB.print(buffer1);
SerialUSB.println(buffer2);
}
}

void setup()
{
//USB Serial initialize

onlyOnceHappened=false;
counter=0;
debugOutputOn=false;

SerialUSB.begin();
Dxl.begin(1);
delay (3000);

debugOutputUSB("Setuped", true);
}

void checkIfDebugOn()
{
SerialUSB.print("Put debug ON?, y/n");
charReaded=SerialUSB.read();

if (charReaded=='y' || charReaded=='Y')
debugOutputOn=true;
else
debugOutputOn=false;

debugOutputPairUSB ("DebugPut is:", debugOutputOn);
}

void loop()
{
delay (1500);
SerialUSB.println ("Simple example #1");

if (onlyOnceHappened==false)
{
onlyOnceHappened=true;
checkIfDebugOn();
}

debugOutputPairUSB  ("Loop: ",counter);
counter++;
delay(500);

debugOutputUSB("Starting loop", true);

while(true) // we'll repeat this loop forever
{
id=getId(); // get the ID of the AX-12 that we want to move
position=getPosition(); // get the goal position

Dxl.writeWord( id, P_GOAL_POSITION_L, position); // sent the command to the Dynamixel
debugOutputUSB ("Dxl.writeWorded", true);
}
}
// I have created a simple ayoi because I have problem compiling atoi
int myatoi(char *buffer)
{
int len=strlen(buffer)-2;
int value=0;
int i=0;
int base=0;
int number=0;

for (i=len;i>=0;i--)
{
number=int(buffer[i])-int('0');

debugOutputPairUSB ("buffer[i]: ", int(buffer[i]));

if (i==len)
{
value=number;
}
else
{
value+=base * number;
}

debugOutputPairUSB ("i: ",i);
debugOutputPairUSB ("number: ", number);
debugOutputPairUSB("base: ", base);
debugOutputPairUSB("valor: ", value);

if (base==0)
{
base=10;
}
else
base=base*10;
}

return value;
}

bool isValid(int value, int MinValue, int MaxValue)
{
return (value>=MinValue && value<=MaxValue);
}

void readString(char *bufferParameter)
{
int i=0; // We'll use this variable as index of the buffer where we will store data

do
{
bufferParameter[i]=(char) SerialUSB.read(); // it store the read character in the i position of bufferParameter
SerialUSB.print(bufferParameter[i]); // showing it
if (bufferParameter[i]=='\b') // if Backspace was pressed
i--; // it goes to the previous position, rewritting the previoulsy typed character
else //
i++; // it will write in the next position
//    SerialUSB.println(int(bufferParameter[i-1]));
}while(bufferParameter[i-1]!=10); // while the last values is not INTRO. The symmbol ! represents the logical operator NOT

bufferParameter[i]=0; // A NULL (0, zero) is necessary in the last position of any string
}

/*
It read an string, it's converted to integer and returned
*/
int readInteger(char *bufferParameter)
{
//  return SerialUSB.parseInt();

readString(bufferParameter);

//  int valor=int(bufferParameter[0]-int('0'));
debugOutputPairUSB ("Leido: ", bufferParameter);
int valor=myatoi(bufferParameter);

debugOutputPairUSB ("Valor leido: ", valor);

return valor;
}

int getId()
{
/*
We define an array enough large, 256 bytes (characters). Probably it's enough with 4 bytes, but if we type more than the defined size we will get an error*/
char buffer[256];

/*
And we define another integer variable, it's very advisable to asign a value in the definition, in this case we assign the minimun value, 1*/
int ax12Id=1;

do
{ // starting the loop
SerialUSB.println ("Enter the ID of the AX-12 that you wwant to move, between 1 y 18: ");
SerialUSB.print("Id:");
ax12Id=readInteger(buffer); // this function will read from what we type in the keyboard
//// exclamation (!) is the NOT logical operator. It will repeat the loop while the value is not valid
}while(!isValid(ax12Id, 1, 18));

// Showing the typed value
SerialUSB.println(" ");
SerialUSB.print("AX12 ID:");
SerialUSB.println(ax12Id);

return ax12Id;
}

int getPosition()
{
char buffer[256];
int position=0;

do
{
SerialUSB.println ("Enter a value between 0 and 1023 as the goal position");
SerialUSB.print ("Position:");
position=readInteger(buffer);
}while(!isValid(position, 0, 1023));

// Showing the typed value
SerialUSB.println(" ");
SerialUSB.print("Position:");
SerialUSB.println(position);

return position;
}

[/sourcecode]

lunes, 25 de marzo de 2013

So... let's the Bioloid, C++ and QT games start!

To cretate this workshop I'm using Ubuntu 12.04, GNU g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 (see Synaptic installer capture),

[caption id="attachment_1635" align="aligncenter" width="300"]Synaptic G++ Synaptic G++[/caption]

QT 5.0.1 and QT creator 2.6.2,

QT creator is a very easy, and good, free IDE with a great design tool for creating user interfaces:

Be careful with this bug: Qt Creator 2.0: UI layout is not updated before launching the application http://qt-project.org/forums/viewthread/292 Is very annoying and time consuming, the solution is in the last comment (setting the UI_DIR in the .pro file)

[caption id="attachment_1637" align="aligncenter" width="600"]QTCreator Bioloid QTWorkshop QTCreator Bioloid QTWorkshop[/caption]

I also will use it with Windows 7.

I also use Boost to get some C++11 features for threading. For example:

pWorkThread = new thread(&Activity::doWork, this, parameter);

std::lock_guard < std::mutex > guard(myMutex);

Don't bother if you don't understand it right now, it's in the guts of the AXControl_v2 library we will use it in a very easy way, as you will see below. Here you will find a lot of resources to learn basic and advanced C++

Example context fot std::lock_guard < std::mutex > guard(myMutex);

[sourcecode language="cpp"]

short DynamixelCommunication::readSensorValue(int id, AX12Address address,
int port) {
std::lock_guard < std::mutex > guard(myMutex);
short value = -1;
try {
int size = getReadSensorWordCommand(buffer, (byte) (id), address,
(byte) (port));
memset(&result, 0, MaxBufferSize);
serialPort.query(buffer, result, size, WaitTimeReadSensor);
value = getQueryResult(result, size);
if (value <= 0)
Debug::show("DynamixelCommunication.readSensorValue", value);

} catch (exception e) {
Debug::show("DynamixelCommunication.readSensorValue", e.what());
}
return value;
}

[/sourcecode]

And context for pWorkThread = new thread(&Activity::doWork, this, parameter);:

[sourcecode language="cpp"]

class Activity {
private:

protected:
std::thread *pWorkThread;

...

}

void Activity::start(int parameter) {
working = true;
pWorkThread = new thread(&Activity::doWork, this, parameter);
Util::sleepMS(10);
}
Let's see how to open the connection
[/sourcecode]

Let's see how to open the connection to the CM-510:

[sourcecode language="cpp"]
void MainWindow::on_B_Open_clicked()
{
//QString output="Open it";
//QMessageBox::information(this, "Output", output, QMessageBox::Ok);

//dynComm.open("/dev/ttyUSB0",57600); //open with these parameters
if (pDynComm->open()) //open getting the parameter from the configuration fiel
{
//Connection opened
setConnectionButtons(true); //User interface update
updateAX12Parameters(ui->SB_AX12_1_ID->text().toInt()); //User interface update
}
else
{
//Show problem opening the connection
string cantOpenPortName="I can't open port: ";
cantOpenPortName+=pConf->getStringValue(DynamixelCommunication::ParameterSerialPortName);

QMessageBox::information(this, "Error", QString::fromStdString(cantOpenPortName), QMessageBox::Ok);
}
}
[/sourcecode]

and get a beep from the Robotis CM-510 (using this alternative firmware):

[sourcecode language="cpp"]
pDynComm->sendOrder(200, MyCommunications::BeepCM510, 0); //200 is the Dynamixel device ID used for the CM-510, 0 because beep doesn't need any additional value
[/sourcecode]

Getting the AX12 position and showing it:

[sourcecode language="cpp"]
void MainWindow::on_B_AX12_1_GET_POS_clicked()
{
QString qStr;

int id = getAX12_1_Id();

int position = pDynComm->readValue(id, MyCommunications::PresentPosition);

ui->SB_AX12_1_POS->setValue(position);
[/sourcecode]

Setting the AX12 position:

[sourcecode language="cpp"]
void MainWindow::on_B_AX12_1_SET_POS_clicked()
{
int id = getAX12_1_Id();

int position= ui->SB_AX12_1_POS->text().toInt();
pDynComm->sendOrder(id, MyCommunications::GoalPosition,position);
}
[/sourcecode]

Putting the selected AX12 LED on and off

[sourcecode language="cpp"]
void MainWindow::on_CH_AX12_1_LED_clicked(bool checked)
{
int id = getAX12_1_Id();

pDynComm->sendOrder(id, MyCommunications::LED, (checked?1:0));// if checked 1, else 0
}
[/sourcecode]

And an auxiliary UI method to get the id from the selected AX-12

[sourcecode language="cpp"]
{
int MainWindow::getAX12_1_Id()
{
QString qStr=ui->SB_AX12_1_ID->text();
int id=Util::convertToInt(qStr.toStdString());

return id;
}
[/sourcecode]

You can download sources and Linux binaries here

A diagram with all the AXControl_v2 lib classes and their methods:

[caption id="attachment_1384" align="aligncenter" width="600"]c++ signatura c++ signatura[/caption]

[Update]

[caption id="attachment_1722" align="aligncenter" width="164"]QT5 Bioloid Workbench QT5 Bioloid Workbench[/caption]

domingo, 17 de marzo de 2013

C++, Bioloid and Raspberry Pi (v0.2)

[V.02 updates: AX C++ architecture, core classes diagram and HexaWheels scanning video]

Why C++, Bioloid and Raspberry Pi?


[caption id="attachment_1254" align="alignleft" width="150"]C++ Stroustrup's book C++ Stroustrup's book[/caption]

C++, specially with the great improvements of the last C++11 standard, joins together a great efficiency in performance and a low memory footprint with advanced high level language features, making C++ a great tool for embedding, robotics, programming.

If you want to know how to use C++ very efficiently these two guides will help you:

- The JSF air vehicle C++ coding standards ( F-35 fighter aircraft)

- ISO C++ committee's report on performance

.

.

 

[caption id="attachment_1221" align="alignleft" width="300"]Bioloid Premium Bioloid Premium[/caption]

Bioloid Premium is a wonderful kit for creating legged and wheeled robots, including (here full parts list):

- 18 powerful and versatile AX-12 servos

- an ATMega 2561 (CM-510) or, recently, an ARM STM32F103RE 32bits (CM-530), based controller. Also you can control the AX-12 with the USB2Dynamixel straight from your USB with a FTDI driver.

- And a lot of parts to create the structure of the robot

.

[caption id="attachment_1257" align="alignleft" width="216"]RaspberryPi RaspberryPi[/caption]

Raspberry Pi is the cheaper and more brilliant conceived SBC (more specifications here):

- Broadcom BCM2835 SoC full HD multimedia applications processor

- 700 MHz Low Power ARM1176JZ-F Applications Processor

- Dual Core VideoCore IV® Multimedia Co-Processor

- 256/512 MB SDRAM

One simple example:
[youtube http://www.youtube.com/watch?v=Yhv43H5Omfc&w=480&h=360]

Learning C++



Starting:

C++ is a very powerful but complex programming language, so I think that the better approach is to start step by step, from the most easy features (yes, C++ could be used in an easy way) to the most advanced features it offers. What is C++? I will quote (I try to not explain anything that already is explained), Stroustrup, "his father", from his book The C++ programming language 3th Edition:
"C++ is a general-purpose programming language with a bias towards systems programming that
– is a better C,
– supports data abstraction,
– supports object-oriented programming, and
– supports generic programming."

And wikipedia:
C++ (pronounced "see plus plus") is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features.[3] Developed by Bjarne Stroustrup starting in 1979 at Bell Labs, it adds object oriented features, such as classes, and other enhancements to the C programming language.

Web resources:

If you want more C++ links, these found at JUCE will help you.




[caption id="attachment_1385" align="alignright" width="140"]Programming -- Principles and Practice Using C++Programming -- Principles and Practice Using C++ Programming -- Principles and Practice Using C++[/caption]

Free books and documents:




- Maintain stability and compatibility with C++98 and possibly with C;
- Improve C++ to facilitate systems and library design, rather than to introduce new features useful only to specific applications;
- Increase type safety by providing safer alternatives to earlier unsafe techniques;
- Increase performance and the ability to work directly with hardware


Books:

Advancing:

In robotics, and embedded programming in general, we will need some advanced knowledge and practices to reach our goals.

Free books and documents:


  • Concurrent programming, threading Our robots we will need to do several actions simultaneously, like perceiving the world with several sensors, moving and deciding what to do to reach is objectives.



  • Communications, the serial port communications functions are used for wireless and wired connections, and we will need to communicate between controllers and with sensors and servos.


Books:

C++ robotics programming


Well, this is really the goal, robotics programming.

As this is a workshop it will follow the creation of the the walker and vehicle Hexapod showed above in the video. This is currently the core architecture and the HexaWheels module (namespace classes):

[caption id="attachment_1391" align="aligncenter" width="300"]AX C++ architecture v2 AX C++ architecture v2[/caption]

And these are the core classes:

todo_signatura

The workshop will include:

- Basics

Like communications with serial port and wireless, using Dynamixels, sensors, ... Language features for robotics, like asynchronous communications and threads and... delays!.

- Intermediate

Combination of basics features using sensors (like scanning) and servos (walking motions). For example, scanning with a DMS sensor:

As a simple example:

[youtube http://www.youtube.com/watch?v=UHKaYuaZi4A&w=480&h=360]

- Advanced

Advanced perception and behaviours

I think this could very funny, using an advanced sensor like Asus Xtion, to detect certain objects to interact, and create configurable and amusing behaviours.

CM-510 mirocontroller programming

- Tools:

PC, Raspberry Pi and Pandaboard, installation and configuration, tool and projects

- GNU C++, Boost
- Eclipse
- QT 5

The contents will come soon, very soon...

miércoles, 13 de marzo de 2013

Playing With Qt 5, C++ and Bioloid

I have been searching the best UI (libraries and UI creating tools) multiplatform framework for several years, and QT 5 is the best option I have found. Its libraries are easy to use, specially the slots (UI widgets connection to code) of QT5.  QT Creator is pretty easy to use and the UI designer is the free best tool I have tested. Really I'm learning to use it as creating these examples.

A very simple example:

[caption id="attachment_1508" align="aligncenter" width="287"]QT Bioloid Workshop QT Bioloid Workshop[/caption]

The code uses two classes from the AXControl_v2 library:

- Configuration, it loads the  parameters from the file HexaWheels.conf (currently in spanish):
Tiempo_Espera_ms=36 // wait time
Tiempo_Espera_Sensores_ms=60 // wait time for sensors
Nombre_Puerto_Serie=/dev/ttyUSB0 // serial port name
Baudios_Puerto_Serie=57600 // baud rate

- DynamixelCommunication, it offers the commands to control Dynamixel items

Connecting to the Dynamixel bus:

[sourcecode language="cpp"]
void MainWindow::on_B_Open_clicked()
{
pDynComm->open(); // open the connection using the parameters from the configuration file
setConnectionButtons(true); // enable and disable conveniently the buttons
}
[/sourcecode]

Getting and setting the AX12 Dynamixel position:

[sourcecode language="cpp"]
void MainWindow::on_B_AX12_1_GET_POS_clicked()
{
QString qStr;

int id=ui->SB_AX12_1_ID->text().toInt();
int position = pDynComm->readValue(id, MyCommunications::PresentPosition);
string str=std::to_string(position);

ui->E_AX12_1_POS->setText(qStr.fromStdString(str));
}

void MainWindow::on_B_AX12_1_SET_POS_clicked()
{
QString qStr=ui->SB_AX12_1_ID->text();
int id=Util::convertToInt(qStr.toStdString());

int position= ui->E_AX12_1_POS->text().toInt();
pDynComm->sendOrder(id, MyCommunications::GoalPosition,position);
}

[/sourcecode]

And this is the (unfinished) main window code:

[sourcecode language="cpp"]
#include

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "Configuration.h"
#include "DynamixelCommunication.h"
#include "Util.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
pConf=new Configuration ("/home/jose/proyectos_svn_win/trunk/bioloid/Comun/CPP/AXControl_v2/src/HexaWheels.conf");
pDynComm=new DynamixelCommunication (pConf);
}

MainWindow::~MainWindow()
{
delete ui;

pDynComm->close();
delete pDynComm;
delete pConf;
}

void MainWindow::setConnectionButtons(bool onOff)
{
ui->B_Open->setEnabled(!onOff);
ui->B_Beep->setEnabled(onOff);
ui->B_Close->setEnabled(onOff);
}

void MainWindow::on_B_Open_clicked()
{
//QString output="Open it";
//QMessageBox::information(this, "Output", output, QMessageBox::Ok);

//dynComm.open("/dev/ttyUSB0",57600);
pDynComm->open();

setConnectionButtons(true);
}

void MainWindow::on_B_Beep_clicked()
{
pDynComm->sendOrder(200, MyCommunications::BeepCM510, 5);
}

void MainWindow::on_B_Close_clicked()
{
pDynComm->close();
setConnectionButtons(false);
QString output="Port closed!";
QMessageBox::information(this, "Output", output, QMessageBox::Ok);

}

void MainWindow::on_B_AX12_1_GET_POS_clicked()
{
QString qStr;

int id=ui->SB_AX12_1_ID->text().toInt();
int position = pDynComm->readValue(id, MyCommunications::PresentPosition);
string str=std::to_string(position);

ui->E_AX12_1_POS->setText(qStr.fromStdString(str));
}

void MainWindow::on_B_AX12_1_SET_POS_clicked()
{
QString qStr=ui->SB_AX12_1_ID->text();
int id=Util::convertToInt(qStr.toStdString());

int position= ui->E_AX12_1_POS->text().toInt();
pDynComm->sendOrder(id, MyCommunications::GoalPosition,position);
}

[/sourcecode]

But it's "growing":

[caption id="attachment_1546" align="aligncenter" width="285"]QT_Workbench QT_Workbench[/caption]

I have uploaded the source and binary of this work in progress to
https://www.box.com/s/mdsdeoem0gg4o2rapipj/s/mdsdeoem0gg4o2rapipj

viernes, 1 de marzo de 2013

Workshop: USB, serial and remote communications with C#

[Previous post: Workshop: Dynamixel communications with C#]

[caption id="attachment_1117" align="alignright" width="150"]Bioloid SerialPort2Dynamixel C# Bioloid SerialPort2Dynamixel C#[/caption]

SerialPort2Dynamixel


Encapsulating  the SerialPort .Net class offers an easy way to use the serial port and receive Dynamixel Zig messages with the Dynamixel protocol.

.

.

Collaborator classes:


[caption id="attachment_1134" align="alignright" width="150"]Bioloid SerialPort2Dynamixel C# Collaborators Bioloid SerialPort2Dynamixel C# Collaborators[/caption]

- The SerialPort .Net class.

- RCDataReader class, which unpack the Dynamixel Zigbee sequence offering the clean data received.

Operations:


The public interface that others classes will use offers principally these operations:

public void setRemoteControlMode(bool on), which sets on or off the reception of data

[sourcecode language="csharp"]

public void setRemoteControlMode(bool on)
{
if (on)
setReceiveDataMethod(rdDataReader.rawRemoteDataReceived);
else
setReceiveDataMethod(null);
}

[/sourcecode]

public void setReceiveDataMethod(remoteControlDataReceived rcDataReceived), that sets the method that will be called when serial port data is received.

And some basics serial port data operations:

[caption id="attachment_1112" align="alignright" width="131"]Raspberry Pi - USB2Dynamixel - CM510 Raspberry Pi - USB2Dynamixel - CM510[/caption]

public bool open(String com, int speed), to open the serial port which name is in the com parameter. Wireless communications and USB ports, as used by Zig or USB2Dynaniel, are also serial ports  (COM1, COM2, ... or /ttyUSB0, ttyUSB1).

public void close(), it will do nothing if the port is already closed.

public byte[] query(byte[] buffer, int pos, int wait), send (write) a query and gets (read) the result.

public void rawWrite(byte[] buffer, int pos), well... it will write whatever contains the buffer in the first pos positions

public byte[] rawRead() , read and returns the data received.

Notes:


To avoid concurrency problems all the operations that use the Dynamixel bus are protected with a Mutex object that avoids that two or more concurrent objects use SerialPort2Dynamixel simultaneously entering the same operation or using the same resources, like variables, objects or the Dynamixel bus.

[caption id="attachment_1620" align="aligncenter" width="300"]Xevel USB2AX Xevel USB2AX[/caption]

[caption id="attachment_1622" align="aligncenter" width="300"]USB2AX over USB2DYNAMIXEL USB2AX over USB2DYNAMIXEL[/caption]


RCDataReader


[caption id="attachment_1155" align="alignright" width="150"]Bioloid RCDataReader C# Bioloid RCDataReader C#[/caption]

[caption id="attachment_1128" align="alignleft" width="112"]Remote communications RemoteCommunications[/caption]

Its responsability is to receive the Dynamixel Zig packets and extract the data.

Collaborator class:


- The ZigSequence enum, with the Dynamixels protocols data sections

[caption id="attachment_1171" align="aligncenter" width="300"]RC-100 packet RC-100 packet[/caption]

Operations:


[caption id="attachment_1146" align="alignleft" width="105"]Robotis RC-100 remote controller values Robotis RC-100 remote controller values[/caption]

public void rawRemoteDataReceived(byte[] rcData), receives the Zigbee data.

public int getValue(), returns the last value received

miércoles, 27 de febrero de 2013

Workshop: Dynamixel communications with C#

[Next post: Workshop: USB, serial and remote communications with C#]

As I wrote in the previous post, I am not using Robotis Dynamixel SDK USB2Dynamixelbecause it only works with the  USB2Dynamixel, and I need that it also should work with the serial port and with zigbee or bluetooth (really all 4 use the serial connection). Also I want to query sensors connected to the CM-510.

[caption id="attachment_1053" align="alignright" width="150"]Zigbee device Zigbee[/caption]

Using the CM-510 and computer serial port (or USB to serial) connection you are free to use any wired or wireless device. Really there are a lot of possibilities.

We will start connecting to the Dynamixel bus and sending commands and queries. These classes do the work:

- DynamixelCommunication

- SerialPort2Dynamixel

- RCDataReader

But there are other classes that offer to them some additional services, like Configuration, Utils, Hex and several enumeration types.

I will use the Class-Responsability-Collaboration template to present the classes.

DynamixelCommunicationBioloid DynamixelCommunication class C#


The main responsibility of this class is sending commands and queries to any Dynamixel device, including the sensors, sound and other capabilities of the CM-510 controller.

Collaborator classes:


SerialPort2Dynamixel,  that offers operations to use the serial port encapsulating .Net SerialPort class

- Three enums for easy use and avoid errors, using an specific type is safer that using simple integers.

    public enum AXS1_IRSensor { Left, Center, Right, None };
    public enum AXS1_SoundNote { LA, LA_, SI, DO, DO_, RE }; //Only the first six 
    public enum DynamixelFunction, with all the Dynamixel protocols codes and some that I added for the CM-510.

- Configuration class, that reads a file where are stored basic configuration parameters. like:

        private static string ParameterSerialPortName
        private static string ParameterSerialPortBaudRate
        private static string ParameterWaitTime_ms
        private static string ParameterWaitTimeForSensors_ms

Bioloid communications C#



Operations:


The public operations are the interface that other classes will use, like:

- short readValue(int id, DynamixelFunction address), reads the value of any AX-12 parameter (or other Dynamixels)


- bool sendOrder(int id, DynamixelFunction address, int value), send commands, like position, speed or torque.


And the private that do internal work supporting the public interface, like:

static int getReadWordCommand(byte[] buffer, byte id, DynamixelFunction address), create the Dynamixel hexadecimal sequence (FF FF 0F 05 03 1E CB 01 FE)


- static short getQueryResult(byte[] res), once the query or command is sent it gets the result.


Let's see readValue and two other called functions:

[sourcecode language="csharp"]

public short readValue(int id, DynamixelFunction address)
{
mutex.WaitOne();
short position = -1;

try
{
int size = getReadWordCommand(buffer, (byte)id, address);
byte[] res = serialPort.query(buffer, size, WaitTimeReadSensor);

position = getQueryResult(res);
if (position < 0)
Debug.show("DynamixelCommunication.readValue", position);

}
catch (Exception e)
{
Debug.show("DynamixelCommunication.readValue", e.Message);
}

mutex.ReleaseMutex();

return position;
}

private static int getReadWordCommand(byte[] buffer, byte id, DynamixelFunction address)
{
//OXFF 0XFF ID LENGTH INSTRUCTION PARAMETER1 …PARAMETER N CHECK SUM
int pos = 0;

buffer[pos++] = 0xff;
buffer[pos++] = 0xff;
buffer[pos++] = id;

// bodyLength = 4
buffer[pos++] = 4;

//the instruction, read => 2
buffer[pos++] = 2;

// AX12 register
buffer[pos++] = (byte)address;

//bytes to read
buffer[pos++] = 2;

byte checksum = Utils.checkSumatory(buffer, pos);
buffer[pos++] = checksum;

return pos;
}

private static short getQueryResult(byte[] res)
{
short value = -1;

if (res != null)
{
int length = res.Length;
if (res != null && length > 5 && res[4] == 0)
{
byte l = 0;
byte h = res[5];
if (length > 6)
{
l = res[6];
}

value = Hex.fromHexHLConversionToShort(h, l);
}
}
return value;
}

[/sourcecode]

Notes:


To avoid concurrency problems all the operations that use the Dynamixel bus are protected with a Mutex object that avoids that two or more concurrent objects use DynamixelCommunication simultaneously entering the same operation or using the same resources, like variables, objects or the Dynamixel bus.

All the operations use the same buffer, but being protected with the Mutex object I think that is the better option, although in a previous version I used a very different approach where there were AX12 objects with their own buffer.

[Next post: Workshop: USB, serial and remote communications with C#]

domingo, 24 de febrero de 2013

Workshop: Programming a Bioloid robot workbench using C# and C++

[Next post: Dynamixel communications with C#]

It would be a workshop using C# .Net and C++ with Qt 5. The code presented here is used in this two different robots and boards, a HP 214 Ipaq with Windows Mobile and a Raspberry Pi, using the Robotis CM-510 as the servo and sensors controller:

[youtube http://www.youtube.com/watch?v=mvaMTdlb48E&w=281&h=210][youtube http://www.youtube.com/watch?v=Yhv43H5Omfc&w=281&h=210]

These will be the first steps, using C# and .Net , here the code and the exe for the Workbench UI:

Bioloid Workbench


Using this enhaced Toss Mode that adds some new functions.  Some of them: