arduino에서 i2c 그 5

2086 단어 ArduinoI2C

개요



arduino에서 i2c 해 보았습니다.
풀 스크래치로 slave 써 보았다.

사진





샘플 코드


#include <inttypes.h>
#include <compat/twi.h>

#define TWI_STX_ADR_ACK                 0xA8
#define TWI_STX_ADR_ACK_M_ARB_LOST      0xB0
#define TWI_STX_DATA_ACK                0xB8
#define TWI_STX_DATA_NACK               0xC0
#define TWI_STX_DATA_ACK_LAST_BYTE      0xC8
#define TWI_SRX_ADR_ACK                 0x60
#define TWI_SRX_ADR_ACK_M_ARB_LOST      0x68
#define TWI_SRX_GEN_ACK                 0x70
#define TWI_SRX_GEN_ACK_M_ARB_LOST      0x78
#define TWI_SRX_ADR_DATA_ACK            0x80
#define TWI_SRX_ADR_DATA_NACK           0x88
#define TWI_SRX_GEN_DATA_ACK            0x90
#define TWI_SRX_GEN_DATA_NACK           0x98
#define TWI_SRX_STOP_RESTART            0xA0

uint8_t t = 0;

void i2c_init(uint8_t dat)
{
}
void Rx(uint8_t dat)
{
    t = dat;
}
uint8_t Tx(void)
{
    t++;
    return t;
}
void setup()
{
    uint8_t adrs = 0x55;
    adrs <<= 1;
    TWAR = adrs;
    TWCR = (1 << TWEA) | (1 << TWEN);
}
void loop()
{
    if (!(TWCR & (1 << TWINT))) return;
    switch (TWSR)
    {
    case TWI_SRX_ADR_ACK:
        i2c_init(TWDR);
        TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWINT);
    break;
    case TWI_SRX_ADR_DATA_ACK:
        Rx(TWDR);
        TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWINT);
    break;
    case TWI_STX_ADR_ACK:
        i2c_init(TWDR);
        TWDR = Tx();
        TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWINT);
    break;
    case TWI_STX_DATA_ACK:
        TWDR = Tx();
        TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWINT);
    break;
    case TWI_STX_DATA_NACK:
    case TWI_SRX_STOP_RESTART:
        TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWINT);
    break;
    }
}




이상

좋은 웹페이지 즐겨찾기