Created
May 15, 2020 23:44
-
-
Save szczys/71ad6f4e02e827f730104f800e98ac3c to your computer and use it in GitHub Desktop.
ESP32 Interrupt Based SPI Slave (receive only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using ESP32 HSPI (SPI2) | |
// CS is SS --> | |
// WR is SCK --> | |
// DATA is MOSI --> | |
#define SO 12 | |
#define SI 13 | |
#define SCLK 14 | |
#define SS 15 | |
volatile uint16_t bitcount; | |
volatile uint8_t bytearray[20]; | |
volatile uint8_t messageFlag; | |
volatile uint8_t curbyte; | |
volatile uint8_t bytefiller; | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(115200); | |
Serial.println("I'm alive!!!"); | |
messageFlag = 0; | |
clearByteArray(); | |
curbyte = 0; | |
bytefiller = 0; | |
pinMode(SS, INPUT); | |
pinMode(SCLK, INPUT); | |
pinMode(SI, INPUT); | |
//Falling SS enables falling clock interrupt | |
//Rising SS disabled falling clock and flags serial output | |
attachInterrupt(digitalPinToInterrupt(SS), changeSS, CHANGE); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
if (messageFlag) { | |
messageFlag = 0; | |
for (uint8_t i=0; i<20; i++) { Serial.print(bytearray[i]); Serial.print(" "); } | |
Serial.println(); | |
} | |
} | |
void clearByteArray(void) { | |
for (uint8_t i=0; i<20; i++) { | |
bytearray[i] = 0; | |
} | |
} | |
void changeSS(void) { | |
if(digitalRead(SS)) { | |
//Rising Edge | |
//Serial.println("Rising Edge!"); | |
//Packet is done, stop listening to clock and flag for a completed message | |
detachInterrupt(digitalPinToInterrupt(SCLK)); | |
//Shift in the remaining bits to the nearest byte | |
if (bitcount) { | |
bytearray[bytefiller] = (curbyte << (8-bitcount)); | |
} | |
//Tell main to print the message | |
messageFlag = 1; | |
} | |
else { | |
//Serial.println("Falling Edge!"); | |
//Falling Edge | |
//Listen for falling clock and keep track of bit count | |
bitcount = 0; | |
bytefiller = 0; | |
attachInterrupt(digitalPinToInterrupt(SCLK), fallingSCLK, FALLING); | |
} | |
} | |
void fallingSCLK(void) { | |
curbyte = (curbyte << 1) + digitalRead(SI); | |
if (++bitcount > 7) { | |
bitcount = 0; | |
bytearray[bytefiller++] = curbyte; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment