AFE

Dependencies:   mbed-os-retarget-segger-rtt

source/main.cpp

Committer:
d4rth_j0k3r
Date:
2020-08-13
Revision:
0:8388b3dcbdf3
Child:
1:0cdad594b7e0

File content as of revision 0:8388b3dcbdf3:

/*  Pneumoscope Version 1.0
    Florian CHAYS
 */

#include "mbed.h"
#include <main.h>

// ==== Main ====
int main() {
    uint32_t data_in, data_out;
    char buffer[4];
    
    SUP_EN.write(1);
    myled.write(1);
    spi.frequency(8000000);
    
    SPI_Write(CONTROL0,0x8);    // Soft Reset
    while((SPI_Read(CONTROL0) >> 3) & 0x1){} // Waiting for Reset bit back to 0
    SPI_Write(CONTROL2,0x20100);
    SPI_Write(CONTROL1,0x2);
    ThisThread::sleep_for(1000);
    
    // Chip must be deselected
    for (char address = 1; address < 10; address++){
        // Generating data to be written
        data_in = rand() % 65535;
        data_out = 0;

        // Send data
        SPI_Write(address, data_in);
        
        // Read data written
        data_out = SPI_Read(address);
        nr_error = error_check(address, data_in, data_out);
        while (nr_error){
            blinky(100);
        }
    }
    
    if (!nr_error){
        printf("Test passed successfully\n\r");
        while(1){
            myled.write(1);
            //blinky(500);
        }
    }
}



// ==== Functions ====
void SPI_Write(char address, uint32_t data){
    cs.write(0);
    spi.write(CONTROL0);
    spi.write(0);
    spi.write(0);
    spi.write(0);
    cs.write(1); 
    
    cs.write(0);
    spi.write(address);
    spi.write((data >> 16) & 0xFF);
    spi.write((data >> 8) & 0xFF);
    spi.write(data & 0xFF);
    cs.write(1);   
}

uint32_t SPI_Read(char address){
    uint32_t data = 0;
    
    cs.write(0);
    spi.write(CONTROL0);
    spi.write(0);
    spi.write(0);
    spi.write(0x1);
    cs.write(1); 
    
    cs.write(0);
    spi.write(address);
    data |= (uint32_t)spi.write(0x00) << 16;
    data |= (uint32_t)spi.write(0x00) << 8;
    data |= (uint32_t)spi.write(0x00);
    cs.write(1);
    
    // disable reading from registers
    SPI_Write(CONTROL0,0);
    
    return data;
}

bool error_check(int index, unsigned char data_in, unsigned char data_out){
    if (data_in != data_out){
        printf("[ERROR] Address %d : In = %d / Out = %d\n\r",index ,data_in,data_out);
        return 1;
    }else{
        return 0;
    }
}

void blinky(int delay){
    state = !state;
    myled.write(state);
    ThisThread::sleep_for(delay);
}