정보나눔

오픈소스하드웨어 프로젝트에 대한 다양한 정보를 나누는 공간입니다.

아두이노 NRF24L01 통신모듈에 관한 질문
탐구생활 | 2017-05-16

NRF24L01에 대한 공부를 하던 중 RF24 라이브러리를 설치하면 아두이노에 있는 예제 gettingstarted 를 공부하던 중 이해가 안가는 부분이 있어서 이렇게 글을 올리게 되었습니다.

 

하단에 코드 전부분을 일단 올려 놓았구요. NRF24L01을 공부하신 분이면 누구나 한번쯤 보셨을 코드라고 생각합니다. 원리는 간단한 것 같은데 제가 뭔가 기본적인 걸 모르는 것 같습니다.

 

 

 

byte addresses[][6] = {"1Node","2Node"};    에서 

 

byte란 -125~125 까지의 정수를 나타내는 데이터형이고 addresses[ ][6] 은 2차원 배열인 것으로 이해했습니다.

 

그런데 1Node, 2Node는 텍스트인데 정수형 데이터로 선언한 배열에 어떻게 문자가 들어가는 걸까요???

 

예를 들어

 

addresses[0][0] = 1

 

addresses[0][1] = N

 

addresses[0][2] = o

 

addresses[0][3] = d

 

addresses[0][4] = e

 

addresses[0][5] = " "

 

이렇게 들어간단 말입니까?

 

그리고 밑에 보면  

 

radio.openWritingPipe(addresses[1]);  

 

과 같이 위에서 선언하고 값을 넣어준 addresses 배열을 사용하기 시작하는데

 

2차원 배열이었던 addresses가 1차원 배열이 되어 버렸습니다.

 

대체 addresses[1]에는 무슨 값이 들어있을까 궁금하여

 

새 스케치 창을 열어 아래와 같이 실험을 했더니 컴파일시에 오류가 나버립니다.

 

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

 

int i;
byte addresses[][6] = {"1Node","2Node"};
  
void setup() {
  // put your setup code here, to run once:

 

  Serial.begin(9600);

}

 

void loop() {
  // put your main code here, to run repeatedly:
  
    Serial.println(addresses[1]);

}

 

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

 

컴파일 에러 메시지

 

exit status 1
call of overloaded 'println(byte [6])' is ambiguous

 

 

누구라도 좋으니 알려주시면 감사하겠습니다.

 

그리고 하나 더 있습니다.

 

    radio.openReadingPipe(1,addresses[1]);    에서 괄호열고 바로 적혀있는 1이 무슨 의미인지도 알고 싶습니다.

 

알려 주시면 감사하겠습니다.

 

 

 

 

---------------------------------------------------------------------------
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/

 

#include <SPI.h>
#include "RF24.h"

 

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 1;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);
/**********************************************************/

byte addresses[][6] = {"1Node","2Node"};

// Used to control whether this node is sending or receiving

 

bool role = 0;

 

void setup() {
    Serial.begin(115200);
    Serial.println(F("RF24/examples/GettingStarted"));
    Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
  
  radio.begin();

  // Set the PA Level low to prevent power supply related issues since this is a
 // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW);
  
  // Open a writing and reading pipe on each radio, with opposite addresses
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }
  
  // Start the radio listening for data
  radio.startListening();
}

void loop() {
  
  
/****************** Ping Out Role ***************************/  
if (role == 1)  {
    
    radio.stopListening();                                    // First, stop listening so we can talk.
    
    
    Serial.println(F("Now sending"));

    unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
     if (!radio.write( &start_time, sizeof(unsigned long) )){
       Serial.println(F("failed"));
     }
        
    radio.startListening();                                    // Now, continue listening
    
    unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
    boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not
    
    while ( ! radio.available() ){                             // While nothing is received
      if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
          timeout = true;
          break;
      }      
    }
        
    if ( timeout ){                                             // Describe the results
        Serial.println(F("Failed, response timed out."));
    }else{
        unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
        radio.read( &got_time, sizeof(unsigned long) );
        unsigned long end_time = micros();
        
        // Spew it
        Serial.print(F("Sent "));
        Serial.print(start_time);
        Serial.print(F(", Got response "));
        Serial.print(got_time);
        Serial.print(F(", Round-trip delay "));
        Serial.print(end_time-start_time);
        Serial.println(F(" microseconds"));
    }

    // Try again 1s later
    delay(1000);
  }

 

/****************** Pong Back Role ***************************/

  if ( role == 0 )
  {
    unsigned long got_time;
    
    if( radio.available()){
                                                                    // Variable for the received timestamp
      while (radio.available()) {                                   // While there is data ready
        radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
      }
     
      radio.stopListening();                                        // First, stop listening so we can talk   
      radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.      
      radio.startListening();                                       // Now, resume listening so we catch the next packets.     
      Serial.print(F("Sent response "));
      Serial.println(got_time);  
   }
 }

 


/****************** Change Roles via Serial Commands ***************************/

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == 0 ){      
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1;                  // Become the primary transmitter (ping out)
    
   }else
    if ( c == 'R' && role == 1 ){
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));      
       role = 0;                // Become the primary receiver (pong back)
       radio.startListening();
       
    }
  }


} // Loop

프로필사진

수박쨈 2017-05-17 09:52:13

byte는 1바이트의 값이 들어간다는건 아실테니..

문자는 아스키코드로 256까지의 숫자로 표현가능하다는 건 아실거라 생각합니다.

 

byte addresses[][6] = {"1Node","2Node"}; 이렇게 표현된 배열은 말씀해주신 아래 순서대로 들어가는 것이 맞습니다.

확인해 보고 싶으시면 for문으로 addresses[0][i]로 Serial.println()가 아닌 Serial.write()로 출력해보시면 저렇게 들어가는 것을 볼 수 있습니다. (아스키코드로 입력된 문자는 println()로 할경우 숫자로 출력됩니다.)

 

addresses[0][0] = 1
 
addresses[0][1] = N
 
addresses[0][2] = o
 
addresses[0][3] = d
 
addresses[0][4] = e
 
addresses[0][5] = " "

 

 

addresses[0][0]부터 addresses[0][5]까지 1Node가 들어가면

addresses[1][0]부터 addresses[1][5]까지 2Node가 들어갑니다.

 

 

radio.openReadingPipe(1,addresses[1])에서는

앞에 있는 저도 라이브러리를 분석해보지 않아서 뭔지는 잘 모르겠지만 파이프의 종류를 말하는거 같습니다.

자세한 내용은 라이브러리의 cpp파일을 열어보면 더 자세하게 보실 수 있을거 같네요!ㅎ

프로필사진

탐구생활 2017-05-17 14:29:27

답변 너무 감사합니다. 저는 아두이노-상상을 현실로 만드는 프로젝트 란 책을 한번 봤는데

 

Serial.write는 못본거 같아요.

 

아두이노 프로그래밍 관련해서 레퍼런스할만한 책이 있나요?? 수박쨈님은 Serial.write 명령어를 어느 책을 통해 보게 되셨는지 알려주시면 감사하겠습니다.

프로필사진

수박쨈 2017-05-17 15:27:14

아두이노의 레퍼런스 책이라면 시중에 많이 나와있을거 같은데 저도 딱히 책을 보고 한거 아니라;;ㅎㅎ

 

가장 잘나와있는곳이라면 아마 아두이노 홈페이지의 레퍼런스페이지가 아닐까 싶네요.

https://www.arduino.cc/en/Reference/HomePage

 

책으로 공부한것은 반복학습 하지 않으면 까먹지만 직접 코딩하면서 실패해보고 부딪혀서 터득한 것들은 쉽게 까먹지 않게 되는거 같네요.

이전글   |    오렌지보드BLE와 PC간 블루투스 통신방법 2017-05-16
다음글   |    아두이노 핀에 대해 질문 올립니다 2017-05-17