Create Sinewave Using C# | Saatody | Amit Padhiyar
Welcome again, Today I will create sinewave on slider using C# WPF. Here I need to use Math.sin(angle). First I want to show using little demo of sinewave.This is example of sinewave. Here sin() function always give output between -1 to 1 range. The x-axis is known as frequency(time) and the y-axis known as amplitude. Here The angles 0, 180 and 360 gives output 0. But angle 90 gives +1 value while angle 270 gives -1 value in output.
We can manipulate range instead of -1 to 1. For example: 0 to 255 or -255 to 255. Let's start coding with two different scenarios.
First we need to make common structure using C#. First create slider using WPF XAML.
<Slider Name="Slider" Value="0" Minimum="-2" Maximum="2" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<Label Name="Value" HorizontalAlignment="Stretch" VerticalAlignment="Bottom"/>
Now create DispatcherTimer from System.Windows.Threading namespace.
DispatcherTimer Timer = new DispatcherTimer();
Timer.IsEnabled = false;
Timer.Interval = TimeSpan.FromMilliseconds(20);
Timer.Tick += (sender, e) =>
{
};
Timer.Start();
Now take an integer for angle and increase by 1 at the end of the Tick event.
private int i = 0;
Above is common structure for both scenarios. We take 20 milliseconds interval. Both scenarios coding will be inside Tick event. See the below first scenario.
Direct put angle as a parameter of sin(a) function.
double value = Math.Sin(i);
Slider.Value = value;
Value.Content = value.ToString();
Here is 'i' angle put in Math.Sin(i) as direct input. see below entire code and its output.
DispatcherTimer Timer = new DispatcherTimer();
Timer.IsEnabled = false;
Timer.Interval = TimeSpan.FromMilliseconds(20);
Timer.Tick += (sender, e) =>
{
double value = Math.Sin(i);
Slider.Value = value;
Value.Content = value.ToString();
i++;
};
Timer.Start();
Output.....
To get bigger view, Click on image for full screen. Here we got sinewave but this wave has little bug. Its value generate sinewave but some bits are jumping as you can see in image. To solve this problem, I have another scenario. Let's check it out.
Manipulate angle as a parameter of sin(a) function.
According the first scenario, We have just put 'i' as parameter but in this scenario we multiply 'i' by Math.PI and then divide using 180 degree.
double value = Math.Sin((Math.PI * i) / 180);
Slider.Value = value;
Value.Content = value.ToString();
As you can compare both scenarios, Both have different calculation methods. Now see the full code,
DispatcherTimer Timer = new DispatcherTimer();
Timer.IsEnabled = false;
Timer.Interval = TimeSpan.FromMilliseconds(20);
Timer.Tick += (sender, e) =>
{
double value = Math.Sin((Math.PI * i) / 180);
Slider.Value = value;
Value.Content = value.ToString();
i++;
};
Timer.Start();
Output.....
Now we successfully got smooth and perfect output of sinewave.
Comments
Post a Comment