2021年11月19日 星期五

B4R PWM方式控制LED (Arduino UNO)

 B4R PWM方式控制LED 






#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---------GPIO16
' potentiometer-------------------GPIO13 
'  
#End Region
#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 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(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)

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





沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...