I'm using an AVR microcontroller to take readings from a MAX6675 (SPI K-type thermocouple ADC chip).
I am having difficulty understanding what is required by this chip's SPI interface. The datasheet (https://datasheets.maximintegrated.com/en/ds/MAX6675.pdf) is a bit confusing on the matter. Pages 5 and 6 discuss the signalling.
I'd like to take readings at a rate of about 16 times per second, one sample each from an array of 16 thermocouples (muxed together using analog mux chips). But the problem I'm having is that even though the analog muxing does work, it seems like the 6675 gets "stuck" sometimes and either repeats a reading over and over again or perhaps delays it by one channel's worth.
Here's the code I'm using to read the SPI data...
unsigned short ReadThermocouple(char channel)
{
char i;
unsigned short retval = 0;
//select the thermocouple channel...
channel &= THERMOCOUPLE_ADDR_PINS; //keep the low 4 bits of the channel
PORTC &= ~THERMOCOUPLE_ADDR_PINS; //clear the channel address pins (e.g. select channel 0 momentarily)
PORTC |= channel; //select the actual channel requested
Serial_Send_Char('A' + channel);
Serial_Send_Char('=');
//CS LOW
PORTD &= ~SPI_SCn;
for(i = 0 ; i < 16 ; i++)
{
//raise clock line
PORTD |= SPI_SCK;
//lower clock line
PORTD &= ~SPI_SCK;
//read the bit
retval <<= 1;
retval |= (PIND & SPI_MISO) >> 2;
}
//CS HIGH
PORTD |= SPI_SCn;
return retval;
}
The problem looks to be that the data that gets returned seems to "lag behind" by one channel. E.g. I try to read channel 1 and I get channel 0's reading. Similarly after the first time through the 16-channel loop, channel 0's reading actually contains the temperature from the previous iteration's channel 15.
Obviously I'm driving the SPI incorrectly. But I can't figure out what's wrong.
The datasheet doesn't suggest how long it takes to record a reading. Perhaps I'm going too fast? It also does not suggest in detail how to properly arrange and synchronise raising and lowering the Chip Select line. The text of the datasheet and the timing diagram seem to contradict each-other.
I've tried all combinations of raising and lowering the various signals with different degrees of delays between them, but I can't get coherent output from this MAX6675, unless I go VERY slowly indeed, and then I still have this "off-by-one-channel" problem.
I've checked the physical hardware and it all seems fine, I'm driving the mux chips correctly. And I can prove that warming any given thermocouple with my hand does have a reliable effect on the readings. I'm fairly certain this is a timing issue or some mess-up with the sequence of events.
Am I driving this chip incorrectly? Am I asking too much of it to take readings at 16 times per second?