DeqingSun / ch55xduino

An Arduino-like programming API for the CH55X
GNU Lesser General Public License v2.1
439 stars 86 forks source link

analogWrite not working on 0 #71

Closed foadyousefi closed 2 years ago

foadyousefi commented 2 years ago

I'm working on warm and cold LED lighting. Both CH552 and CH554 are perfect candidates since they have two PWM channels.

Everything works perfectly fine, except analogWrite(pin, 0) is not working. After some digging, I found removing digitalWrite(pin, LOW); from this line does the trick and my LEDs go all the way down to zero.

Before finding this solution, I tried to set the value of the pin to LOW using digitalWrite(pin, LOW) if the value is zero, but it was not working.

Basically, if a pin is initiated as PWM (by running analogWrite on it), digitalWrite stops working on that pin.

DeqingSun commented 2 years ago

@foadyousefi thanks for reporting the issue. I remember I did test to it long ago. Would you mind sharing which pin you used? And some sample code?

foadyousefi commented 2 years ago

I use pins 30 and 31. Here is a sample of my code:

uint8_t led = 30;
uint16_t brightness = 0;
uint16_t fadeAmount = 5;

int inputCLK = 14;
int inputDT = 15;
int currentStateCLK;
int previousStateCLK;
volatile int lastEncoding = 0;

void setup() {
  pinMode (inputCLK, INPUT_PULLUP);
  pinMode (inputDT, INPUT_PULLUP);
  previousStateCLK = digitalRead(inputCLK);
}

void loop() {
   currentStateCLK = digitalRead(inputCLK);
   encodingTime = millis();
   if (currentStateCLK != previousStateCLK && encodingTime - lastEncoding > 50) {
     if (digitalRead(inputDT) != currentStateCLK) {
       if (brightness <= 255) {
         brightness = brightness + fadeAmount;
      }
      } else {
        if (brightness >= fadeAmount) {
          brightness = brightness - fadeAmount;
        }
      }
      lastEncoding = encodingTime;
   }

  analogWrite(led, brightness);
  previousStateCLK = currentStateCLK;
}

I tried

if (brightness == 0) {
  digitalWrite(led, LOW);
} else {
  analogWrite(led, brightness);
}

and it didn't work. Even I tried to digitalWrite via a button press, still no success.

DeqingSun commented 2 years ago

@foadyousefi Let me know if this fix your issue. It seems working on my side. https://github.com/DeqingSun/ch55xduino/commit/2e1e933471bfe9b827f565c54227e19cb0eb8e18 If it works with your issue as well, I'll move it to main branch.

foadyousefi commented 2 years ago

Yes, it is working now. You are amazing. Thanks! 👍