带寄存器的Arduino Uno SPI

时间:2019-07-06 18:37:58

标签: arduino spi atmel

我正在尝试直接从寄存器激活SPI。

我将Arduino Uno与ATMEGA328P一起使用 使用以下代码:

void setup() {
  // put your setup code here, to run once:
  cli();
  Serial.begin(9600);
  SPI_MasterInit();
  sei();
}

void loop() {
  // put your main code here, to run repeatedly:
  SPI_MasterTransmit(10);
}

void SPI_MasterInit(void)
{
  int spcr;
  /* Set MOSI and SCK output, all others input */
  DDRB = (1 << DDB3) | (1 << DDB5);
  /* Enable SPI, Master, set clock rate fck/16 */
  SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPIE);
  spcr = SPCR;
  Serial.println(SPCR, BIN);
}

void SPI_MasterTransmit(char cData) {
  /* Start transmission */
  SPDR = cData;
  /* Wait for transmission complete */
  while (!(SPSR & (1 << SPIF))){
    Serial.println(SPSR, BIN); // stuck here
  }
}

卡在SPI_MasterTransmit函数中。

传输永无止境。

帮助任何人吗?

编辑:

我将代码更改为此:

void setup() {
  sei();
  Serial.begin(9600);
  SPI_MasterInit();
}

void loop() {
  SPI_MasterTransmit("A");
  Serial.println("pass transmit");
}

void SPI_MasterInit(void)
{
  /* Set MOSI and SCK output, all others input */
  DDRB = (1 << DDB3) | (1 << DDB5);
  /* Enable SPI, Master, set clock rate fck/16 */
  SPCR = (1 << SPE) | (1 << MSTR);
}

void SPI_MasterTransmit(char cData) {
  /* Start transmission */
  SPDR = cData;
  /* Wait for transmission complete */
  while (!(SPSR & (1 << SPIF))) ;
}

和“传递”仅打印一次。

1 个答案:

答案 0 :(得分:0)

我在内部添加了SS控件后,问题出在SS端口上

SPI_MasterInit()和SPI_MasterTransmit()有效

新代码是:

void setup() {
  sei();
  Serial.begin(9600);
  SPI_MasterInit();
}

void loop() {
  SPI_MasterTransmit("A");
  Serial.println("pass transmit");
}

void SPI_MasterInit(void)
{
  /* Set MOSI and SCK output, all others input */
  DDRB = (1 << DDB3) | (1 << DDB5);
  PORTB |= (1 << PORT2); //set SS
  /* Enable SPI, Master, set clock rate fck/4 */
  SPCR = (1 << SPE) | (1 << MSTR);
}

void SPI_MasterTransmit(char cData) {
  /* Unset SS */
  PORTB |= (0 << PORT2);
  /* Start transmission */
  SPDR = cData;
  /* Wait for transmission complete */
  while (!(SPSR & (1 << SPIF))) ;
  PORTB |= (1 << PORT2); //set SS
}