Skip to content
Snippets Groups Projects
conversion.c 1.79 KiB

#include "conversion.h"

// takes a floating point percentage and converts to a
// receiver command in the range min_rx_cmd to max_rx_cmd
// if percentage is < 0 then returns a value less than
//		center_rx_cmd but >= min_rx_cmd
// if percentage is > 0 then returns a value greater than
//		center_rx_cmd but <= max_rx_cmd
// if percentage is = 0 then returns center_rx_cmd
// acceptable range of values for percentage: [-100, 100]
int map_to_rx_cmd(float percentage, int min_rx_cmd, int center_rx_cmd,
	int max_rx_cmd)
{
	//bounds checking
	// imagine a human flying and the stick is minimum
	if(percentage >= 100.0)
		return max_rx_cmd;

	//bounds checking
	// imagine a human flying and the stick is minimum
	if(percentage <= -100.0)
		return min_rx_cmd;

	// 0 percentage is center cmd
	// imagine a human flying and not touching the stick
	if(percentage == 0)
		return center_rx_cmd;

	// calculate and return a percentage of the max/min command
	if(percentage < 0)
	{
		return center_rx_cmd + ((int) (percentage/100.0 *
				((float) max_rx_cmd - center_rx_cmd)));
	}
	else
	{
		return center_rx_cmd + ((int) (percentage/100.0 * (
				(float) center_rx_cmd - min_rx_cmd)));
	}

	return 0;
}

int convert_to_receiver_cmd(int var_to_convert, float max_var_to_convert, float min_var_to_convert, int center_receiver_cmd,  int max_receiver_cmd, int min_receiver_cmd)
{

	if(var_to_convert <= 0) {
		int ret = ((int) ((float)(min_receiver_cmd - center_receiver_cmd))/min_var_to_convert * var_to_convert) + center_receiver_cmd;

		if(ret < min_receiver_cmd)
			ret = min_receiver_cmd;

		return ret;
	}

	else {
		int ret = ((int) ((float)(max_receiver_cmd - center_receiver_cmd))/max_var_to_convert * var_to_convert) + center_receiver_cmd;

		if(ret > max_receiver_cmd)
			ret = max_receiver_cmd;

		return ret;
	}

	return 0;
}