简体   繁体   English

带寄存器的Arduino Uno SPI

[英]Arduino Uno SPI with registers

I'm trying to activate the SPI directly from the registers. 我正在尝试直接从寄存器激活SPI。

I'm using Arduino Uno with ATMEGA328P with this code: 我将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
  }
}

and got stuck in SPI_MasterTransmit function. 并卡在SPI_MasterTransmit函数中。

the transmission never ends. 传输永无止境。

help anyone? 帮助任何人?

EDIT: 编辑:

I change the code to this: 我将代码更改为此:

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))) ;
}

and "pass transmit" printed just once. 和“通过传输”仅打印一次。

The problem was with the SS port after I added the SS control inside 我在内部添加了SS控件后,问题出在SS端口上

SPI_MasterInit() and SPI_MasterTransmit() it worked SPI_MasterInit()和SPI_MasterTransmit()有效

the new code is: 新的代码是:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM