Reading a SPI device on the Bela Mini
This sketch initialises the second SPI device (SPI1) on the Bela Mini, and reads data from it.
The SPI pins are: P2-25: MOSI P2-27: MISO P2-29: CLK P2-31: CS
To enable these pins for SPI you must first run the following commands (e.g.: in the console at the bottom of the Bela IDE, or via ssh)
config-pin P2.25 spi config-pin P2.27 spi config-pin P2.29 spi_sclk config-pin P2.31 spi_cs
The SPI readouts are then performed in an Auxiliary Task, seperate from the real-time audio thread.
#include <stdio.h>
#include <libraries/Spi/Spi.h>
void readSpi(void*);
float readInterval = 0.5;
int readCount = 0;
int readIntervalSamples;
unsigned char exampleOutput;
{
.device = "/dev/spidev2.1",
.speed = 500000,
.delay = 0,
.numBits = 8,
.mode = Spi::MODE3
});
return true;
}
{
for(
unsigned int n = 0; n < context->
audioFrames; n++) {
if(++readCount >= readIntervalSamples) {
readCount = 0;
}
}
}
void readSpi(void*)
{
int transmissionLength = 4;
unsigned char Tx[transmissionLength];
unsigned char Rx[transmissionLength];
Tx[0] = 0xff;
Tx[1] = 0x22;
Tx[2] = 0xff;
Tx[3] = 0x0;
if (spiDevice.transfer(Tx, Rx, transmissionLength) == 0)
{
printf("Spi: Transaction Complete. Sent %d bytes, received: ", transmissionLength);
int n = 0;
for(n = 0; n < transmissionLength; ++n)
printf("%#02x ", Rx[n]);
printf("\n");
exampleOutput = Rx[0];
}
else
fprintf(stderr, "Spi: Transaction Failed\r\n");
}
{
}
int setup(const Settings &settings)
Definition Spi.cpp:38
void * AuxiliaryTask
Definition Bela.h:561
int Bela_scheduleAuxiliaryTask(AuxiliaryTask task)
Run an auxiliary task which has previously been created.
AuxiliaryTask Bela_createAuxiliaryTask(void(*callback)(void *), int priority, const char *name, void *arg=NULL)
Create a new auxiliary task.
void render(BelaContext *context, void *userData)
User-defined callback function to process audio and sensor data.
Definition render.cpp:68
bool setup(BelaContext *context, void *userData)
User-defined initialisation function which runs before audio rendering begins.
Definition render.cpp:51
void cleanup(BelaContext *context, void *userData)
User-defined cleanup function which runs when the program finishes.
Definition render.cpp:96
Structure holding audio and sensor settings and pointers to I/O data buffers.
Definition Bela.h:231
const uint32_t audioFrames
The number of audio frames per block.
Definition Bela.h:322
const float audioSampleRate
The audio sample rate in Hz (currently always 44100.0).
Definition Bela.h:328