Creating a new library

Hello, I am starting a knew library for a project i am working at. The project is building an autonomous car.

The reason why I want to build this library is because the code of the motors is to long and I want to optimize it, by making this library.

I am using the adafruit motorshield to control the four dc motors. I let the code of the contol of the motors below (motors.ino).

I would like to transform that code into a library but I don’t know how to do it. I dont know how to initialize the motorshield as well as introduce the library of adafruit to control the motorshield.

I let the code I have written so far of the library also below (Motors.h and Motors.cpp).

Thank you for your time.

Motors.cpp (6.8 KB)

Motors.h (972 Bytes)

motors.ino (7.43 KB)

void Motors::speed100Forward(){		//100%
	m1->run(FORWARD);
	m2->run(FORWARD);
	m3->run(FORWARD);
	m4->run(FORWARD);
	m1->setSpeed(255);
	m2->setSpeed(255);
	m3->setSpeed(255);
	m4->setSpeed(255);
}

void Motors::speed90Forward(){		//90%
	m1->run(FORWARD);
	m2->run(FORWARD);
	m3->run(FORWARD);
	m4->run(FORWARD);
	m1->setSpeed(230);
	m2->setSpeed(230);
	m3->setSpeed(230);
	m4->setSpeed(230);
}

I’d start over…

just have one speedForward() member function that takes a speed argument!! Isn’t the purpose of your library to make things easier?

void Motors::speedForward(int speed)
{
  speed = map(speed, 0, 100, 0, 255); // programmer puts speed as a percentage of 255...
  // and so on...
}

Thank you for your fast answer. I will include that into my code but the real problem is that i don’t know how to initialize the motorshield in the library.

I dont know how to inlcude this into the library:

#include <Adafruit_MotorShield.h> //library fror the motorshield

//initialize the motorshield
Adafruit_MotorShield afms = Adafruit_MotorShield();

//set the motors
Adafruit_DCMotor *m1 = afms.getMotor(4);
Adafruit_DCMotor *m2 = afms.getMotor(3);
Adafruit_DCMotor *m3 = afms.getMotor(1);
Adafruit_DCMotor *m4 = afms.getMotor(2);

void setup()
{
Serial.begin(9600);

afms.begin();

//initialize the motor functions, so it can go forward, backward or don’t move
m1->setSpeed(0); //set the speed of the motor at 0
m1->run(FORWARD);
m1->run(BACKWARD);
m1->run(RELEASE);

m2->setSpeed(0);
m2->run(FORWARD);
m2->run(BACKWARD);
m2->run(RELEASE);

m3->setSpeed(0);
m3->run(FORWARD);
m3->run(BACKWARD);
m3->run(RELEASE);

m4->setSpeed(0);
m4->run(FORWARD);
m4->run(BACKWARD);
m4->run(RELEASE);
}

Any advice for that?

Thank you very much.

where do you get this:

#include <Adafruit_MotorShield.h> //library fror the motorshield

I cannot find that library