Skip to content

Commit 3422e4c

Browse files
author
Qinghao Shi
authored
Merge pull request #75 from mprse/io_examples
Add IO examples: SPIMaster and I2CSlave
2 parents 091aef1 + 889907d commit 3422e4c

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

APIs_IO/I2CSlave/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# I2C Slave example
2+
3+
This example shows how an `I2C` responder works.
4+
5+
**Note:** Please adapt `I2C` pins for target different than `K64F`.

APIs_IO/I2CSlave/main.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <mbed.h>
2+
3+
#if !DEVICE_I2CSLAVE
4+
#error [NOT_SUPPORTED] I2C Slave is not supported
5+
#endif
6+
7+
I2CSlave slave(D14, D15);
8+
9+
int main()
10+
{
11+
char buf[10];
12+
char msg[] = "Slave!";
13+
14+
slave.address(0xA0);
15+
while (1) {
16+
int i = slave.receive();
17+
switch (i) {
18+
case I2CSlave::ReadAddressed:
19+
slave.write(msg, strlen(msg) + 1); // Includes null char
20+
break;
21+
case I2CSlave::WriteGeneral:
22+
slave.read(buf, 10);
23+
printf("Read G: %s\n", buf);
24+
break;
25+
case I2CSlave::WriteAddressed:
26+
slave.read(buf, 10);
27+
printf("Read A: %s\n", buf);
28+
break;
29+
}
30+
for (int i = 0; i < 10; i++) {
31+
buf[i] = 0; // Clear buffer
32+
}
33+
}
34+
}

APIs_IO/SPISlave/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# SPI Slave example
2+
3+
This example shows how an `SPI` slave responder works.
4+
5+
**Note:** Please adapt `SPI` pins for target different than `K64F`.

APIs_IO/SPISlave/main.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#include "mbed.h"
2+
3+
SPISlave device(D12, D11, D13, D10); // mosi, miso, sclk, ssel
4+
5+
int main()
6+
{
7+
device.reply(0x00); // Prime SPI with first reply
8+
while (1) {
9+
if (device.receive()) {
10+
int v = device.read(); // Read byte from master
11+
v = (v + 1) % 0x100; // Add one to it, modulo 256
12+
device.reply(v); // Make this the next reply
13+
}
14+
}
15+
}

0 commit comments

Comments
 (0)