The [SPI](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface) protocol offers a fast connection to an external device using only 4 I/O pins. Below is an example using the [bit banging](https://en.wikipedia.org/wiki/Bit_banging) mechanism to connect to it. Any four GPIO pins can be used for this purpose. Hardware support adds more and faster ways to connect, see the [[spi]] page.
## Attaching a 23K256 SRAM chip
https://ww1.microchip.com/downloads/en/DeviceDoc/22100F.pdf
## Read & write data: `sram.cpp`
```c++
#include <jee.h>
#include <jee/hal.h>
using namespace jeeh;
#include "defs.h"
spi::Gpio sram;
void rdMem (uint16_t addr, void* buf, uint16_t len) {
sram.enable();
sram.rwByte(0x03); // read
sram.rwByte(addr >> 8);
sram.rwByte(addr);
sram.transfer(false, (uint8_t*) buf, len);
sram.disable();
}
void wrMem (uint16_t addr, void const* buf, uint16_t len) {
sram.enable();
sram.rwByte(0x02); // write
sram.rwByte(addr >> 8);
sram.rwByte(addr);
sram.transfer(true, (uint8_t*) buf, len);
sram.disable();
}
int main () {
initBoard();
sram.init("A7,A6,A5,A4");
cycles::msBusy(20); // needs time to init?
sram.enable();
sram.rwByte(0x01); // write status
sram.rwByte(0x40); // sequential mode
sram.disable();
uint8_t buf [2][32];
memset(buf, 0, sizeof buf);
wrMem(0, buf, sizeof buf);
wrMem(30, "hello", 5);
wrMem(40, "world", 5);
rdMem(20, buf[0], sizeof buf[0]);
wrMem(35, "-spi-", 5);
rdMem(20, buf[1], sizeof buf[1]);
logDump(buf, sizeof buf);
while (true) { led.toggle(); cycles::msBusy(500); }
}
```
## Sample output
```text
sram: STM32F411xx @ 100 MHz
000: 00000000 00000000 00006865 6c6c6f00 .... .... ..he llo.
010: 00000000 776f726c 64000000 00000000 .... worl d... ....
020: 00000000 00000000 00006865 6c6c6f2d .... .... ..he llo-
030: 7370692d 776f726c 64000000 00000000 spi- worl d... ....
```