Arduino Robot - R04 Compass

Hello

I have modified the sketch R04 Compass for the Arduino Robot to use with the motors in reverse and to head in the direction read when switching on. However, no matter which direction I place the AR or where I place the AR (magnetics etc), it will always head off about 10-20 degrees left of the direction I place it in. The code is pretty short and simple and I cant see the problem. Probably me being simple. Can anyone spot any potential issues please.

Thanks

Rob

straightFuncTest.ino (1.26 KB)

The code is pretty short

So, why did you post it as an attachment? Post the code here, using code tags.

My apologies

#include <ArduinoRobot.h>
#include <Wire.h>
#include <SPI.h>
#include <NewPing.h>
#define LRUS  TKD2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define MAX_DISTANCE 200
NewPing sonar4(LRUS, LRUS, MAX_DISTANCE); // NewPing setup of pin and maximum distance.

void setup() 
{
  Robot.begin();
  Robot.beginTFT();
  delay(500);
}

void straightFunc()
{
  int speedLeft;
  int speedRight;
  int compassValue;
  int direc = Robot.compassRead();
  Robot.debugPrint(direc);
  delay(2000);
  int rear;
  
  //while(dist1 < rear)
  while(1)
  {
    //rear = sonar4.ping() / US_ROUNDTRIP_CM;
    
    compassValue = Robot.compassRead();
    delay(50);
    Robot.debugPrint(compassValue);
  
    int diff = compassValue - direc;
    if (diff > 180)
      diff = -360 + diff;
    else if (diff < -180)
      diff = 360 + diff;
  
    //Rescale value
    diff = map(diff, -180, 180, -255, 255);
    
    if (diff > 0) //positive diff, need to turn left
    {
      speedRight = -90 + diff;
      speedLeft = -90;
    } 
    else 0//negative diff, need to turn right
    {
      speedRight = -90;
      speedLeft = -90 - diff;
    }
    Robot.motorsWrite(speedLeft, speedRight);
  }
  return;
}
void loop() 
{
  //int dist = 10;
  straightFunc();
  Robot.motorsStop();
}

It's hard to say what might be wrong without seeing the debug output.

I don't understand why, if the actual angle is wrong, you map the deviation from the range -180 to 180 to the range -255 to 255, and then add or subtract that to/from 90.

Since the motors are continuous rotation servos, the usual range of values to make them move is from 0 to 180 (0 being as fast as possible one way, 90 being stopped, and 180 being as fast as possible the other way). So, why is the to range -255 to 255?

Hello Paul

The motor drive function is prewritten for the Arduino Robot and accepts arguments from 0-255 forward and -(0-255) for reverse, that is why map() is rescaling the difference to the 8 bit scale.
The code shown was written by someone else and is shown as an example sketch in the IDE, I have only modified it so that it works with the motors in reverse and I have also made the direc a variable instead of it being preset to 180.
Thank you for having a look at the code, I was hoping it might be something glaring as I am not a seasoned coder.