Submitted by Angela Hsueh, Maya Mardini, Yi Tong Slingshot controller using a force sensor and accelerometer for an Angry Birds clone game.

Dependencies:   LSM303DLHC MMA8451Q PinDetect USBDevice mbed

Fork of hw3_controller by HW3 Controller Team!

main.cpp

Committer:
ahsueh
Date:
2015-09-21
Revision:
6:753418e86c95
Parent:
4:fea2289b42cd
Child:
7:689f891d62cd

File content as of revision 6:753418e86c95:

#include "mbed.h"
//#include "MMA8451Q.h"
//#include "USBMouse.h"
//#include "USBKeyboard.h"
#include "USBMouseKeyboard.h"
#include "LSM303DLHC.h"
#include "PinDetect.h"
#include "math.h"

// define I2C Pins and address for KL25Z. Taken from default sample code.
PinName const SDA = D14;
PinName const SCL = D15;
PinDetect button(D2);
AnalogIn fsr(A5);
#define MMA8451_I2C_ADDRESS (0x1d<<1)

//serial connection to PC via USB
Serial pc(USBTX, USBRX);
LSM303DLHC lsm(SDA, SCL);
USBMouseKeyboard mouseKey;


float fsrVal;
float fsrValPrev;
int count;
// acc and mag values
float ax, ay, az, mx, my, mz;
float theta;

int oldx, oldy;

int mouseTravelX = 0;
int mouseTravelY = 0;

float angles[8] = {0};
float forces[8] = {0};

void mouseMem(int x_, int y_) {
    mouseTravelX += x_;
    mouseTravelY += y_;
}

float filter(float* array, int len, float value) {
    float mean = 0.0;
    for(int i = 0; i<len - 1; i++) {
        mean += array[i + 1];
        array[i] = array[i + 1];
    }
    mean += value;
    array[len - 1] = value;
    return mean / (float)len;
}

int main(void){
    int x = 0;
    int y = 0;
    while(1){
        fsrVal = fsr.read();
        lsm.read(&ax, &ay, &az, &mx, &my, &mz);
        
        float cur_angle = atan(ax / az);
        float cur_force = fsrVal*500;
        
        float flt_force = filter(forces, 8, cur_force);
        float flt_angle = filter(angles, 8, cur_angle);
        

        
        //mouseKey.printf("ax: %1.2f az: %1.2f fsrVal: %1.2f \n", ax, az, fsrVal);
        
        //if((FsrVal > FsrValPrev && FsrVal > 0 && FsrValPrev > 0 && count <100) || (FsrVal > 0.8 && count <70)){
        
        
            if (ax > 0 && az > 0) {
                x = (int) (0.0 - cos(flt_angle) * flt_force);
                y = (int) (sin(flt_angle) * flt_force);
            } else if (ax < 0 && az > 0) {
                x = (int) (0.0 - cos(flt_angle) * flt_force);
                y = (int) (sin(flt_angle) * flt_force);                
            }
            
            //mouseKey.printf("Angle: %1.2f Force: %1.2f Move: x: %0d y: %0d x_: %0d y_ = %0d\n", 
            //                flt_angle, flt_force, x, y, mouseTravelX, mouseTravelY);
                            
            mouseKey.move((x-oldx), (y-oldy));
            mouseMem((x-oldx),(y-oldy));
            oldx = x;
            oldy = y;
        
        
        wait(0.02);
    }
}