User Tools

Site Tools


arduino:gammon-spi-data-controller

From SPI - Serial Peripheral Interface - for Arduino by Nick Gammon. Modified to use the newish and preferred SPI.beginTransaction() and SPI.endTransaction().

gammon-spi-data-controller.ino
// Written by Nick Gammon
// April 2011
// With Mithat Mods -- July 2023
 
#include <SPI.h>
 
void setup (void)
{
  Serial.begin (115200);
  Serial.println ();
 
  digitalWrite(SS, HIGH);  // ensure SS stays high for now
 
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();
 
  // Slow down the master a bit
  // SPI.setClockDivider(SPI_CLOCK_DIV8);  // mithat: let's do this the preferred way
 
}  // end of setup
 
byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait
 
void loop (void)
{
  byte a, b, c, d;
 
  SPI.beginTransaction(SPISettings(400000, MSBFIRST, SPI_MODE0));  // mithat: this is the preferred way
  // enable Slave Select
  digitalWrite(SS, LOW);    
 
  transferAndWait ('a');  // add command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);
 
  // disable Slave Select
  digitalWrite(SS, HIGH);
  SPI.endTransaction();      // mithat: finish preferred way
 
  Serial.println ("Adding results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);
 
 
  // enable Slave Select
  digitalWrite(SS, LOW);   
 
  transferAndWait ('s');  // subtract command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);
 
  // disable Slave Select
  digitalWrite(SS, HIGH);
 
  Serial.println ("Subtracting results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);
 
  delay (1000);  // 1 second delay 
}  // end of loop
arduino/gammon-spi-data-controller.txt · Last modified: 2023/07/25 00:13 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki