Advertisement
amigojapan

arduino1 USB SPI bridge

Oct 16th, 2016
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. // Written by Nick Gammon and Matthias Bock
  2. // Licensed as GNU GPL v2
  3.  
  4. /*
  5.  * For some reason this script won't read in the data ...
  6.  */
  7.  
  8. /**
  9.  * Send arbitrary number of bits at whatever clock rate (tested at 500 KHZ and 500 HZ).
  10.  * This script will capture the SPI bytes, when a '\n' is recieved it will then output
  11.  * the captured byte stream via the serial.
  12.  */
  13.  
  14. /*
  15.  * http://arduino.cc/en/Reference/SPI
  16.  *
  17.  * Arduino Mega2560 SPI pins:
  18.  *  MISO: 50
  19.  *  MOSI: 51
  20.  *  SCK:  52
  21.  *  SS:   53
  22.  */
  23. #include <SPI.h>
  24.  
  25. char buf [100];
  26. volatile byte pos;
  27. volatile boolean process_it;
  28.  
  29. void setup (void)
  30. {
  31.   // setup USB-serial port
  32.   Serial.begin (9600);
  33.   Serial.println("arduino1 slave");
  34.  
  35.   // receive on master out / slave in
  36.   pinMode(MOSI, INPUT);
  37.  
  38.   // send on master in / slave out
  39.   pinMode(MISO, OUTPUT);
  40.  
  41.   // turn SPI on
  42.   SPCR |= 1 << SPE;
  43.  
  44.   // switch to slave mode
  45.   SPCR &= 0xff - (1 << MSTR);
  46.  
  47.   // most significant bit first
  48.   SPI.setBitOrder(MSBFIRST);
  49.  
  50.   // the base value of the clock is LOW: polarity=0
  51.   // data is captured on the clock's rising edge: phase=0
  52.   SPI.setDataMode(SPI_MODE1);
  53.  
  54.   // SPI sampling frequency as a fraction of the 16 MHz crystal
  55.   // 16 MHz / 16 = 1 MHz
  56.   SPI.setClockDivider(SPI_CLOCK_DIV16);
  57.  
  58.   // get ready for an interrupt
  59.   pos = 0;   // buffer empty
  60.   process_it = false;
  61.  
  62.   // now turn on interrupts
  63.   SPI.attachInterrupt();
  64.  
  65.   // the rest of the magic is done in SPI.h
  66. }
  67.  
  68. // SPI interrupt service routine
  69. ISR (SPI_STC_vect)
  70. {
  71.     // grab byte from SPI Data Register
  72.     byte c = SPDR;
  73.  
  74.     // add to buffer if room
  75.     if (pos < sizeof buf)
  76.     {
  77.     buf [pos++] = c;
  78.    
  79.     // example: newline means time to process buffer
  80.     if (pos >= 64)
  81.         buf [pos] = 0;  
  82.         pos = 0;
  83.         process_it = true;
  84.     }
  85. }
  86.  
  87. void loop (void)
  88. {
  89.     // wait for flag set in interrupt routine
  90.     if (process_it)
  91.     {
  92.         for (int i=0; i<8; i++)
  93.         {
  94.           Serial.print( int(buf[i]) );
  95.           Serial.print("-");
  96.         }
  97.         Serial.println();
  98.         process_it = false;
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement