pezi / dart_periphery

dart_periphery is a Dart port of the native c-periphery library
BSD 3-Clause "New" or "Revised" License
40 stars 12 forks source link

SPI slave reading #5

Closed AlbanDurrheimer closed 2 years ago

AlbanDurrheimer commented 2 years ago

Hi,

I'm trying to integrate an SPI connection to my flutter project, so I use a Raspberry Pi as master and an arduino as slave.
The arduino gets each byte of the request and returns a byte not related to the request (tested and working with another arduino as master).
When I try to communicate with my program, the arduino does retrieve the command sent, but in the result logged in the flutter project, it shows me the command sent and not the one the arduino is supposed to return.

My Flutter code:

      var spi = SPI(0, 0, SPImode.MODE0, 500000);
      try {
        print('SPI info:' + spi.getSPIinfo());
        var data = utf8.encode("Some data\r");
        var result = spi.transfer(data, false);
        var index = 0;
        for (var v in data) {
          print('Send $v->Answer ${result[index++]}');
        }
        print(utf8.decode(result));
      } catch (e) {
        print(e);
      } finally {
        spi.dispose();
      }

My Arduino code:

#include <SPI.h>
char buff [50];
char resp [50] = "Helo diti\r";
volatile byte indx;

void setup (void) {
  Serial.begin (9600);
  pinMode(MISO, OUTPUT); // have to send on master in so it set as output
  SPCR |= _BV(SPE); // turn on SPI in slave mode
  indx = 0; // buffer empty
  SPI.attachInterrupt(); // turn on interrupt
}
ISR (SPI_STC_vect)
{
  byte c = SPDR; // read byte from SPI Data Register

  if (indx < sizeof buff) {
    buff [indx] = c; // save data in the next index in the array buff
    SPDR = byte(resp[indx]);
    indx++;
    if (c == '\r') {
      Serial.println(buff);
      indx = 0; //reset button to zero
    }
  }
}

void loop (void) {
}

What is logged:

flutter: SPI info:SPI (fd=29, mode=0, max_speed=500000, bit_order=MSB_FIRST, bits_per_word=8, extra_flags=0x00000004)
flutter: Send 83->Answer 0
flutter: Send 111->Answer 83
flutter: Send 109->Answer 111
flutter: Send 101->Answer 109
flutter: Send 32->Answer 101
flutter: Send 100->Answer 32
flutter: Send 97->Answer 100
flutter: Send 116->Answer 97
flutter: Send 97->Answer 116
flutter: Send 13->Answer 97
flutter: Some data

Expected:

flutter: Send 83->Answer 0
flutter: Send 111->Answer 72
flutter: Send 109->Answer 101
flutter: Send 101->Answer 108
flutter: Send 32->Answer 111
flutter: Send 100->Answer 32
flutter: Send 97->Answer 100
flutter: Send 116->Answer 105
flutter: Send 97->Answer 116
flutter: Send 13->Answer 105
flutter: Helo diti

Returned with master Arduino:

Helo diti

Thank you for your help

AlbanDurrheimer commented 2 years ago

I found the solution, the maximum speed was much too high for the arduino.

The fix:

var spi = SPI(0, 0, SPImode.MODE0, 125000);

Sorry for the inconvenience.