Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Written by Nick Gammon and Matthias Bock
- // Licensed as GNU GPL v2
- /*
- * For some reason this script won't read in the data ...
- */
- /**
- * Send arbitrary number of bits at whatever clock rate (tested at 500 KHZ and 500 HZ).
- * This script will capture the SPI bytes, when a '\n' is recieved it will then output
- * the captured byte stream via the serial.
- */
- /*
- * http://arduino.cc/en/Reference/SPI
- *
- * Arduino Mega2560 SPI pins:
- * MISO: 50
- * MOSI: 51
- * SCK: 52
- * SS: 53
- */
- #include <SPI.h>
- char buf [100];
- volatile byte pos;
- volatile boolean process_it;
- void setup (void)
- {
- // setup USB-serial port
- Serial.begin (9600);
- Serial.println("arduino1 slave");
- // receive on master out / slave in
- pinMode(MOSI, INPUT);
- // send on master in / slave out
- pinMode(MISO, OUTPUT);
- // turn SPI on
- SPCR |= 1 << SPE;
- // switch to slave mode
- SPCR &= 0xff - (1 << MSTR);
- // most significant bit first
- SPI.setBitOrder(MSBFIRST);
- // the base value of the clock is LOW: polarity=0
- // data is captured on the clock's rising edge: phase=0
- SPI.setDataMode(SPI_MODE1);
- // SPI sampling frequency as a fraction of the 16 MHz crystal
- // 16 MHz / 16 = 1 MHz
- SPI.setClockDivider(SPI_CLOCK_DIV16);
- // get ready for an interrupt
- pos = 0; // buffer empty
- process_it = false;
- // now turn on interrupts
- SPI.attachInterrupt();
- // the rest of the magic is done in SPI.h
- }
- // SPI interrupt service routine
- ISR (SPI_STC_vect)
- {
- // grab byte from SPI Data Register
- byte c = SPDR;
- // add to buffer if room
- if (pos < sizeof buf)
- {
- buf [pos++] = c;
- // example: newline means time to process buffer
- if (pos >= 64)
- buf [pos] = 0;
- pos = 0;
- process_it = true;
- }
- }
- void loop (void)
- {
- // wait for flag set in interrupt routine
- if (process_it)
- {
- for (int i=0; i<8; i++)
- {
- Serial.print( int(buf[i]) );
- Serial.print("-");
- }
- Serial.println();
- process_it = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement