<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Techniques &#8211; chillibasket</title>
	<atom:link href="https://wired.chillibasket.com/category/techniques/feed/" rel="self" type="application/rss+xml" />
	<link>https://wired.chillibasket.com</link>
	<description>A Robotics and Technology Blog</description>
	<lastBuildDate>Thu, 18 Jun 2020 18:46:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://wired.chillibasket.com/wp-content/uploads/2015/03/4e9d6895b4e9e70456edbdb2b46312aa1-550c5afcv1_site_icon-32x32.png</url>
	<title>Techniques &#8211; chillibasket</title>
	<link>https://wired.chillibasket.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Servo Trajectory Controller for Arduino</title>
		<link>https://wired.chillibasket.com/2020/05/servo-trajectory/</link>
					<comments>https://wired.chillibasket.com/2020/05/servo-trajectory/#comments</comments>
		
		<dc:creator><![CDATA[Simon Bluett]]></dc:creator>
		<pubDate>Tue, 19 May 2020 17:06:17 +0000</pubDate>
				<category><![CDATA[Robotics]]></category>
		<category><![CDATA[Techniques]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Dynamics]]></category>
		<category><![CDATA[Servo]]></category>
		<category><![CDATA[Velocity]]></category>
		<guid isPermaLink="false">https://wired.chillibasket.com/?p=1188</guid>

					<description><![CDATA[Servo motors are used in almost all hobby robotics projects, as they allow you to control the position of joints without too much effort. Using the core &#8220;Servo&#8221; library which comes with Arduino, it is easy to command the motor to move to a specific position/angle. However, controlling the speed and acceleration of the movement [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Servo motors are used in almost all hobby robotics projects, as they allow you to control the position of joints without too much effort. Using the core &#8220;Servo&#8221; library which comes with Arduino, it is easy to command the motor to move to a specific position/angle. However, controlling the speed and acceleration of the movement is a bit more difficult. In this post, I describe how servo motors work, and different ways in which they can be controlled. To make it easier to precisely control the motion of servo motors, I have created a &#8220;Trajectory&#8221; library which can be used in conjunction with the &#8220;Servo&#8221; library to control the motion of servo motors. A full description of how to use this controller is included in this post, along with an example sketch to show how it can be used in practice. The full library and example sketch can be downloaded from <a href="https://github.com/chillibasket/arduino-classes/tree/master/servo-trajectory">my GitHub page</a>.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>Contents:</strong></p>



<ol class="wp-block-list"><li><a href="#servos-work">How do Servo Motors Work?</a></li><li><a href="#controlling-servos">Controlling Hobby Servo Motors</a></li><li><a href="#using-controller">Using my Trajectory Controller</a></li><li><a href="#example-sketch">Example Sketch</a></li><li><a href="#timing">Timing</a></li></ol>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="624" src="https://wired.chillibasket.com/wp-content/uploads/2020/05/servo-motors-1024x624.jpg" alt="" class="wp-image-1202" srcset="https://wired.chillibasket.com/wp-content/uploads/2020/05/servo-motors-1024x624.jpg 1024w, https://wired.chillibasket.com/wp-content/uploads/2020/05/servo-motors-300x183.jpg 300w, https://wired.chillibasket.com/wp-content/uploads/2020/05/servo-motors-768x468.jpg 768w, https://wired.chillibasket.com/wp-content/uploads/2020/05/servo-motors.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div style="height:80px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading" id="servos-work">1. How do Servo Motors Work?</h2>



<p class="wp-block-paragraph">A servo motor is any type of actuator which uses sensor feedback to control the position, velocity or acceleration of the output. This type of system is commonly used in industrial automation, and there are a wide variety of different sensors, motors and control algorithms to choose from. However, in hobby electronics the term &#8220;<em>servo motor</em>&#8221; usually refers to a specific type of motor commonly used in small robots and radio-controlled vehicles. The image above shows what these types of motor look like; a regular servo motor and a <em>micro</em> servo motor are shown.</p>



<p class="wp-block-paragraph">Hobby servo motors usually consist of a small DC motor, a gearbox, a controller chip and a potentiometer (rotary variable resistor) connected directly to the output shaft. As the output shaft turns, the resistance of the potentiometer changes which allows the controller to determine how far the motor has moved. When you send a new position command to the servo motor (usually in the form of a PWM signal), the controller moves the motor until the error between the target position and the current position is zero. </p>



<p class="wp-block-paragraph">Most servo motors can only turn up to 180°. This limitation is caused by the potentiometer within the servo, which cannot rotate much more than this without breaking. It is possible to buy &#8220;continuous rotation&#8221; servo motors, but these aren&#8217;t quite the same; the name is actually a bit misleading. In continuous rotation servo motors, the potentiometer is removed so that the output shaft can rotate more than 180°. However, this also removes the motor&#8217;s ability to figure out how far it has turned. It therefore acts more like a normal DC motor with a speed controller (h-bridge), and shouldn&#8217;t actually be called &#8220;servo&#8221; since it isn&#8217;t using any sensor feedback to control its position.</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><a href="https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components.jpg"><img decoding="async" src="https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components-1024x619.jpg" alt="" class="wp-image-1203" width="512" height="310" srcset="https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components-1024x619.jpg 1024w, https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components-300x181.jpg 300w, https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components-768x464.jpg 768w, https://wired.chillibasket.com/wp-content/uploads/2020/05/micro-servo_components.jpg 1200w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure></div>



<div style="height:80px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading" id="controlling-servos">2. Controlling Hobby Servo Motors</h2>



<p class="wp-block-paragraph">When you send a new position command to the servo motor, it quickly jumps to the target position at maximum speed (see <strong>Example 1</strong>). While this is very simple to program, it is only useful in a small number of applications where the speed of the motion doesn&#8217;t matter. For example, if you are trying to control a humanoid robot, you want to joints to move slowly and smoothly, rather than creating a robot which wildly flails its arms around! To get around this limitation, most programs split the movement down into small steps, which get sent to the servo motor individually over time. This is how the standard &#8220;Sweep&#8221; servo example sketch works (see <strong>Example 2</strong>). The code splits the movement into smaller but equal steps, making the servo move at a constant slower speed.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>Example 1:</strong> Raw servo commands</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<pre class="wp-block-code language-arduino"><code class="" data-line="">// Include servo library
#include &lt;Servo.h&gt;
Servo myservo;

void setup() {
    myservo.attach(9);
}

void loop() {
    // Move to 180°
    myservo.write(180);  
    delay(2700);

    // Move back to 0°
    myservo.write(0);
    delay(2700);
}</code></pre>
</div>



<div class="wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-large"><img decoding="async" width="500" height="475" src="https://wired.chillibasket.com/wp-content/uploads/2020/05/servo_example_1.gif" alt="" class="wp-image-1233"/></figure>
</div>
</div>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>Example 2:</strong> Sweep servo commands</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<pre class="wp-block-code language-arduino"><code class="" data-line="">#include &lt;Servo.h&gt;
Servo myservo;
int pos = 0; 

void setup() {
    myservo.attach(9);
}

void loop() {
    // Move to 180° in steps of 1°
    for (pos = 0; pos &lt;= 180; pos += 1) {
        myservo.write(pos);
        delay(15);
    }
    // Move back to 0° in steps of 1°
    for (pos = 180; pos &gt;= 0; pos -= 1) {
        myservo.write(pos);
        delay(15);
    }
}</code></pre>
</div>



<div class="wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="500" height="475" src="https://wired.chillibasket.com/wp-content/uploads/2020/05/servo_example_2.gif" alt="" class="wp-image-1234"/></figure>
</div>
</div>



<p class="wp-block-paragraph">However, when I was building my <a href="https://wired.chillibasket.com/3d-printed-wall-e/">Wall-E robot</a>, this was not quite good enough. Joints don&#8217;t usually move by just jumping suddenly to a certain velocity, and then stopping dead when the target is reached. There should be a gradual acceleration as the movement starts, and a slow deceleration as the joint approaches its target position. This motivated me to write my own Arduino class, which makes performing these types of movements simple!</p>



<div style="height:80px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading" id="using-controller">3. Using my Trajectory Controller</h2>



<p class="wp-block-paragraph">In this section, all of the different functions of the class are described individually. If you are impatient and want to see how to use it all together in practice, you can jump straight to the &#8220;<a href="#example-sketch">Example Sketch</a>&#8221; section! To download the full trajectory controller library, please visit <a href="https://github.com/chillibasket/arduino-classes/tree/master/servo-trajectory">my GitHub repository</a>.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="underline-heading wp-block-heading">a. Instantiating the Class</h3>



<p class="wp-block-paragraph">First of all, make sure that the file &#8220;trajectory.h&#8221; is contained within the same folder as the Arduino sketch you want to use the controller in. To tell the sketch that you want to use the class, you need to include it at the top of the code:</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">#include &quot;trajectory.h&quot;</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Next, the class needs to be instantiated. In this step, there are several parameters which you can provide, which determine how the controller will function. If you are happy with using some of the default values, you can omit parameters from the right side of the instantiation statement&#8230; An example of how it works is shown below. &#8220;Units&#8221; refers to the unit type used to measure the position of the system. For servo motors, this would usually be measured in degrees, but the class can actually work in any units (meters, radians, feet etc.). The &#8220;Threshold&#8221; is the difference between the current position and target position at which the controller turns off. </p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">/**
 * FORMAT: Trajectory(float maxVelocity, float acceleration, float deceleration, float threshold)
 * @param Maximum Velocity (units/second) - default = 100
 * @param Acceleration (units/second^2) - default = 50
 * @param Deceleration (units/second^2) - default = same as acceleration
 * @param Threshold (units) - default = 0.1
 */
// For example:
Trajectory servoTrajectory(20, 15, 12.5, 0.01);

// If the default threshold of 0.1 doesn&#039;t need to be changed:
Trajectory servoTrajectory(20, 15, 12.5);

// If you want the acceleration and deceleration to be the same:
Trajectory servoTrajectory(20, 15);</code></pre>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="underline-heading wp-block-heading">b. Setting a new Target</h3>



<p class="wp-block-paragraph">The class has three main ways in which it can be controlled:</p>



<p class="wp-block-paragraph"><strong>i. Position</strong> &#8211; when a new position target is provided, the system accelerates at a constant rate until a maximum velocity is reached. Then once it approaches the target, it decelerates and comes to a stop just on the target position: </p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// FORMAT: void setTargetPos(float newPosition)
// For example, move to the 180° position:
servoTrajectory.setTargetPos(180);</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>ii. Position and Time </strong>&#8211; it is also possible to provide a target position and the amount of time the system should take to reach that position. While the acceleration and deceleration stay the same, the maximum velocity is reduced so that the system takes just the right amount of time to reach the target (it took me a while to figure out the formula for that! If you are interested to see how it works, check out this <a rel="noreferrer noopener" href="https://www.desmos.com/calculator/lljhxgiwkv" target="_blank">interactive graph I made</a>). Depending on the maximum acceleration and velocity, it may not be possible for the system to reach the target position within the specified time. In these cases, the function notifies this by returning &#8220;False&#8221; rather than &#8220;True&#8221;, and it reverts to the normal position-only control.</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// FORMAT: bool setTargetPos(float newPosition, float timeSeconds)
// For example, move to 180° over 2 seconds:
bool status = servoTrajectory.setTargetPos(180, 2));
if (status) Serial.println(&quot;Command Successful&quot;);
else Serial.println(&quot;Unable to reach target within specified time&quot;);</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>iii. Velocity</strong> &#8211; Finally, it is also possible to control just the velocity of the system. This is not applicable to normal hobby servo motors which can only rotate 180°, but it can be used for continuous-rotation motors with encoders. When a new velocity value is provided, the system accelerates/decelerates at a constant rate from the initial velocity until the target speed is reached. </p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// FORMAT: void setTargetVel(float newVelocity)
// For example, set velocity to 50°/s:
servoTrajectory.setTargetVel(50);</code></pre>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="underline-heading wp-block-heading">c. Using the Output from the Controller</h3>



<p class="wp-block-paragraph">To use the controller to control the position and velocity of a servo motor, the &#8220;update&#8221; function needs to be called at regular intervals in order to recalculate all the values. This new position value then can be sent to the servo motor. The control system inside most hobby analogue servo motors updates at a frequency of 60Hz, so updating the velocity controller class at a frequency equal to or slightly higher than this will give the best results. An example of how to use the &#8220;update&#8221; function is shown below. In the example, the variable &#8220;nextTime&#8221; is used to ensure that the update function is only run once every 1/60th of a second, to achieve a frequency of 60Hz. The new angle value is obtained directly from the update function, and is then rounded to the nearest integer before being sent to the servo motor:</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">#define TIMER_FREQ 60
unsigned long nextTime = millis();

void loop() {

	// Run this code once every 16ms (~60Hz)
	if (nextTime &lt;= millis()) {
		nextTime = millis() + (1000 / TIMER_FREQ);

		// Update the controller and get the new position value
		float newAngle = servoTrajectory.update();
 
		// Send the new value to the servo motor
		myservo.write(round(newAngle));
	}
}</code></pre>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="underline-heading wp-block-heading">d. Other Functions</h3>



<p class="wp-block-paragraph"><strong>i. Current Position/Velocity: </strong>The current position and velocity of the controller can be read, along with the value of the current target. There is also a function with which the current position of the system can be changed:</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// Get the current position and velocity
float currentPosition = servoTrajectory.getPos();
float currentVelocity = servoTrajectory.getVel();

// To change the current position to 22.5°
servoTrajectory.setPos(22.5);

// To reset the position back to 0°, the input can be left empty
servoTrajectory.setPos();

// To read the current target position/velocity value
float currentTarget = servoTrajectory.getTarget();</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>ii. Update class settings: </strong>The class provides some functions with which you can read and update the current velocity, acceleration and deceleration settings of the controller:</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// For example, setting the maximum velocity to 40.5°/s,
// acceleration to 10.6°/s^2 and deceleration to 23°/s^2
servoTrajectory.setMaxVel(40.5);
servoTrajectory.setAcc(10.6);
servoTrajectory.setDec(23);

// To read the current settings for velocity, acceleration and deceleration
float maxVelocity = servoTrajectory.getMaxVel();
float acceleration = servoTrajectory.getAcc();
float deceleration = servoTrajectory.getDec();</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>iii. Reset controller:</strong> The controller uses an integrated timer which calculates the time difference since the &#8220;update&#8221; function was last called. If the controller is turned on again after the &#8220;update&#8221; function has not been used for a while, the timer needs to be reset. The reset function should be called once at the end of the &#8220;setup&#8221; function. The current position of the controller gets set back to 0 by default, but this can be changed by providing the desired position to the function:</p>



<pre class="wp-block-code language-arduino"><code class="" data-line="">// To reset the controller, resetting the current position to 0°
servoTrajectory.reset();

// To reset the controller and change the position to 22.5°
servoTrajectory.reset(22.5);

// To reset the controller, but keep the position the same as it was
servoTrajectory.reset(servoTrajectory.getPos());</code></pre>



<div style="height:80px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading" id="example-sketch">4. Example Sketch</h2>



<p class="wp-block-paragraph">I have written a small example sketch for my library, which shows how the class can be used in practice. In the example, the aim is to smoothly move a servo motor back and forth between the 20° and 180° position. The maximum velocity is set to 60°/second, the acceleration to 40°/s<sup>2</sup> and the deceleration to 34°/s<sup>2</sup>. The first two moves use the basic &#8220;setTargetPos&#8221; function to rotate the servo to the target position as quickly as possible. The last two move specify both the target position and time to the class, causing the servo to move at a slower speed. The servo position is recalculated and updated at a rate of 100Hz (once every 10 milliseconds):</p>



<pre class="wp-block-code language-arduino code-600 line-numbers"><code class="" data-line="">/* * * * * * * * * * * * * * * * * * * * * * *
 * EXAMPLE SKETCH FOR THE SERVO TRAJECTORY CONTROLLER CLASS
 *
 * Code by: Simon Bluett
 * Version: 1.2
 * Copyright (C) 2020, MIT License
 * * * * * * * * * * * * * * * * * * * * * * */


// --- Include the library ---
// Make sure that the file &quot;trajectory.h&quot; is included in 
// the same folder as the Arduino sketch
#include &quot;trajectory.h&quot;
#include &lt;Servo.h&gt;


// --- Instantiate the class ---
/**
 * If you want the acceleration and deceleration to be the same
 * FORMAT: Trajectory(max velocity, acceleration)
 */
//Trajectory servoTrajectory(60, 40);

/**
 * If the acceleration and deceleration are different
 * FORMAT: Trajectory(max velocity, acceleration, deceleration)
 */
Trajectory servoTrajectory(60, 40, 34);

/**
 * By default the dynamics controller turns off when it is within 0.1 units
 * of the target position. This threshold value can be changed in the declaration
 * FORMAT: Dynamics(max velocity, acceleration, deceleration, threshold)
 */
//Trajectory servoTrajectory(60, 40, 34, 0.05);

Servo myservo;


// --- Define global variables ---
// The controller will be updated at a rate of 100Hz
#define UPDATE_FREQUENCY 100
#define UPDATE_TIME (1000 / UPDATE_FREQUENCY)
unsigned long updateTimer = 0;
int moveNumber = 0;


/* * * * * * * * * * * * * * * * * * * * * * *
 * SETUP
 * * * * * * * * * * * * * * * * * * * * * * */
void setup() {

	Serial.begin(115200);
	Serial.println(&quot;Starting program&quot;);

	// Attaches the servo on pin 9 to the servo object
	myservo.attach(9);

	// We want the servo to start at an angle of 20°
	myservo.write(20);

	// By default the controller starts at 0, so we need to
	// set the starting angle as well
	servoTrajectory.reset(20);

	/**
	 * If we suddenly decide we want to change the maximum velocity to 30°/s,
	 * the acceleration to 15°/s^2 and deceleration to 5.3°/s^2
	 */
	//servoTrajectory.setMaxVel(30);
	//servoTrajectory.setAcc(15);
	//servoTrajectory.setDec(5.3);

	/**
	 * To read what the current velocity and acceleration settings are
	 */
	//float maxVelocity = servoTrajectory.getMaxVel();
	//float acceleration = servoTrajectory.getAcc();
	//float deceleration = servoTrajectory.getDec();
}


/* * * * * * * * * * * * * * * * * * * * * * *
 * NEW MOVEMENT COMMANDS
 * * * * * * * * * * * * * * * * * * * * * * */
void nextMove() {
	switch (moveNumber) {
		case 0:
			// First we move to the 180° position as fast as possible
			servoTrajectory.setTargetPos(180);
			break;

		case 1:
			// Then move back to 20° as fast as possible
			servoTrajectory.setTargetPos(20);
			break;

		case 2:
			// Next move to 180°, but over the course of 5 seconds
			servoTrajectory.setTargetPos(180, 5);
			break;

		case 3:
			// Finally back to 20°, taking 8.5 seconds
			servoTrajectory.setTargetPos(20, 8.5);
			break;

		default:
			// If all other moves have completed, stop the program
			Serial.println(&quot;All moves completed&quot;);
			while(1) {}
	}

	moveNumber++;
}


/* * * * * * * * * * * * * * * * * * * * * * *
 * LOOP
 * * * * * * * * * * * * * * * * * * * * * * */
void loop() {

	// Update the servo position at regular intervals
	if (updateTimer &lt;= millis()) {
		if (updateTimer &lt;= millis() - UPDATE_TIME) updateTimer = millis() + UPDATE_TIME;
		else updateTimer += UPDATE_TIME;

		// Update the controller
		float currentAngle = servoTrajectory.update();

		// Set the new servo position; the function only takes integer numbers
		myservo.write(round(currentAngle));

		/**
		 * For more precise servo control, you could use writeMicroseconds.
		 * The min and max PWM pulse widths which correspond to the 0° and 180°
		 * positions needs to be inserted for MIN_PWM and MAX_PWM.
		 */
		//myservo.writeMicroseconds(map(currentAngle, 0, 180, MIN_PWM, MAX_PWM));

		// Output the target position, along with the current position and velocity
		Serial.print(&quot;Target: &quot;);
		Serial.print(servoTrajectory.getTarget());
		Serial.print(&quot;, Angle: &quot;);
		Serial.print(servoTrajectory.getPos());
		Serial.print(&quot;, Velocity: &quot;);
		Serial.println(servoTrajectory.getVel());

		// Only once the servo has reached the desired position, complete the next move
		if (servoTrajectory.ready()) {
			nextMove();
		}
	}
}
</code></pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The output position, velocity and acceleration of the system for each of the four moves is shown in the diagram below. As you can see, the position stops and starts smoothly. This type of motion is called a &#8220;trapezoidal velocity&#8221; trajectory, which comes from the shape seen in the &#8220;Velocity&#8221; graph. You may notice the there is sudden drop in the velocity just as the system reaches the target position. This is caused by the position &#8220;threshold&#8221; defined in the class, which turns off the controller when the system comes within a certain distance of the target position (by default this is set to 0.1). </p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><a href="https://wired.chillibasket.com/wp-content/uploads/2020/05/example-dynamics.jpg"><img loading="lazy" decoding="async" src="https://wired.chillibasket.com/wp-content/uploads/2020/05/example-dynamics.jpg" alt="" class="wp-image-1237" width="541" height="616" srcset="https://wired.chillibasket.com/wp-content/uploads/2020/05/example-dynamics.jpg 721w, https://wired.chillibasket.com/wp-content/uploads/2020/05/example-dynamics-263x300.jpg 263w" sizes="auto, (max-width: 541px) 100vw, 541px" /></a></figure></div>



<div style="height:80px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading" id="timing">5. Timing</h2>



<p class="wp-block-paragraph">The class is relatively fast, making it useful for controlling systems which need a high refresh rate. The table below records the approximate times taken by a variety of micro-controllers to run the main functions of the class. The results show that using an Arduino Uno at an update rate of 100Hz, the class should be able to control up to 30 servo motors before slowing down. The Arduino Uno and Pro Mini both use the same ATmega 328P micro-processor, which explains why their speed is identical:</p>



<figure class="wp-block-table aligncenter is-style-regular"><table class="has-fixed-layout"><thead><tr><th><strong>Function</strong></th><th><strong>Arduino Uno</strong></th><th><strong>Arduino 101</strong></th><th><strong>Pro Mini</strong></th></tr></thead><tbody><tr><td>update()</td><td>0.164 ms</td><td>0.014 ms</td><td>0.164 ms</td></tr><tr><td>targetPos(x)</td><td>0.008 ms</td><td>0.002 ms</td><td>0.008 ms</td></tr><tr><td>targetPos(x,t)</td><td>0.28 ms</td><td>0.40 ms</td><td>0.28 ms</td></tr><tr><td>targetVel(v)</td><td>0.01 ms</td><td>0.005 ms</td><td>0.01 ms</td></tr></tbody></table></figure>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<div style="background:#13aff0; color:white; padding: 20px;">If you have any questions or comments, please leave a reply below:</div>
]]></content:encoded>
					
					<wfw:commentRss>https://wired.chillibasket.com/2020/05/servo-trajectory/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Batteries &#038; Micro-Controllers</title>
		<link>https://wired.chillibasket.com/2014/12/micro-controller-batteries/</link>
					<comments>https://wired.chillibasket.com/2014/12/micro-controller-batteries/#comments</comments>
		
		<dc:creator><![CDATA[Simon Bluett]]></dc:creator>
		<pubDate>Tue, 16 Dec 2014 21:12:28 +0000</pubDate>
				<category><![CDATA[Galileo]]></category>
		<category><![CDATA[Techniques]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Battery]]></category>
		<category><![CDATA[Gen2]]></category>
		<category><![CDATA[Measurement]]></category>
		<category><![CDATA[Power]]></category>
		<category><![CDATA[Voltage]]></category>
		<guid isPermaLink="false">http://wired.chillibasket.com/?p=203</guid>

					<description><![CDATA[How to connect a battery to the Arduino When working with sensitive circuits and micro-controllers, batteries can be a tricky thing to get right. It is not as simple as just buying a battery with the same voltage as what the micro-controller requires; the issue&#160;with batteries is that their voltage does&#160;not remain constant. The voltage [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-1.jpg"><img loading="lazy" decoding="async" width="1200" height="671" src="https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-1.jpg" alt="" class="wp-image-214" srcset="https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-1.jpg 1200w, https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-1-300x167.jpg 300w, https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-1-1024x572.jpg 1024w" sizes="auto, (max-width: 1200px) 100vw, 1200px" /></a><figcaption>A lithium quad-copter battery, powering a Galileo Gen2 Board</figcaption></figure></div>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading">How to connect a battery to the Arduino</h2>



<p class="wp-block-paragraph">When working with sensitive circuits and micro-controllers, batteries can be a tricky thing to get right. It is not as simple as just buying a battery with the same voltage as what the micro-controller requires; the issue&nbsp;with batteries is that their voltage does&nbsp;not remain constant. The voltage stated on the battery usually tells you the approximate voltage when it is at 50% charge. The voltage tends to be slightly higher when fully charged, and drops below this value as it is drained. Battery power level indicators work by analysing this voltage and then calculating how much power is left.</p>



<p class="wp-block-paragraph">Most Arduino compatible micro-controllers have several different ways in which they can be powered. Through the (1) USB jack, the (2) Power Jack, the (3) 5V Pin, and the (4) Vin Pin. Many Arduino&#8217;s also have a 3.3V pin, however this is only a voltage output and cannot be used to power the board. The voltage input (Vin) pin and power jack are both connected to the same power regulation circuitry, which can take in voltages between 7-12V and convert them into stable 5V used by the micro-controller. If you use the 5V pin to provide power, this regulation circuitry is bypassed and feeds the chip directly. This means that if the voltage provided to the 5V pin deviates by as little as ±0.1v, you could potentially fry the board. </p>



<p class="wp-block-paragraph">As the voltage of a battery varies with&nbsp;use, I would always connect it through the Vin pin or the power jack. This allows the power regulation circuitry to deal with any variances in the voltage and prevent the battery from frying the board. </p>



<p class="wp-block-paragraph">However, frying the board isn&#8217;t the only danger when using a battery! As the battery is drained and its voltage drops below the micro-controller&#8217;s minimum voltage requirement, a brown-out can occur. Brown-outs happen when the micro-controller partially shuts-down due to a power shortage. These usually cause the controller to restart, but they could also potentially damage the controller. Some batteries (especially LiPos) also are damaged if they are over-discharged and the voltage drops too low. This makes it important to monitor the voltage of the battery during use, so that we know when the battery level is too low and it needs to be recharged.</p>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="striped-heading wp-block-heading">Protecting your Battery from being Over-discharged</h2>



<p class="wp-block-paragraph">The best way to prevent a brown-out is to make sure that the voltage being supplied is always above the minimum required voltage for the controller. If the battery falls below this minimum voltage, the micro-controller should display a warning message, or switch itself off. A nice way of dealing with this is to make the micro-controller monitor its own power supply by using one of the analogue input pins. If the voltage of the battery is less than 5V, it can be connected directly into the analogue pin of an Arduino. Otherwise, we will have to use a potential divider circuit in order to reduce the voltage to a&nbsp;safe level.</p>



<p class="wp-block-paragraph">For my second version of the self-balancing robot, I am using a 11.1V lithium quad-copter battery to power a Galileo Gen2 Board and two 12V motors. As the voltage of the battery is greater than 5V, I used the following circuit in order to monitor the battery as it is being used:</p>



<div class="wp-block-dgwt-justified-gallery">
<a href='https://wired.chillibasket.com/3d-printed-wall-e/battery_level_circuit/'><img loading="lazy" decoding="async" width="300" height="227" src="https://wired.chillibasket.com/wp-content/uploads/2020/02/battery_level_circuit-300x227.jpg" class="attachment-medium size-medium" alt="" srcset="https://wired.chillibasket.com/wp-content/uploads/2020/02/battery_level_circuit-300x227.jpg 300w, https://wired.chillibasket.com/wp-content/uploads/2020/02/battery_level_circuit.jpg 500w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a>
<a href='https://wired.chillibasket.com/2014/12/micro-controller-batteries/testing-batteries-2/'><img loading="lazy" decoding="async" width="300" height="143" src="https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-2-300x143.jpg" class="attachment-medium size-medium" alt="" srcset="https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-2-300x143.jpg 300w, https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-2-1024x490.jpg 1024w, https://wired.chillibasket.com/wp-content/uploads/2014/12/Testing-Batteries-2.jpg 1200w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a>
</div>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">When two resistors are connected in series like this, with one end connected to a certain voltage and the other to ground, the voltage at the junction of the two resistors is determined by the ratio of the two resistances. The formula is as follows, where (Vin) is the input voltage, (R1) and (R2) the resistances of the first and second resistor, and (Vdiv) the voltage at the junction between both resistors:</p>



<div class="wp-block-katex-display-block katex-eq" data-katex-display="true">V_{div}=\frac{V_{in}R_2}{R_1+R_2}</div>



<p class="wp-block-paragraph">The ratio of the resistors should be chosen, so that the voltage at the junction (Vdiv) is below 5V when the battery is at its maximum voltage. Since the Arduino measures the lower voltage (Vdiv) at the junction of both resistors, this formula can be rearranged to calculate the voltage of the battery (Vin):</p>



<div class="wp-block-katex-display-block katex-eq" data-katex-display="true">V_{in}=V_{div}\frac{R_1+R_2}{R_2}=V_{div}\left(\frac{R_1}{R_2}+1\right)</div>



<p class="wp-block-paragraph">The code I use to monitor the battery percentage on the Arduino is shown below. The same formula is used on line 22 to calculate the actual battery voltage. For the 11.1V LiPo battery I used, the maximum voltage at full charge was 12.6V. The minimum voltage below which it should no longer be used was 10.2V.</p>



<pre class="wp-block-code line-numbers language-arduino"><code class="" data-line="">// Pin number of the analog input being used for the reading
#define ANALOG_PIN 2

// Values for the two resistors used in the potential divider
float resistorOne = 100000;
float resistorTwo = 47000;

float vRef = 5;               // Reference voltage - usually 5v or 3.3v
float maxVoltage = 12.6;      // The voltage of the battery when fully charged
float minVoltage = 10.2;      // Voltage below which battery isn&#039;t safe to use

void setup() {
    // Initialize serial communication
    Serial.begin(9600);
}

void loop() {
    // Calculate voltage at the analog pin
    float voltage = analogRead(ANALOG_PIN) * vRef / 1024.0;

    // Calculate the battery voltage
    voltage = voltage * (resistorOne / resistorTwo + 1);

    // Calculate the battery percentage
    float batteryPercentage = (voltage - minVoltage) / (maxVoltage - minVoltage) * 100;

    // Limit the percentage value to be between 0 to 100%
    if (batteryPercentage &gt; 100) batteryPercentage = 100;
    else if (batteryPercentage &lt; 0) batteryPercentage = 0;

    // Output the calculated values to the serial monitor
    Serial.print(voltage); Serial.print(&quot;V, &quot;);
    Serial.print(batteryPercentage); Serial.println(&quot;%&quot;);
    delay(1000);
}</code></pre>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">
The serial output I got from the system then&nbsp;looked like this:

</p>



<pre class="wp-block-code language-none"><code class="" data-line="">11.07V, 36%
11.29V, 45%
11.29V, 45%
11.29V, 45%</code></pre>



<p class="wp-block-paragraph">In my test, the actual voltage of the battery according to the Lithium battery charger was 11.3V, so the value recorded by the micro-controller was relatively accurate. </p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<hr>



<p class="wp-block-paragraph">Here is a quick summary of the points I discussed above:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>1. Never connect a battery directly into the 5v or 3.3v pins of the micro-controller. These inputs require the voltage to be properly regulated.</p><p>2. Always ensure that the battery is within &nbsp;the controller&#8217;s specified voltage input range. For the Arduino Uno this is 7-12V.</p><p>3. Avoid brown-outs and battery over-discharge by monitoring the voltage of the battery and switching off the system if it drops below the minimum voltage.</p><p>4. When monitoring the voltage, take caution that the voltage being measured does not exceed the reference voltage (5V). Reduce the voltage by using a potential divider circuit.</p></blockquote>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-text-color has-cyan-bluish-gray-color wp-block-paragraph"><em><strong>Updated:</strong> 24th May 2019 – Reformatted post</em> </p>



<p class="has-text-color has-cyan-bluish-gray-color wp-block-paragraph"><em><strong>Updated:</strong> 28th May 2020 – Added extra detail about the potential divider circuit</em></p>
]]></content:encoded>
					
					<wfw:commentRss>https://wired.chillibasket.com/2014/12/micro-controller-batteries/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
