简体   繁体   中英

Arduino Uno SPI transfer

The task I need to accomplish is as followed:

I have an analog/digital converter witch sends out a 10 bit signal. This bit signal needs to be transferred to an Arduino Uno using the SPI protocol. Because the SPI protocol works with a 16 bit pattern I need to expand the incoming signal. The Slave Arduino then needs to put out the transfered number as a decimal one

For my task I will imitated the ADC with another Arduino Uno setting as a Master, but unfortunately at the time I only have one Arduino so I can't test my code. And furthermore I don't really have a clue how to "expand" a 10 bit signal to a 16 bit one.

Code for the Master Arduino

#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {

  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  SPI.beginTransaction(SPISettings(62500, LSBFIRST, SPI_MODE0));
}

void loop() {

  byte x=0000001101;
  byte y=0011111111;

  digitalWrite(SS,LOW);
  SPI.transfer(x,y);
  digitalWrite(SS,HIGH);

  delay(1000);
}

Code for the Slave Arduino

#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {

  pinMode(SS, INPUT);
  pinMode(MOSI, INPUT);

}

void loop() {
  byte x=SPDR;
  byte y=SPDR;
  printf(x,DEC);
  printf(y,DEC);

  delay(1000);
}

First issue:

byte x=0000001101; byte y=0011111111;

the above looks like binary numbers but in fact they are DECIMAL numbers 1101 (one thousand one hundred and one) and 11 111 111 (eleven million something). Such assignment doees not make sense. both will overflow the byte.

let's suppose you do really place somehow the value received from ADC into two byte values, 8 younger bits in y, 2 higher bits in x. So:

unsigned int z = (x<<8) + y;

combines those two numbers into one 16 bit correct uint value.

Now you should simply use the

SPI.transfer16(z);

to pass the value over SPI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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