Hardware Reference
In-Depth Information
Listing 10-4. SABB
const byte myAddress = '2'; // Address range from 0 - 255
const int bufferSize = 64; // 64 matches the size of serial buffer
byte txBuffer[bufferSize]; // Created to hold data waiting to be sent to the slave
byte rxBuffer[bufferSize]; // Created to hold incoming data received from the slave
volatile byte rxBufferSlave[bufferSize]; // Holds data when used as slave
volatile boolean flag = true; // Change LED state flag
void setup() {
Serial.begin(115200); // Open serial connection
PORTB |= 0b00000100; // Set SS HIGH
while (!(PINB & 0b00000100)); // Wait to initialize if SS held LOW externally
initSPI(); // Prepare to connect to the network
txBuffer[0] = 0b00000000; // Load tx buffer with a null byte
transferSPI(1); // Send null byte to release waiting devices
initSPI(); // Set idle state for board to board communication
Serial.println("Ready"); // Alert that device is fully initialized
}
void loop() {
if (Serial.available()) {
delay(1000); // Wait a sec to receive serial data
int count = 1; // Store data begining 2nd byte in array
txBuffer[0] = 0b00000000; // Send null byte first
while (Serial.available()) {
txBuffer[count] = Serial.read(); // Dump serial buffer into the txBuffer
count++;
}
Serial.flush(); // Clear serial buffer
transferSPI(count); // Sends and receives data as master
printBuffer(count); // Prints data that was sent and received
initSPI(); // Return to idle state
}
if (flag == true ){ // Flag sets true when addressed by master
PORTB = (~(PINB << 7) >> PINB7); // Change the LED state
flag = false; // Clear the flag
}
}
void initSPI() { // Sets idle state of connection
DDRB |= 0b00000001; // LED Output
DDRB &= 0b11000011; // MOSI MISO SCK SS Input
PORTB |= 0b00000100; // Set slave select HIGH
PORTB &= 0b11000111; // MISO MOSI SCK LOW
SPCR = 0b11000000; // SPIE, SPE, SLAVE, MODE0, CLOCK DIV_4
sei(); // Global interrupt enabled
}
int printBuffer(int nBytes) { // Display data tx and rx when master
Serial.println();
Serial.write (txBuffer, nBytes);
Serial.println();
Search WWH ::




Custom Search