Created
February 23, 2024 09:02
-
-
Save a1678991/a130c864a0a51865f5542a69bfd95192 to your computer and use it in GitHub Desktop.
esp32をシリアルのレベルシフター代わりにするやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cmath> | |
#include <HardwareSerial.h> | |
#include <freertos/FreeRTOS.h> | |
#include <freertos/task.h> | |
const int SERIAL_RX_PIN = 16; // シリアル受信ピン | |
const int SERIAL_TX_PIN = 17; // シリアル送信ピン | |
const int SERIAL_BAUD_RATE = 115200; // シリアルのボーレート | |
const int SERIAL_LOOP_DELAY_MS = 0.1; // ループ毎の待機時間 | |
const int LED_RX_PIN = 2; // 受信用LEDのピン | |
const int LED_TX_PIN = 4; // 送信用LEDのピン | |
const int LED_ON_DURATION_MS = 20; // 信号が流れたときにLEDを点灯させる時間 | |
unsigned long lastTxTime = 0; | |
unsigned long lastRxTime = 0; | |
// LED制御タスク | |
void ledControlTask(void *pvParameters) { | |
while (1) { | |
if (millis() - lastRxTime < LED_ON_DURATION_MS) { | |
digitalWrite(LED_RX_PIN, HIGH); | |
} else { | |
digitalWrite(LED_RX_PIN, LOW); | |
} | |
if (millis() - lastTxTime < LED_ON_DURATION_MS) { | |
digitalWrite(LED_TX_PIN, HIGH); | |
} else { | |
digitalWrite(LED_TX_PIN, LOW); | |
} | |
vTaskDelay(pdMS_TO_TICKS(1)); // 1msごとに状態を更新 | |
} | |
} | |
void setup() { | |
pinMode(LED_RX_PIN, OUTPUT); | |
pinMode(LED_TX_PIN, OUTPUT); | |
// バッファサイズの計算と設定 | |
const int bufferSize = ceil((SERIAL_BAUD_RATE / 8.0) * (SERIAL_LOOP_DELAY_MS / 1000.0)); | |
Serial.setRxBufferSize(bufferSize); | |
Serial1.setRxBufferSize(bufferSize); | |
Serial.begin(SERIAL_BAUD_RATE); | |
Serial1.begin(SERIAL_BAUD_RATE, SERIAL_8N1, SERIAL_RX_PIN, SERIAL_TX_PIN); | |
// LED制御タスクの作成 | |
xTaskCreate(ledControlTask, "LEDControlTask", 1024, NULL, 1, NULL); | |
} | |
void loop() { | |
if (Serial.available()) { | |
Serial1.write(Serial.read()); | |
lastTxTime = millis(); | |
} | |
if (Serial1.available()) { | |
Serial.write(Serial1.read()); | |
lastRxTime = millis(); | |
} | |
delay(SERIAL_LOOP_DELAY_MS); // 適当にCPUを休ませる | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment