How to generate a square wave using C#?
I would like to generate a digital signal, whi开发者_开发问答ch'll then be used to implement an ASK(Amplitude Shift Keying) Signal.
Let's say the message bits are 10110, data rate : 3.9 Khz & amplitude A.
What would be the best way to generate a Square signal(Digital).
I tried the following code, but the outcome is not a desired one.
double[] x = new double[1000];
double[] y = new double[1000];
double freq = 3900.0;
for (int k = 0; k < y.Length; k++)
{
x[k] = k;
y[k] = (4 / Math.PI) * (((Math.Sin(((2 * k) - 1) * (2 * Math.PI * freq))) / ((2 * k) - 1)));
}
// Plot Square Wave
plotSquare(x, y, Msg);
The easiest way I can think of is to set y to be sign of a sine wave, making allowances for when it equals zero. I don't know if C# has the triple-operator, but something like this might work:
y[k] = Math.Sin(freq * k)>=0?A:-1*A;
Math.Sin
is useful for sine wave, but a square wave should be far, far simpler (i.e. signal is 'high' for a period, then 'low' for a period). If you have a Math.Sin
anywhere, you are generate a sine wave, not a square wave. Bearing in mind a square wave can be generated with a condition (is x>y) and a sine wave needs a full mathematical operation, it's far more efficient, too.
C#'s Iterator Block support comes to mind:
IEnumerable<Tuple<double, double>> SquareWave(double freq, double lowAmp, double highAmp)
{
for (var x = 0.0; true; x += 1.0)
{
var y = ((int)(x / freq) % 2) == 0 ? lowAmp : highAmp;
yield return Tuple.Create(x, y);
}
}
use like this:
foreach(var t in SquareWave(10, -5, 5).Take(30))
Console.WriteLine("X: {0:0.0}/Y: {1:0.0}", t.Item1, t.Item2);
精彩评论