为什么我的SPI通信不起作用? (Atmega644)

问题描述 投票:0回答:2

我正在构建一个鼓机,我已经存储了一个带有踢声的样本头文件,其值介于0到170之间。我想通过SPI将其发送到10位MCP4811 DAC,然后将其输出到3.5mm音频插孔。

我的MISO,MOSI,SCK和RESET引脚连接到我的USB编程器和DAC。

以下是存储在“samples.h”中的音频文件片段

unsigned const char sample_1[2221] PROGMEM = {0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, ...}
unsigned int sample_len[1] = {2221}

所以它是2221位的样本。我想用freq = 22 kHz的SPI发送到DAC。

我使用的是16 MHz晶振,因此我将相应的保险丝设置为使用它。

我正在使用一个溢出22 kHz的定时器。

volatile unsigned int sample_count[1] = {0};
volatile unsigned int audio_out = 0;
volatile unsigned char spi_junk;

int main (void)
sei();
DDRB = 0b10110000; //Set MOSI, SCK and SS as output.
PORTB = (1 << PINB4) //active low on SS.

TIMSK1 = (1<<OCIE1A); //Enable interrupt
TCCR1B = (1<<WGM12) | (1<<CS11); // set CTC mode and divide clk by 8 
OCR1A = 91; //16 MHz/(8*91) ~ 22068 Hz

//SPI Init
SPCR = (1<<SPE) | (1<<MSTR);  //master, 8 MHz
SPSR = (1<<SPI2X);

ISR (TIMER1_COMPA_vect) {
    audio_out = 0;

//If play_track == 1, then the sound should be played back.
if (play_track && sample_count[0] < sample_len[0]){
   audio_out += (pgm_read_byte(&(sample_1[sample_count[0]++)));

// send audio_out to 10-bit DAC on SPI
PORTB &= ~(1<<PINB4); // B.4 (DAC /CS)
SPDR = (char) ((audio_out >> 6) & 0x000f); //byte 1 0 0 0 0 b9 b8 b7 b6
while (!(SPSR & (1<<SPIF)));
spi_junk = SPDR;

SPDR = (char) ((audio_out & 0x003f) << 2); //byte 2 b5 b4 b3 b2 b1 b0 0 0
while (!(SPSR & (1<<SPIF)));
spi_junk = SPDR;
PORTB |= (1<<PINB4);
}

我的PIN设置是。

Atmega644 - > DAC

MOSI -> SDI

SCK -> SCK

SS -> /CS

在MCP4811上

Vdd -> 5V

Vss -> GND

V_out -> Audio jack.

MCP4811上的其余引脚未连接任何东西。

通过在LCD屏幕上显示audio_out值,我看到audio_out正常工作。但是没有任何东西输出到DAC。有人看到可能出错的地方吗?

编辑:添加了我错过了添加的SPI init。

c microcontroller spi atmega
2个回答
0
投票

你的路线在这里

SPDR = (char) ((audio_out >> 6) & 0x000f); //byte 1 0 0 0 0 b9 b8 b7 b6

将¬SHDN设置为0将关闭DAC

0 = Shutdown the device. Analog output is not available. VOUT pin is connected to 500 kohm typical)

将位12设置为1

SPDR = (char) ((audio_out >> 6) & 0x0f)|0x10; //byte 1 0 0 0 1 b9 b8 b7 b6

来自数据表

1 = Active mode operation. VOUT is available.


0
投票

代码中没有SPI初始化。

添加到main()

SPSR = (1 << SPI2X);  // double speed (to get maximum of 8MHz output)
SPCR = (1 << SPE)  | (1 << MSTR); // 1:1 prescaler, master mode, SPI mode 0, SPI enable

您的代码还有几点评论:

在完成所有初始化之后才使用sei(),以避免在未初始化的外设上发生中断。

首先将PB4设置为高电平,然后将其设置为输出,以避免两个命令之间的PB输出低电平:

PORTB = (1 << PINB4) //active low on SS.
DDRB = 0b10110000; //Set MOSI, SCK and SS as output.
© www.soinside.com 2019 - 2024. All rights reserved.