CNC II Project

Direcciones:
     Rulemanes: Balparda - Rio Negro 1600 Esq. Cerro Largo (29021249)
                       Modelo ruleman: EE 3 2RS/R62RS SUMEC ($42)


    Barras de acero: ALTIX http://www.altix.com.uy/materiales.php
                              Dr. Pablo Ehrlich No. 3974 | Tel : (598) 2208 6700
                         
                                        BARRACA DE HIERROS SAN MARTIN
                                        José M. Penco 3422 - Tel: 2081561-2007521 


---------------------------------------------------------------------------------------------------------------------------
Circuito CNC-Arduino:


Terminal azul - El que esta al lado de los tips:


pos 1: motor (verde)
pos 2: motor (rojo)
pos 3: motor (blanco verde)
pos 4: motor (blanco rojo)


Terminal azul - El que esta debajo del de arriba:



pos 1: arduino (digital 7)
pos 2: arduino (digital 6)
pos 3: arduino (digital 5)
pos 4: arduino (digital 4)


los dos common del motor (cables blanco y negro) van a +
gnd de arduino va a -



---------------------------------------------------------------------------------------------------------------------------



Mach3: explicación de step y dir:
The standard signalling for hobby CNC axes is know as STEP/DIR. Two lines, one indicating direction (High/Low=Fwd/Rev), and the second is pulsed (Low to High to Low) to indicate a single step.


Motores:
     ASTROSYN - MINIANGLE STEPPER
     TYPE: 23LM - C343 - P2H
     3.5 v/PHASE
     1.4 amp/PHASE
     1.8 deg/STEP
     NO. T0615
     MINEBEA CO., LTD. 782-22


     Cableado:
          common (+12v) = rojo+negro
          secuencia=blanco_rojo, blanco_verde, rojo, verde
-------------------------------------------------------------------------------------------------------
Como calcular los amperes necesarios para un motor:

P = V x I

Si el motor es de 180Watts y la alimentacion es 24V, los amp que requiere son 180/24 = 5amp


-------------------------------------------------------------------------------------------------------
tip102. visto de frente: pata izq=base, pata medio=colector, pata der=emisor  ***LA PLACA METALICA ES COLECTOR***

Ventilador:

base -> 10k -> +5v
colector -> negativo del ventilador
emisor -> -12v
positivo del ventioador -> +12v

Stepper:

negro y blanco del stepper -> +12v

base -> 1.5k -> digital pin 11 de arduino
colector -> blanco_rojo del stepper
emisor -> tierra

base -> 1.5k -> digital pin 10 de arduino
colector -> blanco_verde del stepper
emisor -> tierra

base -> 1.5k -> digital pin 9 de arduino
colector -> rojo del stepper
emisor -> tierra

base -> 1.5k -> digital pin 8 de arduino
colector -> verde del stepper
emisor -> tierra

gnd de arduino -> tierra ***todas las tierras juntas, como siempre!!***


Codigo del arduino:

int motorPin1 = 8;
int motorPin2 = 9;
int motorPin3 = 10;
int motorPin4 = 11;
int delayTime = 2;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void detener() {
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, LOW);
  while (true);
}

void loop() {
  detener();
  
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, LOW);
  delay(delayTime);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, HIGH);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, LOW);
  delay(delayTime);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
  delay(delayTime);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, HIGH);
  delay(delayTime);
}

-------------------------------------------------------------------------------------------------------




Backslash explicado y metodos para evitarlo:


http://www.machinetoolhelp.com/Repairing/What_is_backlash.html


Ejemplo de eje x con plataforma movil:


http://www.buildyouridea.com/cnc/Shrapnel/phase_one/phase_one.html


Apuntes sobre acoples, varillas roscadas, etc


 stainless steel threaded rod


http://melca.com.ar/apuntes.html


http://www.cncsimulator.com


Urls de 3 axis stepper motor driver board y motor couplers:



http://cgi.ebay.com/CNC-3-axis-Stepper-Motor-Driver-Board-Controller-TB6560-/110712814497?pt=LH_DefaultDomain_0&hash=item19c6ff7ba1#ht_2600wt_1185


http://cgi.ebay.com/3-Axis-CNC-TB6560-Stepper-Motor-Driver-Controller-Board-/260782799764?pt=LH_DefaultDomain_0&hash=item3cb7ddbb94#ht_907wt_952


Este es el que tiene las imagenes:
http://cgi.ebay.com/3-Axis-TB6560-CNC-Stepper-Motor-Driver-Board-Controller-/270549461424?pt=LH_DefaultDomain_0&hash=item3efe0129b0#ht_4614wt_952


Motor coupler
http://cgi.ebay.com/CNC-Stepper-Motor-Flexible-Coupling-Coupler-6x6mm-/180700376869?pt=LH_DefaultDomain_0&hash=item2a1294ef25#ht_4538wt_905

Con free shipping
http://cgi.ebay.com/3x-CNC-Stepper-Motor-Flexible-Coupling-Coupler-Shaft-/170671010420?pt=LH_DefaultDomain_0&hash=item27bcc8f274#ht_2199wt_952


Flexible Coupling Motor Shaft Coupler
http://www.ebay.com/itm/5mm-X-5mm-Flexible-Coupling-Motor-Shaft-Coupler-/250865518774?pt=LH_DefaultDomain_0&hash=item3a68c008b6#ht_1427wt_952

Pillow block bearing
http://www.ebay.com/itm/1-2-UCP201-8-PREMIUM-Pillow-Block-Bearing-/390289943324?_trksid=p4340.m1374&_trkparms=algo%3DPI.WATCH%26its%3DC%252BS%26itu%3DUCC%26otn%3D15%26ps%3D63%26clkid%3D2438999684422364687#ht_2110wt_1139

THK LINEAR BALL BEARING SLIDE TABLE WITH / BALLSCREW
http://www.ebay.com/itm/THK-LINEAR-BALL-BEARING-SLIDE-TABLE-BALLSCREW-/380364985607?_trksid=p4340.m1374&_trkparms=algo%3DPI.WATCH%26its%3DC%252BS%26itu%3DUCC%26otn%3D15%26ps%3D63%26clkid%3D2439000852926923977#ht_1540wt_1185

10 Ball Bearings DELTA 14"Band Saw Blade Guide Bandsaw
http://www.ebay.com/itm/10-Ball-Bearings-DELTA-14-Band-Saw-Blade-Guide-Bandsaw-/130343841011?_trksid=p4340.m1374&_trkparms=algo%3DPI.WATCH%26its%3DC%252BS%26itu%3DUCC%26otn%3D15%26ps%3D63%26clkid%3D2439001682456578259#ht_783wt_905

Linear Ball Bearing Rack Slides Rails, NEW $120 model!
http://www.ebay.com/itm/Linear-Ball-Bearing-Rack-Slides-Rails-NEW-120-model-/230235510593?pt=COMP_EN_Servers&hash=item359b1b1741#ht_656wt_1139


Configurar Mach 3
http://www.youtube.com/watch?v=A49gKd7g8FQ

No se puede hacer debug de una aplicacion .aspx

Cuando se pone un breakpoint y la aplicacion no se detiene allí, hacer lo siguiente:

1. Abrir el archive de registro (RegEdit)
2. Buscar la llave HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3. Agregar la clave "Dword" llamada "TabProcGrowth" y asígnale el valor "0"

WebService y JSON con jQuery, con Visual Studio 2008 que corre en Visual Studio 2005

1. Crear un web service con visual studio 2008
2. Luego de comprobar que funciona, crear un WebService vacio en Visual Studio 2005 e incorporar los archivos del paso1 (web.config, .asmx, .vb, etc)

Codigo que funciona en VS2005:

web.config


<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
<compilation debug="true" strict="false" explicit="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages>
<namespaces>
<clear/>
<add namespace="System"/>
<add namespace="System.Collections"/>
<add namespace="System.Collections.Generic"/>
<add namespace="System.Collections.Specialized"/>
<add namespace="System.Configuration"/>
<add namespace="System.Text"/>
<add namespace="System.Text.RegularExpressions"/>
<add namespace="System.Linq"/>
<add namespace="System.Xml.Linq"/>
<add namespace="System.Web"/>
<add namespace="System.Web.Caching"/>
<add namespace="System.Web.SessionState"/>
<add namespace="System.Web.Security"/>
<add namespace="System.Web.Profile"/>
<add namespace="System.Web.UI"/>
<add namespace="System.Web.UI.WebControls"/>
<add namespace="System.Web.UI.WebControls.WebParts"/>
<add namespace="System.Web.UI.HtmlControls"/>
</namespaces>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
<authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>


Prueba.asmx


Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function Consulta1(param1 As String, param2 As String) As String

        Return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }"

    End Function
End Class

Llamado desde javascript con jquery:

var url_ws
url_ws = "http://" + window.self.location.hostname + "/wsTEST/Prueba.asmx/Consulta1";
jQuery.ajax({
type: "POST",
url: url_ws,
data: "{'param1': '4', 'param2': '10'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
async: false,
cache: false,
success: function(response) {
var v = getJSON(response);
if (v.datos[0].nombre != "")
$("#"+div_display).html("&nbsp;&nbsp" + v.datos[0].nombre);
else
$("#"+div_display).html("Cliente no existe");
},
error: function(xhr, ajaxOptions, thrownError) {
//$("#"+div_display).html("Error al obtener el nombre del cliente");
}
});

         function getJSON(data_obj)
        {
                if (data_obj.d)
                      data_ok = data_obj.d;
               else
                      data_ok = data_obj;

               evalJson = eval("var varJSON = " + data_ok + ";"); 

               return varJSON;  
         }




Controlador de steppers FET-3

http://www.stepperworld.com/fet3.htm

Software CNC: http://www.linuxcnc.org/

Bionical Arduino con WII

http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/

http://todbot.com/blog/bionicarduino/

idea: grabar secuencia de movimientos y luego enviarlos por puerto serie para que se reproduzcan en los servos.


Codigo:

WinChuckDemo.pde



/*
 * WiiChuckDemo --
 *
 * 2008 Tod E. Kurt, http://thingm.com/
 *
 */

#include <Wire.h>
#include "nunchuck_funcs.h"

int loop_cnt=0;

byte accx,accy,zbut,cbut;
int ledPin = 13;


void setup()
{
    Serial.begin(19200);
    nunchuck_setpowerpins();
    nunchuck_init(); // send the initilization handshake
   
    Serial.print("WiiChuckDemo ready\n");
}

void loop()
{
    if( loop_cnt > 100 ) { // every 100 msecs get new data
        loop_cnt = 0;

        nunchuck_get_data();


nunchuck_obtener_datos();
/*
        accx  = nunchuck_accelx(); // ranges from approx 70 - 182
        accy  = nunchuck_accely(); // ranges from approx 65 - 173
        zbut = nunchuck_zbutton();
        cbut = nunchuck_cbutton();
           
        Serial.print("accx: "); Serial.print((byte)accx,DEC);
        Serial.print("\taccy: "); Serial.print((byte)accy,DEC);
        Serial.print("\tzbut: "); Serial.print((byte)zbut,DEC);
        Serial.print("\tcbut: "); Serial.println((byte)cbut,DEC);*/
    }
    loop_cnt++;
    delay(1);
}



WinChuckDemo.pde


/*
 * Nunchuck functions  -- Talk to a Wii Nunchuck
 *
 * This library is from the Bionic Arduino course :
 *                          http://todbot.com/blog/bionicarduino/
 *
 * 2007 Tod E. Kurt, http://todbot.com/blog/
 *
 * The Wii Nunchuck reading code originally from Windmeadow Labs
 *   http://www.windmeadow.com/node/42
 */

#include <WProgram.h>

static uint8_t nunchuck_buf[6];   // array to store nunchuck data,

// Uses port C (analog in) pins as power & ground for Nunchuck
static void nunchuck_setpowerpins()
{
#define pwrpin PORTC3
#define gndpin PORTC2
    DDRC |= _BV(pwrpin) | _BV(gndpin);
    PORTC &=~ _BV(gndpin);
    PORTC |=  _BV(pwrpin);
    delay(100);  // wait for things to stabilize      
}

// initialize the I2C system, join the I2C bus,
// and tell the nunchuck we're talking to it
static void nunchuck_init()
{
    Wire.begin();                // join i2c bus as master
    Wire.beginTransmission(0x52);// transmit to device 0x52
    Wire.send(0x40);// sends memory address
    Wire.send(0x00);// sends sent a zero.
    Wire.endTransmission();// stop transmitting
}

// Send a request for data to the nunchuck
// was "send_zero()"
static void nunchuck_send_request()
{
    Wire.beginTransmission(0x52);// transmit to device 0x52
    Wire.send(0x00);// sends one byte
    Wire.endTransmission();// stop transmitting
}

// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
static char nunchuk_decode_byte (char x)
{
    x = (x ^ 0x17) + 0x17;
    return x;
}

// Receive data back from the nunchuck,
// returns 1 on successful read. returns 0 on failure
static int nunchuck_get_data()
{
    int cnt=0;
    Wire.requestFrom (0x52, 6);// request data from nunchuck
    while (Wire.available ()) {
        // receive byte as an integer
        nunchuck_buf[cnt] = nunchuk_decode_byte(Wire.receive());
        cnt++;
    }
    nunchuck_send_request();  // send request for next data payload
    // If we recieved the 6 bytes, then go print them
    if (cnt >= 5) {
        return 1;   // success
    }
    return 0; //failure
}

// Print the input data we have recieved
// accel data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits.  That is why I
// multiply them by 2 * 2
static void nunchuck_print_data()
{
    static int i=0;
    int joy_x_axis = nunchuck_buf[0];
    int joy_y_axis = nunchuck_buf[1];
    int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
    int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
    int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;

    int z_button = 0;
    int c_button = 0;

    // byte nunchuck_buf[5] contains bits for z and c buttons
    // it also contains the least significant bits for the accelerometer data
    // so we have to check each bit of byte outbuf[5]
    if ((nunchuck_buf[5] >> 0) & 1)
        z_button = 1;
    if ((nunchuck_buf[5] >> 1) & 1)
        c_button = 1;

    if ((nunchuck_buf[5] >> 2) & 1)
        accel_x_axis += 2;
    if ((nunchuck_buf[5] >> 3) & 1)
        accel_x_axis += 1;

    if ((nunchuck_buf[5] >> 4) & 1)
        accel_y_axis += 2;
    if ((nunchuck_buf[5] >> 5) & 1)
        accel_y_axis += 1;

    if ((nunchuck_buf[5] >> 6) & 1)
        accel_z_axis += 2;
    if ((nunchuck_buf[5] >> 7) & 1)
        accel_z_axis += 1;

    Serial.print(i,DEC);
    Serial.print("\t");

    Serial.print("joy:");
    Serial.print(joy_x_axis,DEC);
    Serial.print(",");
    Serial.print(joy_y_axis, DEC);
    Serial.print("  \t");

    Serial.print("acc:");
    Serial.print(accel_x_axis, DEC);
    Serial.print(",");
    Serial.print(accel_y_axis, DEC);
    Serial.print(",");
    Serial.print(accel_z_axis, DEC);
    Serial.print("\t");

    Serial.print("but:");
    Serial.print(z_button, DEC);
    Serial.print(",");
    Serial.print(c_button, DEC);

    Serial.print("\r\n");  // newline
    i++;
}

static void nunchuck_obtener_datos()
{
    static int i=0;
    int joy_x_axis = nunchuck_buf[0];
    int joy_y_axis = nunchuck_buf[1];
    int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
    int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
    int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;

    int z_button = 0;
    int c_button = 0;

    // byte nunchuck_buf[5] contains bits for z and c buttons
    // it also contains the least significant bits for the accelerometer data
    // so we have to check each bit of byte outbuf[5]
    if ((nunchuck_buf[5] >> 0) & 1)
        z_button = 1;
    if ((nunchuck_buf[5] >> 1) & 1)
        c_button = 1;

    if ((nunchuck_buf[5] >> 2) & 1)
        accel_x_axis += 2;
    if ((nunchuck_buf[5] >> 3) & 1)
        accel_x_axis += 1;

    if ((nunchuck_buf[5] >> 4) & 1)
        accel_y_axis += 2;
    if ((nunchuck_buf[5] >> 5) & 1)
        accel_y_axis += 1;

    if ((nunchuck_buf[5] >> 6) & 1)
        accel_z_axis += 2;
    if ((nunchuck_buf[5] >> 7) & 1)
        accel_z_axis += 1;

    Serial.print(i,DEC);
    Serial.print(",");

    //Serial.print("joy:");
    Serial.print(joy_x_axis,DEC);
    Serial.print(",");
    Serial.print(joy_y_axis, DEC);
    Serial.print(",");

    Serial.print("acc:");
    Serial.print(accel_x_axis, DEC);
    Serial.print(",");
    Serial.print(accel_y_axis, DEC);
    Serial.print(",");
    Serial.print(accel_z_axis, DEC);
    Serial.print(",");

    Serial.print("but:");
    Serial.print(z_button, DEC);
    Serial.print(",");
    Serial.print(c_button, DEC);

    Serial.print("\r\n");  // newline
    i++;
}

// returns zbutton state: 1=pressed, 0=notpressed
static int nunchuck_zbutton()
{
    return ((nunchuck_buf[5] >> 0) & 1) ? 0 : 1;  // voodoo
}

// returns zbutton state: 1=pressed, 0=notpressed
static int nunchuck_cbutton()
{
    return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1;  // voodoo
}

// returns value of x-axis joystick
static int nunchuck_joyx()
{
    return nunchuck_buf[0];
}

// returns value of y-axis joystick
static int nunchuck_joyy()
{
    return nunchuck_buf[1];
}

// returns value of x-axis accelerometer
static int nunchuck_accelx()
{
    return nunchuck_buf[2];   // FIXME: this leaves out 2-bits of the data
}

// returns value of y-axis accelerometer
static int nunchuck_accely()
{
    return nunchuck_buf[3];   // FIXME: this leaves out 2-bits of the data
}

// returns value of z-axis accelerometer
static int nunchuck_accelz()
{
    return nunchuck_buf[4];   // FIXME: this leaves out 2-bits of the data
}