Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: main.cpp
- Revision:
- 2:49bb6ee1191c
- Parent:
- 1:e8ff4ff5a726
- Child:
- 3:01b322df3731
--- a/main.cpp Mon Oct 13 13:31:30 2014 +0000
+++ b/main.cpp Mon Oct 13 14:34:40 2014 +0000
@@ -6,54 +6,81 @@
const int SLAVE_ADDRESS = 0x84;
const int MEMORY_SIZE = 16;
+const int I2C_FREQUENCY = 100000;
+const int I2C_BUFFER_SIZE = 10;
+
+enum COMMAND { PUSH, PULL, CLEAR };
int memory[MEMORY_SIZE];
+/*
+ * Set all memory locations to 0x55
+ */
void initializeMemory(void)
{
for (int i = 0; i < MEMORY_SIZE; i++) {
- memory[i] = 0;
+ memory[i] = 0x55;
}
}
int main() {
pc.baud(115200);
- pc.printf("I am the slave device (SLAVE_ADDRESS = 0x%x)\r\n", SLAVE_ADDRESS);
pc.printf("Size of integer is %d bytes\r\n", sizeof(int));
pc.printf("Size of memory buffer is %d elements\r\n", MEMORY_SIZE);
+
+ // Alive LED
+ int cAlive = 0;
+
+ // Configure I2C
+ slave.frequency(I2C_FREQUENCY);
+ pc.printf("Slave is working @ %dHz\r\n", I2C_FREQUENCY);
+ slave.address(SLAVE_ADDRESS);
+ pc.printf("Slave is working @ SLAVE_ADDRESS = 0x%x\r\n", SLAVE_ADDRESS);
// Make sure memory buffer is zeroed
initializeMemory();
-
- // Alive LED
- int cAlive = 0;
-
- char buffer[10];
- char msg[] = "Slave!";
-
- slave.address(SLAVE_ADDRESS);
+ // I2C buffer
+ char buffer[I2C_BUFFER_SIZE];
while (1) {
int i = slave.receive();
switch (i) {
- case I2CSlave::ReadAddressed:
+ /*case I2CSlave::ReadAddressed:
pc.printf("Slave received command: %d [ReadAddressed]\r\n", i);
if (slave.write(msg, strlen(msg) + 1) == 0) {
printf("Sending %s to master\r\n", msg);
}
- break;
+ break;*/
case I2CSlave::WriteAddressed:
- pc.printf("Slave received command: %d [WriteAddressed]\r\n", i);
-
- if (slave.read(buffer, 10) == 0) {
- pc.printf("Received %s from master\r\n", buffer);
+
+ if (!slave.read(buffer, I2C_BUFFER_SIZE)) {
+ // Check command byte
+ switch (buffer[0]) {
+ case PUSH:
+ pc.printf("Storing %d@%d\r\n", *((int*)(&(buffer[2]))), buffer[1]);
+ if (buffer[1] < MEMORY_SIZE) {
+ memory[buffer[1]] = *((int*)(&(buffer[2])));
+ } else {
+ pc.printf("Address out of boundary\r\n");
+ }
+ break;
+
+ default:
+ pc.printf("Unknown command byte\r\n");
+ }
+ } else {
+ pc.printf("Received WriteAddressed] without data\r\n");
}
break;
}
- for (int i = 0; i < 10; i++) buffer[i] = 0; // Clear buffer
+
+ // Clear buffer
+ for (int i = 0; i < I2C_BUFFER_SIZE; i++) {
+ buffer[i] = 0;
+ }
// Alive LED
cAlive = (cAlive + 1) % 100000;