This is the multi-page printable view of this section. Click here to print...

Return to the regular view of this page

As of 2025-07-24

Wire (Member Function Version)

Wire (using member functions)

    This method using member functions has relatively low abstraction and follows a general API structure similar to that provided by C language libraries. It offers a more intuitive procedure for operating a two-wire serial bus.

    However, you need to explicitly manage the start and end of bus usage.

    Reading

    requestFrom()

    size_type requestFrom(
        uint8_t u8address,
        size_type length,
        bool b_send_stop = true)

    Reads a specified number of bytes in one operation. The result is stored in a queue, so you should call the .read() method repeatedly until the queue is empty immediately afterward.

    ParameterDescription
    u8addressI2C address to read from
    lengthNumber of bytes to read
    b_send_stop=trueIf true, a STOP bit is issued at the end of reading
    Return type size_typeNumber of bytes read. 0 indicates failure

    Code Example

    int len = Wire.requestFrom(0x70, 6);
    for (int i = 0; i < 6; i++) {
      if (Wire.available()) {
        au8data[i] = Wire.read();
        Serial.print(buff[i], HEX);
      }
    }
    // skip the rest (just in case)
    // while (Wire.available()) Wire.read(); // normally, not necessary.
    

    Writing

    The writing process starts with beginTransmission(), then proceeds with the write() method. After the entire write operation is complete, call endTransmission().

    #define DEV_ADDR (0x70)
    const uint8_t msg[2] =
      {SHTC3_SOFT_RST_H, SHTC3_SOFT_RST_L};
    
    Wire.beginTransmission(DEV_ADDR);
    Wire.write(msg, sizeof(msg));
    Wire.endTransmission();

    beginTransmission()

    void beginTransmission(uint8_t address)

    Initializes a write transfer. After the write process, call endTransmission() promptly.

    ParameterDescription
    u8addressI2C address to write to

    write(value)

    size_type write(const value_type value)

    Writes a single byte.

    ParameterDescription
    valueByte to write
    Return size_typeNumber of bytes written. 0 indicates an error.

    write(*value, quantity)

    size_type write(
      const value_type* value,
      size_type quantity)

    Writes a sequence of bytes.

    ParameterDescription
    *valueByte sequence to write
    size_typeNumber of bytes
    Return size_typeNumber of bytes written. 0 indicates an error.

    endTransmission()

    uint8_t endTransmission(bool sendStop = true)

    Finalizes the write operation.

    ParameterDescription
    sendStop = trueIssues a STOP bit
    Return uint8_t0: success, 4: failure