概要
arduinoでi2cやってみた。
twi.h使って、i2cスキャナー、やってみた。
写真
回路図
サンプルコード
extern "C" {
# include <stdlib.h>
# include <string.h>
# include <inttypes.h>
# include "twi.h"
}
uint8_t rxBuffer[32];
uint8_t rxBufferIndex = 0;
uint8_t rxBufferLength = 0;
uint8_t txAddress = 0;
uint8_t txBuffer[32];
uint8_t txBufferIndex = 0;
uint8_t txBufferLength = 0;
void i2c_start(uint8_t address)
{
twi_init();
txAddress = address;
}
uint8_t i2c_stop(uint8_t sendStop)
{
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop);
return ret;
}
void setup()
{
char outdata;
outdata = 0x09;
Serial.begin(115200);
Serial.println("\nI2C Scanner");
byte error = 1;
byte address;
int nDevices = 0;
Serial.println("Scanning...");
for (address = 1; address < 127; address++)
{
i2c_start(address);
error = i2c_stop(true);
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("Unknow 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");
Serial.println("ok");
}
void loop()
{
delay(100);
}
結果
I2C Scanner
Scanning...
I2C device found at address 0x27 !
done
ok
以上。