Folks, I’m not an EE… but try to play one!
Here’s the circuit I cobbled together:
The Led is a few amps, so I understand that I can’t drive it directly!
I had a TIP42 PNP laying around.
Here’s the code I wrote:
#include "math.h"
int dim = 0;
int toggle;
void setup() {
pinMode(D1,INPUT_PULLDOWN);
pinMode(D6,INPUT_PULLUP);
toggle = digitalRead(D6);
Particle.function("SetDim",SetDim);
Particle.variable("DimValue", &dim, INT);
}
void loop() {
if (digitalRead(D6)!=toggle)
{
if (dim>0)
dim =0;
else
dim = 254;
toggle = digitalRead(D6);
}
for (int i=0;i<100;i++)
{
if (dim<254)
{
//off duty cycle
if (getPinMode(D1)!=INPUT_PULLDOWN)
{
pinMode(D1,INPUT_PULLDOWN);
}
delayMicroseconds(1*(254-dim));
}
if (dim>0)
{
//on duty cycle
if (getPinMode(D1)!=OUTPUT)
{
pinMode(D1,OUTPUT);
digitalWrite(D1, 0);
}
delayMicroseconds(1*(dim));
}
}
}
int SetDim(String command) {
/* Particle.functions always take a string as an argument and return an integer.
Since we can pass a string, it means that we can give the program commands on how the function should be used.
In this case, telling the function "on" will turn the LED on and telling it "off" will turn the LED off.
Then, the function returns a value to us to let us know what happened.
In this case, it will return 1 for the LEDs turning on, 0 for the LEDs turning off,
and -1 if we received a totally bogus command that didn't do anything to the LEDs.
*/
dim = (254*command.toInt()/100);
return dim;
}
I’m essentially PWMing between input and output mode on D1.
With SetDim(1-100), everything appears to work fine.
SetDim(0) does turn the Led off, but randomly, the Led blips…
What am I doing wrong?
Thanks
-Fred