시퀀스와 아두이노
I2C : 주소 확인하는 코드
RS
2021. 7. 11. 18:08
SMALL
저는 SPI 통신보다 I2C방식을 더 선호합니다.
자주 사용하는 아두이노 모듈이 프로 미니라서 선 두 개(SDA, SCL)로 통신이 가능한 I2C가 좀 더 사용하기 부담이 덜하거든요. 속도가 좀 딸리기는 하지만 그렇게 신경 쓰일 정도도 아니고요.
I2C 통신 방식을 지원하는 장치는 반드시 주소를 가지고 있습니다.
장치의 메이커에서 공개를 하는 게 당연하지만, 메이커 파악 불가능한 중국제 짭퉁은 어디서 확인하는지도 모르는 경우가 태반이라서, 이 코드로 돌려본 뒤에서야 장치의 I2C주소를 알 수 있습니다.
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
while (!Serial); // Leonardo: wait for serial monitor
Serial.println("\nI2C Scanner");
}
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(5000); // wait 5 seconds for next scan
}
아두이노에 코드를 넣은 뒤 시리얼 모니터창을 켜면 반복적으로 해당 장치의 I2C주소를 출력하고 있을 겁니다.
I2C기기를 두 개 이상 연결하고 프로그램을 돌려도 두 개의 각각의 주소가 따로 제대로 출력됩니다.
LIST