Servo to Motor

I'm new to arduino

I found some code that work whit smartthings to control a Servo.
Now need to control a Motor not a Servo.

I have L9110S DC Stepper Motor Driver Board H Bridge By Atomic Market.
Module power supply voltage: 2.5-12 v 0.8A maximum working current.
Vent Miser motor use 1.5v.
The Vent Miser run on 2 AAA battery.
So what I need to change in the code?

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <Servo.h>
#include <EEPROM.h>
#include <math.h>
#include <ArduinoJson.h>

#define VERSION 19
#define DEFAULT_WIFI_SSID "My Wifi Nework 5G"
#define DEFAULT_WIFI_PASSWORD "MyWifiP@ssword"
#define DEFAULT_HOSTNAME "esp8266-smart-blinds"
#define DEFAULT_SPEED "2" // 1 or 2
#define DEFAULT_DURATION "3500" // 9 characters 1000-9999
#define DEFAULT_LAST_ACTION "0"


char host[25];
char ssid[25];
char password[25];
int servoPin = 2;
int tryCount = 0;
Servo Servo1;

ESP8266WebServer server(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){
  
  // Avoid Randomly Vibrating when turning on
  Servo1.attach(servoPin);
  Servo1.write(90); 
  delay(200); 
  Servo1.detach();

  Serial.begin(115200);
  EEPROM.begin(512);

  if(getData(84,86,"0") == "1"){
    // Yay I know you
  } else {
    // I don't know you
    clearEEPROM();
    setData(84, 86, "1"); // Getting to know you
  }

  String theSSID = getData(0,25, DEFAULT_WIFI_SSID);
  String thePassword = getData(26,50, DEFAULT_WIFI_PASSWORD);
  String theHostname = getData(61,80, DEFAULT_HOSTNAME);

  Serial.println("Trying " + theSSID + " / " + thePassword + " / " + theHostname);
  
  theSSID.toCharArray(ssid, 25);
  thePassword.toCharArray(password, 25);
  theHostname.toCharArray(host, 25);
  
  
  WiFi.begin(ssid, password);
  Serial.println("Started");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    tryCount = tryCount + 1;
    Serial.print("Try #" + String(tryCount) + " ");
    if(tryCount > 30){
      Serial.println("Giving up, reverting back to default Wifi settings");
      setData(0,25, DEFAULT_WIFI_SSID);
      setData(26,50, DEFAULT_WIFI_PASSWORD);
      setData(61,80, DEFAULT_HOSTNAME);
      delay(1000);
      WiFi.disconnect();
      ESP.reset();
    }
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin(host)) {
    Serial.println("MDNS responder started");
  }


  server.on("/version", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    Serial.println("version");
    json["version"] = VERSION;
    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);
  });

  server.on("/status", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    Serial.println("status");
    json["isOpen"] = getData(81,83,DEFAULT_LAST_ACTION) == "1";;
    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);
  });

  server.on("/clear", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    Serial.println("clear");
    json["message"] = "Clearing EEPROM data and resetting";
    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);

    clearEEPROM();
    WiFi.disconnect();
    ESP.reset();
  });

  server.on("/reset", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["message"] = "resetting";
    Serial.println("Resetting");
    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);
    WiFi.disconnect();
    ESP.reset();
  });

  server.on("/open", [](){
    openOrClose(1);
  });

  server.on("/close", [](){
    openOrClose(0);
  });

  server.on("/config", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();

    int theSpeed = getData(51,55, DEFAULT_SPEED).toInt();
    if(server.hasArg("speed")){
      theSpeed = server.arg("speed").toInt();
      setData(51,55, String(theSpeed));
    }
    json["speed"] = theSpeed;

    int theDuration = getData(81,90, DEFAULT_DURATION).toInt();
    if(server.hasArg("duration")){
      theDuration = server.arg("duration").toInt();
      setData(81,90, String(theDuration));
    }
    json["duration"] = theDuration;


    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);
  });

  server.on("/wifi", [](){
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    bool resetMe = false;

    String aSsid = getData(0,25, DEFAULT_WIFI_SSID);
    if(server.hasArg("ssid")){
      aSsid = setData(0,25, server.arg("ssid"));
      resetMe = true;
    }
    json["ssid"] = aSsid;

    String aPassword = getData(26,50, DEFAULT_WIFI_PASSWORD);
    if(server.hasArg("password")){
      aPassword = setData(26,50, server.arg("password"));
      resetMe = true;
    }
    json["password"] = aPassword;

    String aHostname = getData(61,80, DEFAULT_HOSTNAME);
    if(server.hasArg("hostname")){
      aHostname = setData(61,80, server.arg("hostname"));
      resetMe = true;
    }
    json["hostname"] = aHostname;

    json["ip"] = WiFi.localIP().toString();

    String clientMac = "";
    unsigned char mac[6];
    WiFi.macAddress(mac);
    clientMac += macToStr(mac);
    clientMac.toUpperCase();
    json["mac"] = clientMac;

    if(resetMe){
      json["message"] = "Changes detected, now resetting.";
    }

    String output;
    json.prettyPrintTo(output);
    server.send(200, "application/json", output);

    if(resetMe){
      ESP.reset();
    }
  });

  server.onNotFound(handleNotFound);

  httpUpdater.setup(&server);
  server.begin();
  MDNS.addService("http", "tcp", 80);
  Serial.println("HTTP server started");
  
}

String macToStr(const uint8_t* mac){
  String result;
  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);
    if (i < 5)
      result += ':';
  }
  return result;
}

void openOrClose(int direction) {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();

  bool toSpin = true;

  String lastAction = getData(81,83, DEFAULT_LAST_ACTION);
  if(lastAction == String(direction)){
    toSpin = false;
    json["message"] = "did not spin";
  }

  int theSpeed = getData(51,55, DEFAULT_SPEED).toInt();
  if(server.hasArg("speed")){
    theSpeed = server.arg("speed").toInt();
  }
  int theDuration = getData(81,90, DEFAULT_DURATION).toInt();
  if(server.hasArg("duration")){
    theDuration = server.arg("duration").toInt();
  }
  int dutyCycle = calculateDutyCycleFromSpeedAndDirection(theSpeed, direction);
  if(server.hasArg("dutyCycle")){
    dutyCycle = server.arg("dutyCycle").toInt();
  }

  json["action"] = direction ? "open" : "close";
  json["speed"] = theSpeed;
  json["duration"] = theDuration;
  json["calulatedDutyCycle"] = dutyCycle;

  String output;
  json.prettyPrintTo(output);
  server.send(200, "application/json", output);

  if(toSpin){
    Servo1.attach(servoPin);
    Servo1.write(dutyCycle); 
    delay(theDuration); 
    Servo1.detach();

    setData(81,83,String(direction));
  }
}

void handleNotFound(){
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

int calculateDutyCycleFromSpeedAndDirection(int speed, int direction){
  if(speed == 1 && direction == 1){
    return 80;
  } else if(speed == 2 && direction == 1){
    return 0;
  } else if(speed == 1 && direction == 0){
    return 95;
  } else if(speed == 2 && direction == 0){
    return 180;
  } else{
    return 180;
  }
}

// Get EEPROM Data
String getData(int startingIndex, int endingIndex, String defaultValue){
  String data;
  for (int i = startingIndex; i < endingIndex; ++i) {
    String result = String(char(EEPROM.read(i)));
    if(result != ""){
      data += result; 
    }
  }
  if(!data.length()){
    return defaultValue;
  }else{
    return data;
  }
}

// Set EEPROM Data
String setData(int startingIndex, int endingIndex, String settingValue){
  for (int i = startingIndex; i < endingIndex; ++i){
    EEPROM.write(i, settingValue[i-startingIndex]);
    Serial.print("Wrote: ");
    Serial.println(settingValue[i-startingIndex]); 
  }

  EEPROM.commit();
  delay(250);
  return settingValue;
}

void loop(void){
  server.handleClient();
}

void clearEEPROM(){
  for (int i = 0 ; i < 512 ; i++) {
    EEPROM.write(i, 0);
  }
  EEPROM.commit();
  delay(500);
}

All I need to do is change in the code control Vent Miser motor. All smartthings need to do is open and close the Vent Miser. I have no idea what type of motor is in it.

Everything the others have said above.

If you’re going to a DC motor or stepper to replace the r/c style servo, the very least you need to do is rename & rewrite the servo_move() function.

Then keep in mind that an r/c servo is an absolute positioner with its own internal capability (called a servo).
Changing to any other open-loop type of actuator means that you have to provide and keep track of the position from moment to moment.

It may help if you understand the difference between the types of motors.
In this case, you’re trying to convert from a self-contained ‘servo’ to a motor with external feedback, acting as a servo-motor. There’s a post in Introductory Tutorials that explains some of this.

Edit. Fixed typos

I'd like to help but I don't know what a "Vent Miser" is, I don't know what sort of motor it uses, I don't know what the motor does or how it should be controlled.

And if the only information you can provide is the name "Vent Miser" then I'm never going to be able to help.

Steve

Is this the code that need change?

if(toSpin){
   //Servo1.attach(servoPin);
   //Servo1.write(dutyCycle); 
   delay(theDuration); 
   //Servo1.detach();
   setData(81,83,String(direction));
}

665e92c5ee_689x390.jpg

slipstick:
I'd like to help but I don't know what a "Vent Miser" is, I don't know what sort of motor it uses, I don't know what the motor does or how it should be controlled.

And if the only information you can provide is the name "Vent Miser" then I'm never going to be able to help.

Steve

It was a product that you program with a little circuit board to open and close an air vent.

https://www.ebay.com/itm/Vent-Miser-Programable-Energy-Saving-Vent-6-12/112977283302?ssPageName=STRK%3AMEBIDX%3AIT&_trksid=p2057872.m2749.l2649

I don't have much information on it.
But the link above is using an Intel Edison board.

All I need the motor to do is open the vent and close the vent basically reversing the polarity.

From what you’re saying, and the packaging notes - it’s NOT a servo of any type. Just a small motor driving the air vanes?
It sounds like you need to pull it apart to identify exactly what is inside.
For the solution, it’s probably going to be the smallest processor you can find with a minimal h-bridge to drive the vane motor.

lastchancename:
From what you’re saying, and the packaging notes - it’s NOT a servo of any type. Just a small motor driving the air vanes?
It sounds like you need to pull it apart to identify exactly what is inside.
For the solution, it’s probably going to be the smallest processor you can find with a minimal h-bridge to drive the vane motor.

I also linked to instructable that does it through http. We're not talking about a servo and I do believe it's not a stepper motor either.

Yeah, i had a quick look at that.
I think we need to understand what you’re trying to do.
(1) Go with the remote control ‘model’, or as your initial post hinted, (2) re-engineer the vent with your own actuator.

  1. is easy - follow the ‘ideas’ in the instructable with your chosen hardware - you don’t need to. modify the vent itself.
  2. is more interesting as a project, but maybe beyond your current skills.

All I'm trying to do is in a integrate it in to SmartThings using a motor that is built into it. Take the red and black cables from the motor hook it up to Arduino with WiFi and let it talk to SmartThings. I started the project with a servo and quickly found out that was beyond my skill set. On the hardware side and electronics of it. All I'm asking for is some code to replace the servo functionality in the code that I found. Basically I just need to drive the motor forwards and backwards. Now that I look at it further I think it's using a gear type motor. It's using a gear type system.

ok, i think i’m getting closer.
I was getting fixated on the vent-miser, while you really need to solve the fundamentals first - controlling a small motor.
Forget the vent for now, and read about using an h-bridge for bidirectional control of a small DC motor.
Not a stepper, not a servo - just simple control of a dc motor.
Practice with that to understand the direction colntrol, and possibly speed using PWM (analogWrite())).
Consider your power supply and mechanical requirements to drive the motor as well as a clean supply for the controller.

That is some sample code that I found to test the h-bridge that just came in today.

I was also attached the Arduino file from that instructable if that would help

int M1_Izq = 12; //Direccion
int M1_Derecha = 13; //Direccion

void setup()
{
 pinMode(M1_Izq, OUTPUT);
 pinMode(M1_Derecha, OUTPUT);
}

void loop(){
 girar (1); 
 delay(1000); //1 sg 
 
 stop();
 delay(1000); //250ms

 girar (2); 
 delay(1000); //1 sg 
 
 stop();
 delay(1000); //250ms
}


void girar(int direccion)
{
 boolean inPin1 = LOW;
 boolean inPin2 = HIGH;

 if(direccion == 1){
   inPin1 = HIGH;
   inPin2 = LOW;
 }
   digitalWrite(M1_Izq, inPin1);
   digitalWrite(M1_Derecha, inPin2);
}

void stop(){
   digitalWrite(M1_Izq, LOW);
   digitalWrite(M1_Derecha, LOW);
}

FDGTEOYIBU5875H.ino (8.13 KB)

ok, so that looks ok as a starting point.
As only a few have the same hardware as you, can you sketch out or post how it’s all wired together.
I’m guessing you already have a small h-bridge connected to M1-Izq, and M1-Derecha.
In that case the basics of what you’re doing is correct.
There are some improvements possible, but let’s start from where we are!
(Hint: learn about millis() timing as a replacement for delay(). )
p.s. 1000 is not 250 ! Just an oversight...

Basically I've got two alligator clips connected to the vent Miser then they go into motor signal a then I grab power and ground from Arduino. That was just a sample code I found on the internet. If that code is good enough to be used where do I put it in the code that I posted at the beginning of this thread. Like I said before I did not write the original code. I tried it with a servo and the problem I was running into was once I built a mount and put it on a standard air vent the hole in the wall would have to be severely modified to make it all fit.

Depending on your motor, that should be fine for small hobby motors.
The example only shows on/off control, but does indicate what’s needed for PWM speed control.

As a motor driver, that board controls the motor, but you have to decide when you’re at a limit or other position that you want reach.(open, close) etc.

As a simple dc controller, you need to understand the input pin control requirements - which will develop your programming skills a bit more than a straight h-bridge. Remember to use ‘analog’ output pins if you’re going to try PWM speed control.

now ware do I put this code at in my code?

void openVent()
{
 if (!bVentStatus)
 {
   // set to green once opened
   digitalWrite(OPEN_VENT_PIN, LOW);               
   delay(200);
   digitalWrite(OPEN_VENT_PIN, HIGH);
   bVentStatus = true;
   
// when vent is opened, send the room temperature data to Intel  IoT Analytics 
 }
}

void closeVent()
{
 if (bVentStatus)
 {
   // set to red once closed
       digitalWrite(CLOSE_VENT_PIN, LOW);               
   delay(200);
   digitalWrite(CLOSE_VENT_PIN, HIGH);
   bVentStatus = false;
 } 
}

I have no idea what you’re asking.
Perhaps someone else can come up with suggestions.
I realisethat you’re learning, but you need to break down the code you already have and understand what it does.
Simply putting ‘some’ new code ‘somewhere’ will rarely work.

it’s all tightly linked together.

this is the code that work Servo

Did you read the project description of the github link ?

This is for a modified RC servo - yet another variant of our first discussion.
Choose what you have, what you want to do, and start from there.

There is another topic in Introductory Tutorials that may help you get a grip on the best approach.