Skip to content

CmdMessenger

Dongwon Lee edited this page Jun 7, 2018 · 3 revisions

아두이노와 PC간에 command를 주고 받을수 있는 protocol

아두이노 홈페이지에서 찾을 수 있다. 현재 4.0까지 나와있음

https://github.com/thijse/Arduino-CmdMessenger

기본 적인 구조는 아래 그림과 같다. 시리얼 포트를 통해 CmdID,para1,para2...paraN; (끝에 세미콜론) 의 형태로 command를 주고 받는다

아두이노 코드는

Step1 시리얼 포트와 CmdMessenger object 연결

// Attach a new CmdMessenger object to the default Serial port
CmdMessenger cmdMessenger = CmdMessenger(Serial);

Step2 command List 선언

enum
{
  kAcknowledge,
  kError,
  kSetLed, // Command to request led to be set in specific state
  kSetLedFrequency,
};

Step3 command ID 와 실행될 함수 (callback function)연결

// Callbacks define on which received commands we take action
void attachCommandCallbacks()
{
  // Attach callback methods
  cmdMessenger.attach(OnUnknownCommand);
  cmdMessenger.attach(kSetLed, OnSetLed);
  cmdMessenger.attach(kSetLedFrequency, OnSetLedFrequency);
}

Step5 callback function에서 실행될 동작 정의

// Callback function that sets led on or off
void OnSetLed()
{
  // Read led state argument, interpret string as boolean
  ledState = cmdMessenger.readBoolArg();
  cmdMessenger.sendCmd(kAcknowledge,ledState);
}

// Callback function that sets leds blinking frequency
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

Step6 setup

void setup() 
{
  // Listen on serial connection for messages from the PC
  Serial.begin(115200); 

  // Adds newline to every command
  cmdMessenger.printLfCr();   

  // Attach my application's user-defined callback methods
  attachCommandCallbacks();

  // Send the status to the PC that says the Arduino has booted
  // Note that this is a good debug function: it will let you also know 
  // if your program had a bug and the arduino restarted  
  cmdMessenger.sendCmd(kAcknowledge,"Arduino has started!");
}

Step7 Loop에서 명령 기다리기

void loop() 
{
  // Process incoming serial data, and perform callbacks
  cmdMessenger.feedinSerialData();
  delay(10);
}

Clone this wiki locally