Published on

Level 7 (C++ and Motor Encoder)

Table of Contents

Pre Requisites

  • Pointers
  • Functions
  • Scope of variables
  • Fundamentals of Arduino

A BRIEF OUTLINE

  • Structures and Classes
  • Inheritance
  • Interrupts
  • Stepper
  • Encoders

Structures

  • A collection of objects with heterogeneous data types.
  • Convenient tool for handling logically related data items.
// format
struct tag_name{
    <type> member1;
    <type> member2;
        . . .
        . . .
};  // Always put semicolon don't forget!

// Use struct keyword for creating a structure
struct Book{
    char *title;
    char *author;
    int totalPages;
    float prices;
};

*Syntax is expressed through convention. <> : have relevant placeholders, eg: <type>

Reference: https://www.geeksforgeeks.org/structures-c/

Accesing Members

  • All members of structure can be accessed by '.' member access operator.
  • Two variables of same structure type can be copied the same way as ordinary variables.
  • Cannot perform logical operations on structure variables.
struct Person{
    char *nickName;
    float age;
};

// Declaring struct Person var
struct Person p1;

// <struct var>.<member>
p1.nickName = "CyberPunk";
p1.age = 0.2;

*Syntax is expressed through convention. <>: have relevant placeholders, eg: < struct var > You can tinker with this example : Tinkercad

HW :- Is there a way to have a function as a member of a structure?

Object Oriented Programming

  • In this we assume a real world entity as a set of features and these features are represented using data types and functions. We define them under something called as a class.
  • In formal sense, OOP is a type of programming in which we define type of data structures and also types of operations that can be applied to data structure.

Reference: https://www.geeksforgeeks.org/c-classes-and-objects/

Classes

  • Classes are a form of containerization of data. The idea behind classes is to abstract and encapsulate data and show the user only the information relevant to them.
  • Classes are the template and objects are individual entities from the same template.

Consider an analogy - A car is a class and there are several different cars of different brands, Example - Honda civic, Swift desire.

// Use class keyword to create a class
class Car{

    // Access specifier
    private:
    // Data members
        int locX;
        int locY;
        float speed;

    // Member functions
        void getSpeed(){
            // Some defination
        }
}; // Always put semicolon, don't forget!

This is an example on how to create a class-

  • When we define class only specifications of an object are defined and no memory is allocated.
  • Member functions of class are called methods.
  • By default access specifier to members is private and can be accessed only through methods.

You can tinker with this example : TinkerCAD

HW - Find the differences between Structures and Classes.

Class Methods

  • Methods are used to achieve data abstraction and encapsulation.
  • Methods are just like any other functions except that they are used with class.
  • They define the properties and behaviour of objects in a Class.
class Point{
    // By default private
        int x;
        int y;

    int getX(){
        return x;
    }
    int getY(){
        return y;
    }
};

Since x and y are private, the only way you can get the values stored in x, y is by using methods getX() and getY().

Constructors

  • A constructor is a special class method.
  • A constructor initializes the initial values for the object's attributes.
  • Constructors are just like any other class methods but it cannot return a value.
  • You'll learn more about "this" keyword in the next slide.
class Point{

    // By default private
    int x;
    int y;

    public:
    // Constructor
    Point(int x,int y){
        this->x = x;
        this->y = y;
    }

    int getX(){
        return this->x;
    }

    int getY(){
        return this->y;
    }
};

Objects

  • Objects are like variables of data type class. We can use attributes of class with the help of
  • member access operator '.'
  • Objects are also called an instance of a class.
  • "this" keyword refers to the current instance of the class. (Can think of it as a pointer).
  • In order to access a member using this keyword, we need to use the arrow operator '->'.
  • An object is initialized in a similar fashion as variables.
class Point{

    // By default private
    int x;
    int y;

    public:
    // Constructor
    Point(int x,int y){
        this->x = x;
        this->y = y;
    }

    int getX(){
        return this->x;
    }

    int getY(){
        return this->y;
    }
};

// Creating an object
Point p1(10,20);
int myCoordinateX = p1.getX();
int myCoordinateY = p1.getY();

In the above example, we create an instance of a class Point as p1 by passing the necessary arguments in the constructor.

Inheritance

The capability of a class to derive properties and characteristics from another class is called Inheritance.

  • Child Class/Sub Class :- The class that inherits properties from another class.

  • Parent Class/Super Class :- The class whose properties are inherited by subclass.

Inheritance
  • The visibility mode specifies whether the features of the base class are publicly inherited or privately inherited.

  • Default mode of visibility is private. The private members of the base class are never inherited.

  • In the given example - Dog inherits properties from Animal class.

// Syntax for derived class from base class
class <sub class> : <visibility> <base class>

// Example -
class Animal{
    public:
    void eat(){
        // Some defination
    }
};

class Dog : public Animal{
    public:
    void bark(){
        // Some defination
    }
};

Dog d1; // Can access eat() too now

Types of Inheritance :-

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hybrid Inheritance
  • Hierarchial Inheritance

Interrupts

  • An interrupt is a signal that tells the processor to immediately stop what it is doing and handle some high priority processing.
  • That high priority processing is called an Interrupt Service routine (ISR).
//syntax

attachInterrupt(<InterruptPin>,<ISR>,<Mode>);

// <InterruptPinNo> = digitalPinToInterrupt(pin);

*Syntax is expressed through convention. <> : have relevant placeholders, eg: <type>

Reference: https://youtu.be/9VZUb5cMrV0

Interrupt Service Routine

  • ISRs are special kinds of functions.
  • An ISR cannot have any parameters and they shouldn't return anything.
  • They should as short and fast as possible.
  • Typically volatile global variables are used to pass data between an ISR and the main program.
const int LED = 13;
const int InterruptPin = 2;
volatile int state = LOW;

void setup(){
    // Pin Configuration
    pinMode(LED,OUTPUT);
    pinMode(InterruptPin,INPUT_PULLUP);

    attachInterrupt(digitalPinToInterrupt(InterruptPin),blink,RISING);
}

void loop(){
    digitalWrite(LED,state);
}

void blink(){
    state = !state;
}

HW - In the given example, If you connect pushbutton in INPUT_PULLUP Mode, What will happen when you press it?

Stepper Motors

A stepper motor is an electric motor whose main feature is that its shaft rotates by performing steps, that is, by moving by a fixed amount of degrees. This feature is obtained thanks to the internal structure of the motor, and allows to know the exact angular position of the shaft by simply counting how may steps have been performed, with no need for a sensor. This feature also makes it fit for a wide range of applications.

Video on how to use a stepper motor

Stepper Motor Working Principles

  • Stationary part (the stator)
  • Moving part (the rotor).

On the stator, there are teeth on which coils are wired, while the rotor is either a permanent magnet or a variable reluctance iron core.

Figure 1 shows a drawing representing the section of the motor is shown, where the rotor is a variable-reluctance iron core.

Inheritance

The basic working principle of the stepper motor is the following: By energizing one or more of the stator phases, a magnetic field is generated by the current flowing in the coil and the rotor aligns with this field. By supplying different phases in sequence, the rotor can be rotated by a specific amount to reach the desired final position. At the beginning, coil A is energized and the rotor is aligned with the magnetic field it produces. When coil B is energized, the rotor rotates clockwise by 60° to align with the new magnetic field. The same happens when coil C is energized. In the pictures, the colors of the stator teeth indicate the direction of the magnetic field generated by the stator winding.

Stepper Working

Stepper Motor Driver Types

There are different stepper motor drivers available on the market, which showcase different features for specific applications. The most important characteristics include the input interface. The most common options are:

  • Step/Direction - By sending a pulse on the Step pin, the driver changes its output such that the motor will perform a step, the direction of which is determined by the level on the Direction pin.
  • Phase/Enable - For each stator winding phase, Phase determines the current direction and triggers Enable if the phase is energized.
  • PWM - Directly controls the gate signals of the low-side and high-side FETs.

Another important feature of a stepper motor driver is if it is only able to control the voltage across the winding, or also the current flowing through it:

  • With voltage control, the driver only regulates the voltage across the winding. The torque developed and the speed with which the steps are executed only depend on motor and load characteristics.
  • Current control regulate the current flowing through the active coil in order to have better control over the torque produced, and thus the dynamic behavior of the whole system.

Stepper Motor Driving Techniques

Video on operational modes

In wave mode or full step mode, only one phase at a time is energized (see Figure11).

Full Step Mode

In half-step mode,

  • Two phases are always energized at the same time.
  • With this mode, the motor is able to produce a higher torque since more current is flowing in the motor and a stronger magnetic field is generated.
Half Step Mode

Microstepping,

  • Allows to reduce even further the step size and to have a constant torque output.
  • This is achieved by controlling the intensity of the current flowing in each phase.
  • Helps reaching very high position resolution
  • More complicated to control the motor, and a smaller torque generated with each step (the torque is proportional to the sine of the angle between the stator magnetic field and the rotor magnetic field)
  • therefore, when the steps are smaller, the torque is smaller. This may lead to missing some steps, meaning the rotor position does not change even if the current in the stator winding has.
Illustration

'##' / Encoders

What is an encoder?

Simply put, an encoder is a sensing device that provides feedback. Encoders convert motion to an electrical signal that can be read by some type of control device in a motion control system, such as a counter or PLC. The encoder sends a feedback signal that can be used to determine position, count, speed, or direction. A control device can use this information to send a command for a particular function.

How does an encoder work?

Encoders use different types of technologies to create a signal, including: mechanical, magnetic, resistive and optical - optical being the most common. In optical sensing, the encoder provides feedback based on the interruption of light. The graphic at right outlines the basic construction of an incremental rotary encoder using optical technology. A beam of light emitted from an LED passes through the Code Disk, which is patterned with opaque lines (much like the spokes on a bike wheel). As the encoder shaft rotates, the light beam from the LED is interrupted by the opaque lines on the Code Disk before being picked up by the Photodetector Assembly. This produces a pulse signal: light = on; no light = off. The signal is sent to the counter or controller, which will then send the signal to produce the desired function.

Encoder

Encoders use different types of technologies to create a signal. Some common encoder technologies are mechanical, magnetic, resistive, and optical. We can use encoders to either drive a dc motor with way more precision, use in linear actuators, or just use it as a potentiometer. There are two types of encoders classified based on their response to motion:

  • Linear encoder (commonly used in mills)
  • Rotary encoder (used in motors)
Encoder1 Encoder2

Encoders are also classified based on differences in measurements: · Incremental · Absolute

We are taking rotary encoders into consideration.

  • Rotary incremental encoders have equally spaced uniform slots, they work by generating pulses during movement. There is a stationary pickup device minted nearby which picks up pulses so generated and passed through slots to give the relative angular position of the disc. They generally output square waves in two channels that differ from each other by 90 degrees. They help in determining whether it is rotating clockwise or counterclockwise.

  • Rotary absolute encoders also have a stationary pickup but have different slots at each angular position of the encoder disc, therefore, giving out absolute position, for this reason, encoders don't lose track of positioning when there is no power. They are either single-turn or multi-turn. Single turn encoders are useful for short distances, which is opposite for multi-turn.

Rotary Absolute Encoder

Pinout for Encoder in TinkerCAD

Encoder PinoutEncoder Pinout Footer

Using DC Motor with Encoder in TinkerCAD

DC motor with Encoder

FOR MORE INFORMATION ON ENCODERS: How to code for an encoder Motor? The link to the above video's website. Here is another good explanation.

Assignment

Simulate on TinkerCad - A circuit with a DC motor with an encoder, whose RPM can be controlled by potentiometer. It should display RPM of the motor on serial monitor at every interval of 100 ms. Assume that the motor is connected to a wheel. Also use a push button to display the distance travelled by this wheel from time when you start simulation of the code, till the point when the button is pressed. Specifications - MAX RPM - 60 rpm (not accurate) Radius of wheel - 10 cm Use 12V to run the motor -->