'Processing'에 해당되는 글 2건
- 2019.01.01 Hardware | Digital Compass - HMC5883L 사용기 - 2
- 2017.08.20 Hardware | Gyroscope GY-521 MPU-6050 을 사용해 보자
이 글은 전편이 있습니다.
* Hardware | Digitial Compass - HMC5883L 사용기 - 1
- http://chocoball.tistory.com/entry/Hardware-Digital-Compass-HMC5883L-1
위의 포스트에서는 HMC5883L 의 중국 버전인 QMC5883L 을 사용하는 분투기(?) 였고,
이번 글은 AliExpress 에서 정식 HMC5883L 을 파는 업자를 찾아서 구입후 사용해 보는 포스트 입니다.
1. 구매
그냥 저가의 HMC5883L 을 구입하면 아마도 QMC5883L 이 배달될 껍니다.
QMC5883L 은 대략 2 USD 언더로 구입할 수 있고, 정식 HMC5883L 은 3.5 USD 정도 합니다.
중국 판매자들도 조금의 양심은 있는지, 완전 짝퉁을 정식 부품과 동일하게 올려받지는 않는것 같아요.
이번에 구입한 판매 링크는 다음과 같습니다.
* GY-273 3V-5V HMC5883L Triple Axis Compass Magnetometer Sensor Module For Arduino Three Axis Magnetic Field Module
문제 없이 잘 도착했습니다.
두둥!!! 정말 이번에는 정품 chip 일까. 바로 확인해 봅니다.
오~!!! L883 이 찍혀 있군요. 정품 chip 입니다.
AliExpress 어플에서 보면 배송업자에게 구매자들이 질문하는 QnA 가 있는데, 그 질문들을 참고했습니다.
꽤나 많은 사람들이 진짜 "L883" 인지 문의하는 글들이 보입니다.
자세한 샷으로 확실하게 찍어 봅니다.
역시 pin header 는 스스로 납땜하라는 배려를 보여 줍니다.
이 취미는 이 맛에 하는거죠.
이 얼마나 고민하고 기다린 제품인지 모릅니다. 그래서 도착하자 마자 여러장 찍어 봤어요.
2. 회로
저번 QMC5883L 에서 했던 회로 구성과 완벽하게 같습니다.
HMC5883L | Arduino Nano --------------------------- VCC | 3.3V GND | GND SCL | A5 SDA | A4 ---------------------------
저번 그림을 동일하게 사용해 주구요.
실제로 연결해 줍니다. 이것으로 준비는 끝.
I2C 로만 연결되니 다른 센서나 부품들 보다 확연히 단순합니다. 요즘 놀고있는 ESP8266 하려면 정말...
I2C detector 로 문제 없이 인식되는지 확인도 해봅니다.
#include "Wire.h" #include "i2cdetect.h" void setup() { Wire.begin(); Serial.begin(9600); Serial.println("i2cdetect example\n"); Serial.print("Scanning address range 0x03-0x77\n\n"); } void loop() { i2cdetect(); // default range from 0x03 to 0x77 delay(2000); }
정식 chip 이라 전혀 문제 없이 인식 됩니다.
역시 돈이 최고인건가요... 싼거 쫒다가 힘들었던 저번 기억이 새록새록 생각납니다.
연결된 모습은 정말 간단하쥬?
3. sketch
저번 QMC5883L 에서 했던 회로 구성과 완벽하게 같습니다.
Arduino IDE 에서 가장 간단한 HMC5883L_compass 를 사용해 봅니다.
/* HMC5883L Triple Axis Digital Compass. Compass Example. Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-magnetometr-hmc5883l.html GIT: https://github.com/jarzebski/Arduino-HMC5883L Web: http://www.jarzebski.pl (c) 2014 by Korneliusz Jarzebski */ #include "Wire.h" #include "HMC5883L.h" HMC5883L compass; void setup() { Serial.begin(9600); // Initialize Initialize HMC5883L Serial.println("Initialize HMC5883L"); while (!compass.begin()) { Serial.println("Could not find a valid HMC5883L sensor, check wiring!"); delay(500); } // Set measurement range compass.setRange(HMC5883L_RANGE_1_3GA); // Set measurement mode compass.setMeasurementMode(HMC5883L_CONTINOUS); // Set data rate compass.setDataRate(HMC5883L_DATARATE_30HZ); // Set number of samples averaged compass.setSamples(HMC5883L_SAMPLES_8); // Set calibration offset. See HMC5883L_calibration.ino compass.setOffset(0, 0); } void loop() { Vector norm = compass.readNormalize(); // Calculate heading float heading = atan2(norm.YAxis, norm.XAxis); // Set declination angle on your location and fix heading // You can find your declination on: http://magnetic-declination.com/ // (+) Positive or (-) for negative // For Bytom / Poland declination angle is 4'26E (positive) // Formula: (deg + (min / 60.0)) / (180 / M_PI); float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI); heading += declinationAngle; // Correct for heading < 0deg and heading > 360deg if (heading < 0) { heading += 2 * PI; } if (heading > 2 * PI) { heading -= 2 * PI; } // Convert to degrees float headingDegrees = heading * 180/M_PI; // Output Serial.print(" Heading = "); Serial.print(heading); Serial.print(" Degress = "); Serial.print(headingDegrees); Serial.println(); delay(100); }
예전에 삽질한게 무엇? 이라고 말하듯 바로 실행됩니다.
4. Processing
Processing 이라는 어플은 센서로부터 오는 신호를 시각적으로 실시간 표현해 주는 어플 입니다.
이 Processing 을 이용하여 실시간으로 공간 데이터를 시각적으로 표현하고자 합니다.
순서는 다음과 같습니다.
- Arduino 에 Processing 과 연동하기 위한 sketch 를 업로드 한다
- Processing 을 띄워, Arduino 와 연동용으로 만든 Processing sketch 를 실행한다
고맙게도 processing 과 연동해주는 소스를 jarzebski 라는 분이 만들었습니다.
* jarzebski/Arduino-HMC5883L
- https://github.com/jarzebski/Arduino-HMC5883L
위 zip 파일을 풀어서 "Arduino > libraries" 에 풀어줍니다.
그러면 아래와 같이 HMC5883L_processing 이라는 sketch 를 찾을 수 있습니다. Arduino 에 업로드 해 줍니다.
File > Examples > HMC5883L > HMC5883L_processing
이제 Processing을 실행시켜서, 아까 다운로드 받은 소스 안에 Processing 이라는 폴더를 찾아 봅니다.
그 안에 "HMC5883L_processing.pde" 파일이 아래 경로에 있습니다.
Arduino > libraries > HMC5883L > Processing > HMC5883L_processing > HMC5883L_processing.pde
Processing 에서 위의 파일을 로드해 줍니다.
그냥 실행시키면 그냥 까만 화면이 나옵니다.
소스에서 Serial.list 부분과 baud rate 를 바꿔줘야 합니다.
우선 Serial.list 는 Arduino IDE 에서 봤을 때, 위에서부터 몇번째 COM port 를 선택했냐에 따라서 바꿔 주면 됩니다.
저의 PC 는 COM6 에 연결되어 있으니, Serial.list 의 두번째가 됩니다.
Array 로 표현되어 있으니, 대괄호 안이 0 --> 1 으로 바뀌어야 하겠습니다. Serial.list()[1] 처럼요.
추가로 baud rate 를 115200 으로 맞춥니다.
이는 아래 그림처럼 arduino 에 올린 sketch 에서도 바꿔서 맞춰줘야 합니다.
요즘은 ESP8266 도 그렇고, Arduino Nano 의 세로운 Bootloader 도 그렇고, 기본 baud rate 를 115200 으로 통일되는 것 같아요.
이 Processing 과 Arduino sketch 도 baud rate 부분은 모두 115200 으로 통일해 줍니다.
여기까지 무사히 왔다면 문제 없이 Processing 에서 구동될 것입니다.
짜잔~~!!! 잘 연동되어서 digital compass 역할을 실시간으로 보여주고 있습니다.
동영상 갑니다.
FIN
좀 멀리 돌아온 감이 있지만, 마무리가 잘 되어 기분이 좋네요.
2019년 1월 1일 이른 아침부터 준비하여 글 올리는 것도 나름 뿌듯합니다.
이 HMC5883L 이라는 물건이 calibration - 영점 조정 을 하지 않으면 쓸수 있는 물건이 아니라고 합니다.
언제가 될 지 모르겠지만, 다음에는 HMC5883L 의 calibration 에 대해서 다뤄보겠습니다.
'Hardware' 카테고리의 다른 글
Hardware | Kovea Gas Torch 사용기 (2) | 2019.01.13 |
---|---|
Hardware | Samsung Galaxy J3 LCD 를 교환 DIY 해보자 (0) | 2019.01.12 |
Hardware | ESP-01 or ESP8266 사용기 - 2 (2) | 2018.12.31 |
Hardware | RadarBox24 멘터넌스 (0) | 2018.12.21 |
Hardware | Breadboard Jumper 구입하기 (0) | 2018.12.21 |
1. 자이로스코프
드론이 호버링 하거나 방향전환시 필요한 것중 하나가 위치조정 일것 같습니다.
이런걸 가능하게 하는 센서가 "Gyroscope" 입니다.
중력을 이용하여 자기의 위치를 알아내는 센서가 있다는게 신기할 따름입니다.
AliExpress 에서 검색해 보니, 1.09 USD!
아니 이게 1천원정도의 가격이라고?
2. 원리
전통적인 자이로스코프는 원심력을 이용하여 자기 위치를 되돌리려는 성질의 기구가 있습니다.
- https://en.wikipedia.org/wiki/Gyroscope
그런데, 이걸 반도체 안에 센싱하는 소자들을 구성하여 만든게 이번에 리뷰하는 MPU-6050 칩 입니다.
그림을 보니 중력을 이용하여 이동하는 mass 와 그걸 감지하고 원래로 복원하려고 하는 스프링 등으로 구성되었네요.
그 작은 반도체 안에 저런것을 만들어 놓다니. 거기에 1.09 USD 처럼 저렴하다는 것에 한번 더 놀랍니다.
관련된 문서는 아래에 있습니다.
어디선가 배웠던 "코리올리 효과"를 이용한다고 합니다.
참고해 보세요.
3. 도착
잊을만 하고 있을 적에 도착하였습니다. 거진 한달 걸린것 같습니다.
구성품은 GY-521 breakout 보드와 구부러진 male pin 과 똑바른 male pin 이 각각 들어있습니다.
Chip 을 보면 중간 부분에 희미하게 MPU-6050 이라고 적혀 있습니다.
좀더 잘 찍힌 제품사진은 다음과 같습니다. Chip 이 잘 보이네요.
뒷면입니다. MPU-6050 을 사용한 제품 중, 가장 일반적으로 사용되는 breakout 보드는 GY-521 이라고 하네요.
구부러진 pin 을 납땜하느냐, 곧은 pin 을 납땜하느냐 고민했습니다.
향후 어떤 보드 위에 설치하게 될 것이냐를 상상하여, 그 보드가 평평할 듯 하여 곧은 pin 을 납땜하였습니다.
4. Pinout
Breakout 보드에는 8개의 pinout이 있지만, 실제로 사용되는 것은 5개, 또는 6개만 사용됩니다.
GY-521 | Arduino Nano ---------------------------- VCC | 3.3V GND | GND SCL | A5 SDA | A4 AD0 | GND INT | D2 ----------------------------
GY-521 pinout 에 대한 몇가지 지식을 적어 봅니다.
- 원래 3.3V 가 구동 voltage 이지만, GY-521 은 자체 레귤레이터가 있어서 5V 도 가능합니다.
- Arduino 에는 2개의 MPU-6050 을 연결할 수 있게 되어 있고, AD0 의 high/low voltage 로 구분합니다.
- SCL 은 I2C 의 clock 담당이고, SDA 는 data 를 담당합니다.
관련된 내용을 영문 페이지들에서 가져와 봤습니다.
The MPU-6050 can have address of 0x68 or 0x69, depending on if the AD0 pin is held high or low.
Without anything connected, it was at 0x68 for me.
AD0 can be used to control the I2C-address. If it is connected to ground then the address is 0x68 and if it is connected to VLOGIC then the address is 0x69. The data sheet for the chip states that VLOGIC ranges from 1.71V to the working voltage of the chip. To find out the address the I2C scanner sketch can be uploaded to the Arduino when it is connected to the GY-521. The result can be viewed through the serial monitor. For the GY-521 the I2C device is found at address 0x68. This means that ADO must be connected to a pull down resistor. This holds the signal at 0V.
The gyro module communicates with the Arduino through I2C serial communication via the serial clock (SCL) and data (SDA). The MPU6050 chip needs 3.3V but a voltage regulator on the GY-521 board allows you to give it up to 5V.
Layout 은 다음과 같습니다.
실제 연결한 사진입니다.
5. I2C
Arduino 와의 인터페이스가 I2C 입니다.
우선 잘 인식 되는지 확인해 보도록 합니다.
Arduino IDE 의 Library Manager 에서 "i2cdetect" 를 인스톨 하여 돌려봅니다.
소스는 간단합니다.
#include "Wire.h" #include "i2cdetect.h" void setup() { Wire.begin(); Serial.begin(9600); Serial.println("i2cdetect example\n"); Serial.print("Scanning address range 0x03-0x77\n\n"); } void loop() { i2cdetect(); // default range from 0x03 to 0x77 delay(2000); }
결과는 다음과 같이 잘 나옵니다.
잘 인식 되었네요.
다만 MPU6050 전용 sketch 를 돌리기 위해서는 "I2Cdev.h" 가 IDE 에 등록이 되어야 합니다.
필요한 파일은 아래 링크에서 다운로드 받을 수 있습니다.
- https://github.com/jrowberg/i2cdevlib
다운로드 받은 zip 파일 내부를 보면 "I2Cdev" 라는 폴더가 있습니다.
이 "I2Cdev" 폴더를 IDE 의 library 폴더 하위에 copy 하면 library 등록이 됩니다.
- I2Cdev path : i2cdevlib-master > Arduino > I2Cdev
- library path : Arduino > library
아래는 다운로드 받은 zip 파일의 path 입니다.
아래는 Arduino 의 library path 입니다.
이제 I2C 준비는 완료 되었습니다.
5. MPU-6050 sketch
이제 MPU-6050 을 구동해 볼 차례 입니다.
위에서 다운로드 받았던 zip 파일인 "i2cdevlib-master.zip" 에서 다음 path 에서 찾아보면,
"MPU6050" 이라는 폴더가 있습니다.
- I2Cdev path : i2cdevlib-master > Arduino > MPU6050
이 폴더를 I2Cdev 와 동일한 library 폴더에 옮겨 놓으면 sketch example 을 사용할 수 있게 됩니다.
소스는 다음과 같습니다.
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0) // 6/21/2012 by Jeff Rowberg// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib // // Changelog: // 2013-05-08 - added seamless Fastwire support // - added note about gyro calibration // 2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error // 2012-06-20 - improved FIFO overflow handling and simplified read process // 2012-06-19 - completely rearranged DMP initialization code and simplification // 2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly // 2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING // 2012-06-05 - add gravity-compensated initial reference frame acceleration output // - add 3D math helper file to DMP6 example sketch // - add Euler output and Yaw/Pitch/Roll output formats // 2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee) // 2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250 // 2012-05-30 - basic DMP initialization working /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files // for both classes must be in the include path of your project #include "I2Cdev.h" #include "MPU6050_6Axis_MotionApps20.h" //#include "MPU6050.h" // not necessary if using MotionApps include file // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation // is used in I2Cdev.h #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE #include "Wire.h" #endif // class default I2C address is 0x68 // specific I2C addresses may be passed as a parameter here // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board) // AD0 high = 0x69 MPU6050 mpu; //MPU6050 mpu(0x69); // <-- use for AD0 high /* ========================================================================= NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch depends on the MPU-6050's INT pin being connected to the Arduino's external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is digital I/O pin 2. * ========================================================================= */ /* ========================================================================= NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error when using Serial.write(buf, len). The Teapot output uses this method. The solution requires a modification to the Arduino USBAPI.h file, which is fortunately simple, but annoying. This will be fixed in the next IDE release. For more info, see these links: http://arduino.cc/forum/index.php/topic,109987.0.html http://code.google.com/p/arduino/issues/detail?id=958 * ========================================================================= */ // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual // quaternion components in a [w, x, y, z] format (not best for parsing // on a remote host such as Processing or something though) //#define OUTPUT_READABLE_QUATERNION // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles // (in degrees) calculated from the quaternions coming from the FIFO. // Note that Euler angles suffer from gimbal lock (for more info, see // http://en.wikipedia.org/wiki/Gimbal_lock) //#define OUTPUT_READABLE_EULER // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/ // pitch/roll angles (in degrees) calculated from the quaternions coming // from the FIFO. Note this also requires gravity vector calculations. // Also note that yaw/pitch/roll angles suffer from gimbal lock (for // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock) #define OUTPUT_READABLE_YAWPITCHROLL // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration // components with gravity removed. This acceleration reference frame is // not compensated for orientation, so +X is always +X according to the // sensor, just without the effects of gravity. If you want acceleration // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead. //#define OUTPUT_READABLE_REALACCEL // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration // components with gravity removed and adjusted for the world frame of // reference (yaw is relative to initial orientation, since no magnetometer // is present in this case). Could be quite handy in some cases. //#define OUTPUT_READABLE_WORLDACCEL // uncomment "OUTPUT_TEAPOT" if you want output that matches the // format used for the InvenSense teapot demo //#define OUTPUT_TEAPOT #define INTERRUPT_PIN 2 // use pin 2 on Arduino Uno & most boards #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6) bool blinkState = false; // MPU control/status vars bool dmpReady = false; // set true if DMP init was successful uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer // orientation/motion vars Quaternion q; // [w, x, y, z] quaternion container VectorInt16 aa; // [x, y, z] accel sensor measurements VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements VectorFloat gravity; // [x, y, z] gravity vector float euler[3]; // [psi, theta, phi] Euler angle container float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector // packet structure for InvenSense teapot demo uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' }; // ================================================================ // === INTERRUPT DETECTION ROUTINE === // ================================================================ volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high void dmpDataReady() { mpuInterrupt = true; } // ================================================================ // === INITIAL SETUP === // ================================================================ void setup() { // join I2C bus (I2Cdev library doesn't do this automatically) #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif // initialize serial communication // (115200 chosen because it is required for Teapot Demo output, but it's // really up to you depending on your project) Serial.begin(115200); while (!Serial); // wait for Leonardo enumeration, others continue immediately // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to // the baud timing being too misaligned with processor ticks. You must use // 38400 or slower in these cases, or use some kind of external separate // crystal solution for the UART timer. // initialize device Serial.println(F("Initializing I2C devices...")); mpu.initialize(); pinMode(INTERRUPT_PIN, INPUT); // verify connection Serial.println(F("Testing device connections...")); Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed")); // wait for ready Serial.println(F("\nSend any character to begin DMP programming and demo: ")); while (Serial.available() && Serial.read()); // empty buffer while (!Serial.available()); // wait for data while (Serial.available() && Serial.read()); // empty buffer again // load and configure the DMP Serial.println(F("Initializing DMP...")); devStatus = mpu.dmpInitialize(); // supply your own gyro offsets here, scaled for min sensitivity mpu.setXGyroOffset(220); mpu.setYGyroOffset(76); mpu.setZGyroOffset(-85); mpu.setZAccelOffset(1788); // 1688 factory default for my test chip // make sure it worked (returns 0 if so) if (devStatus == 0) { // turn on the DMP, now that it's ready Serial.println(F("Enabling DMP...")); mpu.setDMPEnabled(true); // enable Arduino interrupt detection Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)...")); attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING); mpuIntStatus = mpu.getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it Serial.println(F("DMP ready! Waiting for first interrupt...")); dmpReady = true; // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) Serial.print(F("DMP Initialization failed (code ")); Serial.print(devStatus); Serial.println(F(")")); } // configure LED for output pinMode(LED_PIN, OUTPUT); } // ================================================================ // === MAIN PROGRAM LOOP === // ================================================================ void loop() { // if programming failed, don't try to do anything if (!dmpReady) return; // wait for MPU interrupt or extra packet(s) available while (!mpuInterrupt && fifoCount < packetSize) { // other program behavior stuff here // . // . // . // if you are really paranoid you can frequently test in between other // stuff to see if mpuInterrupt is true, and if so, "break;" from the // while() loop to immediately process the MPU data // . // . // . } // reset interrupt flag and get INT_STATUS byte mpuInterrupt = false; mpuIntStatus = mpu.getIntStatus(); // get current FIFO count fifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); Serial.println(F("FIFO overflow!")); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) fifoCount -= packetSize; #ifdef OUTPUT_READABLE_QUATERNION // display quaternion values in easy matrix form: w x y z mpu.dmpGetQuaternion(&q, fifoBuffer); Serial.print("quat\t"); Serial.print(q.w); Serial.print("\t"); Serial.print(q.x); Serial.print("\t"); Serial.print(q.y); Serial.print("\t"); Serial.println(q.z); #endif #ifdef OUTPUT_READABLE_EULER // display Euler angles in degrees mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetEuler(euler, &q); Serial.print("euler\t"); Serial.print(euler[0] * 180/M_PI); Serial.print("\t"); Serial.print(euler[1] * 180/M_PI); Serial.print("\t"); Serial.println(euler[2] * 180/M_PI); #endif #ifdef OUTPUT_READABLE_YAWPITCHROLL // display Euler angles in degrees mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); Serial.print("ypr\t"); Serial.print(ypr[0] * 180/M_PI); Serial.print("\t"); Serial.print(ypr[1] * 180/M_PI); Serial.print("\t"); Serial.println(ypr[2] * 180/M_PI); #endif #ifdef OUTPUT_READABLE_REALACCEL // display real acceleration, adjusted to remove gravity mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetAccel(&aa, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity); Serial.print("areal\t"); Serial.print(aaReal.x); Serial.print("\t"); Serial.print(aaReal.y); Serial.print("\t"); Serial.println(aaReal.z); #endif #ifdef OUTPUT_READABLE_WORLDACCEL // display initial world-frame acceleration, adjusted to remove gravity // and rotated based on known orientation from quaternion mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetAccel(&aa, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity); mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q); Serial.print("aworld\t"); Serial.print(aaWorld.x); Serial.print("\t"); Serial.print(aaWorld.y); Serial.print("\t"); Serial.println(aaWorld.z); #endif #ifdef OUTPUT_TEAPOT // display quaternion values in InvenSense Teapot demo format: teapotPacket[2] = fifoBuffer[0]; teapotPacket[3] = fifoBuffer[1]; teapotPacket[4] = fifoBuffer[4]; teapotPacket[5] = fifoBuffer[5]; teapotPacket[6] = fifoBuffer[8]; teapotPacket[7] = fifoBuffer[9]; teapotPacket[8] = fifoBuffer[12]; teapotPacket[9] = fifoBuffer[13]; Serial.write(teapotPacket, 14); teapotPacket[11]++; // packetCount, loops at 0xFF on purpose #endif // blink LED to indicate activity blinkState = !blinkState; digitalWrite(LED_PIN, blinkState); } }
Arduino 에 업로드 하여 확인해 봅니다.
Arduino IDE > Tools > Serial Monitor 를 열어서 확인해 봅니다.
Initializing 이 끝나고 준비상태가 되면, 어떤 character 든 보내면 측정이 시작됩니다.
Gyroscope 의 위치값들이 실시간으로 순식간에 측정이 되기 시작합니다.
잘 되네요.
6. Processing
3D 모델링을 통하여 Gyroscope 의 위치가 어떻게 보여지는지를 해봅니다.
다만, 우선 먼저 업로드 했던 sketch 를 조금 바꾸어서 업로드 해 놓을 필요가 있습니다.
- 코멘트 아웃 : #define OUTPUT_READABLE_YAWPITCHROLL
- 코멘트 제거 : #define OUTPUT_TEAPOT
이제 3D 가시화 하기 위해 "Processing IDE" 라는 프로그램을 다운로드 받고 인스톨 합니다.
- https://processing.org/download/?processing
사용하는 OS 에 맞는 파일을 다운로드 받고 인스톨 합니다.
이제 Arduino MPU 6050 processing example 을 실행에 필요한 "Toxi" library 를 다운로드 받습니다.
- https://bitbucket.org/postspectacular/toxiclibs/downloads/
지금 올라와 있는 최신 버전은 "toxiclibs-complete-0020.zip" 입니다.
다운로드 받으면 processing 폴더의 libraries 안에 copy 합니다.
- Program Files > processing > modes > java > libraries
아래는 copy 완료된 후의 libraries 폴더의 모습.
이제 processing 을 실행시킨 후, Arduino IDE libraries 폴더에 있는 MPU6050 example 에 있는 processing 용 파일을 엽니다.
- Arduino > libraries > MPU6050 > examples > MPU6050_DMP6 > Processing > MPUTeapot > MPUTeapot.pde
이것을 실행하기 전에 마지막으로 port 를 수정합니다.
저는 "COM6" 에 arduino 가 연결되어 있으므로 다음과 같이 수정하였습니다.
- String portName = "COM6";
Linux 의 경우는 "String portName = Serial.list()[0];" 을 활성화 하거나,
"String portName = /dev/ttyUSB0" 등과 같이 직접 기술해 주면 됩니다.
이제 준비는 완료 되었습니다.
7. 3D 결과
Processing 프로그램의 플레이 버튼인 "run" 을 실행시키면 다음 동영상 같이 비행체를 통하여 확인할 수 있습니다.
오오오오오!!! 정말 되었어!
동영상으로 찍어 봤습니다.
신기한 센서를 이용하여 가시화 하니 재미 있네요.
8. 3D object 변경해 보기
못생긴 비행기 모양은 112 ~ 139 라인에서 구현해 놨습니다.
이 모양을 바꾸고 싶으면 이 부분을 수정하면 됩니다.
수정하는 내용은 아래 URL 을 참고하면 되겠습니다.
- https://processing.org/tutorials/p3d/
translate(width/2, height/2, 0); stroke(255); rotateX(PI/2); rotateZ(-PI/6); noFill(); beginShape(); vertex(-100, -100, -100); vertex( 100, -100, -100); vertex( 0, 0, 100); vertex( 100, -100, -100); vertex( 100, 100, -100); vertex( 0, 0, 100); vertex( 100, 100, -100); vertex(-100, 100, -100); vertex( 0, 0, 100); vertex(-100, 100, -100); vertex(-100, -100, -100); vertex( 0, 0, 100); endShape();
적용하면 다음과 같이 변경됩니다. :-)
FIN
주말에 GY-521 센서 가지고 잘 놀았습니다.
향후 드론을 만들게 되면 사용하게 될까요?
'Hardware' 카테고리의 다른 글
Hardware | NEO-6M GPS 를 구동해 보자 (2) | 2017.09.05 |
---|---|
Hardware | Probe Clip 을 사용해 보자 (0) | 2017.08.28 |
Hardware | Resistor Network 을 사용해보자 (0) | 2017.08.17 |
Hardware | LED bar graph 를 이용해 보자 (0) | 2017.08.13 |
Hardware | Soil Moisture Sensor 구동해 보기 (0) | 2017.08.02 |