覚書-ESP32スケッチ-Bluetoothによる制御
Arduino Bluetooth controllerを使用
ボタン設定は、「e」「s」「d」「x」を割り当て
//完成
//Bluetoothによる制御サンプル
//アップまたはダウン入力で1から7のループ動作
//停止入力を「0」とする
#include <BluetoothSerial.h>
//変数の宣言
int ModeNum;
int Old_ModeNum;
boolean boostchk;
//Bluetoothシリアルに付ける名前
const char *btname = "ESP32roter";
BluetoothSerial SerialBT;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(2, INPUT_PULLUP);
pinMode(5, OUTPUT);
pinMode(17, INPUT_PULLUP);
pinMode(23, INPUT_PULLUP);
ModeNum = 0 ;
Old_ModeNum = 0;
boostchk = false ;
ledcSetup(0, 1000, 8);
ledcAttachPin(5, 0);
//Bluetoothシリアルの初期化
SerialBT.begin(btname);//bluetoothシリアルの初期化
}
void Up() {
if (boostchk == true ){
ModeNum = Old_ModeNum - 1 ;
}
if (ModeNum == 0 && Old_ModeNum == 0){
ModeNum = 1 ;
}
else if (ModeNum == 0 ){
ModeNum = Old_ModeNum ;
}
else{
ModeNum = ModeNum + 1 ;
if (ModeNum >=8 ) {
ModeNum = 1;
}
}
Old_ModeNum = ModeNum;
boostchk = false;
}
void Down() {
if (boostchk == true ){
ModeNum = Old_ModeNum + 1 ;
}
if (ModeNum == 0 && Old_ModeNum == 0){
ModeNum = 7 ;
}
else if (ModeNum == 0 ){
ModeNum = Old_ModeNum ;
}
else{
ModeNum = ModeNum - 1 ;
if (ModeNum <= 0 ) {
ModeNum = 7;
}
}
Old_ModeNum = ModeNum;
boostchk = false;
}
//boostモード
void Boost() {
if (boostchk == false ){
Old_ModeNum = ModeNum;
}
ModeNum = 8;
boostchk = true;
}
void Stop() {
ModeNum = 0 ;
boostchk = false ;
}
void read_bt(){
//Bluetoothシリアルから文字を受信しているかを判断する
if(SerialBT.available()){
//Bluetoothシリアルから文字を1文字読み込む
int ch = SerialBT.read();
//文字が「e」の場合
if (ch == 'e'){
//ブーストボタン ModeNumを「8」にする
Boost();
Serial.print("ModeNum = ");
Serial.print(ModeNum);
Serial.print(" Old_ModeNum = ");
Serial.print(Old_ModeNum);
Serial.print(" boostchk = ");
Serial.println(boostchk);
}
//文字が「d」の場合
else if (ch == 'd'){
Up();
Serial.print("ModeNum = ");
Serial.print(ModeNum);
Serial.print(" Old_ModeNum = ");
Serial.print(Old_ModeNum);
Serial.print(" boostchk = ");
Serial.println(boostchk);
}
//文字が「a」の場合
else if (ch == 's'){
Down();
Serial.print("ModeNum = ");
Serial.print(ModeNum);
Serial.print(" Old_ModeNum = ");
Serial.print(Old_ModeNum);
Serial.print(" boostchk = ");
Serial.println(boostchk);
}
//文字が「x」の場合
else if (ch == 'x'){
Stop();
Serial.print("ModeNum = ");
Serial.print(ModeNum);
Serial.print(" Old_ModeNum = ");
Serial.print(Old_ModeNum);
Serial.print(" boostchk = ");
Serial.println(boostchk);
}
else{
ModeNum = Old_ModeNum;
}
}
}
void done() {
switch (ModeNum) {
case 1:
ledcWrite(0, 32);
break;
case 2:
ledcWrite(0, 64);
break;
case 3:
ledcWrite(0, 96);
break;
case 4:
ledcWrite(0, 128);
break;
case 5:
ledcWrite(0, 160);
break;
case 6:
ledcWrite(0, 192);
break;
case 7:
ledcWrite(0, 224);
break;
case 8:
ledcWrite(0, 255);
break;
//0で停止する
default:
ledcWrite(0, 0);
break;
}
}
void loop() {
// put your main code here, to run repeatedly
read_bt();
done();
}