주요 콘텐츠

직렬 포트 통신을 사용하여 Arduino에서 스트리밍 데이터 읽어오기

이 예제에서는 serialport 인터페이스를 사용하여 Arduino® 보드에서 스트리밍 ASCII 종결 데이터를 읽어오는 콜백을 활성화하는 방법을 보여줍니다.

이 예제에서는 Arduino Due를 사용하지만, 대부분의 Arduino 보드에 적용됩니다.

Arduino에 프로그램 업로드하기

Arduino 보드를 컴퓨터에 연결합니다.

Arduino IDE를 사용하여 다음 프로그램을 Arduino® 보드에 업로드합니다. 이 프로그램은 "캐리지 리턴" 및 "라인 피드" 종결자가 뒤에 오는, 사인파의 연속적인 점들을 기록합니다.

/*
 SineWavePoints
 
 Write sine wave points to the serial port, followed by the Carriage Return and LineFeed terminator.
 */

int i = 0;

// The setup routine runs once when you press reset:
void setup() {
  // Initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// The routine loops forever:
void loop() {
  // Write the sinewave points, followed by the terminator "Carriage Return" and "Linefeed".
  Serial.print(sin(i*50.0/360.0));
  Serial.write(13);
  Serial.write(10);
  i += 1;
}

Arduino에 대한 연결 설정하기

MATLAB에서 기존 serialport 연결을 모두 닫습니다.

delete(serialportfind);

Arduino가 연결되어 있는 직렬 포트를 찾습니다. Arduino IDE에서 이 직렬 포트를 식별할 수 있습니다. 이 예제에서는 연결부가 포트 COM4에 있는 것으로 Arduino IDE에 나타난다고 가정합니다. 사용 가능한 모든 포트를 나열하여 이 포트가 컴퓨터에 있는지 확인합니다.

serialportlist("available")
ans = 1×2 string
    "COM3"    "COM4"

serialport 객체를 만들어 Arduino Due에 연결합니다. Arduino 코드에 지정된 포트와 보드 레이트를 사용합니다.

serialObj = serialport("COM4",9600)
serialObj = 
  Serialport with properties:

                 Port: "COM4"
             BaudRate: 9600
                  Tag: ""
    NumBytesAvailable: 15

  Show all properties, functions

데이터 스트리밍을 시작하기 위한 serialport 객체 준비하기

속성을 구성하고 오래된 데이터를 지워 serialport 객체를 구성합니다.

Arduino 코드에 지정된 종결자와 일치하도록 Terminator 속성을 설정합니다.

configureTerminator(serialObj,"CR/LF");

serialport 객체를 플러시하여 오래된 데이터를 모두 제거합니다.

flush(serialObj);

Arduino 데이터를 저장하기 위한 UserData 속성을 준비합니다. 이 경우 Data 필드에 사인파 값이 들어 있고 수집된 데이터 점 개수를 Count가 기록하는, 구조체가 되도록 UserData를 정의합니다. 이 구조체를 사용하면 체계적이고 효율적인 액세스가 가능하고 관련 정보 업데이트도 가능합니다.

serialObj.UserData = struct("Data",[],"Count",1)
serialObj = 
  Serialport with properties:

                 Port: "COM4"
             BaudRate: 9600
                  Tag: ""
    NumBytesAvailable: 0

  Show all properties, functions

새 MATLAB 파일에서 처음 1000개의 ASCII 종결 사인파 데이터 점을 읽어오고 그 결과를 플로팅하는 콜백 함수 readSineWaveData를 만듭니다. 이 함수는 데이터 플로팅 시점을 결정하는 인수 maxDataPoints를 받습니다.

function readSineWaveData(src, ~, maxDataPoints)

% Read the ASCII data from the serialport object.
data = readline(src);

% Convert the string data to numeric type and save it in the UserData
% property of the serialport object.
src.UserData.Data(end+1) = str2double(data);

% Update the Count value of the serialport object.
src.UserData.Count = src.UserData.Count + 1;

% If over maxDataPoints points have been collected from the Arduino, switch off the
% callbacks and plot the data, starting from the second point. 
if src.UserData.Count > maxDataPoints
    configureCallback(src, "off");
    plot(src.UserData.Data(2:end));
end
end

종결자로 표시된 새 데이터를 Arduino에서 읽어올 수 있을 때마다 readSineWaveData 함수를 실행하도록 직렬 포트 객체를 구성합니다. 다음 configureCallback 명령은 BytesAvailableFcnMode를 "terminator"로 설정하고, BytesAvailableFcn 속성을 readSineWaveData 함수에 대한 핸들로 설정합니다.

maxDataPoints = 1002; 
configureCallback(serialObj, "terminator", @(src,event) readSineWaveData(src,event,maxDataPoints))

콜백 함수가 호출되면 처음 1000개의 데이터 점 플롯이 있는 MATLAB Figure가 열립니다.

figure.png