esp32 חיבור I2C master slave
slave i2c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <Wire.h> const char *response = "hello i'm slave from address 0x69 temp 27.5 c"; void setup() { Serial.begin(115200); Serial.write("i2c slave start...\n"); Wire.begin(0x69); Wire.onRequest(requestEvent); } void loop() { } void requestEvent() { Serial.write("i2c requested\n"); Wire.write(response); } |
master i2c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <Wire.h> #define SLAVE_ADDRESS 0x69 char msg[100]; void setup() { Serial.begin(115200); Serial1.begin(115200, SERIAL_8N1, 16, 17); Wire.begin(); } void loop() { Serial.println("request data"); Wire.beginTransmission(SLAVE_ADDRESS); Wire.endTransmission(); Wire.requestFrom(SLAVE_ADDRESS, 100); int i = 0; while (Wire.available()) { msg[i++] = Wire.read(); } msg[i] = '\0'; Serial.println(msg); Serial1.println(msg); Wire.beginTransmission(SLAVE_ADDRESS); Wire.write("o.k"); Wire.endTransmission(); delay(1000); } |