Học lập trình STM32 với Visual Code | Bài 7: Giao tiếp I2C

 

Học lập trình STM32 với Visual Code | Bài 7: Giao tiếp I2C

I2C là gì?

I2C kết hợp các tính năng tốt nhất của SPI và UART. Với I2C, bạn có thể kết nối nhiều slave với một master duy nhất (như SPI) và bạn có thể có nhiều master điều khiển một hoặc nhiều slave. Điều này thực sự hữu ích khi bạn muốn có nhiều hơn một vi điều khiển ghi dữ liệu vào một thẻ nhớ duy nhất hoặc hiển thị văn bản trên một màn hình LCD.

Giống như giao tiếp UART, I2C chỉ sử dụng hai dây để truyền dữ liệu giữa các thiết bị:
SDA (Serial Data) - đường truyền cho master và slave để gửi và nhận dữ liệu.
SCL (Serial Clock) - đường mang tín hiệu xung nhịp.
I2C là một giao thức truyền thông nối tiếp, vì vậy dữ liệu được truyền từng bit dọc theo một đường duy nhất (đường SDA).
Giống như SPI, I2C là đồng bộ, do đó đầu ra của các bit được đồng bộ hóa với việc lấy mẫu các bit bởi một tín hiệu xung nhịp được chia sẻ giữa master và slave. Tín hiệu xung nhịp luôn được điều khiển bởi master.

Source code STM32F103RC (Master):

 
  #include <Arduino.h>
  #include <Wire.h>
  #include <HardwareSerial.h>

  HardwareSerial Serial_Mon(PA10PA9);  //RX,TX
  String buff_sent = "";
  void setup() {
    Serial_Mon.begin(9600);
    // Wire.setSDA(PB11);
    // Wire.setSCL(PB10);
    Wire.begin();  // Mac dinh la SDA: PB7 , SCL: PB6
  }

  int bytesToInt(byte lowBytebyte highByte){
    int val = (highByte << 8) | lowByte;
    return val;
  }

  void loop() {
    while (Serial_Mon.available())
    {
      char c = (char)Serial_Mon.read();
      buff_sent += c;
      if(c == '\n'){
        Wire.beginTransmission(2);
        Wire.write(buff_sent.c_str());
        Wire.endTransmission();
        buff_sent = "";
      }
    }

    delay(100);
    Wire.requestFrom(22);
    byte arr_rev[2];
    while (Wire.available())
    {
      Wire.readBytes(arr_rev2);
    }
    int analogVal = bytesToInt(arr_rev[0], arr_rev[1]);
    Serial_Mon.println(analogVal);
  }
  




Source Arduino Uno (Slave):


  #include <Wire.h>
  #define LED 13

  String buff_rev = "";
  void setup() {
    Serial.begin(9600);
    Wire.begin(2);
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
    pinMode(LEDOUTPUT);
  }

  void loop() {
    

  }

  void receiveEvent(){
    while(Wire.available()){
      char c = (char)Wire.read();
      if(c != '\n'){
        buff_rev += c;
      }else{
        if(buff_rev=="1"){
          digitalWrite(LEDHIGH);
        }
        if(buff_rev=="0"){
          digitalWrite(LEDLOW);
        }
        buff_rev = "";
      }
    }
  }

  void requestEvent(){
    int ai0 = analogRead(A0);
    bytebuff_sent = new byte[2];
    buff_sent = intToBytes(ai0);
    Wire.write(buff_sent2);
  }

  byte* intToBytes(int val){
    static bytearr = new byte[2];
    arr[0] = byte(val);
    arr[1] = byte(val >> 8);
    return arr;
  }


Link download file source code: Download


Video hướng dẫn: 



No comments:

Post a Comment