Aleksandar Kodzhabashev / Mbed 2 deprecated TrackballQuery

Dependencies:   Servo mbed

main.cpp

Committer:
d3alek
Date:
2013-10-28
Revision:
2:e35627187804
Parent:
1:d290d6a34bef
Child:
3:eb3c3c9587d7

File content as of revision 2:e35627187804:

#include "PS2MS.h"
#include "PS2MS_INIT.h"
#include "mbed.h"

#define ENABLE_1 true
#define ENABLE_2 true

DigitalOut myled(LED1);
DigitalInOut clk(p23);
DigitalInOut dat(p22);
Serial pc(USBTX, USBRX); // tx, rx
/*
 * 0xFF: Reset command.
 * 0xF3: Set sample rate.
 * 0xF2: Read device type.
 * 0xE8: Set resolution.
 * 0xE6: Set scaling.
 * 0xF4: Enable device.
 */

int send(uint8_t c);
int recv();

//TODO should Iuse sensor1_init? maybe no 255s?
PS2MS_INIT sensor1_init(p23, p22);
PS2MS sensor1(p23, p22);

PS2MS_INIT sensor2_init(p26, p25);
PS2MS sensor2(p26, p25);

int process_sensor_input(char c, int bytenum, char* bytes, int ind);

int sensorXs[2];
int sensorYs[2];
bool sensorToPrint[2];

int main()
{
    int s1bytenum = 0;
    char s1bytes[3];

    int s2bytenum = 0;
    char s2bytes[3];

    char s1c, s2c;
    s1c = sensor1.getc();
    s2c = sensor2.getc();
    
    sensorToPrint[0] = sensorToPrint[1] = false;
    
    while(1) {
        if (ENABLE_1) {
            s1bytenum = process_sensor_input(s1c, s1bytenum, s1bytes, 0);
            s1c = sensor1.getc();
        }
        if (ENABLE_2) {
            s2bytenum = process_sensor_input(s2c, s2bytenum, s2bytes, 1);
            s2c = sensor2.getc();
        }
        // TODO only prints when both are enabled now
        if (sensorToPrint[0] || sensorToPrint[1]) {
            printf("%d : %d %d %d %d\n\r", 2, sensorXs[0], sensorYs[0], sensorXs[1], sensorYs[1]);
            sensorToPrint[0] = sensorToPrint[1] = false;
            sensorXs[0] = sensorYs[0] = sensorXs[1] = sensorYs[1] = 0;
        }
    }
}

int process_sensor_input(char c, int bytenum, char* bytes, int ind)
{
    if (c == 255) {
        bytenum = -1;
    } else if (bytenum % 3 == 0) {
        bytes[0] = c;
        if (!((1 << 3) & c)) {
            // not byte[0] wrong offset, skip c
            bytenum = -1;
        }
    } else if (bytenum % 3 == 1) {
        bytes[1] = c;
    } else if (bytenum % 3 == 2) {
        bytes[2] = c;

        //TODO: check for overflow
        if ((1 << 6) & bytes[0]) {
            printf("Overflow x!\n\r");
        }
        if ((1 << 7) & bytes[0]) {
            printf("Overflow y!\n\r");
            printf("Byte1 is %d\n\r", bytes[0]);
        }
        // check x and y signs
        int x = bytes[1] - ((bytes[0] << 4) & 0x100);
        int y = bytes[2] - ((bytes[0] << 3) & 0x100);
        //printf("%s: x = %d   y = %d\n\r", id, x, y);
        sensorXs[ind] = x;
        sensorYs[ind] = y;
        sensorToPrint[ind] = true;
        bytenum = -1;
    }
    return (bytenum + 1) % 3;
}