Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.7 kB
2
Indexable
Never
uint32_t readADC(uint32_t bit_CS, uint32_t bit_CLK, uint32_t bit_SDO)
{   // ADC 12-bit (2^12 == 4096)
    
    uint32_t bit_CSmask = 1 << bit_CS;
    uint32_t bit_SCLKmask = 1 << bit_CLK;

    // enable outputs for /CS and SCLK    
    uint32_t bitsMask = bit_CSmask | bit_SCLKmask;
    gpio_oe_and_or(~bitsMask, bitsMask); // inverted mask + mask 

    // fire /CSx
    gpio_out_and_or(~bit_CSmask, 0); // inverted mask + target value

    // init result  
    uint32_t result = 0;
    uint32_t dataADC = 0;

    uint32_t magicNumber = getMagicNumber(bit_SDO);
    
    for (int i = 1; i < 16; i++)
    {        
        
        // clock tact
        gpio_out_and_or(~bit_SCLKmask, 0); // inverted mask + target value        
        gpio_out_and_or(~bit_SCLKmask, bit_SCLKmask); // inverted mask + mask
        
        if (i > 1 && i < 14) // we're skipping two 0 before & two 0 after (see datasheet)
        {
            // get data from INPUT register            
            dataADC = gpio_in();// ^ 0xffff;            
            //printf("bit# %d register value %d\n", i, dataADC);
            
            // pseudo-scientific part
            if (dataADC != magicNumber)
            {
                result++;
                //printf("Result incremented \n");
            }            
            if (i > 1 && i < 13)
                result = result << 1;
            //printf("bit# %d result value %d\n", i, result);
        }        
    }

    // restore /CSx
    gpio_out_and_or(~bit_CSmask, bit_CSmask); // inverted mask + target value

    //printf("Result: %d\n", result);

    return result;
}
Leave a Comment