Good morning,
i wrote a code to drive a dc motor(right and left) with potensiometer.
Now i have to modify this code and set the frequency 40khz and then modify the duration of pwm with the potensiometer. Could you please give me a help with that?
int potPin = 0;
int speedPin = 3;
int motor1Pin = 6;
int motor2Pin = 7;
int ledPin = 13;
int val = 0;
int x = 0;
void setup() {
// set digital i/o pins as outputs:
pinMode(speedPin, OUTPUT);
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
digitalWrite(ledPin, HIGH);
val = analogRead(potPin);
if (val <= 511) {
x=255-(val/2);
digitalWrite(motor1Pin, LOW);
digitalWrite(motor2Pin, HIGH);
analogWrite(speedPin, x);
}
else {
x=(val/2)-256;
digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
analogWrite(speedPin, x); // output speed as PWM value
}
Serial.print("X: ");
Serial.println(x, DEC);
}
void startTransducer()
{
TCCR2A = _BV(COM2A0) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS20);
OCR2A = B11000111; // 199, so timer2 counts from 0 to 199 (200 cycles at 16 MHz)
}
void setup()
{
pinMode(11, OUTPUT);
startTransducer();
}
void loop()
{
}