Go Down

Topic: Servo to Motor (Read 781 times) previous topic - next topic

bob5731

Jun 23, 2018, 11:51 pm Last Edit: Jun 24, 2018, 06:20 am by bob5731
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?
Code: [Select]

#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);
}

Delta_G

So what I need to change in the code?

Start by reading the forum guidelines on how to post code and how to ask a good question.  Then come back and fix your post to include code tags and all the relevant details about your project that someone might need in order to help you.

I mean, don't you think you should at least mention what kind of motor you want to control?  Would you be happy if we gave you code for the wrong type of motor?
|| | ||| | || | ||  ~Woodstock

Please do not PM with technical questions or comments.  Keep Arduino stuff out on the boards where it belongs.

bob5731

#2
Jun 24, 2018, 12:10 am Last Edit: Jun 24, 2018, 12:13 am by bob5731
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.

lastchancename

#3
Jun 24, 2018, 12:27 am Last Edit: Jun 24, 2018, 12:53 am by lastchancename
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
Experienced responders have a nose for laziness, (they were beginners once)... expecting the poster to contribute to the learning experience.

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


bob5731

#5
Jun 24, 2018, 12:48 am Last Edit: Jun 24, 2018, 12:59 am by bob5731
Is this the code that need change?


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

bob5731

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.

Delta_G

It was a product that you program with a little circuit board to open and close an air vent.
Yeah, that nails it right down.  [sarcasm]I know exactly what that is.[/sarcasm]

Why don't you provide a link or a datasheet or something that will help someone to know how to work with that thing.  Seems like that would get you a lot better responses than just being vague about it.   
|| | ||| | || | ||  ~Woodstock

Please do not PM with technical questions or comments.  Keep Arduino stuff out on the boards where it belongs.

bob5731

#8
Jun 24, 2018, 03:55 am Last Edit: Jun 24, 2018, 04:01 am by bob5731
http://www.instructables.com/id/IntelliVent-The-Smart-Vent-controlled-by-REST-api/

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.



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.
Experienced responders have a nose for laziness, (they were beginners once)... expecting the poster to contribute to the learning experience.

bob5731

#10
Jun 24, 2018, 04:12 am Last Edit: Jun 24, 2018, 04:17 am by bob5731
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.

lastchancename

#11
Jun 24, 2018, 04:17 am Last Edit: Jun 24, 2018, 04:18 am by lastchancename
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.
Experienced responders have a nose for laziness, (they were beginners once)... expecting the poster to contribute to the learning experience.

bob5731

#12
Jun 24, 2018, 04:21 am Last Edit: Jun 24, 2018, 04:35 am by bob5731
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.

https://community.smartthings.com/t/smart-air-vents/4913/22

lastchancename

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.
Experienced responders have a nose for laziness, (they were beginners once)... expecting the poster to contribute to the learning experience.

bob5731

#14
Jun 24, 2018, 04:40 am Last Edit: Jun 24, 2018, 04:50 am by bob5731
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

Code: [Select]
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);
}

Go Up