티스토리 뷰

반응형

다른 언어에서 디버깅을 위해 printf 구문을 많이 사용한다.

ex : printf(" 이거슨 : %s ", "디버그")  


printf 의 장점이라고 하면 짧은 문장 안에 여러 변수가 들어가야 할때, 보기 좋고 관리하기 좋다는 장점이 있다.


그런데 아두이노에서는 기본적으로 print 문 밖에 없어서 문장 안에 여러 변수가 들어가야 할때에는 print 문을 여러번 잘라서 사용해야한다..


하지만 printf 구문을 사용할수 있는 방법이 있다.


이곳 아두이노 공식 홈피에 가면 자세한 설명이 있으니 참고해도 좋다. [ http://playground.arduino.cc/Main/Printf ]


기존 print 클래스에 printf 함수를 추가하는것이다.

그럴려면 print 클래스 파일을 찾아야 하는데...


필자는 윈도우7 64bit , 아두이노 1.6.3 버전을 사용중이다.


C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\Print.h 

위의 파일을 찾아 편집기로 열어준다.


그런다음 다음의 코드를 Print 클래스 내부에 삽입해준다.


    #include <stdarg.h>

    #define PRINTF_BUF 80 // define the tmp buffer size (change if desired)

       void printf(const char *format, ...)

       {

       char buf[PRINTF_BUF];

       va_list ap;

            va_start(ap, format);

            vsnprintf(buf, sizeof(buf), format, ap);

            for(char *p = &buf[0]; *p; p++) // emulate cooked mode for newlines

            {

                    if(*p == '\n')

                            write('\r');

                    write(*p);

            }

            va_end(ap);

       }

    #ifdef F // check to see if F() macro is available

       void printf(const __FlashStringHelper *format, ...)

       {

       char buf[PRINTF_BUF];

       va_list ap;

            va_start(ap, format);

    #ifdef __AVR__

            vsnprintf_P(buf, sizeof(buf), (const char *)format, ap); // progmem for AVR

    #else

            vsnprintf(buf, sizeof(buf), (const char *)format, ap); // for the rest of the world

    #endif

            for(char *p = &buf[0]; *p; p++) // emulate cooked mode for newlines

            {

                    if(*p == '\n')

                            write('\r');

                    write(*p);

            }

            va_end(ap);

       }

    #endif


*Print 클래스 내부에 추가하는.. 참고용 사진


그리고 저장하면 된다. ( 아두이노는 라이브러리 추가나, 클래스파일 수정등 거의 웬만한 작업에 IDE를 재실행 할 필요가 없다. ) 


사용 예시는 다른 언어와 큰 차이는 없다. 다음 코드는 미세먼지 농도를 lcd 에 출력할떄 사용한 코드이다.  

lcd.printf("Dust: %dug %s", dh,outstr[c]);

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함