Sille Van Landschoot / Mbed 2 deprecated mbed_slave_full

Dependencies:   mbed

main.cpp

Committer:
dwini
Date:
2014-10-13
Revision:
1:e8ff4ff5a726
Parent:
0:e24b497adfce
Child:
2:49bb6ee1191c

File content as of revision 1:e8ff4ff5a726:

#include "mbed.h"

DigitalOut aLED(LED1);
Serial pc(USBTX, USBRX); // tx, rx
I2CSlave slave(p28, p27);

const int SLAVE_ADDRESS = 0x84;
const int MEMORY_SIZE = 16;

int memory[MEMORY_SIZE];

void initializeMemory(void)
{
    for (int i = 0; i < MEMORY_SIZE; i++) {
        memory[i] = 0;
    }
}

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);

    // Make sure memory buffer is zeroed
    initializeMemory();
    
    // Alive LED
    int cAlive = 0;


    char buffer[10];
    char msg[] = "Slave!";

    slave.address(SLAVE_ADDRESS);
    
    while (1) {
        int i = slave.receive();
        switch (i) {
            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;
    
            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);
                }
                break;
        }
        for (int i = 0; i < 10; i++) buffer[i] = 0;   // Clear buffer
        
        // Alive LED
        cAlive = (cAlive + 1) % 100000;
        if (!cAlive) {
            aLED = !aLED;
        }
    }
}