본문 바로가기

모듈/Pixy2

Pixy2 cam 아두이노 코딩하기 ― 물체 따라서 서보모터 움직이기

728x90
반응형

아두이노 카메라 Pixy2 소개▽

 

색깔 인식(학습)가능한 아두이노 카메라 Pixy cam ― Pixy2 소개

Pixy2 소개 원하는 물체(색)를 학습시킬 수 있는 카메라 Pixy cam. 사용해보니 만족 스러웠습니다. 그런데 Pixy2가 한참전에 나와서 살펴보았더니 아주 좋더라구요. ▲Pixy2 소개 동영상 가격은 이전버전에 비해..

ddangeun.tistory.com

Pixy2 색 인식하기▽

 

Pixy2 cam 물체 인식, 색 학습 하는 법

아두이노 카메라 Pixy2 소개 ▽ 색깔 인식(학습)가능한 아두이노 카메라 Pixy cam ― Pixy2 소개 Pixy2 소개 원하는 물체(색)를 학습시킬 수 있는 카메라 Pixy cam. 사용해보니 만족 스러웠습니다. 그런데 Pixy2가..

ddangeun.tistory.com

Pixy2 cam을 이용해서 색을 학습하였습니다.

이제 색 출력을 아두이노로 확인하고, Pan/Tilt 서보모터를 움직여 보겠습니다.

 

 

Pixy2 cam 아두이노 코딩


 

아래 링크의 가이드를 참고하였습니다.

https://docs.pixycam.com/wiki/doku.php?id=wiki:v2:hooking_up_pixy_to_a_microcontroller_-28like_an_arduino-29

 

아두이노에 연결

 

위 그림과 같이 Pixy2 를 아두이노에 연결해줍니다.

위 방법은 ICSP SPI를 이용하였는데요. 다른 통신 방법은 아래 글을 참조해 주세요.

[모듈/Pixy2] - Pixy2 cam 아두이노와 통신하기

 

받은 아두이노 라이브러리 파일(arduino_pixy2-x.y.z.zip)을

아두이노 라이브러리 추가해야합니다.

툴➜라이브러리 포함하기➜Add .ZIP Library…

 

(위 Pixy2 소개 링크에서 아두이노 라이브러리를 설치했으니 참고해주세요.)

설치링크▽

https://pixycam.com/downloads-pixy2/

 

 

추가되었으면

파일->예제->Pixy2 에 예제 소스가 있습니다.

ccc_hello_world를 열어 시리얼 모니터에 잘 출력하는지 확인하였습니다.

*먼저 물체를 인식해놔야합니다.

위에 설명했다시피, PixyMon v2 프로그램을 써도되구요, 위의 버튼을 눌러 간단히 인식시킬 수 있습니다.

 

 

Pixy2 가 물체를 인식할 수 있는 상태

 

 

#include <Pixy2.h> // This is the main Pixy object Pixy2 pixy; 

void setup() { 

  Serial.begin(115200); 
  Serial.print("Starting...\n"); 
  pixy.init(); 
 
} 

void loop() { 

  int i; // grab blocks! 
  pixy.ccc.getBlocks(); // If there are detect blocks, print them!
 
  if (pixy.ccc.numBlocks) {
	Serial.print("Detected ");
	Serial.println(pixy.ccc.numBlocks); 
	for (i=0; i<pixy.ccc.numBlocks; i++) { 
		Serial.print(" block "); 
		Serial.print(i); 
		Serial.print(": "); 
		pixy.ccc.blocks[i].print(); 
	} 
  }
}

 

 

물체의 width, height, x, y 를 알 수 있죠.

 

 


 

Arduino API


 

getBlocks() 로 감지된 Pixy object의 수를 return 하고, pixy.ccc.blocks[] array로 감지된 object의 정보를 볼수 있습니다.

  • pixy.ccc.blocks[i].m_signature 물체의 signature number (1-7)
  • pixy.ccc.blocks[i].m_x 물체 중심의 x 위치 (0 ~ 316)
  • pixy.ccc.blocks[i].m_y 물체의 중심의 y 위치 (0 ~ 208)
  • pixy.ccc.blocks[i].m_width 물체의 너비 (1 ~ 316)
  • pixy.ccc.blocks[i].m_height 물체의 높이 (1 ~ 208)
  • pixy.ccc.blocks[i].m_angle  검출 된 물체가 컬러 코드 인경우 검출 된 물체의 각도 (-180 ~180)
  • pixy.ccc.blocks[i].m_index 블록의 tracking index
  • pixy.ccc.blocks[i].m_age  블록이 추적 된 프레임 수
  • pixy.ccc.blocks[i].print() 감지된 물체 정보를 Serial 포트에 인쇄하는 멤버 함수

 

Member Fuctions
int8_t setServos(uint16_t s0, uint16_t s1)

pan/tilt 서보 설정 함수. (s0,s1 range 0-1000) error vlaue를 리턴한다.

  • PIXY_RCS_MIN_POS         0
  • PIXY_RCS_MAX_POS       1000
  • PIXY_RCS_CENTER_POS  (PIXY_RCS_MAX_POS-PIXY_RCS_MIN_POS)/2
int8_t setBrightness(uint8_t brightness) Pixy cam 밝기 설정 함수. (range 0-255) error vlaue를 리턴한다.
int8_t setLED(uint8_t r, uint8_t g, uint8_t b) Pixy 앞쪽 RGB LED 설정 함수. (r,g,b range 0-255) error vlaue를 리턴한다.
int8_t setLamp(uint8_t upper, uint8_t lower) ligt source를 on/off 한다. upper agrument는 위의 두개의 white LED, lower argument는 밑의 RGB LED. white로 나타난다. (0 혹은 1) error vlaue를 리턴한다.
int8_t init(uint32_t arg [optional]) Pixy랑 communicate 하기위한 init()함수. error vlaue를 리턴한다.
int8_t getVersion() Pixy2의 firmware와 hardware 버전, init()함수 안에서 불러온다. error vlaue를 리턴한다.
int8_t changeProg(const char *prog)

program을 바꾸는 함수. "color_connected_components" 등. error vlaue를 리턴한다.

int8_t getResolution() 프레임의 넓이와 높이를 가져온다. 이 함수를 가져온 후 frameWidth와 frameHeight 멤버 변수를 알 수 있다. changeProg()함수에서 자동으로 불러온다.
int8_t getFPS() framerate를 가져온다. (range 2-62)

 

 

Member Variables
Version *version getVersion()의 결과인 version 정보
void print() version information을 프린트한다. 
uint16_t hardware hardware version number.
uint8_t firmwareMajor firmware major version number.
uint8_t firmwareMinor firmware minor version number.
uint16_t firmwareBuild firmware build version number.
char *firmwareType firmware type의 string description.
uint16_t frameWidth 프레임의 넓이 픽셀. init()에서 불러오는 changeProg()함수에서 update된다.
uint16_t frameHeight 프레임의 높이 픽셀. init()에서 불러오는 changeProg()함수에서 update된다.
Pixy2CCC ccc Color Connected Components object 의 instance이다. (color_connected_components program)
Pixy2Line line This is an instance of the Line Tracking object의 instance이다. (line_tracking program)

 

 

Error codes


error value<0 이면 실패. 0이면 PIXY_RESULT_OK로 성공.

  • PIXY_RESULT_ERROR General error result
  • PIXY_RESULT_BUSY This is returned when Pixy has no new data. It is used in polling mode, as opposed to blocking mode.
  • PIXY_RESULT_CHECKSUM_ERROR This is returned when the data packet received contains a checksum error.
  • PIXY_RESULT_TIMEOUT This is returned when Pixy2 has taken too long to return its result.
  • PIXY_RESULT_BUTTON_OVERRIDE This is returned when the user is interacting with the button (e.g. teaching Pixy a signature) and can't perform the requested action.

 


Pan & Tilt 서보모터 움직이기


 

색깔 인식(학습) 후,

아래 그림을 참고해 서보(pan, tilt)를 잘 연결해주세요.

세트를 구입했다면 밑의 링크에 조립 가이드가 있습니다.

https://docs.pixycam.com/wiki/doku.php?id=wiki:v2:assembling_pantilt_mechanism

 

또한 밑의 링크의 글에서 서보모터 움직이는 법도 확인해주세요!▼

 

Pixy2 Pan&Tilt 서보 움직이기 ― Pixy2 서보 모터 값 조정

Pixy2 아두이노 코딩하기 ― Pixy2 소개 https://youtu.be/EcCbEWiyiQY ▲풀버전 동영상 링크 Pixy 이전버전으로 아두이노 코딩하며 놀다가, Pixy2 버전을 발견하여 구매하였습니다. 가격은 이전버전에 비해 저렴..

ddangeun.tistory.com

 

 

 예제 ccc_pantilt를 열고 업로드하여줍니다.

주의할 점은 업로드 시 아두이노와 Pixy2의 연결을 잠시 분리해야 하더라구요.(업로드 안됨.)

#include <Pixy2.h>
#include <PIDLoop.h>

Pixy2 pixy;
PIDLoop panLoop(400, 0, 400, true);
PIDLoop tiltLoop(500, 0, 500, true);

void setup()
{
  Serial.begin(115200);
  Serial.print("Starting...\n");
 
  // We need to initialize the pixy object 
  pixy.init();
  // Use color connected components program for the pan tilt to track 
  pixy.changeProg("color_connected_components");
}

void loop()
{  
  static int i = 0;
  int j;
  char buf[64]; 
  int32_t panOffset, tiltOffset;
  
  // get active blocks from Pixy
  pixy.ccc.getBlocks();
  
  if (pixy.ccc.numBlocks)
  {        
    i++;
    
    if (i%60==0)
      Serial.println(i);   
    
    // calculate pan and tilt "errors" with respect to first object (blocks[0]), 
    // which is the biggest object (they are sorted by size).  
    panOffset = (int32_t)pixy.frameWidth/2 - (int32_t)pixy.ccc.blocks[0].m_x;
    tiltOffset = (int32_t)pixy.ccc.blocks[0].m_y - (int32_t)pixy.frameHeight/2;  
  
    // update loops
    panLoop.update(panOffset);
    tiltLoop.update(tiltOffset);
  
    // set pan and tilt servos  
    pixy.setServos(panLoop.m_command, tiltLoop.m_command);
   
#if 0 // for debugging
    sprintf(buf, "%ld %ld %ld %ld", rotateLoop.m_command, translateLoop.m_command, left, right);
    Serial.println(buf);   
#endif

  }  
  else // no object detected, go into reset state
  {
    panLoop.reset();
    tiltLoop.reset();
    pixy.setServos(panLoop.m_command, tiltLoop.m_command);
  }
}

업로드 후, 잘 동작하는 것을 볼 수 있습니다. ^^

 

 

 

 

이상하게 작동한다면 USB 선을 분리해주세요.  5V라 정상 작동하지 않고 따로 6V-10V를 연결해야합니다.

 

모바일 로봇에 연결해 모터도 연동해서 물체를 따라가고

라인트레이싱도 해볼 예정이에요^^

 

아두이노 Pixy2 cam 모터 연동하기▼

 

Pixy2 cam 아두이노로 색 물체 따라 움직이는 모바일 로봇 만들기!

이번 포스팅에서는 모바일 로봇의 모터와 연동하여 색 물체를 따라 움직여 보겠습니다. 우선 색을 먼저 학습시키는 법은 아래 포스팅을 확인해주세요. 더보기 Pixy2 색 인식하기▽ Pixy2 cam 물체 인식, 색 학습..

ddangeun.tistory.com

 

728x90
반응형