Sunday, February 28, 2010

Using Accelerometers API on Maemo

Maemo is very powerful platform for creating application and Qt as application development framework make development on maemo fun. Maemo provide various API to developer to create application so i thought to try out accelorometer API on maemo.

Accelerometer API can be used in two way. Reading file which store orientation data or Using Dbus API to get orientation data.

You can find more details here http://wiki.maemo.org/Accelerometers

For my purpose reading data from file was quite enough. My puropose to detect in which direction user has Shake the phone.

Here is code for using acceleromete API.

class MotionSenser : public QObject
{
Q_OBJECT

public:
    explicit MotionSenser(QObject *parent = 0); 
private slots:
    void timerEvent(QTimerEvent* event );

private:
    void readCurrentPos();

private:
    QPointF mLastPos;
    QPointF mCurrentPos;
    QObject* mParent;

};


static const QString PROC_ENTRY = "/sys/class/i2c-adapter/i2c-3/3-001d/coord";

MotionSenser::MotionSenser(QObject *parent)
: QObject(parent),mParent(parent)
{
    mLastPos = mCurrentPos = QPointF(0,0);
    this->startTimer(100);   
}
void MotionSenser::timerEvent(QTimerEvent* /*event*/)
{
    if( qAbs( mLastPos.y() - mCurrentPos.y() ) < 250 ) {
        //ignore event
        return;
    }

    if( mCurrentPos.y() > 150 ) {
        qDebug() << "####### Posting right event";
        QCoreApplication::postEvent(mParent,new QKeyEvent(QEvent::KeyPress,Qt::Key_Right,Qt::NoModifier));
    }
    else if ( mCurrentPos.y() < -150 ) {
        qDebug() << "####### Posting left event";
        QCoreApplication::postEvent(mParent,new QKeyEvent(QEvent::KeyPress,Qt::Key_Left,Qt::NoModifier));
    }
    mLastPos = mCurrentPos;
}

void MotionSenser::readCurrentPos()
{
    QFile f(PROC_ENTRY);
    if (!f.exists() or !f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "could not read motion data";
    }
    else {
        QByteArray line = f.readLine();
        QRegExp rx("([0-9-]+) ([0-9-]+) ([0-9-]+)");

        rx.indexIn(line);
        qreal x = rx.cap(1).toInt();
        qreal y = rx.cap(2).toInt();
        qreal z = rx.cap(3).toInt();

        mCurrentPos.setX(x);
        mCurrentPos.setY(y);

        f.close();
    }
}

No comments:

Post a Comment