2021年11月20日 星期六

B4R PWM方式控制LED (ESP32-WROOM-32)

B4R PWM方式控制LED (ESP32-WROOM-32)






 


#Region Project Notes
'B4R HowTo Project: Light Dimmer (ESP32-WROOM-32)
'
'Connection (looking at the blue sensor from right to left)
' pushbutton switch --------------GPIO23
' blue LED 220 Ω resistor---------GPIO12
' potentiometer-------------------GPIO13 
'  
#End Region
#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 600
#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 TimerPulsePeriod As Timer 'Timer for PulsePeriod
Private PulseWidth As ULong 'calculated in TimerPulse_Tick
Private PulsePeriod = 50 As ULong 'remains constant
Private BounceTime As ULong
Private BounceDelay = 10 As ULong
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")

'Using the internal pull up resistor to prevent the pin from floating.
pinButton.Initialize(23, pinButton.MODE_INPUT_PULLUP) 
pinButton.AddListener("pinButton_StateChanged")
pinLED.Initialize(12, pinLED.MODE_OUTPUT)
pinPot.Initialize(13, pinPot.MODE_INPUT)

TimerPulsePeriod.Initialize("TimerPulsePeriod_Tick", PulsePeriod)
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)
BounceTime = Millis
TimerPulsePeriod.Enabled = StateON_OFF
Log("Reading: ", StateON_OFF) 'Log for testing
If StateON_OFF = False Then
pinLED.DigitalWrite(False)
End If
End If
End If
End Sub
Private Sub TimerPulsePeriod_Tick
Log(pinPot.AnalogRead) 'Log for testing

'calculate PulseWidth in function of the pot slider 
'Map the min max values: 
'Min:    0 pot > PulseWidth = 0 
'Max: 1023 pot > PulseWidth = PulsePeriod
PulseWidth = MapRange(pinPot.AnalogRead, 0, 1023, 0, PulsePeriod)
If PulseWidth = PulsePeriod Then '100% modulation
pinLED.DigitalWrite(True) 'switch the LED ON
Else If PulseWidth = 0 Then '0% modulation
pinLED.DigitalWrite(False) 'switch the LED OFF
Else
pinLED.DigitalWrite(True) 'switch the LED ON
CallSubPlus("EndPulse", PulseWidth, 0)
End If
End Sub
Private Sub EndPulse(Tag As Byte)
pinLED.DigitalWrite(False) 'switch the LED OFF 
Log("EndPulse") 'Log for testing
End Sub


沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...