バージョン情報
Arduino Uno , Arduino IDE 1.0.5 , windows 8.1
前回の続き。
今回は超音波センサで測定した距離をTFTカラー液晶に表示してみた。
材料
Arduino Uno
HC-SR04 超音波距離センサーモジュール For Arduino
1.8″ TFT カラー LCD ディスプレイ
回路
ソースコード
Arduinoライブライから “TFT.h” “SPI.h”をありがたく使用させて貰う。
#include <TFT.h>
#include <SPI.h>
// pin definition for the Uno
#define cs 10
#define dc 9
#define rst 8
// create an instance of the library
TFT TFTscreen = TFT(cs, dc, rst);
// char array to print to the screen
char sensorPrintout[7];
const int TrigPin = 2;
const int EchoPin = 3;
float cm;
int mm;
String str_buf = "string";
void setup() {
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
// Put this line at the beginning of every sketch that uses the GLCD:
TFTscreen.begin();
TFTscreen.background(0, 0, 0);
// write the static text to the screen
// set the font color to white
TFTscreen.stroke(255,255,255);
TFTscreen.setTextSize(2);
// write the text to the top left corner of the screen
TFTscreen.text("Distance :\n ",0,0);
// ste the font size very large for the loop
TFTscreen.setTextSize(3);
}
void loop() {
digitalWrite(TrigPin, LOW); //Low high and low level take a short time to TrigPin pulse
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
cm = pulseIn(EchoPin, HIGH) / 58.0; //Echo time conversion into cm
mm = int(cm * 10.0);
if (mm < 20 || mm > 4000){
str_buf = "----";
}else{
str_buf = String(mm) + " mm";
int len_str = str_buf.length();
for (int iii=7; iii>len_str;iii--){
str_buf = ' ' + str_buf;
}
}
// convert the reading to a char array
str_buf.toCharArray(sensorPrintout, 8);
// set the font color
TFTscreen.stroke(255,255,255);
// print the sensor value
TFTscreen.text(sensorPrintout, 0, 20);
// wait for a moment
delay(250);
// erase the text you just wrote
TFTscreen.stroke(0,0,0);
TFTscreen.text(sensorPrintout, 0, 20);
}
動作確認
良好良好!






