c

Fork of MyLib by gaku takasawa

Nunchuck/Nunchuck.cpp

Committer:
kikoaac
Date:
2018-01-14
Revision:
11:827d1ccc8bec
Parent:
10:d0b1160ee5c2

File content as of revision 11:827d1ccc8bec:

#include "Nunchuck.h"


Nunchuck::Nunchuck(PinName SDA, PinName SCL) : I2C(SDA, SCL)
{
    flag = 0;
    for(int i = 0; i < 6; i++)
        data[i] = 0;
    init();
    timer.start();   
}

bool Nunchuck::init()
{
    unsigned char cmd[] = {0x40, 0x00};
    if (I2C::write(NUNCHUCK_ADDR, (const char*)cmd, sizeof(cmd)) == 0)
        return 1;
    else
        return 0;
}

void Nunchuck::getdata()
{
    if(timer.read_ms() < 50) 
        return;
    
    
    if(flag) {
        const unsigned char cmd[] = {0x00};
        if (I2C::write(NUNCHUCK_ADDR, (const char*)cmd, sizeof(cmd)) == 0) 
        {
            wait(0.01);
            if (I2C::read(NUNCHUCK_ADDR, data, sizeof(data)) == 0) 
            {
                for(int i = 0; i < 6; ++i)
                    data[i] = (data[i] ^ 0x17) + 0x17;
           }
        }
    }
    else
        flag = init();
        
    timer.reset();
}


int8_t Nunchuck::analogx()
{
    getdata();
    int8_t temp;
    temp = data[0] - 128;
#if NUNCHUCK_ANALOGDATA
    if(-1*(NUNCHUCK_DEADZONE) < temp && temp < NUNCHUCK_DEADZONE)
        temp = 0;
#else
    if(-50 < temp && temp < 50)
        temp = 0;
    else if(temp <= -50)
        temp = -1;
    else if(temp >= 50)
        temp = 1;
#endif
    return temp;
}


int8_t Nunchuck::analogy()
{
    getdata();
    int8_t temp;
    temp = data[1] - 128;
#if NUNCHUCK_ANALOGDATA
    if(-1*(NUNCHUCK_DEADZONE) < temp && temp < NUNCHUCK_DEADZONE)
        temp = 0;
#else
    if(-50 < temp && temp < 50)
        temp = 0;
    else if(temp <= -50)
        temp = -1;
    else if(temp >= 50)
        temp = 1;
#endif
    return temp;
}


double Nunchuck::analograd()
{
    double x = analogx();
    double y = analogy();
        
    return atan2(y, x);
}


double Nunchuck::analogdeg()
{
    return analograd() * 180.0 / PI;
}


double Nunchuck::analogrange()
{
    double x = analogx();
    double y = analogy();
    return sqrt((x*x + y*y));
}


int Nunchuck::accx()
{
    getdata();
    int temp = data[2] << 2;
    if ((data[5] >> 2) & 1) temp += 2;
    if ((data[5] >> 3) & 1) temp += 1;
    return temp;
}


int Nunchuck::accy()
{
    getdata();
    int temp = data[3] << 2;
    if ((data[5] >> 4) & 1) temp += 2;
    if ((data[5] >> 5) & 1) temp += 1;
    return temp;
}


int Nunchuck::accz()
{
    getdata();
    int temp = data[4] << 2;
    if ((data[5] >> 6) & 1) temp += 2;
    if ((data[5] >> 7) & 1) temp += 1;
    return temp;
}


bool Nunchuck::buttonz()
{
    getdata();
    return !(data[5] & 0x01);
}

    
bool Nunchuck::buttonc()
{
    getdata();
    return !(data[5] & 0x02);
}