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


沒有留言:

張貼留言

ESP32 微控制器 採集的環境數據,經由 MQTT 協定 轉換並寫入工業標準的 Modbus 暫存器 中

  一個典型的 IoT(物聯網)與工業自動化系統整合(SCADA/機台連線) 的架構圖。它透過 Node-RED 作為核心資料網關,將前端 ESP32 微控制器 採集的環境數據,經由 MQTT 協定 轉換並寫入工業標準的 Modbus 暫存器 中。 1. 各模組功能拆解...