เป็นตัวอย่างการประยุกต์ใช้ Analog meter จากหัวข้อ 14.Analog meter 1 โดยการใช้บอร์ด Arduino รับสัญญาณอนาลอกแล้วส่งออกทางพอร์ทอนุกรม มาให้โปรแกรม Processing รับมาแสดงผลด้วยิเตร์เข็ม เมื่อประปรับค่า R (Potentiometer) ดข็มจะเปลี่ยนไป ตามค่า แต่สูงสุดไม่เกิน 50 ซึ่งแทน 5 โวลท์ ระบบประกอบด้วย บอร์ด Arduino และ PC ตามรูป
โปรแกรมสำหรับ Arduino
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
float volt = 0.0; // Convert from sensor
void setup()
{
Serial.begin(9600);
}
void loop()
{
sensorValue = analogRead(sensorPin); // read the value from the sensor: = analogRead(sensorPin); // read the value from the sensor:
volt = 50.0*sensorValue/1023;
Serial.println(volt);
delay(100);
}
โปรแกรมสำหรับ Processing
PImage img;
import processing.serial.*;
Serial myPort; // กำหนดตัวแปรสำหรับพอร์ทอนุกรม
int lf = 10; // Linefeed in ASCII
String myString = null;
void setup() {
size(450,400);
img = loadImage("voltmeter_3.jpg");
println(Serial.list()); // แสดงพอร์ทที่มีอยู่
myPort = new Serial(this, Serial.list()[1], 9600); // เรียกใช้พอร์ทหมายเลข [1]
}
void draw() {
// float v = random(0, 60);
myString = myPort.readStringUntil(lf);
if (myString != null)
{
print(myString); // Prints String
float v =float(myString); // Converts to float
background(255);
draw_meter(20,50,v);
}
}
// x,y = Upper left corner.
// v = 0 to 60
void draw_meter(int x,int y,float v)
{
image(img, x, y);
float angle = PI*(60-v)/60;
float length = 140;
float px = width/2 + cos(angle)*length;
float py = height/2 + sin(angle)*length;
strokeWeight(2);
stroke(255, 0, 0);
line(200+x, 198+y, 200+x+cos(angle)*length, 198+y-sin(angle)*length);
fill(255,0,0);
ellipse(200+x, 198+y, 10, 10);
}