注意点は、
Arduino はスレーブアドレスを7ビットで指定
mbedはスレーブアドレスを8ビットで指定
するというところ。
https://developer.mbed.org/questions/3712/KL46z-as-I2C-Slave/
(Arduinoで指定するアドレス) = (mbedで指定するアドレス) ÷ 2
になる。
Master
Arduino Mega
#include <Wire.h> #define ADDR 0x01 #define DELAY_T 100 int bytes; uint8_t hbyte; uint8_t lbyte; void setup() { Wire.begin(); Serial.begin(9600); } void loop() { Wire.requestFrom(ADDR, 2); hbyte = Wire.read(); lbyte = Wire.read(); // Serial.print("hbyte: 0x"); // Serial.print(hbyte,HEX); // Serial.print(", "); // Serial.print("lbyte: 0x"); // Serial.print(lbyte,HEX); // Serial.print(", calc: "); Serial.println((hbyte<<8)+lbyte); delay(DELAY_T); }
Slave
mbed(Nucleo F401RE)
#include "mbed.h" #define SDA PB_9 #define SCL PB_8 #define ADDR 0x02 AnalogIn ain(PA_0); I2CSlave slave(SDA, SCL); Serial pc(SERIAL_TX, SERIAL_RX); char msg[2]; int main() { msg[0]=0; msg[1]=0; slave.frequency(100000); int receive; slave.address(ADDR); while(1) { receive = slave.receive(); if(receive==1) { float fval = ain.read(); int ival = (int) (fval*5000.0); char hbyte = ival / 256; char lbyte = ival % 256; msg[0] = hbyte; msg[1] = lbyte; slave.write(msg,2); pc.printf("fval: %.4f, ADC: %d, hbyte: %d, lbyte: %d\n",fval,ival,lbyte,hbyte); } } }