Skip to content

Add IO examples: SPIMaster and I2CSlave #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions APIs_IO/I2CSlave/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# I2C Slave example

This example shows how an `I2C` responder works.

**Note:** Please adapt `I2C` pins for target different than `K64F`.
34 changes: 34 additions & 0 deletions APIs_IO/I2CSlave/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <mbed.h>

#if !DEVICE_I2CSLAVE
#error [NOT_SUPPORTED] I2C Slave is not supported
#endif

I2CSlave slave(D14, D15);

int main()
{
char buf[10];
char msg[] = "Slave!";

slave.address(0xA0);
while (1) {
int i = slave.receive();
switch (i) {
case I2CSlave::ReadAddressed:
slave.write(msg, strlen(msg) + 1); // Includes null char
break;
case I2CSlave::WriteGeneral:
slave.read(buf, 10);
printf("Read G: %s\n", buf);
break;
case I2CSlave::WriteAddressed:
slave.read(buf, 10);
printf("Read A: %s\n", buf);
break;
}
for (int i = 0; i < 10; i++) {
buf[i] = 0; // Clear buffer
}
}
}
5 changes: 5 additions & 0 deletions APIs_IO/SPISlave/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# SPI Slave example

This example shows how an `SPI` slave responder works.

**Note:** Please adapt `SPI` pins for target different than `K64F`.
15 changes: 15 additions & 0 deletions APIs_IO/SPISlave/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "mbed.h"

SPISlave device(D12, D11, D13, D10); // mosi, miso, sclk, ssel

int main()
{
device.reply(0x00); // Prime SPI with first reply
while (1) {
if (device.receive()) {
int v = device.read(); // Read byte from master
v = (v + 1) % 0x100; // Add one to it, modulo 256
device.reply(v); // Make this the next reply
}
}
}