'Wire 라이브러리'에 해당되는 글 3건

  1. 2017.12.01 MPU6050 센서 1
  2. 2017.11.30 MPU6050을 이용한 기울기 측정의 예제
  3. 2017.03.18 아두이노의 TWI(I2C) 통신


MPU6050 센서는 가속도계(Accelerometer)와 자이로(Gyroscope)가 1개의 칩에 모두 포함하고 있는 6DOF(Degrees of Freedom) MEMS(Micro Electro Mechanical Systems) 센서로, I2C(Inter Integrated Circuit) 통신 프로토콜을 통해서 데이터를 가져올 수 있습니다. 다음은 MPU6050의 메뉴얼입니다.


http://www.invensense.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf



MPU6050의 특징입니다.

      • 3-axis Accel + 3-axis Gyroscope DMP(Digital Motion Processor)

      • ±1% Temperature Sensor( Digital output )

      • 7개의 16bit ADC를 내장하여 16bit 정교한 기울기 출력

      • ±250,±500,±1000,±2000(˚/sec) dps 자이로, ±2,±4,±8,±16g 가속도 (User programable)

      • 1024byte fifo buffer

      • I2C 400KHz

      • Programable Interrupts

      • High-G Interrupts

      • VDD: 2.375V ~ 3.46V

      • Gyroscope Operating current 3.6mA( Standby 5uA )

      • Accelerometer Operating current 500uA( Low Power mode 10uA~ )

      • Programable Low-Pass Filter

      • -40℃ ~ +85℃ (TA 25℃ )

      • StartUp time 30msec

      • Self Test

      • I2C Address : 0x68 ( except R/W 0x1 )

      • I2C Master or Slave

      • Auxiliary I2C bus for communicating to an off-chip 3-Axis digital output magnetometer(지자계 센서) or other sensors.


MPU6050은 24pin QFN 패키지로 내부 timing generator를 사용하지 않는 경우 외장 32.768kHz 혹은 19.2MHz 클럭이 필요합니다. 따라서 사용이 용이하도록 주변 소자를 내장한 MPU6050의 Breakout 보드가 있으며 GY-521의 그 중의 하나입니다.


GY-521의 회로도


GY-521 모듈

(가속도계와 자이로의 방향은 MPU6050 칩의 1번 핀을 기준으로 3차원 축이 결정되며 MPU6050과 동일함을 알 수 있습니다)


MPU6050(GY-521)은 가속도계를 포함하므로 가속도를 측정하는 센서는 아닙니다. 단지 가속도를 이용하여 3차원 공간상 X, Y 그리고 Z 축을 중심으로 기울어진 각도(기울기)를 얻는 센서입니다. 가속도는 중력 방향과의 반대 방향일 때 양(+)이고 아래에서 각 축에 곡선 화살표는 자이로의 회전방향을 나타냅니다. 가속도계와 자이로 외에도 온도도 측정할 수 있는데 이는 이와같은 센서가 온도에 따라 약간 변화하기 때문에 이를 보정하는 목적으로 제공합니다.


만일 MPU6050을 비행기에 탑재하고 진행방향이 Y축 방향과 같다면 가속도계 출력 AccX는 롤(Roll), AccY는 피치(Pitch)그리고 AccZ는 요(Yaw)가 됩니다. 즉 AccX는 X축을 기준으로 기울어진 각도를 의미합니다. 가속도계는 X, Y축에 대해서 기울어진 정도를 중력가속도[g]의 단위로 출력합니다. 이때 기준 방향은 중력방향입니다. 그러나 Z축이 중력방향이 일치하는 경우 요를 구할 수 없다는 것입니다.


만일 움직이지 않고 이동하는 경우 진행 방향의 가속도의 영향으로 중력 방향이 변하게 되어 부정확하게 된다는 것입니다. 이러한 이유로 자이로의 측정 결과를 참조하게 되는데, 자이로는 짧은 시간은 정확하기 때문입니다. 하지만 긴 시간에 대해서는 자이로 센서가 측정시 함유하는 잡음 등을 각속도를 적분하여 기울기를 얻기 때문에 적분하는데, 이 과정에서 오차(적분상수)는 누적되고 시간에 따라 자이로 측정값은 드리프트하게 됩니다. 이때 변화분을 bias라고도 부릅니다.



위 그림에서 X축을 중심으로 회전한 각도 φ와 Y축을 중심으로 회전한 각도 ρ의 계산식입니다. 만일 X축 자체가 기울어지지 않았다면, 중력이 X축 상에 기여도는 없어 φ는 arctan(Ay/Az)으로 간략하게 됩니다. 여기서 Ax, Ay, Az는 AccX, AccY, AccZ입니다. ρ에서 음의 부호는 X축 중심으로 회전각도는 Y축이 위쪽으로 기울어져야 양이지만, Y축 중심으로 회전각도는 X축이 아래로 기울어져야 양이기 때문입니다.


MPU6050을 사용해 실시간으로 기울기를 요구하는 시스템은 가속도계의 측정값과 자이로의 측정값을 적절히 잡음을 고려하여 융합하고 최적의 가장 정확한 기울기를 얻어냅니다. 이때 사용하는 필터는 보상필터(Complementary filter; 혹은 상보필터)와 칼만필터(Kalman filter)로 알려집니다.


MPU6050은 7개의 채널에 대해서 16bit 크기의 값을 출력해주는 고성능 ADC를 내장하므로 각 축의 센서 출력값에 대해서 int16_t(-32768~32767)의 자료형으로 접근해야 합니다. 또한 MPU6050은 update rate(sampling time)이 가속도, 자이로에 대해서 각각 4~1000Hz, 4~8000Hz으로 출력값을 제공합니다.


MPU6050은 내부 레지스터를 이용해서 출력 값의 범위를 조정할 수 있습니다. 예를 들어 가속도계에서 AFS_SEL=0으로 설정함으로써 출력은 ±2[g]까지 나타낼 수 있으며 이를 2byte 크기로 나타내게 됩니다. 만일 AFS_SEL=0과 FS_SEL=0을 설정하였다면 다음과 같습니다.



가속도계에서는 최대 ±2[g]이고(-2g에서 +2g까지 측정하여 -32768에서 +32767까지 매핑Scale Factor가 1g당 16,384로 출력에 이를 나누어주면 실제 [g] 단위를 얻을 수 있습니다. 그러나 우리가 원하는 것은 기울어지 각도이므로 arctan에서는 비율(ratio)만을 사용하므로 단위는 의미가 없게 됩니다. 자이로에서는 최대 ±250[deg/s]이고(-250에서 +250까지 측정하여 -32768에서 32767까지 매핑Scale Factor가 131(32767/250)로 출력에 이를 나누어주면 실제 [deg/s] 단위의 각가속도를 얻을 수 있습니다. 각 센서는 감도(Sensitivity)를 증가시킬수록 미세하게 측정 가능하지만 정확도는 떨어집니다.


다음은 아두이노(Arduino) 보드와 GY-521(MPU6050) 모듈과의 연결 방법과 Wire 라이브러리를 이용하여 실행한 MPU6050의 데이터 출력의 예제입니다.


아두이노 보드와 연결 방법



// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain

#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  Wire.begin(); // Wire 라이브러리 초기화
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);      // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)     
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); 
}




'Flight Controller 이해 > 센서' 카테고리의 다른 글

관성측정장치(IMU)의 원리  (0) 2017.03.14
드론에 요구되는 각종 센서들  (0) 2017.02.26
Posted by Nature & Life
Embedded Lecture/Arduino2017. 11. 30. 18:04


아두이노에서 기본적으로 제공하는 Wire 라이브러리를 이용해도 되지만 I2C 라이브러리를 이용하여 MPU6050의 X축, Y축 그리고 Z축의 기울기를 구하였습니다.


i2c.ino

const uint8_t IMUAddress = 0x68; // AD0 is logic low on the PCB

const uint16_t I2C_TIMEOUT = 1000; // Used to check for errors in I2C communication


uint8_t i2cWrite(uint8_t registerAddress, uint8_t data, bool sendStop) {

  return i2cWrite(registerAddress,&data,1,sendStop); // Returns 0 on success

}


uint8_t i2cWrite(uint8_t registerAddress, uint8_t* data, uint8_t length, bool sendStop) {

  Wire.beginTransmission(IMUAddress);

  Wire.write(registerAddress);

  Wire.write(data, length);

  return Wire.endTransmission(sendStop); // Returns 0 on success

}


uint8_t i2cRead(uint8_t registerAddress, uint8_t* data, uint8_t nbytes) {

  uint32_t timeOutTimer;

  Wire.beginTransmission(IMUAddress);

  Wire.write(registerAddress);

  if(Wire.endTransmission(false)) // Don't release the bus

    return 1; // Error in communication

  Wire.requestFrom(IMUAddress, nbytes,(uint8_t)true); // Send a repeated start and then release the bus after reading

  for(uint8_t i = 0; i < nbytes; i++) {

    if(Wire.available())

      data[i] = Wire.read();

    else {

      timeOutTimer = micros();

      while(((micros() - timeOutTimer) < I2C_TIMEOUT) && !Wire.available());

      if(Wire.available())

        data[i] = Wire.read();

      else

        return 2; // Error in communication

    }

  }

  return 0; // Success

}


Kalman.h

/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics-> All rights reserved->

 This software may be distributed and modified under the terms of the GNU

 General Public License version 2 (GPL2) as published by the Free Software

 Foundation and appearing in the file GPL2->TXT included in the packaging of

 this file-> Please note that GPL2 Section 2[b] requires that all works based

 on this software must also be made publicly available under the terms of

 the GPL2 ("Copyleft")->


 Contact information

 -------------------

 Kristian Lauszus, TKJ Electronics

 Web      :  http://www->tkjelectronics->com

 e-mail   :  kristianl@tkjelectronics->com

 */


#ifndef _Kalman_h

#define _Kalman_h


struct Kalman {

    /* Kalman filter variables */

    double Q_angle; // Process noise variance for the accelerometer

    double Q_bias; // Process noise variance for the gyro bias

    double R_measure; // Measurement noise variance - this is actually the variance of the measurement noise


    double angle; // The angle calculated by the Kalman filter - part of the 2x1 state vector

    double bias; // The gyro bias calculated by the Kalman filter - part of the 2x1 state vector

    double rate; // Unbiased rate calculated from the rate and the calculated bias - you have to call getAngle to update the rate


    double P[2][2]; // Error covariance matrix - This is a 2x2 matrix

    double K[2]; // Kalman gain - This is a 2x1 vector

    double y; // Angle difference

    double S; // Estimate error

};


void Init(struct Kalman* klm){

    /* We will set the variables like so, these can also be tuned by the user */

    klm->Q_angle = 0.001;

    klm->Q_bias = 0.003;

    klm->R_measure = 0.03;


    klm->angle = 0; // Reset the angle

    klm->bias = 0; // Reset bias

   klm->P[0][0] = 0; // Since we assume that the bias is 0 and we know the starting angle (use setAngle), the error covariance matrix is set like so - see: http://en->wikipedia->org/wiki/Kalman_filter#Example_application->2C_technical

    klm->P[0][1] = 0;

    klm->P[1][0] = 0;

    klm->P[1][1] = 0;

}


// The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds

double getAngle(struct Kalman * klm, double newAngle, double newRate, double dt) {

    // KasBot V2  -  Kalman filter module - http://www->x-firm->com/?page_id=145

    // Modified by Kristian Lauszus

   // See my blog post for more information: http://blog->tkjelectronics->dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it


    float P00_temp;

    float P01_temp;


    // Discrete Kalman filter time update equations - Time Update ("Predict")

    // Update xhat - Project the state ahead


   /* Step 1 */

    klm->rate = newRate - klm->bias;

    klm->angle += dt * klm->rate;


    // Update estimation error covariance - Project the error covariance ahead


    /* Step 2 */

    klm->P[0][0] += dt * (dt*klm->P[1][1] - klm->P[0][1] - klm->P[1][0] + klm->Q_angle);

    klm->P[0][1] -= dt * klm->P[1][1];

    klm->P[1][0] -= dt * klm->P[1][1];

    klm->P[1][1] += klm->Q_bias * dt;


    // Discrete Kalman filter measurement update equations - Measurement Update ("Correct")

    // Calculate Kalman gain - Compute the Kalman gain


    /* Step 4 */

    klm->S = klm->P[0][0] + klm->R_measure;


    /* Step 5 */

    klm->K[0] = klm->P[0][0] / klm->S;

    klm->K[1] = klm->P[1][0] / klm->S;


    // Calculate angle and bias - Update estimate with measurement zk (newAngle)


    /* Step 3 */

    klm->y = newAngle - klm->angle;

 

   /* Step 6 */

    klm->angle += klm->K[0] * klm->y;

    klm->bias += klm->K[1] * klm->y;


    // Calculate estimation error covariance - Update the error covariance


    /* Step 7 */

    P00_temp = klm->P[0][0];

    P01_temp = klm->P[0][1];


    klm->P[0][0] -= klm->K[0] * P00_temp;

    klm->P[0][1] -= klm->K[0] * P01_temp;

    klm->P[1][0] -= klm->K[1] * P00_temp;

    klm->P[1][1] -= klm->K[1] * P01_temp;

 

   return klm->angle;

}

// Used to set angle, this should be set as the starting angle

void setAngle(struct Kalman* klm, double newAngle) { klm->angle = newAngle; }


// Return the unbiased rate

double getRate(struct Kalman* klm) { return klm->rate; }

 

/* These are used to tune the Kalman filter */

void setQangle(struct Kalman* klm, double newQ_angle) { klm->Q_angle = newQ_angle; }


/* Default value is (0.003f), raise this to follow input more closely, lower this to smooth result of kalman filter */

void setQbias(struct Kalman* klm, double newQ_bias) { klm->Q_bias = newQ_bias; }

void setRmeasure(struct Kalman* klm, double newR_measure) { klm->R_measure = newR_measure; }

double getQangle(struct Kalman* klm) { return klm->Q_angle; }

double getQbias(struct Kalman* klm) { return klm->Q_bias; }

double getRmeasure(struct Kalman* klm) { return klm->R_measure; }

#endif


mpu6050.ino

/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.

This software may be distributed and modified under the terms of the GNU

General Public License version 2 (GPL2) as published by the Free Software

Foundation and appearing in the file GPL2.TXT included in the packaging of

this file. Please note that GPL2 Section 2[b] requires that all works based

on this software must also be made publicly available under the terms of

the GPL2 ("Copyleft").

Contact information

-------------------

Kristian Lauszus, TKJ Electronics

Web : http://www.tkjelectronics.com

e-mail : kristianl@tkjelectronics.com

Updated by Joe YOON in 2017.12.02

*/


#include <Wire.h>

#include "Kalman.h"


struct kalman Kal_struct_X, Kal_struct_Y; // Create the Kalman instances


/* IMU Data */

int16_t accX, accY, accZ; // 3-axis accelerometer

int16_t tempRaw;

int16_t gyroX, gyroY, gyroZ; // 3-axis gyroscope


double accXangle, accYangle; // Angle calculate using the accelerometer

double temp; // Temperature

double gyroXangle, gyroYangle; // Rate calculate using the gyro

double compAngleX, compAngleY; // Calculate the angle using a complementary filter

double kalAngleX, kalAngleY; // Calculate the angle using a Kalman filter


uint32_t timer;

uint8_t i2cData[14]; // Buffer for I2C data


void setup() {

  Init(&Kal_struct_X); // Initialize Kalman filter for X-axis

  Init(&Kal_struct_Y); // Initialize Kalman filter for Y-axis

  Serial.begin(9600);

  Wire.begin();

  i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz

  i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling

  i2cData[2] = 0x00; // Set Gyro Full Scale Range to +/-250[deg/s]

  i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to +/-2[g]

  while(i2cWrite(0x19,i2cData,4,false)); // Write to all four registers at once

  while(i2cWrite(0x6B,0x01,true)); // PLL with X axis gyroscope reference and disable sleep mode

  while(i2cRead(0x75,i2cData,1));

  if(i2cData[0] != 0x68) { // Read "WHO_AM_I" register

    Serial.print(F("Error reading sensor"));

    while(1);

  }

  

  delay(100); // Wait for sensor to stabilize

  

  /* Set kalman and gyro starting angle */

  while(i2cRead(0x3B,i2cData,6));

  accX = ((i2cData[0] << 8) | i2cData[1]);

  accY = ((i2cData[2] << 8) | i2cData[3]);

  accZ = ((i2cData[4] << 8) | i2cData[5]);


  // atan2 outputs the value of -? to ? (radians) - see http://en.wikipedia.org/wiki/Atan2

  // We then convert it to 0 to 2? and then from radians to degrees

  accYangle = atan2(-1*accX/sqrt(pow(accY,2) + pow(accZ,2)))*RAD_TO_DEG;

  accXangle = atan2(accY/sqrt(pow(accX,2) + pow(accZ,2)))*RAD_TO_DEG;

   

  setAngle(&Kal_struct_X, accXangle); // Set starting angle

  setAngle(&Kal_struct_Y, accYangle);


  gyroXangle = accXangle;

  gyroYangle = accYangle;

  compAngleX = accXangle;

  compAngleY = accYangle;

  

  timer = micros();

}


void loop() {

  /* Update all the values */

  while(i2cRead(0x3B,i2cData,14));

  accX = ((i2cData[0] << 8) | i2cData[1]);

  accY = ((i2cData[2] << 8) | i2cData[3]);

  accZ = ((i2cData[4] << 8) | i2cData[5]);

  tempRaw = ((i2cData[6] << 8) | i2cData[7]);

  gyroX = ((i2cData[8] << 8) | i2cData[9]);

  gyroY = ((i2cData[10] << 8) | i2cData[11]);

  gyroZ = ((i2cData[12] << 8) | i2cData[13]);

  

  // atan2 outputs the value of -? to ? (radians) - see http://en.wikipedia.org/wiki/Atan2

  // We then convert it to 0 to 2? and then from radians to degrees

  accYangle = atan2(-1*accX/sqrt(pow(accY,2) + pow(accZ,2)))*RAD_TO_DEG;

  accXangle = atan2(accY/sqrt(pow(accX,2) + pow(accZ,2)))*RAD_TO_DEG;

   

  double gyroXrate = (double)gyroX/131.0;

  double gyroYrate = -((double)gyroY/131.0);

  gyroXangle += gyroXrate*((double)(micros()-timer)/1000000); // Calculate gyro angle without any filter

  gyroYangle += gyroYrate*((double)(micros()-timer)/1000000);

  //gyroXangle += kalmanX.getRate()*((double)(micros()-timer)/1000000); // Calculate gyro angle using the unbiased rate

  //gyroYangle += kalmanY.getRate()*((double)(micros()-timer)/1000000);

  

  compAngleX = (0.93*(compAngleX+(gyroXrate*(double)(micros()-timer)/1000000)))+(0.07*accXangle); // Calculate the angle using a Complimentary filter

  compAngleY = (0.93*(compAngleY+(gyroYrate*(double)(micros()-timer)/1000000)))+(0.07*accYangle);

  

  kalAngleX = getAngle(&Kal_struct_X, accXanglegyroXrate(double)(micros()-timer)/1000000); // Calculate the angle using a Kalman filter

  kalAngleY = getAngle(&Kal_struct_Y, accYanglegyroYrate(double)(micros()-timer)/1000000);

  timer = micros();

  

  temp = ((double)tempRaw + 12412.0) / 340.0;

  

  /* Print Data */

  display_formatted_float(accX, 5, 0, 3, false);

  display_formatted_float(accY, 5, 0, 3, false);

  display_formatted_float(accZ, 5, 0, 3, false);

  display_formatted_float(gyroX, 5, 0, 3, false);

  display_formatted_float(gyroY, 5, 0, 3, false);

  display_formatted_float(gyroZ, 5, 0, 3, false);


  Serial.print("\t");


  display_formatted_float(accXangle, 5, 2, 3, false);

  display_formatted_float(gyroXangle, 5, 2, 3, false);

  display_formatted_float(compAngleX, 5, 2, 3, false);

  display_formatted_float(kalAngleX, 5, 2, 3, false);


  Serial.print("\t");


  display_formatted_float(accYangle, 5, 2, 3, false);

  display_formatted_float(gyroYangle, 5, 2, 3, false);

  display_formatted_float(compAngleY, 5, 2, 3, false);

  display_formatted_float(kalAngleY, 5, 2, 3, false);


  //Serial.print(temp);Serial.print("\t");


  Serial.print("\r\n");

  delay(1);

}


void display_formatted_float(double val, int characteristic, int mantissa, int blank, boolean linefeed) {

  char outString[16];

  int len;


  dtostrf(val, characteristic, mantissa, outString);

  len = strlen(outString);

  for(int i = 0; i < ((characteristic+mantissa+blank)-len); i++) Serial.print(F(" "));

  Serial.print(outString);

  if(linefeed)

    Serial.print(F("\n"));

}


Posted by Nature & Life
Embedded Lecture/Arduino2017. 3. 18. 14:53


USART와 같은 시리얼 통신이 1:1 통신 규약인 반면, TWI(I2C)는 1:n 통신 규약으로 하나의 마스터(master) 기기가 여러 개의 슬레이브(slave) 디바이스들과 통신을 할 수 있다는 장점이 있습니다. Wire 라이브러리는 아두이노의 표준 라이브러리로서 Arduino IDE에 기본으로 내장되어 있습니다. 따라서 아두이노로 TWI 통신을 위해서는 다음의 Wire 라이브러리를 지정하여야 합니다.


#include <Wire.h>


연결 구성은 하나의 마스터와 다수의 슬레이브로 구분되고 슬레이브들은 7bit 혹은 8bit 아이디(숫자)로 서로를 구분합니다. TWI는 모든 통신 주도권을 master가 가진다. 슬레이브에서 데이터를 읽어올 때도 마스터에서 요구하고 슬레이브로 데이터를 보낼 때도 마찬가지로 마스터에서 통신을 요구한 후 보냅니다. 마스터에서는 다음과 같이 초기화 함수를 호출합니다.


Wire.begin(); // 마스터의 TWI 초기화


슬레이브에서는 다음과 같이 초기화 함수를 아이디를 가지고 호출한다.


Wire.begin(n); // 슬레이브의 TWI 초기화


Wire.begin(n) 함수는 n번 슬레이브의 TWI 초기화하는 명령이며, 아이디 n을 가지는 연결된 마스터에서 기기간에 구별을 하게 됩니다.


마스터에서 슬레이브로 데이터 보낼 때는 Wire.beginTransmission(id) 함수로 아이디가 id인 슬레이브와 TWI 통신을 시작합니다. 그리고 Wire.write(byte) 함수로 byte형 데이터를 보내고, Wire.endTransmission() 함수로 통신을 끝냅니다. Wire.write() 함수는 입력 변수의 자료형에 따라 다음과 같이 3가지가 전송할 수 있습니다.


Wire.write(byte by); // byte형 데이터 하나를 전송

Wire.write(string str); // 문자열 str을 전송

Wire.write(const byte *ptrByte, int n); // byte형 포인터에 저장된 byte 배열에서 n개의 데이터를 전송


슬레이브 쪽에서는 마스터에서 데이터를 보냈을 때 호출되는 이벤트 함수를 다음과 같이 등록해 두면 데이터가 보내졌을 때 이 함수가 호출되어 처리가 가능하게 됩니다. Wire.onReceive() 함수를 이용해서 사용자가 지정한 receiveEvent() 함수를 데이터가 보내졌을 때 호출될 함수로 등록합니다.


void setup() {

    Wire.onReceive(receiveEvent);

}

....

....

void receiveEvent(int iNum) 

{

    byte by[iNum];

    for(int n=0; n<iNum; n++)

        by[n] = Wire.read();

}

위와 같이 등록된 이벤트 핸들러는 넘겨받은 바이트 수를 입력으로 건네주게 되고, Wire.read() 함수를 이용하여 by 변수에 저장하게 할 수 있습니다.


마스터가 슬레이브에서 데이터를 받을 때에도 마스터에서 먼저 요구하며 그 요구에 슬레이브가 반응하도록 되어 있는데, 마스터에서 슬레이브에 데이터를 요구하고 읽어오는 과정은 다음과 같습니다.


byte by[n], m=0;

Wire.requestFrom(id, n); // id를 가지는 슬레이브에 n 바이트를 보내기를 요구한다.

while( Wire.available() ) // 읽어올 데이터가 버퍼에 남아있다면

{

    by[m++]=Wire.read(); // 데이터를 읽는다.

}


슬레이브 측에서는 마스터에서 요구가 올 때 처리할 이벤터 핸들러를 다음과 같이 등록해 두면 됩니다. 다음 예를 마스터의 전송 요구시 호출된 사용자 지정의 requestEvent() 함수를 등록합니다. 결론적으로 마스터와 슬레이브 사이에 통신을 할 경우 마스터에서 슬레이브 쪽으로 통신을 하겠다는 요구를 먼저 하게 되어 있다는 것입니다.


Wire.onRequest( requestEvent ); 

...

...

void requestEvent()

{

    Wire.write(100); // (예를 들어) 100이라는 숫자를 전송한다.

}



'Embedded Lecture > Arduino' 카테고리의 다른 글

아날로그 입력  (0) 2017.03.18
인터럽트와 volatile 지시자  (1) 2017.03.18
아두이노의 시리얼 통신  (0) 2017.03.18
인터럽트의 처리(1)  (0) 2017.03.12
LED 깜박이기  (0) 2017.03.12
Posted by Nature & Life