switching motor direction, is for-loop INSIDE if statement possible?


What I am expecting and hoping for, is that a potentiometer (with Arduino codiing) is used to trigger (using if statement) a motor driver only for a certain duration (using a for-loop) for one iteration only (the motor would stop at the end of the for-loop). When the potentiometer is moved back the other way the motor driver would hypothetically go back the same amount of time to the starting position.

Is this at all possible? I also get an error with my code saying a function-definition is not allowed here before ‘{’ token right at the beginning of void loop () {


   int enA = 9;   // Motorshield / Motordriver pin enA to Arduino PWM pin 10, 
   int in1 = 2;  // Motorshield / Motordriver pin in1 to Arduino PWM pin 9
   int in2 = 4;    // Motorshield / Motordriver pin in2 to Arduino pin 8

// Far ends of potentiometer are connected to GND, and another to either 3.3V or 5V terminals on Arduino.
// Middle potentiometer pin is connected to A0 (above code)

// Second potentiometer middle pin is connected to A5

int drive_pote_pin = A0;
int drive_pote_value;

void setup() {

  // Set pins as output:
      pinMode(enA, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);

void loop() {
  // put your main code here, to run repeatedly:
  int x = 1;
  int y = 1;
  int drive_pote_value = analogRead(drive_pote_pin);     // Read the feedback mechanism (or whatever mechanism)

if (drive_pote_value < 512)
  for (int i = 0; i <= 255; i++) 
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        analogWrite(enA, 255);
if (drive_pote_value > 512)
  for (int j = 0; j <= 255; j++)
       digitalWrite(in1, LOW);
       digitalWrite(in2, HIGH);
       analogWrite(enA, 255);

I think that you have some learning to do. There is NO point in having a loop for what will always be a single iteration. Also, you may need to learn better ways to measure durations.

Your loop function is defined inside of your setup function. You are not allowed to define a function within a function - at least, not in C and not in C++, which are the languages used in conjunction with the Arduino IDE.

Move a '}' from the end of the program to a line just ahead of the loop function. In the future, use the Arduino IDE autoformat feature (CTRL-T on a PC) before posting, and look for adjacent lines that have identical brackets in the same column. This should NEVER happen in a correctly written program.