Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of MyLib by
Nunchuck/Nunchuck.cpp
- Committer:
- gaku_sigu
- Date:
- 2017-05-11
- Revision:
- 3:e7a900958f54
- Parent:
- 2:7b7821addb45
- Child:
- 4:ae9dc8d5c37e
File content as of revision 3:e7a900958f54:
#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(ADDR, (const char*)cmd, sizeof(cmd)) == 0)
{
wait(0.01);
if (I2C::read(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);
}
int Nunchuck::accx()
{
getdata();
int temp = data[2] << 2;
if ((data[5] >> 2) & 1) temp += 2;
if ((data[5] >> 3) & 1) temp += 1;
return data[2];
}
int Nunchuck::accy()
{
getdata();
int temp = data[3] << 2;
if ((data[5] >> 4) & 1) temp += 2;
if ((data[5] >> 5) & 1) temp += 1;
return data[3];
}
int Nunchuck::accz()
{
getdata();
int temp = data[4] << 2;
if ((data[5] >> 6) & 1) temp += 2;
if ((data[5] >> 7) & 1) temp += 1;
return data[4];
}
bool Nunchuck::buttonz()
{
getdata();
return !(data[5] & 0x01);
}
bool Nunchuck::buttonc()
{
getdata();
return !(data[5] & 0x02);
}
