Skip to content

Instantly share code, notes, and snippets.

@jrsa
Created May 8, 2017 20:16
Show Gist options
  • Save jrsa/479ed0ee0f48d0589e8c15f72bc37665 to your computer and use it in GitHub Desktop.
Save jrsa/479ed0ee0f48d0589e8c15f72bc37665 to your computer and use it in GitHub Desktop.
// adapted from https://github.com/4ms/PEG-v1
#define SPI_PIN PINB
#define SPI_PORT PORTB
#define SPI_DDR DDRB
#define SPI_MOSI PB3
#define SPI_MISO PB4
#define SPI_SCLK PB5
#define DAC_CS_PORT PORTB
#define DAC_CS_DDR DDRB
#define DAC_CS PB2
#define MCP4921_ABSEL 7
#define MCP4921_BUF 6
#define MCP4921_GAIN 5
#define MCP4921_SHDN 4
void output_dac(char channel, uint16_t data) {
DAC_CS_PORT &= ~(1<<DAC_CS); //pull CS low to enable DAC
SPDR = (channel<<MCP4921_ABSEL) | (1<<MCP4921_BUF) | (1<<MCP4921_GAIN) | (1<<MCP4921_SHDN) | ((data>>8) & 0x0F);
while (!(SPSR & (1<<SPIF)))
;
SPDR = data & 0x00FF;
while (!(SPSR & (1<<SPIF)))
;
DAC_CS_PORT |= (1<<DAC_CS); //pull CS high to latch data
}
void init_spi(void) {
SPI_DDR |= (1<<SPI_MOSI) | (1<<SPI_SCLK); //SCK, MOSI are output
DAC_CS_DDR |= (1<<DAC_CS); //CS for MCP4922 DAC
DAC_CS_PORT |= (1<<DAC_CS); //pull CS high to intialize
SPI_DDR &= ~(1<<SPI_MISO); // MISO is input
SPCR = (1<<SPE) | (1<<MSTR) | (0<<SPR1)| (0<<SPR0); //SPI enable, Master Mode, F_OSC/4, interrupt enabled
SPSR = (1<<SPI2X); //SPI double speed = 2MHz
output_dac(0, 0);
output_dac(1, 0);
}
int t = 69;
void setup() {
init_spi();
}
void loop() {
t++;
int bbval = ((t << 1) ^ ((t << 1) + (t >> 7) & t >> 12)) | t >> (4 - (1 ^ 7 & (t >> 15))) | t >> 7;
output_dac(0, bbval); // output bytebeat signal on outA
output_dac(1, t & 0xffff); // output saw signal on outB
delayMicroseconds(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment