arduino에서 i2c 그 2

2207 단어 ArduinoI2C

개요



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


이상.

좋은 웹페이지 즐겨찾기