0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

arduinoでi2c その2

Posted at

概要

arduinoでi2cやってみた。
twi.h使って、i2cスキャナー、やってみた。

写真

CIMG2521.JPG

回路図

image

サンプルコード

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

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?