# Dc motor position control

**URL:** <https://discourse.processing.org/t/dc-motor-position-control/27482>\
**Category:** Electronics (Arduino, etc.)\
**Created:** [January 30, 2021, 11:06am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482 "2021-01-30T11:06:11Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [January 30, 2021, 11:06am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/1 "2021-01-30T11:06:11Z")

</div>

Good evening  
I would need to check the position of an engine via android (mobile phone)  
everything is managed by arduino uno, with a motor driver, an encoder and dc motor connected, the code should have a text box where you can enter the desired position and a text box where the one reached is displayed  
Can anyone give me information about it?  
Thanks

---

<div class="post-metadata">

**Author:** ![jay\_m](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jay_m/32/11020_2.png) [@jay\_m](https://discourse.processing.org/u/jay_m)\
**Post date:** [January 30, 2021, 11:11am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/2 "2021-01-30T11:11:29Z")

</div>

> I would need to check the position of an engine

what does it mean? is it a Servo Motor, a stepper, or just a spinning motor (then how do you define a position)?

How do you want this to work? if the Arduino is using the value you enter to drive the “motor” to the desired position, assuming it uses the encoder to check “where” it is, the value reported by the Arduino will be the target you gave

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [January 30, 2021, 11:43am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/3 "2021-01-30T11:43:58Z")

</div>

then it is a brushed dc motor with encoder 200 steps per rotation I want to give an input eg: go to 200 and the engine moves to position 200  
input defined by the serial via pc

I would need the arduino code pin 2,3 encoder A, B  
0,1 rx tx serial pin 8, 9, 10 fw rw, pwm

---

<div class="post-metadata">

**Author:** ![jay\_m](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jay_m/32/11020_2.png) [@jay\_m](https://discourse.processing.org/u/jay_m)\
**Post date:** [January 30, 2021, 1:04pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/4 "2021-01-30T13:04:15Z")

</div>

a brushed dc motor does not have a “position”. Do you mean take 200 ticks in one direction and then stop ?

Assuming you know how to send data from processing to the Arduino (tons of examples on line), on the arduino side it’s a matter of getting that target number from the Serial line, powering the motor in the right direction depending on the sign of the data (+200 forward 200 ticks, -200 reverse for 200 ticks) and then counting the ticks until you reach (or overshoot) the target count.

The best library to do count the ticks even at a fast pace on the Arduino is likely [PaulStoffregen’s Encoder library](https://github.com/PaulStoffregen/Encoder)

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [January 30, 2021, 1:10pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/5 "2021-01-30T13:10:38Z")

</div>

the position is given by the encoder the software counts the encoder steps

---

<div class="post-metadata">

**Author:** ![jay\_m](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jay_m/32/11020_2.png) [@jay\_m](https://discourse.processing.org/u/jay_m)\
**Post date:** [January 30, 2021, 1:24pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/6 "2021-01-30T13:24:32Z")

</div>

please share links to your hardware

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [January 30, 2021, 1:27pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/7 "2021-01-30T13:27:33Z")

</div>

[![](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/7/7272acf032040709c0c9f52f1c45bf822d3ad235.jpeg) ](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/7/7272acf032040709c0c9f52f1c45bf822d3ad235.jpeg)

[![](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/ad4dd3d3d73c51c31ab08ca2a98ea6b4baac5962.jpeg) ](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/ad4dd3d3d73c51c31ab08ca2a98ea6b4baac5962.jpeg)

---

<div class="post-metadata">

**Author:** ![jay\_m](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jay_m/32/11020_2.png) [@jay\_m](https://discourse.processing.org/u/jay_m)\
**Post date:** [January 30, 2021, 4:40pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/8 "2021-01-30T16:40:10Z")

</div>

I’m unsure what your question is.

---

<div class="post-metadata">

**Author:** ![erkosone](https://avatars.discourse-cdn.com/v4/letter/e/ba9def/32.png) [@erkosone](https://discourse.processing.org/u/erkosone)\
**Post date:** [January 31, 2021, 6:05am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/9 "2021-01-31T06:05:17Z")

</div>

Send enconder data to PC by Serial.write( encoder\_data ); simply…

On PC side:

void serialEvent(Serial myPort){  
…  
…  
}

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [January 31, 2021, 7:38am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/10 "2021-01-31T07:38:32Z")

</div>

what is your arduino code ?

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [January 31, 2021, 7:54am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/11 "2021-01-31T07:54:16Z")

</div>

try this

```auto
import processing.serial.*;

 int adcValue = 0; // value received from Serial 
 
 Serial myPort;

 void setup() {
                          
  size(480, 180);        
 
  println(Serial.list()); // List all the available serial ports
  // Then open the port you're using, my is the first, i.e. '0'
   myPort = new Serial(this, Serial.list()[0], 9600);
 // don't generate a serialEvent() unless you get a newline character:
   myPort.bufferUntil('\n');
 }

void draw()
{                     
  
}

void serialEvent(Serial myPort) 
{
 String inString = myPort.readStringUntil('\n'); // get the ASCII string:
 if (inString != null) 
    {
     inString = trim(inString);     
     adcValue = int(inString); // convert into an integer
     adcValue =int(map(adcValue, 0, 1023, 0, 1023)); // possible range adjusting
    }
 }

```

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [February 2, 2021, 12:00pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/12 "2021-02-02T12:00:07Z")

</div>

Please Android mode  
Tankyou

---

<div class="post-metadata">

**Author:** ![erkosone](https://avatars.discourse-cdn.com/v4/letter/e/ba9def/32.png) [@erkosone](https://discourse.processing.org/u/erkosone)\
**Post date:** [February 3, 2021, 6:53am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/13 "2021-02-03T06:53:49Z")

</div>

In Andoid mode not exists a “oficial” serial library, you need use bluetoth connection.

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [February 5, 2021, 11:40am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/14 "2021-02-05T11:40:42Z")

</div>

Yes i know  
Let’s clarify the situation: I should create a text box Where can I enter numbers, for example from 1 to 1024 and via Bluetooth send them to Arduino so I would need an Android side code It is an Arduino side code that receives it Thanks

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 11:54am UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/15 "2021-02-05T11:54:05Z")

</div>

try this and modify it as your demand

arduino

```auto
#include <SoftwareSerial.h>
#include <Wire.h>

SoftwareSerial mySerial(11, 12); // RX, TX

int value = 0;
int previous_value = 0;

void setup() {
  mySerial.begin(115200); // Set the baudrate equal to HC06 setting
}

void loop() {
  for (int i = 0; i < 32; i++) value += analogRead(0);
  value /= 32;
  if( value != previous_value) mySerial.print(String(value) + '!');
  previous_value = value;
  delay(100);
}

```

```auto
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Build.VERSION_CODES; 
import processing.core.PConstants;
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Activity activity;
Permission bt, afl;

Thread runThread;
byte[] readBuffer;
int buffer_index;
int counter;
boolean stop_thread, plotting = false, init = true;

String msg = " ";
String device_name = "HC-05";
String r_str = " ";
String str_1, str_2, str_3;
float px, py, x, y;
int ts_1, ts_2, ts_3;

void setup() {
  fullScreen();
  orientation(LANDSCAPE);
  bt = new Permission(this, "BLUETOOTH");
  afl = new Permission(this, "ACCESS_FINE_LOCATION");
  textAlign(CENTER, CENTER);
  textSize(12);
  str_1 = "Click to connect.";
  str_2 = "8888";
  str_3 = "Analog reading value";
  textSize(12); // Start value to create a "textwidth factor",
  // Making it proportional for other screen resolutions
  float twf_1 = width/textWidth(str_1);
  float twf_2 = width/textWidth(str_2);
  float twf_3 = width/textWidth(str_3);
  int f_1 = 4; // Empericaly found 
  int f_2 = 11;
  int f_3 = 8;
  ts_1 = int(f_1*twf_1);
  ts_2 = int(f_2*twf_2);
  ts_3 = int(f_3*twf_3);
  fill(255);
  activity = this.getActivity();
}

void draw() {
  if (init) {
    background(150);
    textSize(ts_1); 
    text(str_1, width/2, height/2);
  }
}

void mousePressed () {
  if (init) {
    try {
      init = false;
      findBluetooth();
      connect();
      plotting = true;
      background(0);
      fill(255, 255, 0);
      textSize(ts_3); 
      text(str_3, width/2, height/8);
      textSize(ts_2);
    } 
    catch (IOException ex) {
      println(ex);
    }
  }
}

void plot(String r_str) {
  if (r_str.length() < 1 || r_str == null) r_str = "0";
  if (plotting) {
    fill(0);
    rect(0, height/3, width, 2*height/3);
    fill(255, 255, 0);
    text(r_str, width/2, 2*height/3);
  }
}

void findBluetooth() {
  mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (mBluetoothAdapter == null) {
    println("No bluetooth adapter available");
  }
  if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    activity.startActivityForResult(enableBluetooth, 0);
  }
  Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  if (pairedDevices.size() > 0) {
    print("Paired devices MAC Adress:");
    printArray(pairedDevices);
    for (BluetoothDevice device : pairedDevices) {
      print("Paired devices by name:");
      println(device.getName());
      if (device.getName().equals(device_name)) {
        mmDevice = device;
        println("Bluetooth device name found");
        break;
      }
    }
  }
}

void connect() throws IOException {
  UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();
  println("Bluetooth connected");
  final byte delimiter = 33; //This is the ASCII code for a ! character
  stop_thread = false;
  buffer_index = 0;
  readBuffer = new byte[1024];
  runThread = new Thread(new Runnable() {
    public void run() {                
      while (!Thread.currentThread().isInterrupted() && !stop_thread) {
        try {
          int bytesAvailable = mmInputStream.available();                        
          if (bytesAvailable > 0) {
            byte[] packetBytes = new byte[bytesAvailable];
            mmInputStream.read(packetBytes);
            for (int i = 0; i < bytesAvailable; i++) {
              byte b = packetBytes[i];
              if (b == delimiter) {
                byte[] encodedBytes = new byte[buffer_index];
                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                final String data = new String(encodedBytes, "US-ASCII");
                plot(data);
                buffer_index = 0;
              } else {
                readBuffer[buffer_index++] = b;
              }
            }
          }
        } 
        catch (IOException ex) 
        {
          stop_thread = true;
        }
      }
    }
  }
  );
  runThread.start();
}

void closeBluetooth() throws IOException {
  stop_thread = true;
  mmOutputStream.close();
  mmInputStream.close();
  mmSocket.close();
  println("Bluetooth stopped");
}

class Permission {
  PApplet parent;
  boolean requestedPortraitImage = false;

  Permission(PApplet pParent, String permissionName) {
    parent = pParent;
    parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
  }

  void onPermissionResult(boolean granted) {
    if (granted) println("User did grant permission.");
    else println("User did NOT grant permission.");
  }
}

void onPause() {
  try {
    closeBluetooth();
  } 
  catch (Exception ex) {
  }
  super.onPause();
}

void onStop () {
  try {
    closeBluetooth();
  } 
  catch (Exception ex) {
  }
  super.onStop();
}

void onRestart() {
  try {
    findBluetooth();
    connect();
  } 
  catch (IOException ex) {
    println(ex);
  }
}

```

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 12:12pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/16 "2021-02-05T12:12:42Z")

</div>

you can use this its working with me

remove the second slider if you wish and put what you need in the slider value

```auto
import ketai.net.bluetooth.*;
import controlP5.*;
import android.os.Bundle;

ControlP5 cP5a;
ControlP5 cP5b;

String device_name = "HC-05";
//String device_mac = "40:45:DA:00:25:05";

KetaiBluetooth bt;

void setup() { 
  cP5a = new ControlP5(this);
  cP5a.addSlider("CYCLE_TIME", 999, 1999,999, 10, 10, 255, 35);
  cP5b = new ControlP5(this);
  cP5b.addSlider("PULSE", 55, 455, 55, 10, 55, 255, 35);
  bt.getPairedDeviceNames();
  bt.start();
  //bt.connectDevice("40:45:DA:00:25:05");
  bt.connectToDeviceByName(device_name);
}

void draw() {
}

void controlEvent(ControlEvent theEvent) {
  if (theEvent.isController()) {
    print("control event from : "+theEvent.getController().getName());
    println(", value : "+theEvent.getController().getValue());
    if (theEvent.getController().getName()=="CYCLE_TIME") {
      int val1 = int(theEvent.getController().getValue());
      send("a" + val1+"\n");
    }
    if (theEvent.getController().getName()=="PULSE") {
      int val2 = int(theEvent.getController().getValue());
      send("b" + val2+"\n");
    }
  }
}

void send(String str) {
  byte[] data = str.getBytes();
  //bt.write(device_mac, data);
  bt.writeToDeviceName(device_name, data);
  //OscMessage m = new OscMessage(str);
  //bt.broadcast(m.getBytes());
}

void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  bt = new KetaiBluetooth(this);
}

```

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [February 5, 2021, 9:08pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/17 "2021-02-05T21:08:02Z")

</div>

why do I only see this?

 ![Screenshot_20210205-220253](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/d/dbff1db8e344b92efd760059b4deb3f4a53cc899.jpeg)

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 9:21pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/18 "2021-02-05T21:21:16Z")

</div>

you are reading analogRead(0) add resister to see the value

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 9:25pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/19 "2021-02-05T21:25:21Z")

</div>

![AnalogReadSerial_BB (1)](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/7/7e0b0f0e4bd2cb7fa1927c1aef419f86ada29761.png)

---

<div class="post-metadata">

**Author:** ![r0x15](https://avatars.discourse-cdn.com/v4/letter/r/4da419/32.png) [@r0x15](https://discourse.processing.org/u/r0x15)\
**Post date:** [February 5, 2021, 9:34pm UTC](https://discourse.processing.org/t/dc-motor-position-control/27482/20 "2021-02-05T21:34:39Z")

</div>

yes I did  
bu i see only this

[Next page](https://discourse.processing.org/t/dc-motor-position-control/27482.md?page=2)
