Changing DC Motor speed based on a reading from a Potentiometer

I have the following code, and I want to change the DC motor speed connected to Ardunio Nano throught a H Bridge and make it dependent on a Potentimortere reading. And help would be apprechiate

`// Motor A connections
int enA = 8;
int in1 = 6;
int in2 = 7;

float floatMap(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void setup() {
   Serial.begin(9600);
  // put your setup code here, to run once:
	pinMode(enA, OUTPUT);
	pinMode(in1, OUTPUT);
	pinMode(in2, OUTPUT);
	// Turn off motors - Initial state
	digitalWrite(in1, LOW);
	digitalWrite(in2, LOW);
}

void loop() {
 int brightness= pontimementer();
  delay(1000);
directionControl(brightness);
	delay(1000);
}

int pontimementer() {
  int analogValue = analogRead(A1);
  // Rescale to potentiometer's voltage (from 0V to 5V):
   float voltage = floatMap (analogValue, 0, 1023, 0, 5);
 int brightness = analogValue / 4;

   // print out the value you read:
  Serial.print("Analog: ");
  Serial.print(analogValue);
  Serial.print(", Voltage: ");
  Serial.println(voltage);

  return brightness;
}

void directionControl(int brightness) {
	// Set motors to maximum speed
	// For PWM maximum possible values are 0 to 255
	analogWrite(enA, 255);

	// Turn on motor A & B
	digitalWrite(in1, brightness);
	digitalWrite(in2, LOW);
	delay(2000);
	
	// Turn off motors
	digitalWrite(in1, LOW);
	digitalWrite(in2, LOW);
  	delay(2000);
}`

Welcome to the forum

Your topic was MOVED to its current forum category which is more appropriate than the original as it has nothing to do with Installation and Troubleshooting of the IDE

1 Like

what about

   	analogWrite (enA, map (analogRead (A1), 0, 1023, 0, 255));

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.