B4X Pulse Period Modulation脈波週期調變 (Adruino UNO , ESP32-WROOM-32)
#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 300
#End Region
Sub Process_Globals
Public Serial1 As Serial
Private pinButton, pinPot, pinLED As Pin
Private StateON_OFF = False As Boolean 'state ON or OFF
Private MaxPulsePeriod = 2000 As ULong 'Max PulsePeriod value
Private PulseWidth = 200 As ULong 'remains constant
Private PulsePeriod As ULong 'calculated in TimerPulse_Tick
Private BounceTime As ULong
Private BounceDelay = 10 As ULong
End Sub
Private Sub AppStart
Serial1.Initialize(9600)
Log("AppStart")
'Using the internal pull up resistor to prevent the pin from floating.
pinButton.Initialize(pinButton.A5, pinButton.MODE_INPUT_PULLUP)
pinButton.AddListener("pinButton_StateChanged")
pinLED.Initialize(10, pinLED.MODE_OUTPUT)
pinPot.Initialize(pinPot.A1, pinPot.MODE_INPUT)
End Sub
Private Sub pinButton_StateChanged (State As Boolean)
Log("state: ", State)
'state will be False when the button is clicked because of the PULLUP mode.
If State = False Then
If Millis - BounceTime < BounceDelay Then
Return
Else
StateON_OFF = Not(StateON_OFF)
Log("SateON_OFF: ", StateON_OFF)
BounceTime = Millis
If StateON_OFF = True Then
NextPulse(0)
Else
pinLED.DigitalWrite(False)
End If
End If
End If
End Sub
Private Sub NextPulse(Tag As Byte)
If StateON_OFF = True Then
PulsePeriod = MapRange(pinPot.AnalogRead, 0, 1023, PulseWidth, MaxPulsePeriod)
If PulsePeriod >= MaxPulsePeriod - 1 Then
pinLED.DigitalWrite(False)
Else if PulsePeriod <= PulsePeriod + 1 Then
pinLED.DigitalWrite(True)
Else
pinLED.DigitalWrite(True)
CallSubPlus("EndPulse", PulseWidth, 0)
End If
CallSubPlus("EndPulse", PulseWidth, 0)
CallSubPlus("NextPulse", PulsePeriod, 0)
Log("NextPulse") 'Log for testing
End If
End Sub
Private Sub EndPulse(Tag As Byte)
pinLED.DigitalWrite(False) 'switch the LED OFF
Log("EndPulse") 'Log for testing
End Sub
'For ESp32-WROOM-32 Pulse_Period_Modulation
沒有留言:
張貼留言