【 3D 프린터 챔버 만들기 】
[ Control Board 제작 #7 : Door Control Class 제작 ]
□ 필요사항
: Serial Port를 통해 '\r' 또는 '\n'으로 끝나는 문자열을 읽어 OP Code로 전환
[ OP Code 예시 : CMD O1 W1 => Object 1에 값 1 쓰기 ]
CMD O1 R0 => Object 1에서 값 읽기
[ DeviceCMD.h ]
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #ifndef DEVICECMD_H #define DEVICECMD_H #if defined(ARDUINO) && (ARDUINO >= 100) #include "Arduino.h" #else #include "WProgram.h" #endif #include <inttypes.h> enum CMD_OP_STATUS { READ, WRITE }; enum CMD_QUEUE_STATUS { FALSE, TRUE, DECODED }; typedef struct { int Object; CMD_OP_STATUS Status; int Value; } CMD, *pCMD; class DeviceCMD { private: char m_chBuffer[32]; int m_nPos = 0; String m_strBuffer; CMD m_CMD; public: DeviceCMD(); CMD_QUEUE_STATUS QueueBuffer(int ch); void ClearBuffer(); bool Decode(char cmd[]); CMD GetCMD(); }; #endif | cs |
[ DeviceCMD.cpp ]
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #include <string.h> #include "DeviceCMD.h" DeviceCMD::DeviceCMD() { memset(&m_chBuffer, 0, sizeof(m_chBuffer)); } CMD_QUEUE_STATUS DeviceCMD::QueueBuffer(int ch) { if((m_nPos)>=(int)sizeof(m_chBuffer)) { m_nPos = 0; return FALSE; } if(isAlpha(ch)) { if(isLowerCase(ch)) m_chBuffer[m_nPos++] = ch - 0x20; else m_chBuffer[m_nPos++] = ch; return TRUE; } if(isDigit(ch) || ch==0x20 || ch=='.') { m_chBuffer[m_nPos++] = ch; return TRUE; } if(ch == '\n' || ch == '\r') { if(m_nPos == 0) return TRUE; bool check = Decode(m_chBuffer); memset(&m_chBuffer, 0, sizeof(m_chBuffer)); m_nPos = 0; if(check) return DECODED; return FALSE; } return TRUE; } void DeviceCMD::ClearBuffer() { m_nPos = 0; } bool DeviceCMD::Decode(char cmd[]) { char *str; char *p = cmd; int stage = 0; while((str = strtok_r(p, " ", &p)) != NULL) { switch(stage) { case 0: // Check CMD if(strcmp_P(str, (PGM_P) F("CMD")) == 0) { stage = 1; continue; } return false; case 1: if(str[0] == 'O') { stage = 2; m_CMD.Object = atoi(&str[1]); continue; } return false; case 2: if(str[0] == 'W') { m_CMD.Status = WRITE; m_CMD.Value = atoi(&str[1]); return true; } else if(str[0] == 'R') { m_CMD.Status = READ; m_CMD.Value = atoi(&str[1]); return true; } default: return false; } } return false; } CMD DeviceCMD::GetCMD() { return m_CMD; } | cs |