megaAVR Experiments - TLC5615 10-bit DAC SPI

The TLC5615 is a 10-bit voltage output digital-to-analog converter (DAC) with a buffered reference input (high impedance). More information can be found here.

The following is some code to talk to the chip over SPI:

/*****************************
 * file name: spi_dac.c
 *****************************/
 
#include <avr/io.h>
#include <stdint.h>
#define F_CPU 7372800UL //7.3728MHz
#include "SPI_DAC.h"

//strobe "pin" on "port" high
#define IO_PIN_STROBE_HIGH(port, pin)	\
		__asm__ __volatile__ (			\
		"sbi %0, %1"					\
		: /* no output */				\
		: "I" (_SFR_IO_ADDR(port)),		\
		  "I" (pin))

//strobe "pin" on "port" low
#define IO_PIN_STROBE_LOW(port, pin)	\
		__asm__ __volatile__ (			\
		"cbi %0, %1"					\
		: /* no output */				\
		: "I" (_SFR_IO_ADDR(port)),		\
		  "I" (pin))

/* SPI port and pin name definition */
#define DDR_SPI DDRB
#define SS   PB0
#define SCK  PB1
#define MOSI PB2
#define MISO PB3

/* Strobe SS high and low */
#define SS_SET() IO_PIN_STROBE_HIGH(PORTB, 0)
#define SS_CLR() IO_PIN_STROBE_LOW(PORTB, 0)

/* Initialize MCU pins for SPI master operation */
void SPI_MasterInit(void)
{
	/* 
	 * Set SS, SCK and MOSI as output, MISO is 
	 * automatically set as input in SPI master 
	 */
	DDR_SPI |= (1<<SS)|(1<<SCK)|(1<<MOSI);
	
	/* SS is active low, so init to 1 */
	SS_SET();
	
	/* Enable SPI, Master, set clock rate fck/4 */
	SPCR = (1<<SPE)|(1<<MSTR);
}

/* Transmit one byte of data over SPI as master */
void SPI_MasterTransmit(uint8_t SPI_Data)
{
	/* Start transmission */
	SPDR = SPI_Data;
	/* Wait for transmission complete */
	while(!(SPSR & (1<<SPIF)))
		;
}

/* Send 10-bit data to the DAC */
void SPI_DAC(uint16_t DAC_Data)
{
	/* Condition the data, two LSB 0's, four MSB dummy bits */
	DAC_Data = DAC_Data << 2;
	
	/* Send conditioned data to DAC in two bytes, MSB first */
	SS_CLR();
	SPI_MasterTransmit((uint8_t)(DAC_Data>>8));
	SPI_MasterTransmit((uint8_t)DAC_Data);
	SS_SET();	
}

And here is the header:

/*****************************
 * file name: spi_dac.h
 *****************************/
 
#ifndef SPI_DAC_H
#define SPI_DAC_H

#include <stdint.h>

/* Initialize MCU pins for SPI master operation */
void SPI_MasterInit(void);

/* Transmit one byte of data over SPI as master */
void SPI_MasterTransmit(uint8_t SPI_Data);

/* Send 10-bit data to the DAC */
void SPI_DAC(uint16_t DAC_Data);

#endif