Wednesday, September 8, 2021

Reverse Engineering Tips and Tricks: A "Where to Start" Guide

Reverse engineering is one of the most important skills a hardware engineer can have, and not just for repair purposes but also for designing upgraded hardware and obsolete legacy equipment. I still remember how reverse engineering my C64 computer taught me so much on computer architecture and bus interfacing. So, here are some simple tips might help you when reverse engineering any board for repair or design purposes: 

 First: The Tools 

 - Have all your tools next to you: screw drivers, pry tool kit, pliers and tweezers, magnifier, benchtop lights and anything else you might need. 

- Make sure to keep an assortment of jumper wires and connectors such as alligator clips, board-to-board jumper wires, test leads, oscilloscope probes with retractable hook tip, needle-tipped multimeter probes, and any other wires. 

- Digital inspection microscope has become an important tool for reverse engineer a surface-mount boards. An inexpensive one will do the job. 

- If you are into computer interfaces such as USB, RS-232, Ethernet…etc, then a packet sniffer will be quite handy. 

- An oscilloscope + logic analyzer can make your life easier, even if it is just a simple 2-channel oscilloscope. 

- The multimeter continuity tester is your best friend, keep it handy. 

- A notebook and a pen to take notes. 

- Optional: a digital camera (or your phone) to record the process and take notes. 

Second: Where to Start 

Before powering on the board 

- Identify the power supply section of the board, it will facilitate tracing the power supply of each chip onboard. 

- Find the ground plane(s) and any ground traces/test points. 

After powering on the board: 

- Find the power rails on the PCB and take a note of the voltage levels. 

Third: Going deeper 

- Identify the connectors on the board and their pinout, especially standard or well-known ones such as the DB9, BNC, SMA, DIN,…etc. Even discrete pin headers are good to identify and figure out their pinout. 

- Look up the datasheets and application notes of all the parts populated on the PCB. The datasheets will tell you the functionality, the application note will give more details on the different design configurations of the component of interest. 

- Make sure to read the reference designator correctly. - Codes on surface-mount passive component are the key to know the value of each part. 

Now you are ready to reverse-engineer the board and understand how it works.

Thursday, October 11, 2018

List of current and future jobs to be impacted by current trends in robotics and automation

Few days ago my wife and I were talking about how automation will impact us and people in our age group, but not necessarily the next generation, and how it will reshape the society we live in over the next 10 or 20 years, and who will be impacted, whether good or bad, more than the others, so I decided to convert our conversation into a compilation of automation technologies introduced to different market segments and jobs:
-         The most famous trend in automation these days is the self-driving vehicles”, almost every automotive manufacturer, plus a handful of tech giants and start-ups are developing self-driving vehicles. And though the experimentation was on small commercial vehicles that can transport 2-4 people, now the development expanded to trucks and mass transportation vehicles like buses and trains. So imagine in the next 5-10 years the following jobs will be impacted: cab drivers, personal drivers (chauffeurs), truck drivers and train operators. A very famous example is Vancouver’s Skytrain, a fully-automated, driverless train system operating since 1986. So transit automation isn’t something new, just it’s trending now with the advances in different technology like AI, computing hardware and sensing technologies.
-         Another job that started to disappear is “cashier”, already many grocery stores around the world started to have “self-checking” kiosks with minimal staff to support its operation.
-         Another field automation and robots are coming for is construction, few days ago Japan’s Advanced Industrial Science and Technology released a video footage of a humanoid robot installing a “drywall”. Also, many of us have watched the giant home-building 3D printer capable of building a small home in 24 hours, so the next wave in automation might hit “construction workers”.
-         With the evolution of optical characters recognition algorithms jobs like “data entry” will disappear in the near future, and a famous example is depositing cheques through banks ATM machines to individuals’ accounts by scanning and recognizing the bank account numbers from the cheque.
-         Policing and law enforcement, and I know it sounds too much like sci-fi, but Dubai announced in 2017 that it will start using robots for police patrolling in some areas. Already drones have been used by the police forces to patrol and roam around roads and highways for few years now. And think about it, it makes a lot of sense and seems realistic, and it will eliminate some of the dangers police personnel face every day in the field.
-         Defence and military, origins of automation can be traced easily to the military, the first attempt was in 1915 during the WWI when engineers tried to build a “flying bomb” (term borrowed from Wikipedia) using a small, single engine plane and a gyroscope for navigation. Then Nazi scientists came up with a more advanced version in the WWII they called Vergeltungswaffe-1, or shortly V-1 (a cousin to the infamous V-2 rocket, the grandparent of ICBMs), and race for automation in military never stopped since then, with more advanced drones, inter-continent missiles, ground, naval and airborne reconnaissance drones and vehicles, satellites (most of them are full automated), a very long list of applications that have been roboticized, last but not least Texas police in 2016 used a “killer robot” to terminate a suspect of killing 5 police officers after a standoff. So, imagine with me future wars with less boots on the ground and armies of robots. I won’t be surprised if it reminded you of the “Terminator” entry scene.
-         In “Medicine”, and bear with me. This area is still at a very early stage but showed promising results. With its ability to scan and compare massive amounts of data, AI showed the capability to discover cancer traces in a patient MRI scan, this year a team from France, Germany and the US developed an AI system was able to detect cancerous moles with accuracy of 95%, so imagine doctors and lab technicians won’t need to go through the different scans anymore, where an AI powered system might take over this task. Robot-assisted surgery already exists since the early 2000’s, with the power of AI, surgical robots might be capable of operating autonomously with minimal supervision, opening the door to another field for automation to invade.
-         Space and Astronomy, whenever the word “space exploration” comes up most of us imagine a guy looking at the stars through one of these giant optical telescopes, and that was true till the early 20th century, which changed completely after the invention of radio frequency telescopes and radioactivity-based space detectors, which brought the space exploration to a whole new level, including massive amounts of data on space. In December 2017 NASA announced the discovery of Kepler-90i, the 8th planet in a sun-like solar system that is 2545 light-years away from us, using an AI system designed by Google. That opens the door to replace scientists and researchers for tasks like scanning the skies and developing conclusions about different celestial objects.
-         Servicing in food industry (waiters and chefs), automated restaurants in Japan replaced waiters with touch-displays for ordering and conveyor-belt system for delivery. Dominos’ pizza started delivering pizza using a self-driving car in Nevada. And last but not least, Moley, a London based tech company, developed a “Robotic Chef”, a robot that can be programmed to cook anything and everything without any human assistance or supervision. So, the day where you gonna email or message your favourite meal or request to your home robot-chef to cook dinner for you isn’t far away.
-         Nuclear waste handling, one of the most dangerous jobs on the planet where robots proved they can do perfectly, robots have been used extensively in Fukushima nuclear disaster site to pick up nuclear waste and perform measurements in the vicinity of nuclear reactor core where it’s extremely dangerous to send humans.
And the list will go on for various jobs and tasks that will be lost to automation and robots in the next few years. So, let me stop here and leave the rest for you. Sources and supporting materials are listed in the first comment. And my apologizes for any grammatical mistakes.

Update (as of February 2020):
-        Epidemics and diseases outbreak prediction: epidemiology is the latest field AI has gotten into and proved to be successful & useful. One of the early alarms on the outbreak of the SARS-CoV-2 Coronavirus disease 2019 (COVID-19) came from BlueDot, a Toronto-based startup that uses AI to develop "infectious disease surveillance" tools. One of their algorithms was tracked the virus spread and issued an alert to the public by scavenging foreign news reports, airlines ticketing data and different online resources on animal and plant diseases. The BlueDot algorithm sent the first alert for the coronavirus spreading in late December 2019, at least one week before WHO announced that coronavirus has become a global health concern.

Sources and supporting material:
-         History of Skytrain:
https://www.translink.ca/About-Us/Corporate-Overview/Operating-Companies/BCRTC/History-of-SkyTrain.aspx
-         Tesla Self-Driving Demonstration:
https://www.tesla.com/en_CA/videos/autopilot-self-driving-hardware-neighborhood-long
-         This Japanese robot contractor can install drywall: https://www.theverge.com/2018/10/1/17923442/aist-japan-humanoid-robot-drywall-hrp-5p-construction
-         3D Printed House Took 24 Hours To Build:
https://www.youtube.com/watch?v=GUdnrtnjT5Q
-         Meet The Terrifying New Robot Cop That's Patrolling Dubai: https://www.forbes.com/sites/susannahbreslin/2017/06/03/robot-cop-dubai/#463087b66872
-         11 Police Robots Patrolling Around the World:
https://www.wired.com/2016/07/11-police-robots-patrolling-around-world/
-         Police used a robot to kill - The keyquestions: https://www.cnn.com/2016/07/09/opinions/dallas-robot-questions-singer/index.html
-         The U.S. Army Is Turning to Robot Soldiers:
https://www.bloomberg.com/news/articles/2018-05-18/the-u-s-army-is-turning-to-robot-soldiers
-         AI cancer detectors:
https://www.theguardian.com/technology/2018/jun/10/artificial-intelligence-cancer-detectors-the-five
-         How AI-Assisted Surgery Is Improving Surgical Outcomes: https://www.roboticsbusinessreview.com/health-medical/ai-assisted-surgery-improves-patient-outcomes/
-         Artificial Intelligence, NASA Data Used to Discover Eighth Planet Circling Distant Star: https://www.nasa.gov/press-release/artificial-intelligence-nasa-data-used-to-discover-eighth-planet-circling-distant-star
-         Exploring a automated sushi bar in Japan-cheeseburger sushi: https://www.youtube.com/watch?v=CuOnMlxmycw
-         Domino's Pizza tests driverless car delivery:
https://www.cbc.ca/news/technology/dominos-pizza-ford-self-driving-car-1.4266349
-         Self-Driving Pizza Delivery Car:
https://www.youtube.com/watch?v=5BEugKgdrxU
-         Robotic Chef Does All The Cooking For You:
https://www.youtube.com/watch?v=SQjXaTlGHIY
-         The Robot Assault On Fukushima:
https://www.wired.com/story/fukushima-robot-cleanup/
-         An AI Epidemiologist Sent the First Warnings of the Wuhan Virus:
https://www.wired.com/story/ai-epidemiologist-wuhan-public-health-warnings/

Monday, June 11, 2018

MCP2221 Tutorial - I2C Interfacing made easy

What is MCP2221?
MCP2221 is a USB to UART & I2C bridge integrated circuit from Microchip Technologies; I would highly recommend reading this tutorial first for further information on it.

How can the MCP2221 be beneficial to me?
Well, if you want to build a computer control and/or data acquisition unit via USB to an I2C slave device without the hustle of using a microcontroller or an Arduino, and less expensive than both of them, the MCP2221 is a good option, it acts as a master I2C device, and it can be programmed easily using its DLL from Microchip on Windows OS, or by configuring it as a USB-I2C dongle on Linux. Another advantage for the MCP2221 that it comes in a PDIP package, which makes it convenient for breadboard prototyping and testing.

What is I2C?
In brief, it is a low speed, master-slave serial communication protocol that uses two lines: data line, named SDA, and clock, named SCL. It is mainly used for sensors interfacing, low speed ADC/DAC or any similar integrated circuits. According to the I2C standard, the maximum speed is 3.2 Mbits/sec between a master and slave but the MCP2221 supports only up to 400 KHz bit rate.
For more C examples for the MCP2221, please visit this GitHub repository. 



Example Code:


#include <stdio.h>
#include "mcp2221_dll_um.h"

//Linking the MCP2221 library, only valid for Visual Studio
#pragma comment(lib, "mcp2221_dll_um_x86.lib")

#define I2cAddr7bit 1
#define I2cAddr8bit 0

//Global variables
void *handle;
wchar_t SerNum = 0x0000075428;
wchar_t LibVer[6];
wchar_t MfrDescriptor[30];
wchar_t ProdDescrip[30];
int ver = 0;
int error = 0;
int flag = 0;
unsigned int PID = 0xDD;
unsigned int VID = 0x4D8;
unsigned int NumOfDev = 0;
unsigned char PowerAttrib;
unsigned char DacVal = 31;
unsigned char SlaveAddress = 0x63;
unsigned char TxBuffer[8];
unsigned char RxBuffer[8];

//Functions prototypes
void ExitFunc();
void Mcp2221_config();

void ExitFunc()
{
    Mcp2221_CloseAll();
 Mcp2221_Reset(handle);
}

void Mcp2221_config()
{
    ver = Mcp2221_GetLibraryVersion(LibVer);  //Get DLL version
    if(ver == 0)
    {
        printf("Library (DLL) version: %ls\n", LibVer);
    }
    else
    {
        error = Mcp2221_GetLastError();
        printf("Version can't be found, version: %d, error: %d\n", ver, error);
    }

    //Get number of connected devices with this VID & PID
    Mcp2221_GetConnectedDevices(VID, PID, &NumOfDev);
    if(NumOfDev == 0)
    {
        printf("No MCP2221 devices connected\n");
        //exit(0);
    }
    else
    {
        printf("Number of devices found: %d\n", NumOfDev);
    }

    //open device by S/N
    //handle = Mcp2221_OpenBySN(VID, PID, &SerNum);

    //Open device by index
    handle = Mcp2221_OpenByIndex(VID, PID, NumOfDev-1);
    if(error == NULL)
    {
        printf("Connection successful\n");       
    }
    else
    {
        error = Mcp2221_GetLastError();
        printf("Error message is %s\n", error);
    }

    //Get manufacturer descriptor
    flag = Mcp2221_GetManufacturerDescriptor(handle, MfrDescriptor);
    if(flag == 0)
    {
        printf("Manufacturer descriptor: %ls\n", MfrDescriptor);

    }
    else
    {
        printf("Error getting descriptor: %d\n", flag);
    }

    //Get product descriptor
    flag = Mcp2221_GetProductDescriptor(handle, ProdDescrip);
    if(flag == 0)
    {
        printf("Product descriptor: %ls\n", ProdDescrip);        
    }
    else
    {
        printf("Error getting product descriptor: %d\n", flag);        
    }

    //Get power attributes
    flag = Mcp2221_GetUsbPowerAttributes(handle, &PowerAttrib, &ReqCurrent);
    if(flag == 0)
    {
        printf("Power Attributes, %x\nRequested current units = %d\nRequested current(mA) = %d\n", PowerAttrib, ReqCurrent, ReqCurrent*2);
    }
    else
    {
        printf("Error getting power attributes: %d\n", flag);      
    }

    //Set I2C bus
    flag = Mcp2221_SetSpeed(handle, 500000);    //set I2C speed to 400 KHz
    if(flag == 0)
    {
        printf("I2C is configured\n");        
    }
    else
    {
        printf("Error setting I2C bus: %d\n", flag);        
    }

    //Set I2C advanced parameters
    flag = Mcp2221_SetAdvancedCommParams(handle, 10, 1000);  //10ms timeout, try 1000 times
    if(flag == 0)
    {
        printf("I2C advanced settings set\n");
    }
    else
    {
        printf("Error setting I2C advanced settings: %d\n", flag);      
    }
}

void main(int argc, char *argv[])
{
    atexit(ExitFunc); //Call exit function

    //Configure any connected MCP2221
    Mcp2221_config();
 
    while(1)
    {
  
  //Write all contents of TxBuffer to I2C slave device 0x63
  flag = Mcp2221_I2cWrite(handle, sizeof(TxBuffer), SlaveAddress, I2cAddr7bit, TxBuffer);    //issue start condition then address
  if(flag == 0)
  {
   printf("Writing to device %x successful\n", SlaveAddress);
  }
  else
  {
   printf("Error writing to I2C device: %x, Error: %d\n", SlaveAddress1, flag);
   Mcp2221_I2cCancelCurrentTransfer(handle);
  }
  
  //Read 8 bytes from I2C slave device 0x63
  flag = Mcp2221_I2cRead(handle, 8, SlaveAddress, I2cAddr7bit, RxBuffer);
  if(flag == 0)
  {
   printf("Data received is %x\n", RxBuffer);
  }
  else 
  {
   printf("Error receiving ack: %d\n", flag);
  } 
    }
}



Sunday, June 12, 2016

MCP2221 Tutorial - USB interfacing made easy

What is MCP2221?
MCP2221 is a USB to UART and I2C bridge IC from Microchip technologies, plus the bridge capability this chip has the following features:
4 GPIO pins, three of them can be configured to become a 10-bits Analog to Digital Converter (ADC) of a 1 KSps sampling rate, also two of these GPIO pins are multiplexed with a 5-bits Digital to Analog Converter (DAC).

Why MCP2221?
This MCP2221 is a simple and inexpensive computer/USB interface solution for computer control applications, with a very few component peripherals you can get it up and running, just a capacitor and pull-up resistor on the reset pin. It can be either bus-powered or self-powered, and it is available in PDIP package which makes it easy to prototype on a breadboard or prototyping PCB.

Development and application tools for the MCP2221:
The chip web page indicates that drivers for Windows OS, Linux, and Mac OS are available, plus a DLL library for C/C++ and .Net under Windows OS environment, other tools include Command Line Interface (CLI) and GUI-based Windows applications to control the MCP2221 I/O’s without the need to develop your own application, for more information check the IC datasheet on Microchip Technologies website here.

MCP2221 Driver:
The MCP2221 is a composite device, i.e. the device supports both HID and CDC classes, the CDC class supports the USB to UART bridge functionality and the HID class the support the USB to I2C bridge, GPIO, ADC and DAC features.  

Circuitry and connection:
VDD and VSS pins (1 and 14) are the IC power supply and ground pins respectively, pull-up (connect to VDD) the reset pin (pin 4) with a resistor (anything between 330 Ohm and 4.7 Kilo Ohms), and a 470 nF ceramic capacitor between VUSB pin (pin 11) and ground.

MCP2221 Circuit


Example applications:
DC and stepper motors control, simple monitoring applications, data input devices, interface to microcontrollers and other embedded processors, LED control.

Example code:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <conio.h>
#include <Windows.h>
#include "mcp2221_dll_um.h"

#pragma comment(lib, "mcp2221_dll_um_x86.lib")  //Link MCP2221 library, applicable for visual studio only

//Global variables
void *handle;

void ExitFunc()
{
 printf("Closing\n");
 _sleep(10);
 //Mcp2221_Reset(handle);
 
 //Close all devices at exit
 Mcp2221_CloseAll();
}
int main()
{
 wchar_t LibVer[6];
 wchar_t MfrDescriptor[30];
 wchar_t ProdDescrip[30];
 int ver = 0; 
 int error = 0;
 int flag = 0;
 unsigned char pinFunc[4] = {MCP2221_GPFUNC_IO, MCP2221_GPFUNC_IO, MCP2221_GP_DAC, MCP2221_GPFUNC_IO};  //Set GP0, GP1, GP3 as digital IO and GP2 as DAC
 unsigned char pinDir[4] = {MCP2221_GPDIR_OUTPUT, MCP2221_GPDIR_OUTPUT, NO_CHANGE, MCP2221_GPDIR_OUTPUT};  //configure GP0, GP1, GP3 as digital output
 unsigned char OutValues[4] = {0, 0, NO_CHANGE, 0};   //set initial values to 0's
 unsigned char PowerAttrib;
 unsigned char DacVal = 31;
 unsigned char DacRefValue = 0;
 unsigned int ReqCurrent;
 unsigned int PID = 0xDD;
 unsigned int VID = 0x4D8;
 unsigned int NumOfDev = 0;

 atexit(ExitFunc); //Call exit function

 ver = Mcp2221_GetLibraryVersion(LibVer);  //Get DLL version
 if(ver == 0)
  printf("Library (DLL) version: %ls\n", LibVer);
 else
 {
  error = Mcp2221_GetLastError();
  printf("Version can't be found, version: %d, error: %d\n", ver, error);
 }

 //Get number of connected devices with this VID & PID
 Mcp2221_GetConnectedDevices(VID, PID, &NumOfDev);
 if(NumOfDev == 0)
 {
  printf("No MCP2221 devices connected\n");
  exit(0);
 }
 else
  printf("Number of devices found: %d\n", NumOfDev);   

 //Open first MCP2221 device discovered by index
 handle = Mcp2221_OpenByIndex(VID, PID, NumOfDev-1); 
 error = Mcp2221_GetLastError();
 if(error == NULL)
  printf("Connection successful\n");
 else
  printf("Error message is %s\n", error);

 //Get manufacturer descriptor
 flag = Mcp2221_GetManufacturerDescriptor(handle, MfrDescriptor);
 if(flag == 0)
  printf("Manufacturer descriptor: %ls\n", MfrDescriptor);
 else
  printf("Error getting descriptor: %d\n", flag);

 //Get product descriptor
 flag = Mcp2221_GetProductDescriptor(handle, ProdDescrip);
 if(flag == 0)
  printf("Product descriptor: %ls\n", ProdDescrip);
 else
  printf("Error getting product descriptor: %d\n", flag);
  
 //Get power attributes
 flag = Mcp2221_GetUsbPowerAttributes(handle, &PowerAttrib, &ReqCurrent);
 if(flag == 0)
  printf("Power Attributes, %x\nRequested current units = %d\nRequested current(mA) = %d\n", PowerAttrib, ReqCurrent, ReqCurrent*2);
 else
  printf("Error getting power attributes: %d\n", flag);

 //Set GPIO
 flag = Mcp2221_SetGpioSettings(handle, RUNTIME_SETTINGS, pinFunc, pinDir, OutValues);
 if(flag != 0)
 {
  printf("Error setting GPIO, error: %d\n", flag);
  system("pause");
 }
 Mcp2221_SetGpioValues(handle, OutValues); //reset all pins at initialization

 //Set DAC reference to VDD
 flag = Mcp2221_SetDacVref(handle, RUNTIME_SETTINGS, VREF_VDD);
 
 if(flag != 0)
 {
  printf("Error setting DAC reference, error: %d\n", flag);
  system("pause");
 }

 while(1)
 {
  //Set DAC value on GP2
  DacVal++;
  if(DacVal == 32)
   DacVal = 0;
  printf("DAC value is: %x\n", DacVal);
  flag = Mcp2221_SetDacValue(handle, RUNTIME_SETTINGS, DacVal);  //must use "RUNTIME_SETTINGS" to enable and output voltage to the DAC
  if(flag != 0)
  {
   printf("Error setting DAC, error: %d\n", flag);
   system("pause");
  }

  //Toggle GPIO pins: GP0, GP1, GP3 for 50mS
  OutValues[0] = MCP2221_GPVAL_HIGH;  //set GP0 (output high)
  OutValues[1] = MCP2221_GPVAL_LOW;   //reset GP1 (output low)
  OutValues[3] = MCP2221_GPVAL_LOW;   //reset GP3 (output low)
  Mcp2221_SetGpioValues(handle, OutValues);  //now set the DIO pins values
  _sleep(50);    //wait for 50mS
  OutValues[0] = MCP2221_GPVAL_LOW;    //reset GP0 (output low)
  OutValues[1] = MCP2221_GPVAL_HIGH;   //set GP1 (output high)
  OutValues[3] = MCP2221_GPVAL_HIGH;   //set GP3 (output high)
  Mcp2221_SetGpioValues(handle, OutValues);   //now set the DIO pins values
  _sleep(50);    //wait for 50mS
 }
 return 0;
}


Tuesday, March 29, 2016

Introduction to Rapid Prototyping: Robotics - Part 3: Robot's Brain

Going back to the human-being analogy, the human body is the most known closed-loop control system to us, it has sensors (human senses of touch, feel, vision, listen…etc), actuators (muscles, tendons, and joints) and finally a decision-making unit, an organ that analyzes and organize the information acquired from different sensors and command the actuators in act in a certain desired way. Robots are the imitation of the human being in all of its details, and without the analysis and decision-making unit the robot is incomplete and most probably will be dysfunctional and thus useless, so, this section is dedicated to the “Brain’s” of the robot to be built.
Microprocessors are the piece of electronics that will replace the brain for robots, they are made of tens or hundreds of millions of transistors all engraved on a silicon die. The personal computer we use every day consists of the microprocessor unit connected to many other peripherals for data processing, storage, input and output using hard-disk drives, RAM memory units, sound cards, keyboards and mice, they are quite efficient for the business and personal activities they are involved in, but when it comes to a small and/or mobile robot they aren’t the best because they are:
  •  Power hungry, personal computers consume a lot of power.
  •  Expensive, they can cost anything between 250$ and more.
  • Physical profile, they are big in size which makes them not suitable to install in a robot, especially a mobile one. 

The Microcontroller:

So, engineers and scientists decided to go for a different version of the microprocessors that has less processing capabilities, yet still sufficient for the processing and analysis required building a decision-making unit for a robot. In the new version, they added a less power, low-power consumption processor with a relatively small amount of RAM memory, replaced the hard-disk drive with a flash EEPROM and a simple input/output system all on one chip and called it a “Microcontroller” or shortly as “MCU”, A simple microcontroller architecture is shown in figure 25.
Figure 25: An example of a microcontroller architecture and some of the peripherals that might be found inside.
Basic Input/Output Modules in Microcontrollers:
  •  Digital Input/output: the simplest way to communicate with a microcontroller or any microprocessor-based system is sending or receiving binary signals to and from it as 0’s and 1’s, a digital input simply is to send a “1” or “0” to the input module of the microcontroller, and the same for a digital output, it is the microcontroller response by outputting a “0” or “1”. In many digital systems, a logic “0” is 0v or ground, while a logic “1” is 5v or 3.3v, however, it’s not standard for all digital systems, some digital systems defines logic “0” with a negative voltage and logic “1” with a positive voltage or the opposite, there are many ways to represent 0’s and 1’s and we call this “Line coding”, but it’s not in the scope of this article.
  • Analog to Digital Converter (ADC): this module converts analog signals from sensors to a digital signal so the MCU can understand (don’t forget, digital systems don’t understand analog signals). An analog signal is continuous in time and amplitude (i.e. voltage level), which is hard for a digital system to interpret because it uses discrete signals in both time and amplitude, so first we have to convert this analog, continuous in amplitude signal to a discrete analog one using a process called “Sampling”, which is basically a process of cutting the analog signal into small pieces, then convert the amplitude of each piece to a binary number through a process called “Quantization”, figure 26 shows the flow of the analog to digital process.


Figure 26: Analog to digital conversion

“Nyquist Frequency”: to avoid any distortion or inaccurate analog to digital conversion, make sure the frequency of the input analog signal is less than half the sampling frequency of the ADC module in the microcontroller, this condition is called the “Nyquist frequency” which defines the maximum frequency of an input analog signal, this information can be found in the microcontroller‘s datasheet.
  • Pulse Width Modulation (PWM): a module that outputs a pulse modulated signal, PWM principle of operation is more explained in detail in my previous article “Introduction to Rapid Prototyping – Part 1: Motion Control”.
  • Serial communication (RS-232 or UART): this module allows the MCU to communicate with any other MCU or a computer serially using the legacy RS-232 serial interface. Serial data transmission means 0’s and 1’s are transmitted serially one after another using a single data line (either input or output).
More about microcontrollers:
  • Interrupts: a microcontroller can be programmed to respond quickly to a sudden event which we call “Interrupts”, when an interrupt occur the MCU stops any running operation and responds to this interrupt first then resumes its operation normally after the interrupt even is gone,  we can define two types of interrupt for an MCU
    • External interrupt: a change in the status of a digital input, or data received from the serial bus (UART).
    •  Internal interrupt: using a “timer”, a timer is a programmable counter module that counts CPU clock ticks and when it reaches the maximum count it issues an “overflow signal”; a CPU then is interrupted and has to respond to the timer’s interrupt signal before resuming its normal operation. Timers are useful to create accurate delay or perform a loop on a certain process in a timely precise manner.
  • Programming a microcontroller: a developer first develops the firmware code on a computer using a specific programming language, C language is the most common one for microcontrollers and embedded systems, compiles and debug it to confirm there are no errors or problems, then download the output file to the MCU internal EEPROM (or flash memory) using a special device called a “Programmer”, an “In-Circuit Programmer”, “In-System Programmer” or an “In-Circuit Debugger”. 
Figure 27: Programming a microcontroller
For more details about different low-cost microcontroller platforms please visit my previous article “Introduction to Rapid Prototyping” published in 2014.  

Introduction to Arduino:
Arduino is a low-cost family of microcontroller boards ranges from 5$ and up. The development software used to program it is called “Arduino IDE”, it is available for free from Arduino official website (https://www.arduino.cc/en/Main/Software). This tutorial is going to teach how to program Arduino boards and I’m using one of Arduino boards called “Arduino Uno” as an example.

Why Arduino?
Arduino platform is easy to understand from both hardware and software prespective compared to other microcontroller platforms that might require previous experience in electronics and programming:

  • Input/Output pins are marked with numbers or simple intuitive labels.
  • Easy to connect input/output pins to external components like sensors, LEDs or another microcontroller board.
  • Easy-to-use, a C-like programming language with fewer details that might confuse the developer.
The Arduino Uno board used in this tutorial is based on Atmega328P microcontroller from Atmel Corporation, a famous semiconductors company specialized in microcontrollers and electronic components. The Arduino Uno has an “In-Circuit Programmer” onboard that you can connect to your computer via USB, An Arduino Uno board is shown in figure 28.
Figure 28: Arduino Uno board

Table 1: Arduino Uno Pinout
Pin number
Function
0
DIO/Serial Tx
1
DIO/Serial Rx
2
DIO
3
DIO
4
DIO
5
DIO
6
DIO
7
DIO
8
DIO
9
DIO
10
DIO
11
DIO
12
DIO
13
DIO
A0
DIO/Analog input
A1
DIO/Analog input
A2
DIO/Analog input
A3
DIO/Analog input
A4
DIO/Analog input
A5
DIO/Analog input
5v
5v supply pin
3.3v
3.3v supply pin
GND
Ground
  • DIO: Digital input/output pin.
  • Tx: Transmit pin for serial communication module (UART).
  • Rx: Receive pin for serial communication module (UART).
  • Analog input: analog input pin to the Analog-to-Digital Converter module.
About Arduino Uno board:
  • General Purpose Inputs/Outputs are the input & output interface pins between the  Arduino board and outside world.
  • Any pin can be configured as either digital input or digital output.
  • The output of digital pins is either +5v or +3.3v for logic "1" or ground (0v) for logic "0".
  • Some pins can be configured to be “Analog Inputs”, i.e. you can input analog signals on these pins to the analog-to-digital converter module.
  • Analog signal: they can take any value between 0v and +5v, the Arduino board converts this analog voltage value to a number, such pins are commonly used with sensors. 
Arduino programming and interfacing is more explained in detail in these SlideShare slides:


--
Published on: March 29, 2016
Vancouver, Canada