Created
August 5, 2023 05:55
-
-
Save hatsunea/b37e854147e7e9f8bf238d0e95a0c8fd to your computer and use it in GitHub Desktop.
This file contains 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
using nanoFramework.M5Stack; | |
using System; | |
using System.IO.Ports; | |
using System.Threading; | |
using Console = nanoFramework.M5Stack.Console; | |
namespace M5StackCore2TFMiniSSample | |
{ | |
public class Program | |
{ | |
const int TFMINI_FRAME_SIZE = 9; | |
private static SerialPort TFMiniS; | |
public static void Main() | |
{ | |
try | |
{ | |
Setup(); | |
Loop(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Could not find a TFMini-S sensor, check wiring! {ex.Message}"); | |
} | |
} | |
private static void Setup() | |
{ | |
M5Core2.InitializeScreen(); | |
Console.Clear(); | |
Console.ForegroundColor = System.Drawing.Color.White; | |
Console.WriteLine("Starting.."); | |
// UART2(G13:RXD2,G14:TXD2)設定 | |
TFMiniS = new SerialPort("COM2", 115200, Parity.None, 8, StopBits.One); | |
TFMiniS.Open(); | |
// | |
Console.WriteLine("Open Serial Port.."); | |
} | |
private static void Loop() | |
{ | |
while (true) | |
{ | |
try | |
{ | |
var distance = GetValue(); | |
if (distance>=0) | |
{ | |
Console.CursorTop = 2; | |
Console.WriteLine($"{distance} cm"); | |
System.Diagnostics.Debug.WriteLine($"{distance} cm"); | |
} | |
// インターバル | |
Thread.Sleep(500); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"{ex.Message}"); | |
} | |
} | |
} | |
private static long GetValue() | |
{ | |
byte[] buffers = new byte[TFMINI_FRAME_SIZE]; | |
byte data = 0x00; | |
uint lastByte = 0x00; | |
long distance = 0; | |
if (TFMiniS.IsOpen) | |
{ | |
while (true) | |
{ | |
data = (byte)TFMiniS.ReadByte(); | |
buffers[0] = data; | |
if (data == 0x59 && lastByte == 0x59) | |
{ | |
uint checksum = 0x59 + 0x59; | |
buffers[1] = data; | |
for (int index = 2; index < TFMINI_FRAME_SIZE; index++) | |
{ | |
data = (byte)TFMiniS.ReadByte(); | |
buffers[index] = data; | |
if (index < TFMINI_FRAME_SIZE - 1) | |
{ | |
checksum += data; | |
} | |
} | |
//System.Diagnostics.Debug.WriteLine(BitConverter.ToString(buffers)); | |
distance = (buffers[3] << 8) + buffers[2]; | |
if (checksum % 256 != buffers[TFMINI_FRAME_SIZE - 1]) | |
{ | |
distance = -1; | |
} | |
lastByte = 0x00; | |
break; | |
} | |
else | |
{ | |
lastByte = data; | |
} | |
} | |
} | |
return distance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment