Libraries

The goal

Use a library

What is a library?

Library is a "package" which provides us
with some ready-made utilities,
that therefore we don't have to implement ourselves

A library provides us with functions, but not just that(?)

N.B. the functions that we've seen to this point are contained
in libraries that are automatically included by Arduino

We can write our own libraries too

But this is a C/C++ topic

Therefore we'll just use other people's libraries today

How to import a library?

On the top of the sketch we have to type:

#import <libraryname.h>
if it's a system-wide library
#import "libraryname.h"
if it's contained in the sketch's folder

The task

We want to control a servo
with a potentiometer

What's a servo motor?

It's an actuator which provides a rotation
movement with a greater torque than speed.
Its rotation is usually limited to 180°.
When the servo reached the desired position
this one keeps it

The circuit

N.B. an inductive load such as a servo shouldn't be connected directly to a MCU
and neither be powered directly by an Arduino board

The sketch

#include <Servo.h>			// includes the servo library

int v, x;
Servo my_servo;				// creates a servo object

void setup() {
	my_servo.attach(9);		// attaches the servo to pin 9
}

void loop() {
	v = analogRead(A1);				// reads the analog value
	x =  map(v, 0, 1023, 0, 180);	// rescales the value
	my_servo.write(x);				// sets the servo position
	delay(100);						// waits a moment
}

What (is supposed to) happen?

Turning the potentiometer will make
the servo change its position