Blog 19

From BitWizard Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

2 Wheeled car: Arduino Version

#define Motor 0x48

#include <Wire.h> 

//Time to pause rotating
//static unsigned long Pause = 10000;
static unsigned long Speed = 40;

void setup()
{
  Wire.begin(); // wake up I2C bus
  Serial.begin(9600);
}

byte get_var(byte address, byte reg)
{
  byte value;   
  Wire.beginTransmission(address);  
  Wire.write(reg);
  Wire.endTransmission(); 
  delayMicroseconds (10);
  Wire.requestFrom(Motor, 1);
  value = Wire.read();
  return value;
} 

void set_var(byte address, byte reg, byte value)
{
  Wire.beginTransmission(address); // transmit to motor     
  delayMicroseconds  (10);
  Wire.write(reg);
  delayMicroseconds  (10);
  Wire.write(value);   
  Wire.endTransmission();    // stop transmitting
} 

void loop()
{
  unsigned long AddressA;
  unsigned long AddressB;  

  char buf[32];
  set_var(0x48, 0x21, Speed); 
  set_var(0x48, 0x31, Speed);  

  AddressA = get_var(0x48, 0x21);
  sprintf (buf, "Speed:  A:%d ", AddressA);
  Serial.write (buf); 

  AddressB = get_var(0x48, 0x31);
  sprintf (buf, " B:  %d\r\n", AddressB);
  Serial.write (buf); 
 
 delay(500);

//  delay(Pause);
}

This is the list I have made for the Raspberry Pi Version, what also counts for the Arduino version(If your car is switched to the other side this can of course be the opposite):

  • # X is forwards - Y is backwards
  • #Wheels at front
  • #20 A backwards
  • #21 A forwards
  • #22 A stop
  • #30 B backwards
  • #31 B forwards
  • #32 B stop

You can also check the motor protocol, for more info.

In my example script we go forward with 0x21 + 0x31 having the same value. For other movements you should have(If you car is flipped this can of course be the opposite!):

To go backwards:

  set_var(0x48, 0x20, Same Speed value); 
  set_var(0x48, 0x30, Same Speed value); 

To go left:

  set_var(0x48, 0x21, High Speed value); 
  set_var(0x48, 0x31, Low Speed value); 

To go right:

  set_var(0x48, 0x21, Low Speed value); 
  set_var(0x48, 0x31, High Speed value); 

To stop the car:

  set_var(0x48, 0x21, Speed value doesn't matter); 
  set_var(0x48, 0x31, Speed value doesn't matter);

To rotate to the left:

  set_var(0x48, 0x21, Same Speed value); 
  set_var(0x48, 0x30, Same Speed value); 

To rotate to the right:

  set_var(0x48, 0x20, Same Speed value); 
  set_var(0x48, 0x31, Same Speed value);

If you do this don't forget to add: static unsigned long Speed2 = "Put here your value";