?? constant PWM

I am trying to get a constant PWM of 20 starting from 0. But it counts from 0 to 20 again and again , no constant PWM after it reaches to 20. The code is following:

#define ENABLEA 2 //encoder channel A
#define ENABLEB 3 //encoder channel B
#define INA 8// left direction
#define INB 9// right direction
#define PW 5 //PWM
#define analogPin A0//sensor data acquisition pin

void setup() {
pinMode(ENABLEA, OUTPUT);
pinMode(ENABLEB, OUTPUT);
digitalWrite(ENABLEA, HIGH);
digitalWrite(ENABLEB, HIGH);

pinMode(INA, OUTPUT);
pinMode(INB, OUTPUT);
pinMode(PW, OUTPUT);
Serial.begin(9600);
pinMode(analogPin, INPUT);

a_read=analogRead(analogPin);
delay(10);
Serial.begin(9600);
pinMode (ENCA, INPUT_PULLUP);
pinMode (ENCB, INPUT_PULLUP);
attachInterrupt(0, Encoder, RISING);
}

void loop() {
a_read = analogRead(analogPin);//read ADC from sensor
int inc;//PWM variable
int PW;//corresponds to PWM on motor

//(Pololu - VNH5019 Motor Driver Carrier) motor driver datasheet

if (a_read>=100 && a_read<=118){// 0 degree
digitalWrite(INA, LOW); // INA otor rotation clockwise
digitalWrite(INB, LOW);//// INB motor rotation anticlockwise
delay(10);
analogWrite(PW, 0);
}

if (a_read>=119 && a_read<=140){
analogWrite(PW, 0);
digitalWrite(INB, LOW);
delay(100);

for (inc= 0; inc <= 19; inc++){
digitalWrite (INA, HIGH);
delay(100);
analogWrite(PW, inc);
if (inc== 19) analogWrite(PW, 20);
}

else if (a_read>=140 && a_read<350){
digitalWrite(INA, HIGH);

delay(10);
for (inc= 20; inc<=100; inc++){
delay(100);
analogWrite(PW, inc);}
}

}

would really appreciate your suggestion. thanks.

Remember that when the loop function finishes, it starts back over again. If you want the PWM to only ramp up once at startup, then put that bit of code into the setup function.

would really appreciate your suggestion. thanks.

1)Post your code using the code tags produced with the </> icon at the top left of the toolbar. It will create the word code in brackets twice. Paste your code between the two words in brackets.

post your code like this

2)Post code which compiles.

  1. Declare your variables properly.

3)Remove all the unused encoder material from your code.

Don't use delay() to manage your timing - use millis() as illustrated in several things at a time

...R

I am trying to get a constant PWM of 20 starting from 0.

This makes no sense to me. "Starting from..." implies that something should change. "constant..." implies that something should not.

read ADC from sensor

  • What sensor?

I am trying to get a constant PWM of 20 starting from 0.

  • I think the OP means to ramp up to a value of 20 for PWM. Perhaps he wants to attain 20 RPM.

  • Scotty

Or replace

  for (inc= 0; inc <= 19; inc++){

by

  while (inc < 20)
  {
     ...
     inc ++ ;
  }

MarkT:
Or replace

  for (inc= 0; inc <= 19; inc++){

by

  while (inc < 20)

{
    …
    inc ++ ;
  }

Thank you. With while loop it works pretty accurate.