Hello, i'm new in this forum. I have read all the arduino projects book from the starter kit, and now i want to do a very simple robot (with two dc motors and some sensors).
I want to create some functions to control a dc motor easily, with an H-brigde. I think i have one, but it only spins in one direction and i think the problem is on software because the same circuit go well with an example of the arduino projects book. This is the code:
librarie.h
typedef struct
{
int power; // These are the pins, i've tried to set up with a byte variable but it takes error
int spin[1];
} motor;
librarie.ino
#include "librarie.h"
// put the typedef here take me error too
void spinMotor(motor M, int v){
if(v>100){
v=100;
}
else if(v<-100){
v=-100;
}
if(v==0){
analogWrite(M.power,0);
}
else if(abs(v)==v){
digitalWrite(M.spin[0],LOW);
digitalWrite(M.spin[1],HIGH);
analogWrite(M.power, map(abs(v), 0, 100, 0, 255));
}
else if(abs(v)!=v){
digitalWrite(M.spin[0],HIGH);
digitalWrite(M.spin[1],LOW);
analogWrite(M.power, map(abs(v), 0, 100, 0, 255));
}
}
motor Motor;
void setup(){
Motor.power=9; //This pin for enable H-brigde pin
Motor.spin[0]=2; //These pins for the spin
Motor.spin[1]=3;
// Motor.spin={2,3}; this line take me error
pinMode(Motor.power,OUTPUT);
pinMode(Motor.spin[0],OUTPUT);
pinMode(Motor.spin[1],OUTPUT);
}
void loop(){
/*digitalWrite(Motor.spin[0],LOW);
digitalWrite(Motor.spin[1],HIGH);
analogWrite(Motor.power, 255);*/ //this lines comented do the same as the following command
spinMotor(Motor, 100);
delay(3000);
/*digitalWrite(Motor.spin[0],HIGH);
digitalWrite(Motor.spin[1],LOW);
analogWrite(Motor.power, 255);*/ //this lines comented do the same as the following command
spinMotor(Motor, -100);
delay(1000);
}
(I think with a logical NOT i could reduce in one pin Motor.spin)
My question is what is bad in my code, and why?
And for the others syntax errors, what is not going? (I read to change the word byte with uint8_t in the typedef or do a #define and an #undef but it doesn't go)
I don't understand very well H-bridge, in one example of arduino projects book with a bridge of 16 pins, the pin 8 went to 9 V and the pin 16 to 5V. Does the pin 16 always go to 5V? And what is the value recommended in pin 8 to optimize the speed of the motor?, does pin 1 map pin 8 value to change the speed of the motor?
Thank you very much