7 years, 7 months ago.

I2C Slave 挙動

I2C Slave として動作させたいと考えています。

下記のようなコードを記述したのですが、 想定している挙動としては、Slave アドレスが一致した際に、

  • データが 0x01, 0xAA となった際に LED 点灯
  • データが 0x01, 0x55 となった際に LED 消灯 です。

実機にて動作確認したところ、 read() 後の buf の値が、1回遅れているような挙動となっています。

  • 1回目送信データ、0x01, 0x55 … buf 値変化なし、LED 変化なし。
  • 2回目送信データ、0x01, 0x55 ... buf 値 0x01, 0x55、 LED 消灯。
  • 3回目送信データ、0x01, 0xAA … buf 値 0x01, 0x55、LED 消灯。
  • 4回目送信データ、0x01, 0xAA … buf 値 0x01, 0xAA、LED 点灯。

コード記述がおかしいのでしょうか、また、ライブラリに問題はないのでしょうか。 ご教授、いただけると幸いです。

include the mbed library with this snippet

#include "mbed.h"

#define SLAVE_ADR  (0x70<<1)
#define LEN_I2CSLV 4

DigitalOut myled(P0_1);
I2CSlave   slave(P0_11, P0_10);
Serial     pc(P0_15, P0_24);

int main() {
    char buf[LEN_I2CSLV];
    int  res = 0;
     
    myled = 1;
    slave.address(SLAVE_ADR);
    pc.printf("welcome!\n");
    
    while (1) {
        int i = slave.receive();
        switch (i) {
            case I2CSlave::ReadAddressed:
                break;
            case I2CSlave::WriteGeneral:
                break;
            case I2CSlave::WriteAddressed:
                res = slave.read(buf, LEN_I2CSLV);
                               
                pc.printf("Read A: %d, %d, %d\n", buf[0],buf[1],buf[2]);
                
                if (buf[0] == 0x01) {              
                    if (buf[1] == 0xAA) {
                        myled = 1;
                        //pc.printf("Write:AA\n");
                    } else if (buf[1] == 0x55) {
                        myled = 0;
                        //pc.printf("Write:55\n");
                    }
                }
                break;
        }

        for(int i = 0; i < LEN_I2CSLV; i++) buf[i] = 0;    // Clear buffer
    }
}

Question relating to:

The Switch Science mbed LPC824 operates at CPU frequencies of 30 MHz. The LPC824 includes up to 32 kB of flash memory, up to 8 kB of data memory, four …

1) Do you have pull-up resistors on I2C SDA & SCL lines ? The resistors are required. 2.2k to 10k value is good. I2C lines are open drain and need the resistors.

2) What is the buf results if you read the buffer after the slave.receive() ?

int i = slave.receive(); res = slave.read(buf, LEN_I2CSLV);

pc.printf("Read A: %d, %d, %d\n", buf[0],buf[1],buf[2]);

posted by Sanjiv Bhatia 03 Sep 2016

mbed LPC824 を mbed LPC1114FN28 に置き換えたところ、 問題なくI2C Slave 動作することを確認しました。

・ソースコードは同様の物を使用ししています (ピンアサインのみ変更) ・I2C バスラインに接続されているものも変えていません。  (I2C Master, pullup res, 配線長 は変えず、I2C Slave IC を変更したのみ)

使用する mbed によって挙動が違うようですね。HW の差異が見えているのでしょうか。 mbed LPC824 で I2CSlave.read(); を使用した Slave 動作事例があるのか気になるところです。

posted by Y Saito 10 Nov 2016
Be the first to answer this question.