Skip to content

PWM functions #2923

Closed
Closed
@Gavin-Perry

Description

@Gavin-Perry

I am using PWM to control a solenoid that can not have full voltage for more than 2ms.
I'm finding limited documentation for analogWriteRange() and analogWriteResolution()
Is there a suggested order for these as they seem do to interact
For example if I have the following driving a Darlington Solenoid driver (UL2803) with 12V output (Common)

#define MyPin 18
#define FULL 100  // 100% 
void setup() {
  analogWriteFreq(30000);   // Get out of audible range
  analogWriteRange(100);  // let me use % for range
  analogWriteResolution(12);  // Should I put Res before Range?
}

void loop() {
  analogWrite(MyPin,FULL);
  delay(2);
  analogWrite(MyPin,FULL/7);     // 1/7 power for hold (1.7V)
    delay(3000);
    digitalWrite(MyPin, LOW); // Make it really off, stop PWM noise
// Is this OK to do or must I use analogWrite(MyPin,0);
}

Because 12 bits is range 0-4095 and I'm only getting fractions of a volt for FULL at 100
It seems that if I ask for 12 bit resolution then Range of 0-100 means all I get is 0 to 100/4096
I thought Range was setting a scale and documentation isn't clear what that means.
If I change FULL to 4095 (or should I use 4096?) I get the expected range (thus why I used FULL/7 instead of 14%)
Should FULL be 4095? Then would I set Range to FULL+1? (or it doesn't matter?)
I read the code in wiring_analog.cpp but it's not straightforward, with lots of scaling games to make things fit, but not as I expected.

Finally, although analogWrite() takes care of everything for the analog output (PWM mode setting...)
do I need to set pinMode(MyPin, OUTPUT); for the digitalWrite() to work? and will that be saved? (looks like it)

Thanks as always for your great support.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions