Program Resource

開発者向け各種コード、アルゴリズム、リソース情報ライブラリ もしくはねふぁの覚え書き

ステッピングモーターのRPMを測定するために作ったM5StickC用の簡易測定スケッチ。

センサーはレーザーと、レーザー受光部のみで受光部の信号ピンを33番に接続するのみ。

他のスケッチを流用しているので、描画周り余分なコードが入っている。

#include <M5StickC.h>
#include <Wire.h>

#define PIN_SENSOR	33
int lastdata[2];
char chbuff[32], chbuff_num[32];
unsigned long current_millis;
unsigned long last_data_update = 0;

void drawflame() {
	//resolution 160x80
	M5.Lcd.fillScreen(BLACK);
	M5.Lcd.drawRoundRect(5, 5, 75, 35, 3, DARKCYAN);
	M5.Lcd.drawRoundRect(5, 5 + 40, 75, 35, 3, DARKCYAN);
	M5.Lcd.drawRoundRect(5 + 80, 5 + 40, 75, 35, 3, DARKCYAN);
	M5.Lcd.setTextColor(WHITE, BLACK);
	M5.Lcd.setTextSize(1);
	M5.Lcd.setCursor(10, 2);
	M5.Lcd.print("rpm");
	M5.Lcd.setCursor(10, 42);
	M5.Lcd.print("---");
	M5.Lcd.setCursor(90, 42);
	M5.Lcd.print("---");
}

void showtext(char *msg) {
	M5.Lcd.fillScreen(BLACK);
	M5.Lcd.setTextColor(WHITE);
	M5.Lcd.setCursor(10, 30);
	M5.Lcd.setTextSize(1);
	M5.Lcd.print(msg);
}

void showtext_relay(char *val) {
	int xshift = 80, yshift = 40;
	M5.Lcd.fillRect(10 + xshift, 10 + yshift, 65, 25, BLACK);
	M5.Lcd.setTextSize(2);
	M5.Lcd.setTextDatum(MC_DATUM);
	M5.Lcd.drawString(val, 40 + xshift, 24 + yshift);
}

void showtext_data(int pos, int val, char *unit) {
	int xshift = 0, yshift = 0;
	if (lastdata[pos] == val)
		return;
	lastdata[pos] = val;

	if (pos == 1)
		yshift = 40;
	M5.Lcd.fillRect(10 + xshift, 10 + yshift, 65, 25, BLACK);
	M5.Lcd.setTextSize(1);
	M5.Lcd.setTextDatum(BR_DATUM);
	M5.Lcd.drawString(unit, 78 + xshift, 34 + yshift);
	M5.Lcd.setTextSize(2);
	M5.Lcd.setTextDatum(MC_DATUM);
	sprintf(chbuff, "%d", val);
	M5.Lcd.drawString(chbuff, 40 + xshift, 24 + yshift);
}

int last_sensor = LOW;
int new_sensor;
unsigned long last_sensor_time;
unsigned long rot_diff;

void setup() {
	M5.begin();
	delay(10);

	Serial.println("boot");

	M5.Lcd.setRotation(1);
	M5.Axp.ScreenBreath(10);

	pinMode(PIN_SENSOR,INPUT);
	last_sensor = digitalRead(PIN_SENSOR);
	
	drawflame();
	//showtext_relay("Off");
	Serial.println("ready");
}

void loop() {
	M5.update();

	new_sensor = digitalRead(PIN_SENSOR);
	if (new_sensor != last_sensor){
		last_sensor = new_sensor;
		if (new_sensor == HIGH){
			//Serial.println("detect");
			if (millis() - last_sensor_time > 22){
				rot_diff = millis() - last_sensor_time;
				Serial.println(rot_diff);
				last_sensor_time = millis();
			}
		}
	}

	current_millis = millis();
	if ((unsigned long)(current_millis - last_data_update) >= 300) {
		last_data_update = current_millis;
		if (rot_diff > 0)
			showtext_data(0, (int)(60000/rot_diff), "rpm");
	}
}

Print Friendly, PDF & Email

This post is also available in: 英語