|
| 1 | +#include <pi_spi.h> |
| 2 | +#include <spi.h> |
| 3 | + |
| 4 | +#define MAX_SPI_FREQ 100000 |
| 5 | + |
| 6 | +uint8_t _channels[4] = { 0, 0, 0, 0 }; |
| 7 | + |
| 8 | +int8_t _open(uint8_t type) |
| 9 | +{ |
| 10 | + if(type == DEFAULT) |
| 11 | + { |
| 12 | + spi_open(SPI_8AI, MAX_SPI_FREQ); |
| 13 | + } |
| 14 | + else if(type == SPARE1) |
| 15 | + { |
| 16 | + spi_open(SPI_SPARE1, MAX_SPI_FREQ); |
| 17 | + } |
| 18 | + else if(type == SPARE2) |
| 19 | + { |
| 20 | + spi_open(SPI_SPARE2, MAX_SPI_FREQ); |
| 21 | + } |
| 22 | + else if(type == SPARE3) |
| 23 | + { |
| 24 | + spi_open(SPI_SPARE3, MAX_SPI_FREQ); |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + return -1; |
| 29 | + } |
| 30 | + |
| 31 | + return 0; |
| 32 | +} |
| 33 | + |
| 34 | +// read data from previously opened SPI device |
| 35 | +uint16_t _read(uint8_t channel) |
| 36 | +{ |
| 37 | + uint8_t data[2] = { channel, channel }; |
| 38 | + |
| 39 | + spi_transfer(data, 2); |
| 40 | + |
| 41 | + return ((uint16_t)data[0] << 8) | data[1]; |
| 42 | +} |
| 43 | + |
| 44 | +void pi_spi_8ai_16b_set_channel(uint8_t channel, uint8_t type) |
| 45 | +{ |
| 46 | + channel = channel > 7 ? 7 : channel; |
| 47 | + |
| 48 | + uint8_t ret = _open(type); |
| 49 | + if(ret < 0) { return; } |
| 50 | + |
| 51 | + _channels[type] = channel; |
| 52 | + |
| 53 | + // read once to write channel to mux |
| 54 | + _read(channel); |
| 55 | + // read twice to ensure ADC has updated reading |
| 56 | + _read(channel); |
| 57 | +} |
| 58 | + |
| 59 | +uint16_t pi_spi_8ai_16b_read(uint8_t type) |
| 60 | +{ |
| 61 | + uint8_t ret = _open(type); |
| 62 | + if(ret < 0) { return 0; } |
| 63 | + |
| 64 | + return _read(_channels[type]); |
| 65 | +} |
0 commit comments