아두이노 코딩-101: Processing에서 버튼 클라스 코딩

codingart(66)
Published in
#kr
Words
507
Reading
3 min
Listen
Play
8y

noname01.png

아두이노 사물인터넷 웹서버 코딩에서는 HTML언어에 의한 버튼 코딩이 편리하게 사용됨에 반하여 Processing 클라이언트 코딩에서는 아두이노에 설치된 LED를 제어하기 위해서 그래픽 화면 상에서 위치 파악이 가능한 mouseX 와 같은 명령을 사용하여 digitalWrite() 명령에 필요한 ON OFF 문자열을 생성하거나 또는 analogWrite() 명령에 적합한 정수형 입력 값을 생성하였다.

Processing에서는 별도로 버튼 명령이 없어서 좀 불편한 느낌이 들지만 나름대로 정교한 컴퓨터 언어이므로 아래와 같은 구조를 가지는 C++ 버튼 클라스 코딩을 시도해 보기로 하자. 이 클라스 코딩 부분은 코드 가장 후반부에 위치시켜 두도록 한다.
class Button {
String label; // 버튼에 출력할 버튼 명칭 라벨
int xcolor; // 사각형 버튼의 색상
float x; // 사각 버튼 corner x position
float y; // 사각 버튼 corner y position
float w; // 사각 버튼 width of button
float h; // 사각 버튼 height of button
⚫⚫⚫
}

이 클라스 코딩 구조에서 ⚫⚫⚫ 에 해당하는 부분은 다음과 같이 3부분으로 구성한다.
Button(String labelB, int x_color, ... ) {
}
void Draw() {
}
boolean MouseIsOver() {
}
return false;
}

Button은 문자 라벨, 버튼 색깔, 사각형 위치와 크기 정보를 정의하여 처리한다.
Draw()는 메인 프로그램의 Draw()와는 달리 클라스 명령에 따른 특별한 Draw() 명령을 수행하는데 여기서는 버튼의 실제 색상 및 버튼 명 출력을 담당한다.

불리언으로 정의 되는 MouseIsOver() 는 mouseX, mouseY 의 위치가 사각버튼 내에 있는지 아닌지 여부르 확인하여 참 또는 거짓 값을 준다.

아래는 Processing에서 헤더 영역에 버튼 클라스 명령을 선언한 후 setup()에서 불러 on_button 으로 설정 후 draw()에서 불러서 사용하는 예이다. 마지막 부분에 mousePressed() 루틴은 버튼을 클릭하였을때를 캐치하여 콘솔 창에 클릭한 횟수를 출력해준다. 또 다른 버튼이 필요하면 버튼 클라스 코딩을 추가하도록 하자.

noname02.png

Processing 버튼 코드를 실행하는 동영상을 관찰해 보자.

첨부된 코드를 실행해 보자.
//button_01
Button on_button; // the button

int clk = 1; // number of times the button is clicked
int x_color = 256;

void setup() {
size (400, 360);
smooth();
on_button = new Button("ON",x_color, 50, 150, 150, 80);
}

void draw() {

// draw a square if the mouse curser is over the button
if (on_button.MouseIsOver()) {
fill(color(256,0,0));
rect(50, 250, 150, 30);
}
else {
// hide the square if the mouse cursor is not over the button
background(0);
}
// draw the button in the window
on_button.Draw();
textAlign(CENTER, CENTER);
fill(256,256,256);
textSize(40);
text("Button Coding", width/2, 50);
}

// mouse button clicked
void mousePressed() {
if (on_button.MouseIsOver()) {
// print some text to the console pane if the button is clicked
print("LED On clicked: ");
println(clk++);
}
}

// the Button class
class Button {
String label; // button label
int xcolor; // button color
float x; // top left corner x position
float y; // top left corner y position
float w; // width of button
float h; // height of button

// constructor
Button(String labelB, int x_color, float xpos, float ypos, float widthB, float heightB) {
label = labelB;
xcolor = x_color;
x = xpos;
y = ypos;
w = widthB;
h = heightB;
}

void Draw() {
fill(xcolor,0,0);
stroke(141);
rect(x, y, w, h, 10);
textAlign(CENTER, CENTER);
fill(256,256,256);
textSize(40);
text(label, x + (w / 2), y + (h / 2));
}

boolean MouseIsOver() {
if (mouseX > x && mouseX < (x + w) && mouseY > y && mouseY < (y + h)) {
return true;
}
return false;
}
}

아두이노 코딩-101: Processing에서 버튼 클라스 코딩 | Ecency