Little confusing

Forums:

I have recently bought an UltraBorg and face a problem.

You have posted this piece of code on the forums a while ago.

// We need the following values here:
// * float position <- the servo position between -1 and +1
// * int UbServo1Min <- the lowest allowed value, the default is UB_DEFAULT_PWM_MIN
//                     read the tuned value using UbGetServoMinimum1
// * int UbServo1Max<- the highest allowed value, the default is UB_DEFAULT_PWM_MAX
//                     read the tuned value using UbGetServoMaximum1
 
// Work out the PWM setting from the position value
float powerOut = (position + 1.0) / 2.0;
unsigned int pwmDuty = (unsigned int)((powerOut * (UbServo1Max - UbServo1Min)) + UbServo1Min);
 
// Build the command
int length = 3;
writeBuffer[0] = UB_COMMAND_SET_PWM1;  // The command to set the position on servo #1 
writeBuffer[1] = (unsigned char)((pwmDuty >> 8) & 0xFF);
writeBuffer[2] = (unsigned char)(pwmDuty & 0xFF);
 
// Send the command
if (write(ultraBorg, writeBuffer, length) != length) {
    // Failed to send correctly !
}

So here are my confusings:
1) why do we use "(UbServo1Max - UbServo1Min) + UbServo1Min)?
2) writeBuffer[1] = (unsigned char)((pwmDuty >> 8) & 0xFF) <- what does that mean and what does that operators do?
3) writeBuffer[2] = (unsigned char)(pwmDuty & 0xFF) <- what does that mean and what does that operators do?

I hope you can help me out!

piborg's picture

The code is basically taking a position between -1.0 and +1.0 stored in the value position and converting it into a command for the UltraBorg.

  1. We use (powerOut * (UbServo1Max - UbServo1Min)) + UbServo1Min to convert from a value between 0.0 and 1.0 into values from UbServo1Min to UbServo1Max.
  2. The writeBuffer[1] line gets the upper byte which represents the value to send.
    << 8 moves the number down by 8 bits (1 byte).
    & 0xFF takes only the byte in the lowest position from the shifted down value.
  3. The writeBuffer[2] line gets the lower byte which represents the value to send.
    & 0xFF takes only the byte in the lowest position from the number.
Subscribe to Comments for &quot;Little confusing&quot;