Skip to content

Instantly share code, notes, and snippets.

@nanase
Created June 3, 2018 12:07
Show Gist options
  • Save nanase/483f491dc329b28966abb3701aa0eb42 to your computer and use it in GitHub Desktop.
Save nanase/483f491dc329b28966abb3701aa0eb42 to your computer and use it in GitHub Desktop.
SPPCM from C#
using System;
using System.IO.Ports;
using System.Threading;
namespace Sppcm
{
internal class Program
{
private static SerialPort _serial;
private static double _phase;
private const double Frac = 440;
private const double SamplingRate = 50000.0;
const int SampleCount = 50;
private static void SendBuffer()
{
var buffer = new byte[SampleCount * 5];
for (var i = 0; i < SampleCount; i++)
{
var lch = Math.Sin(2.0 * Math.PI * Frac * _phase) * 0.5;
var rch = Math.Sin(2.0 * Math.PI * Frac * _phase) * 0.5;
_phase += 1.0 / SamplingRate;
if (lch > +1.0) lch = +1.0;
if (lch < -1.0) lch = -1.0;
if (rch > +1.0) rch = +1.0;
if (rch < -1.0) rch = -1.0;
var lchShort = (short)Math.Round(lch * 32767);
var rchShort = (short)Math.Round(rch * 32767);
buffer[5 * i + 1] = (byte)(lchShort >> 8);
buffer[5 * i + 2] = (byte)lchShort;
buffer[5 * i + 3] = (byte)(rchShort >> 8);
buffer[5 * i + 4] = (byte)rchShort;
}
if (_serial.IsOpen)
{
_serial.Write(buffer, 0, buffer.Length);
_serial.BaseStream.Flush();
}
}
private static void SendEmptyBuffer(int frameCount)
{
var buffer = new byte[frameCount * SampleCount * 5];
_serial.Write(buffer, 0, buffer.Length);
_serial.BaseStream.Flush();
}
private static void Main()
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
using (_serial = new SerialPort("COM4", 3000000, Parity.None, 8, StopBits.One))
{
_serial.ReadBufferSize = 2;
_serial.RtsEnable = false;
_serial.Open();
_serial.Write(new byte[] { 0xff }, 0, 1);
_serial.BaseStream.Flush();
SendEmptyBuffer(20);
_serial.Write(new byte[] { 0x80 }, 0, 1);
_serial.BaseStream.Flush();
while (!Console.KeyAvailable)
{
var request = _serial.ReadByte();
switch (request)
{
case 0x00:
SendBuffer();
break;
case (byte)'S': // S -> P
_serial.ReadByte();
break;
default:
Console.WriteLine("Receive: {0:x2}", request);
break;
}
}
_serial.Write(new byte[] { 0x81 }, 0, 1);
_serial.BaseStream.Flush();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment