tc520.c

Go to the documentation of this file.
00001 
00041 #include <drv/tc520.h>
00042 #include <drv/timer.h>
00043 
00044 #include <hw_tc520.h>
00045 
00046 #include <cfg/macros.h>
00047 #include <cfg/compiler.h>
00048 
00049 #include <drv/ser.h>
00050 
00051 static Serial *spi_ser;
00052 
00053 #define TC520_CONVERSION_TIMEOUT ms_to_ticks(1000)
00054 #define INIT_LOAD_VALUE 0x00
00055 
00087 tc520_data_t tc520_read(void)
00088 {
00089     /* Start convertion and wait */
00090     CE_LOW();
00091     ticks_t start = timer_clock();
00092     do
00093     {
00094         /* timeout check */
00095         if (timer_clock() - start >= TC520_CONVERSION_TIMEOUT)
00096         {
00097             ASSERT(0);
00098             CE_HIGH();
00099             return TC520_MAX_VALUE;
00100         }
00101     }
00102     while(DV_LOW());
00103 
00104     start = timer_clock();
00105     do
00106     {
00107         /* timeout check */
00108         if (timer_clock() - start >= TC520_CONVERSION_TIMEOUT)
00109         {
00110             ASSERT(0);
00111             CE_HIGH();
00112             return TC520_MAX_VALUE;
00113         }
00114     }
00115     while(DV_HIGH());
00116 
00117     /* Ok, convertion finished, read result */
00118     CE_HIGH();
00119     READ_LOW();
00120 
00121     /* RX buffer could be dirty...*/
00122     ser_purge(spi_ser);
00123 
00124     /* I/O buffer */
00125     uint8_t buf[3] = "\x0\x0\x0";
00126 
00127     /* Dummy write to activate recv */
00128     ser_write(spi_ser, buf, sizeof(buf));
00129     ser_drain(spi_ser);
00130     READ_HIGH();
00131 
00132     /* recv */
00133     ASSERT(ser_read(spi_ser, buf, sizeof(buf)) == sizeof(buf));
00134 
00135     tc520_data_t res;
00136 
00137     /* Recompose data */
00138     res = (((tc520_data_t)(buf[0] & 0x3F)) << 10) | (((tc520_data_t)buf[1]) << 2) | (((tc520_data_t)buf[2]) >> 6);
00139 
00140     #define OVERRANGE_BIT BV(7)
00141     /* Handle overrange bit as 17th bit */
00142     if (buf[0] & OVERRANGE_BIT)
00143         res |= BV32(16);
00144 
00145     return res;
00146 }
00147 
00148 
00152 void tc520_init(Serial *spi_port)
00153 {
00154     spi_ser = spi_port;
00155     /* init io ports */
00156     TC520_HW_INIT;
00157     /* Send initial load value */
00158     LOAD_LOW();
00159     ser_putchar(INIT_LOAD_VALUE, spi_ser);
00160     ser_drain(spi_ser);
00161     LOAD_HIGH();
00162 }