자파리 :: 아두이노 wire.h 라이브러리 사용법 I2C통신
반응형

출처:https://www.arduino.cc/reference/en/language/functions/communication/wire/

 

Wire - Arduino Reference

Description This library allows you to communicate with I2C/TWI devices. On the Arduino boards with the R3 layout (1.0 pinout), the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF pin. The Arduino Due has two I2C/TWI interface

www.arduino.cc

 

번역 페이지가 없으므로 간략하게 번역해둔다. 생각하기에 필요없는 부분 생략. 필요한 부분 첨언. 의역이 다수이다.

 


This library allows you to communicate with I2C/TWI devices. On the Arduino boards with the R3 layout (1.0 pinout), the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF pin. The Arduino Due has two I2C/TWI interfaces SDA1 and SCL1 are near to the AREF pin and the additional one is on pins 20 and 21.

이 라이브러리는 I2C/TWI 장비들과 통신할 수 있게 만들어주는 것이다. SDA (data line) and SCL (clock line) 꼽는 부분은 보드마다 다르므로 핀맵을 확인하자.

 

As a reference the table below shows where TWI pins are located on various Arduino boards.

Board I2C/TWI pins
UNO, Ethernet A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 20 (SDA), 21 (SCL), SDA1, SCL1

As of Arduino 1.0, the library inherits from the Stream functions, making it consistent with other read/write libraries. Because of this, send() and receive() have been replaced with read() and write().

Recent versions of the Wire library can use timeouts to prevent a lockup in the face of certain problems on the bus, but this is not enabled by default (yet) in current versions. It is recommended to always enable these timeouts when using the Wire library. See the Wire.setWireTimeout function for more details.

최근 버전의 wire라이브러리는 벽돌처럼 멈추는것을 방지하기 위해 시간제한을 걸어두는 모양이다. 자동설정은 아니므로 이 라이브러리를 사용할 때 Wire.setWireTimeout 기능을 쓰라고 추천하고있다.

Note: There are both 7 and 8-bit versions of I2C addresses. 7 bits identify the device, and the eighth bit determines if it’s being written to or read from. The Wire library uses 7 bit addresses throughout. If you have a datasheet or sample code that uses 8-bit address, you’ll want to drop the low bit (i.e. shift the value one bit to the right), yielding an address between 0 and 127. However the addresses from 0 to 7 are not used because are reserved so the first address that can be used is 8. Please note that a pull-up resistor is needed when connecting SDA/SCL pins. Please refer to the examples for more information. MEGA 2560 board has pull-up resistors on pins 20 and 21 onboard.

The Wire library implementation uses a 32 byte buffer, therefore any communication should be within this limit. Exceeding bytes in a single transmission will just be dropped.

To use this library:

 

#include <Wire.h>

위 구문은 이 라이브러리를 사용하기 위해 들어가는 구문이다.

 
 

다음으로 기능설명이다.

begin()

Description

This function initializes the Wire library and join the I2C bus as a controller or a peripheral. This function should normally be called only once.

와이어 라이브러리를 초기화.

처음 한번만 보므로 깊게 생각할 필요는 없다.

Syntax

Wire.begin()

Wire.begin(address)

Parameters

  • address: the 7-bit slave address (optional); if not specified, join the bus as a controller device.

Returns

None.


end()

Description

Disable the Wire library, reversing the effect of Wire.begin(). To use the Wire library again after this, call Wire.begin() again.

wire라이브러리 사용을 종료하는 스크립트다.

Note: This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the WIRE_HAS_END macro, which is only defined when Wire.end() is available.

원래 버전 라이브러리에 없는 기능이고 아마도 대부분의 플랫폼에서 사용가능하지 않다

Syntax

Wire.end()

Parameters

None.

Returns

None.


requestFrom()

Description

This function is used by the controller device to request bytes from a peripheral device. The bytes may then be retrieved with the available() and read() functions. As of Arduino 1.0.1, requestFrom() accepts a boolean argument changing its behavior for compatibility with certain I2C devices. If true, requestFrom() sends a stop message after the request, releasing the I2C bus. If false, requestFrom() sends a restart message after the request. The bus will not be released, which prevents another master device from requesting between messages. This allows one master device to send multiple requests while in control. The default value is true.

이 기능은 아두이노가 주변기기로부터 정보를 요청하는 것. 바이트수(정보)는 available() and read() 기능을 써서 얻는다.

(아래는 구글 번역기 도움)

Arduino 1.0.1부터 requestFrom()은 특정 I2C 장치와의 호환성을 위해 동작을 변경하는 부울 인수를 허용합니다.

true인 경우 requestFrom()은 요청 후 중지 메시지를 보내 I2C 버스를 해제합니다. 

false인 경우 requestFrom()은 요청 후 다시 시작 메시지를 보냅니다. 

버스가 해제되지 않아 다른 마스터 장치가 메시지 사이에 요청하는 것을 방지합니다. 

이를 통해 하나의 마스터 장치가 제어하는 동안 여러 요청을 보낼 수 있습니다. 기본값은 true입니다.

Syntax

Wire.requestFrom(address, quantity)

Wire.requestFrom(address, quantity, stop)

Parameters

  • address: the 7-bit slave address of the device to request bytes from.
  • quantity: the number of bytes to request.
  • stop: true or false. true will send a stop message after the request, releasing the bus. False will continually send a restart after the request, keeping the connection active.

Returns

  • byte : the number of bytes returned from the peripheral device.

beginTransmission()

Description

This function begins a transmission to the I2C peripheral device with the given address. Subsequently, queue bytes for transmission with the write() function and transmit them by calling endTransmission().

이 기능은 주어진 주소로 I2C 주변 장치로의 전송을 시작합니다. 그 후, write() 함수를 사용하여 전송을 위해 바이트를 큐에 넣고 endTransmission()을 호출하여 전송합니다. (구글 번역기 만세. 나보다 훨씬 낫다)

Syntax

Wire.beginTransmission(address)

Parameters

  • address: the 7-bit address of the device to transmit to.

Returns

None.


write()

Description

This function writes data from a peripheral device in response to a request from a controller device, or queues bytes for transmission from a controller to peripheral device (in-between calls to beginTransmission() and endTransmission())..

이 함수는 컨트롤러 장치의 요청에 대한 응답으로 주변 장치의 데이터를 쓰거나 컨트롤러에서 주변 장치로의 전송을 위해 바이트를 큐에 넣습니다(beginTransmission() 및 endTransmission() 호출 사이).

뭐든 읽고 쓰고가 가장 중요하므로 예시와 함께 설명해주고 있다.

Syntax

Wire.write(value) Wire.write(string) Wire.write(data, length)

Parameters

  • value: a value to send as a single byte.
  • string: a string to send as a series of bytes.
  • data: an array of data to send as bytes.
  • length: the number of bytes to transmit.

Returns

The number of bytes written (reading this number is optional).

Example

#include <Wire.h>

byte val = 0;

void setup() {
  Wire.begin(); // Join I2C bus
}

void loop() {
    Wire.beginTransmission(44);  // Transmit to device number 44 (0x2C)

    Wire.write(val);             // Sends value byte
    Wire.endTransmission();      // Stop transmitting

    val++;                       // Increment value

    // if reached 64th position (max)
    if(val == 64) {
        val = 0;                   // Start over from lowest value
    }

    delay(500);
}

val값 0에서 0.5초 기다리고 val값 1로 바꾼다음에 0.5초 기다려주고 그렇게 64까지 간다음에 다시 0으로 반복시키는 구문같다.


available()

Description

This function returns the number of bytes available for retrieval with read(). This function should be called on a controller device after a call to requestFrom() or on a peripheral inside the onReceive() handler. available() inherits from the Stream utility class.

이 함수는 read()로 검색할 수 있는 바이트 수를 반환합니다. 이 함수는 requestFrom() 호출 후 컨트롤러 장치 또는 onReceive() 핸들러 내부의 주변 장치에서 호출되어야 합니다. available()은 Stream 유틸리티 클래스에서 상속됩니다.

Syntax

Wire.available()

Parameters

None.

Returns

The number of bytes available for reading.


read()

Description

This function reads a byte that was transmitted from a peripheral device to a controller device after a call to requestFrom() or was transmitted from a controller device to a peripheral device. read() inherits from the Stream utility class.

이 함수는 requestFrom() 호출 후 주변 장치에서 컨트롤러 장치로 전송되거나 컨트롤러 장치에서 주변 장치로 전송된 바이트를 읽습니다. read()는 Stream 유틸리티 클래스에서 상속합니다.

Syntax

Wire.read()

Parameters

None.

Returns

The next byte received.

Example

#include <Wire.h>

void setup() {
  Wire.begin();             // Join I2C bus (address is optional for controller device)
  Serial.begin(9600);       // Start serial for output
}

void loop() {
    Wire.requestFrom(2, 6);    // Request 6 bytes from slave device number two

    // Slave may send less than requested
    while(Wire.available()) {
        char c = Wire.read();    // Receive a byte as character
        Serial.print(c);         // Print the character
    }

    delay(500);
}

setClock()

Description

This function modifies the clock frequency for I2C communication. I2C peripheral devices have no minimum working clock frequency, however 100KHz is usually the baseline.

이 기능은 I2C 통신을 위한 클럭 주파수를 수정합니다. I2C 주변 장치에는 최소 작동 클럭 주파수가 없지만 일반적으로 100KHz가 기준선입니다.

Syntax

Wire.setClock(clockFrequency)

Parameters

  • clockFrequency: the value (in Hertz) of the desired communication clock. Accepted values are 100000 (standard mode) and 400000 (fast mode). Some processors also support 10000 (low speed mode), 1000000 (fast mode plus) and 3400000 (high speed mode). Please refer to the specific processor documentation to make sure the desired mode is supported.

Returns

None.


onReceieve()

Description

This function registers a function to be called when a peripheral device receives a transmission from a controller device.

이 함수는 주변 장치가 컨트롤러 장치로부터 전송을 수신할 때 호출될 함수를 등록합니다.

Syntax

Wire.onReceive(handler)

Parameters

  • handler: the function to be called when the peripheral device receives data; this should take a single int parameter (the number of bytes read from the controller device) and return nothing.

Returns

None.


onRequest()

Description

This function registers a function to be called when a controller device requests data from a peripheral device.

This function registers a function to be called when a controller device requests data from a peripheral device.

Syntax

Wire.onRequest(handler)

Parameters

  • handler: the function to be called, takes no parameters and returns nothing.

Returns

None.


setWireTimeout()

Description

Sets the timeout for Wire transmissions in master mode.

Note: these timeouts are almost always an indication of an underlying problem, such as misbehaving devices, noise, insufficient shielding, or other electrical problems. These timeouts will prevent your sketch from locking up, but not solve these problems. In such situations there will often (also) be data corruption which doesn’t result in a timeout or other error and remains undetected. So when a timeout happens, it is likely that some data previously read or written is also corrupted. Additional measures might be needed to more reliably detect such issues (e.g. checksums or reading back written values) and recover from them (e.g. full system reset). This timeout and such additional measures should be seen as a last line of defence, when possible the underlying cause should be fixed instead.

이러한 시간 초과는 거의 항상 장치 오작동, 노이즈, 차폐 부족 또는 기타 전기 문제와 같은 근본적인 문제를 나타냅니다. 이러한 시간 초과는 스케치가 잠기는 것을 방지하지만 이러한 문제를 해결하지는 못합니다. 이러한 상황에서는 시간 초과 또는 기타 오류를 일으키지 않고 감지되지 않은 상태로 유지되는 데이터 손상이 종종 발생합니다. 따라서 시간 초과가 발생하면 이전에 읽거나 쓴 일부 데이터도 손상될 수 있습니다. 이러한 문제(예: 체크섬 또는 기록된 값 다시 읽기)를 보다 안정적으로 감지하고 복구(예: 전체 시스템 재설정)하려면 추가 조치가 필요할 수 있습니다. 이 시간 초과 및 그러한 추가 조치는 가능한 경우 근본적인 원인을 수정해야 하는 최후의 방어선으로 간주되어야 합니다.

Syntax

Wire.setWireTimeout(timeout, reset_on_timeout)

Wire.setWireTimeout()

Parameters

  • timeout a timeout: timeout in microseconds, if zero then timeout checking is disabled
  • reset_on_timeout: if true then Wire hardware will be automatically reset on timeout

When this function is called without parameters, a default timeout is configured that should be sufficient to prevent lockups in a typical single-master configuration.

Returns

None.

Example Code

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
  #if defined(WIRE_HAS_TIMEOUT)
    Wire.setWireTimeout(3000 /* us */, true /* reset_on_timeout */);
  #endif
}

byte x = 0;

void loop() {
  /* First, send a command to the other device */
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write(123);           // send command
  byte error = Wire.endTransmission(); // run transaction
  if (error) {
    Serial.println("Error occured when writing");
    if (error == 5)
      Serial.println("It was a timeout");
  }

  delay(100);

  /* Then, read the result */
  #if defined(WIRE_HAS_TIMEOUT)
  Wire.clearWireTimeoutFlag();
  #endif
  byte len = Wire.requestFrom(8, 1); // request 1 byte from device #8
  if (len == 0) {
    Serial.println("Error occured when reading");
    #if defined(WIRE_HAS_TIMEOUT)
    if (Wire.getWireTimeoutFlag())
      Serial.println("It was a timeout");
    #endif
  }

  delay(100);
}

Notes and Warnings

How this timeout is implemented might vary between different platforms, but typically a timeout condition is triggered when waiting for (some part of) the transaction to complete (e.g. waiting for the bus to become available again, waiting for an ACK bit, or maybe waiting for the entire transaction to be completed).

When such a timeout condition occurs, the transaction is aborted and endTransmission() or requestFrom() will return an error code or zero bytes respectively. While this will not resolve the bus problem by itself (i.e. it does not remove a short-circuit), it will at least prevent blocking potentially indefinitely and allow your software to detect and maybe solve this condition.

If reset_on_timeout was set to true and the platform supports this, the Wire hardware is also reset, which can help to clear any incorrect state inside the Wire hardware module. For example, on the AVR platform, this can be required to restart communications after a noise-induced timeout.

When a timeout is triggered, a flag is set that can be queried with getWireTimeoutFlag() and must be cleared manually using clearWireTimeoutFlag() (and is also cleared when setWireTimeout() is called).

Note that this timeout can also trigger while waiting for clock stretching or waiting for a second master to complete its transaction. So make sure to adapt the timeout to accomodate for those cases if needed. A typical timeout would be 25ms (which is the maximum clock stretching allowed by the SMBus protocol), but (much) shorter values will usually also work.

이 시간 제한이 구현되는 방법은 플랫폼마다 다를 수 있지만 일반적으로 트랜잭션(일부)이 완료될 때까지 대기할 때 시간 초과 조건이 트리거됩니다(예: 버스를 다시 사용할 수 있게 되기를 기다리거나 ACK 비트를 기다리거나 대기 중일 수 있음). 전체 거래가 완료될 때까지).

이러한 시간 초과 조건이 발생하면 트랜잭션이 중단되고 endTransmission() 또는 requestFrom()이 각각 오류 코드 또는 0바이트를 반환합니다. 이것이 버스 문제를 자체적으로 해결하지는 않지만(즉, 단락을 제거하지 않음), 최소한 잠재적으로 무기한 차단을 방지하고 소프트웨어가 이 상태를 감지하고 해결할 수 있도록 합니다.

reset_on_timeout이 true로 설정되고 플랫폼이 이를 지원하는 경우 Wire 하드웨어도 재설정되어 Wire 하드웨어 모듈 내부의 잘못된 상태를 지우는 데 도움이 될 수 있습니다. 예를 들어, AVR 플랫폼에서 노이즈 유발 시간 초과 후 통신을 다시 시작하기 위해 필요할 수 있습니다.

시간 초과가 트리거되면 getWireTimeoutFlag()로 쿼리할 수 있고 clearWireTimeoutFlag()를 사용하여 수동으로 지워야 하는 플래그가 설정됩니다(또한 setWireTimeout()이 호출될 때 지워짐).

이 시간 초과는 클럭 확장을 기다리거나 두 번째 마스터가 트랜잭션을 완료할 때까지 기다리는 동안에도 트리거될 수 있습니다. 따라서 필요한 경우 이러한 경우에 맞게 시간 제한을 조정해야 합니다. 일반적인 시간 초과는 25ms(SMBus 프로토콜에서 허용하는 최대 클록 확장)이지만 (훨씬) 더 짧은 값도 일반적으로 작동합니다.

Portability Notes

This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro, which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.clearWireTimeout() are all available.

When this timeout feature was introduced on the AVR platform, it was initially kept disabled by default for compatibility, expecting it to become enabled at a later point. This means the default value of the timeout can vary between (versions of) platforms. The default timeout settings are available from the WIRE_DEFAULT_TIMEOUT and WIRE_DEFAULT_RESET_WITH_TIMEOUT macro.

If you require the timeout to be disabled, it is recommended you disable it by default using setWireTimeout(0), even though that is currently the default.

이 기능은 Wire 라이브러리의 원래 버전에서 사용할 수 없었고 여전히 모든 플랫폼에서 사용 가능하지 않을 수 있습니다. 플랫폼 및 버전 간에 이식 가능해야 하는 코드는 Wire.setWireTimeout(), Wire.getWireTimeoutFlag() 및 Wire.clearWireTimeout()이 모두 사용 가능한 경우에만 정의되는 WIRE_HAS_TIMEOUT 매크로를 사용할 수 있습니다.

이 시간 제한 기능이 AVR 플랫폼에 도입되었을 때 호환성을 위해 기본적으로 비활성화된 상태로 유지되었으며 나중에 활성화될 것으로 예상했습니다. 이는 타임아웃의 기본값이 플랫폼(버전)마다 다를 수 있음을 의미합니다. 기본 시간 초과 설정은 WIRE_DEFAULT_TIMEOUT 및 WIRE_DEFAULT_RESET_WITH_TIMEOUT 매크로에서 사용할 수 있습니다.

시간 초과를 비활성화해야 하는 경우 현재 기본값이더라도 setWireTimeout(0)을 사용하여 기본적으로 비활성화하는 것이 좋습니다.


clearWireTimeoutFlag()

Description

Clears the timeout flag.

Timeouts might not be enabled by default. See the documentation for Wire.setWireTimeout() for more information on how to configure timeouts and how they work.

시간 초과 플래그를 지웁니다.

시간 초과는 기본적으로 활성화되어 있지 않을 수 있습니다. 시간 초과를 구성하는 방법과 작동 방식에 대한 자세한 내용은 Wire.setWireTimeout() 설명서를 참조하세요.

Syntax

Wire.clearTimeout()

Parameters

None.

Returns

  • bool: The current value of the flag

Portability Notes

This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro, which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.clearWireTimeout() are all available.


getWireTimeoutFlag()

Description

Checks whether a timeout has occured since the last time the flag was cleared.

This flag is set is set whenever a timeout occurs and cleared when Wire.clearWireTimeoutFlag() is called, or when the timeout is changed using Wire.setWireTimeout().

Syntax

Wire.getWireTimeoutFlag()

Parameters

None.

Returns

  • bool: The current value of the flag

Portability Notes

This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro, which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.clearWireTimeout() are all available.

반응형
Posted by 드워프의 자파리
: