Skip to content

Instantly share code, notes, and snippets.

@watab0shi
Created May 14, 2021 08:04
Show Gist options
  • Select an option

  • Save watab0shi/85a7e25e95bc890ff091348d2550ea49 to your computer and use it in GitHub Desktop.

Select an option

Save watab0shi/85a7e25e95bc890ff091348d2550ea49 to your computer and use it in GitHub Desktop.
oF_serialReadExample
#include "ofMain.h"
#include "ofApp.h"
//========================================================================
int main( ){
ofSetupOpenGL(1024,768,OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp(new ofApp());
}
#include "ofApp.h"
namespace {
const int BAUD_RATE = 9600;
}
//--------------------------------------------------------------
void ofApp::setup() {
serial.listDevices();
serial.setup(0, BAUD_RATE);
message = "";
index = 0;
value = 0;
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(0);
}
//--------------------------------------------------------------
void ofApp::update() {
// データがなくなるまで1文字ずつシリアルを読む
while (true) {
int c = serial.readByte();
if (c == OF_SERIAL_NO_DATA || c == OF_SERIAL_ERROR || c == 0) {
break;
}
if (c == '\n') {
// 改行まできたら1行分を区切り文字で分割して値を順番に取り出す
std::vector<std::string> values = ofSplitString(message, "\t");
if (values.size() == 2) {
index = ofToInt(values.at(0));
value = ofToInt(values.at(1));
}
// 1行読み込んだらメッセージをクリア
message = "";
} else {
// 改行以外の文字の場合はメッセージの末尾に追加
message.push_back(c);
}
}
}
//--------------------------------------------------------------
void ofApp::draw() {
ofDrawBitmapStringHighlight("index : " + ofToString(index), 10, ofGetHeight() * 0.5);
ofDrawBitmapStringHighlight("value : " + ofToString(value), 10, ofGetHeight() * 0.5 + 20);
}
#pragma once
#include "ofMain.h"
class ofApp : public ofBaseApp {
public:
void setup();
void update();
void draw();
ofSerial serial;
std::string message;
int index;
int value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment