I have a working VBA code that generates a sine wave given the constant amplitude and RPM. The problem is that the RPM changes abruptly n times within the whole dataset, whereas in between it is constant. This abrupt change interrupts the continuity of my sine wave.
Does anyone have an idea how to make my sine wave continuous despite the abrupt changes in RPM? I.e., the frequency of the sine wave should change while the amplitude remains constant. Thank you in advance!
Sub CalcStroke()
Dim i, Stroke As Long
Dim Pi As Double
Dim Time, RPM, Wave As Variant
Pi = WorksheetFunction.Pi()
Time = Range(Cells(3, 9), Cells(3, 9).End(xlDown))
RPM = Range(Cells(3, 10), Cells(3, 10).End(xlDown))
Stroke = Cells(3, 7)
Wave = Cells(3, 5).Resize(UBound(Time, 1), 1)
For i = LBound(Time) To UBound(Time)
Wave(i, 1) = 0.5 * Stroke * Sin(2 * Pi * RPM(i, 1) / 60 * Time(i, 1))
Next i
Cells(3, 5).Resize(UBound(Time, 1), 1) = Wave
End Sub
Based on some online research, I tried to adopt a technique called phase continuity, but unsuccessfuly. The code results in an extremly frequent change in frequency of the sine wave.
Sub PhaseContinuity()
Dim i, Stroke As Long
Dim Pi, PreviousPhase, CurrentPhase, PhaseAdjustment As Double
Dim Time, RPM, Wave As Variant
Pi = WorksheetFunction.Pi()
Time = Range(Cells(3, 9), Cells(3, 9).End(xlDown))
RPM = Range(Cells(3, 10), Cells(3, 10).End(xlDown))
Stroke = Cells(3, 7)
Wave = Cells(3, 5).Resize(UBound(Time, 1), 1)
'Initialize the phases
PreviousPhase = 0
CurrentPhase = 0
For i = LBound(Time) To UBound(Time)
'Calculate the phase adjustment based on RPM change
CurrentPhase = (2 * Pi * RPM(i, 1) / 60 * Time(i, 1)) + PreviousPhase
Dim PhaseAdjustment As Double
If i > LBound(Time) Then
' Ensure phase continuity by adjusting for phase jumps
PhaseAdjustment = CurrentPhase - PreviousPhase
If PhaseAdjustment > Pi Then
PhaseAdjustment = PhaseAdjustment - 2 * Pi
ElseIf PhaseAdjustment < -Pi Then
PhaseAdjustment = PhaseAdjustment + 2 * Pi
End If
End If
'Update the phase for the next iteration
PreviousPhase = CurrentPhase + PhaseAdjustment
'Calculate the new sine wave value using adjusted phase
Wave(i, 1) = 0.5 * Stroke * Sin(CurrentPhase + PhaseAdjustment)
Next i
Cells(3, 5).Resize(UBound(Time, 1), 1) = Wave
End Sub