You are on page 1of 68

UTM ROBOCON TEAM 2022/23 UNIVERSITI TEKNOLOGI MALAYSIA

ROBOCON BASICS 2022

Mechanism Electronics Programming

Name:
Page | 1

WORKSHOP TENTATIVE PROGRAM


DAY 1: 28/10/2022, Friday

TIME EVENT

7.00am - 8.00am Bus Pickup

8.00am - 8.30am Registration & Breakfast

8.30am – 8.40am Introduction to UTM ROBOCON


8.40am – 9.00am Opening Speech by Team Manager

9.00am – 9.20am Ice Breaking Session

9.20am – 12.30pm Mechanism Presentation


12.30pm – 2.00pm Lunch break/Friday Prayers (for Muslims)

2.00pm – 5.00pm Electronic Presentation

5.00pm End of Day 1

DAY2: 29/10/2022, Saturday

7.00am - 8.00am Bus Pickup


8.00am - 8.30am Registration & Breakfast

8.30am – 9.00am Day 1 Recap


9.00am – 12.00pm Programming Presentation
12.00pm - 1.00pm Lunch Break
1.00pm – 2.00pm Alumni Sharing Session
2.00pm – 3.00pm Q&A, Feedback Session

3.00pm Program END

ROBOCON WORKSHOP © UTM ROBOCON


Page | 2

TABLE OF CONTENTS

CHAPTER 1 Robot Essentials 3

CHAPTER 2 Locomotion 4

CHAPTER 3 Extension 11

CHAPTER 4 Actuator 14

CHAPTER 5 Tools and Machines 17

CHAPTER 6 Fastener 25

CHAPTER 7 Materials 26

CHAPTER 8 Software 30

CHAPTER 9 Sensor 31

CHAPTER 10 Electronic Components 34

CHAPTER 11 Electronic Tools 40

CHAPTER 12 Basic Electronic Circuit 43

CHAPTER 13 C Programming 52

ROBOCON WORKSHOP © UTM ROBOCON


Page | 3

CHAPTER 1 Robot’s Essentials

1.1 Basic Structure

A robot is an automatically guided machine which can do tasks on its own, almost always due to
electronically-programmed instructions.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 4

CHAPTER 2 LOCOMOTION

Locomotion
Enables the robot to move from one position to another

Types of robot locomotion:


● Wheeled robots
● Legged robots
● Flying
● Snaking
● Climbing
● Swimming

2.1 FOCUS: Wheeled robot

ROBOCON WORKSHOP © UTM ROBOCON


Page | 5

2.1.1 Differential wheel

● Movement depends on two separately driven wheels which are placed on either side of the robot.
● Direction can be changed by varying the rpm of the wheels.

3 wheeled robot 4 wheeled robot 6 wheeled robot


Stability Low High High
Mobility High Moderate Low

2.1.2 Steering wheel (Robocon 2009/2012)


The ability of the robot to move in a self-centring direction.

Example of 4 wheels steering and 2 wheels steering

ROBOCON WORKSHOP © UTM ROBOCON


Page | 6

Advantages:
● Can change direction while moving without rotate
● Fast movement
● Higher Speed Maneuvers
Disadvantages:
● Four points problem (slipping of wheels)
● Different motor output performance
● Easily affected by different angles of motor position
Caster
An undriven single, double or compound wheel that is designed to be mounted to the bottom of a
larger object (the “vehicle”) so that it enables the object to be easily moved.

2.1.3 Omni-directional wheeled robot navigation


● Movement depends on 3 or 4 Omni - wheels which enable the robot to move in all directions.
● The direction of the robot depends on the movement of the Omni-wheels

Example of omni wheel and a 4-point omni base

ROBOCON WORKSHOP © UTM ROBOCON


Page | 7

Example of 3-point
omni-directional robot movement

The usage of the Omni wheel enables the robot to move in ALL directions.

Advantage:
● Maneuverability
Disadvantages:
● (Usually)less pushing force
● Complex in terms of mechanism and programming

3-Point Omni- wheeled robot 4-Point Omni-wheeled robot


Stability Low High
Mobility High High
Speed Low High
Weight Lighter Heavier

ROBOCON WORKSHOP © UTM ROBOCON


Page | 8

2.1.4 Mecanum wheeled robot navigation

Mecanum wheel attachment from the top view.

● Movement depends on the four mecanum wheels placed with an X-shaped from the top view of
the robot.
● Move by resolving the vectors of each wheel and the direction depends on the movement of
each wheel.

Advantages:
● Maneuverability
Disadvantages:
● Complex in terms of programming

2.1.5 Tank track robot

Advantages:
● Increased stability
● Increased Traction
● Increased Torque
Disadvantages:
● Lack of speed under certain situations
● Reduce turning ability under certain situations
● Not as energy efficient as wheels

ROBOCON WORKSHOP © UTM ROBOCON


Page | 9

2.1.6 Ways to overcome the 4-point base problem (non-uniformed normal force on each wheel)

1) Use suspension at each wheel flexible base

ROBOCON WORKSHOP © UTM ROBOCON


Page | 10

2.2 LEGGED ROBOT (ABU ROBOCON 2019)

● Movement depends on the leg mechanism, a legged robot usually has 2 or 4 legs.
● Less efficiency compared to wheeled robots.
● Complex in design and programming.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 11

CHAPTER 3 EXTENSION

It is a mechanism which can be extended or change in size, length or position of an object using a slider
mechanism and bearing

Example: single extension, double extension, scissor extension

3.1 Degrees of Freedom (DOF)


Degrees of freedom are the set of independent displacements and/ or rotations that specify
completely the displaced or deformed position and orientation of the body or system

3.1.1 6 General DOF:


● Moving up and down (heaving)
● Moving left and right (swaying)
● Moving forward and backward (surging)
● Tilting forward and backward (pitching)
● Turning left and right (yawing)
● Tilting side to side (rolling)

3.2 Single extension

Advantages
● Simple structure
● More rigid
Disadvantages
● Limited length extension

ROBOCON WORKSHOP © UTM ROBOCON


Page | 12

3.3 Double extension (Robocon 2012)


Uses bearing, Perspex, roller, aluminium or grease as the sliding mechanism
Advantages
● Double extension is longer compared to single extension
● Saves space
Disadvantages
● Complex structure
● More friction between the extension

Before After

3.4 Scissors extension

Advantages
● Saves space
● Able to extend to a great length
Disadvantages
● Complex attachment
● Not rigid (has a lot of joints)
● Low stability

3.5 Heaving extension

Uses roller as the sliding mechanism


Commonly used in UTM Robocon

Advantages
● Less friction
Disadvantages
● Complex attachment
● Heavy

ROBOCON WORKSHOP © UTM ROBOCON


Page | 13

3.6 PE slider

Advantages
● Shaped easily
● Simple attachment
Disadvantages
● Time-consuming in making the PE
● High Friction

3.7 Gripper

Widely used as the robots’ hand for lifting, placing or


holding objects Usually uses pneumatic cylinders and
linkage to actuate the gripper

3.8 Pulley system

Timing belt pulley


● Typically made out of
rubber with high-tensile
fibres.
● A part of an internal
combustion engine that
controls the timing of the
engine's valves.

Timing chain pulley


● Used to transfer rotational
position from the
crankshaft to the valve
and ignition system on an
internal combustion
engine
● A more reliable metal
instead of fibre material.
● Last longer than the timing belt.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 14

CHAPTER 4 ACTUATOR
Move a mechanism using mechanical devices. Uses air and electric current.

Types of Actuator

ROBOCON WORKSHOP © UTM ROBOCON


Page | 15

4.1 Brushless motor (in general)


● High efficiency
● Durable and long-lasting
● Able to withstand heat with long periods of usage
● Higher power-to-weight ratio compared to brush motor with the
same price
➢ Harder to Program
➢ Require Brushless motor driver

4.2 Stepper motor


● Low speed with high precision
● Longer lifespan
● Greater torque than servo with the same size
➢ Lower torque than brush motor
➢ Require Brushless motor driver

4.3 Brushed motor (in general)


● Easy to control
● Reliable
● Lower cost
● Do not require a special driver
➢ Easily heat up when long usage
➢ Lack durability

4.4 Power window


● High holding torque
● Economic
➢ Slow speed
➢ Hard to attach

4.5 Pneumatic cylinders


● Very fast actuator
● Simple usage
● Use air to actuate
● Tendency to bend and thus broken
➢ Expensive
➢ Limited length

ROBOCON WORKSHOP © UTM ROBOCON


Page | 16

4.6 Ducted fan


● Easy to use
● Fast
➢ Drain battery

4.7 Elastic
Example: rubber and spring
● Cheap
● Simple usage
➢ No proper control
➢ Cannot last long

4.8 Servo
● Precise
● Simple usage
➢ Slow speed
➢ Gear will break easily when high torque is required

ROBOCON WORKSHOP © UTM ROBOCON


Page | 17

CHAPTER 5 TOOLS AND MACHINES

5.1 Tools

5.1.1 Spanners and Wrenches

a. Double ended spanner


Used to tighten or loosen fasteners (bolt, nut, etc.)

b. Combination spanner
The ring end allows stronger force to be applied

c. Ratchets & Socket


Comes in sizes to fit different sizes of bolts and nuts lock into various types of handles.

d. Crescent wrench
The width of ‘jaw’ is adjustable to fit different sizes of fasteners

5.1.2 Pliers

a. Combination pliers
For gripping and holding objects or cutting, wires Can be used to bend a light metal rod

ROBOCON WORKSHOP © UTM ROBOCON


Page | 18

b. Needle-nose pliers
To cut and bend wires or electrical wiring Reaches tight and narrow spots

c. Circlip pliers
To insert or remove circlips

Internal circlip

d.Diagonal cutter
Useful for cutting the wires. Not used to grab or turn anything

e Locking pliers
Can be used as both plier or wrench. Able to grip and hold on to object(s) firmly Width of
the ‘jaw’ is adjustable

5.1.3 Hammers
a. Claw Hammer
To hammer nails into an object, specifically wood. The claw is used to draw nails from
wood

ROBOCON WORKSHOP © UTM ROBOCON


Page | 19

b. Ball Pein hammer


Used to form a uniform curved surface on metal

c. Mallet
To adjust the position between joint objects by a slight degree Prevent dents or marks
when shaping objects such as aluminium

5.1.4 Saws

a. Handsaw
For cutting wood or other material

b. Hacksaw
Suitable for cutting wood and light metal
Can cut almost any size or shape of metal object

c. Screwdrivers
A tool for fastening screws, bolts and nails

Parallel tip Phillips head Frearson

ROBOCON WORKSHOP © UTM ROBOCON


Page | 20

5.1.6 Allen key


Used as a driver for screws, bolts, and other fasteners Longer arm of the L-shape for
higher torque driving
The ball on the rear end allows fastening at an odd angle

5.1.7 File
Used to shave excess metal
To smoothen or roughen metal surfaces

5.1.8 L-ruler
Useful when measuring perpendicularly to an object
Used to outline cutting

5.1.9 Riveter
Use to rivet two surfaces together.
Rivet has strong shear and tensile strength

5.1.10 Tube Bender


To bend light metal tubes or bars such as aluminium
Able to bend according to a given radius

ROBOCON WORKSHOP © UTM ROBOCON


Page | 21

5.1.11 G-clamp
To clamp an object to a work surface for sawing or drilling
To prevent denting of workpiece, always use a piece of scrap wood between jaws of the
clamp

5.1.12 Hand drill


To drill different sizes of holes in a metal or wood
Used to undo the rivet

5.1.13 Hand tap and Die set


Used to create screw thread on a light metal
Rethread bolt with damaged thread

5.1.14 Centre punch


Used with a hammer to mark a point on metal surfaces before drilling

5.2 Machines

5.2.1 Stand drill


The workpiece is clamped strongly in position and the drill rotates
to make a straight hole.
More preferred to a hand drill when drilling through two surfaces

ROBOCON WORKSHOP © UTM ROBOCON


Page | 22

5.2.2 Bench Grinder


To sharpen drill bits, centre punches, remove metal from
work piece
To sharpen tools and polish metalwork

5.2.3 Power saw


More efficient and have a better finishing surface than using
a handsaw
An object is mounted firmly on the platform before cutting
Able to cut an object at an odd angle

5.2.4 Hand Grinder


Also known as an angle grinder.
A handheld power tool that is used for cutting, grinding and polishing.
The motor drives a geared head which is mounted on an abrasive disc or a thinner cut-
off disc, either of which can be replaced when worn.
Can be mounted various types of discs, such as cut-off
discs, diamond blades, abrasive grinding discs, grinding
stones, sanding discs, wire brush wheels and polishing
pads.
Used for removing excess material from a piece or simply
cutting it into a piece.

5.2.5 MIG Welding Machine

Advantage of MIG
● Higher welding speeds with high quality
● The process is easily automated process
● No flux requires in most cases

ROBOCON WORKSHOP © UTM ROBOCON


Page | 23

● MIG welding is versatile and can be used with a wide variety of metals and
alloys
● The MIG process can be operated in several ways, including semi and
fully automatic

Disadvantages of MIG
● Higher initial setup cost
● Higher maintenance cost due to the extra electronic component
● The equipment is complex
● MIG welding can only be used on thin to medium-thick metals

Safety precaution
● Work in a well-ventilated area
● Wear a welder cap and safety glasses
with shields
● Keep your head out of fumes
● Wear completely body protection
● Wear dry insulating gloves

5.3 3D printer
A 3D printer is a type of industrial robot which
conducts 3D printing. 3D printing is also known as a
process used to make a 3D object. In 3D printing,
successive layers of material (PLA, ABS, etc) are laid
down under computer control. These objects can be
of almost any shape or geometry and are produced
from a 3D model or other electronic data sources.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 24

Type of 3D printer

Cartesian 3D printer
1. Named after the dimensional coordinate
system — the X, Y, and Z-axis — which is
used to determine where and how to move in
three dimensions
2. Advantage: This is a mechanically simpler
design, and therefore easier to maintain
3. Disadvantage: no overall problems, any
disadvantages of Cartesian style printers
depend on the manufacturer

Delta 3D printer
1. The extruder is suspended above the print bed by three arms
in a triangular configuration
2. Advantage: One of the main advantages of a Delta printer is
its speed. These printers were designed for quick printing.
Delta print heads are built to be as light as possible, which
results in a quicker printing process.
3. Disadvantage: One is the precision of the printer. As the
speed of the printer increases, its precision decreases

ROBOCON WORKSHOP © UTM ROBOCON


Page | 25

CHAPTER 6 FASTENER

6.1 Types of fasteners

6.1.1 Cap screws/ bolts

6.1.2 Nut

6.1.3 Lock nut/ Prevailing torque nut,


Resists loosening under vibrations and torque
Provides a locking action

6.1.4 Rivet
A permanent mechanical fastener

6.1.5 Cable tie


Also known as a zip tie

ROBOCON WORKSHOP © UTM ROBOCON


Page | 26

CHAPTER 7 MATERIALS

ROBOCON WORKSHOP © UTM ROBOCON


Page | 27

Poly-Ethylene (PE)

● Used to create a custom component (i.e. slider, roller, coupling).


● Characteristics: smooth, soft and white.

Perspex

● Advantages: less friction, light, long lasting


● Disadvantage: Expensive

ROBOCON WORKSHOP © UTM ROBOCON


Page | 28

Carbon Fiber
• Composed of carbon atoms bonded together to form a long chain.
• Extremely stiff, strong, and light.
• Used in many processes to create excellent building materials.
• Advantage: Strong, Light, very Durable

ROBOCON WORKSHOP © UTM ROBOCON


Page | 29

7.1 Aluminium: hollow tubes, hollow bar, L bar, flat bar, rod
● Advantages: light, solid
● Disadvantages: soft, expensive

7.2 Aluminium block


● Used to make custom components (i.e. motor coupling)
● Advantages: solid, long-lasting
● Disadvantages: heavy, expensive

7.3 Mild Steel: hollow bar, L bar, flat bar


● Used to create a firm structure
● Usually used as the main structure of the robot
● Advantages: strong, cheap
● Disadvantages: heavy, oxidized easily

7.4 Stainless steel: hollow bar, L bar, flat bar, rod, tube
● Advantages: solid, long-lasting
● Disadvantages: heavy, difficult to cut, expensive

7.5 Poly-Ethylene (PE)


● Used to create a custom component (i.e. slider, roller, coupling)
● Characteristics: smooth, soft and white

7.6 Perspex
● Advantages: less friction, light, long-lasting

ROBOCON WORKSHOP © UTM ROBOCON


Page | 30

CHAPTER 8 SOFTWARE

8.1 SolidWorks
Widely used by students in Universiti Teknologi Malaysia
● Is a 3D mechanical CAD software
● Used to design 3D projects
● Able to do stimulation, analysis of projects, etc

8.2 Ultimaker Cura


A 3D printing software which can cope with a variety of types of 3D printers.
Used to do adjustments and arrangement of parts which are ready to be printed.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 31

CHAPTER 9 SENSOR
Obtains feedback from the surroundings
Measures a physical quantity and converts it into signal
Divided into categories according to their physical quantity feedback

9.1 Light Sensors


Detects light and creates a voltage difference

9.1.1 Photoresistor (Light dependent resistor, LDR)


A resistor whose resistance varies with the light intensity

9.2 Proximity sensors


Detects the presence of a nearby object within a given distance without having any physical
contact

9.2.1 Infrared (IR) Transceiver:


An IR LED transmits a beam of IR light

9.2.2 Ultrasonic Sensor:


Generates high frequency sound waves and evaluate the echo received back by
the sensor

ROBOCON WORKSHOP © UTM ROBOCON


Page | 32

9.2.3 Photoelectric sensor:


Uses light to detect objects via light transmitter and a photoelectric receiver

9.3 Distance sensor

9.3.1 Ultrasonic sensor


(refer to Ultrasonic sensor in proximity sensor)

9.3.2 Infrared sensor


(refer to Infrared (IR) Transceiver in proximity sensor)

9.3.3 Encoder
converts the angular position or motion of the shaft to an analog or digital value

9.4 Contact sensor


Requires physical contact against other objects to trigger

9.4.1 Limit switch

ROBOCON WORKSHOP © UTM ROBOCON


Page | 33

9.5 Navigation/ Positioning Sensors

9.5.1 Digital Magnetic Compass:


Provides directional measurements using the earth’s magnetic field which guides your
robot in the right direction

9.5.2 Gyroscope
Measures rate of rotation and maintains orientation using the principle of angular
momentum

ROBOCON WORKSHOP © UTM ROBOCON


Page | 34

CHAPTER 10 ELECTRONIC COMPONENTS


Electronic components are categorized into passive and active components.

10.1 Passive components:


Components that cannot introduce net energy into the circuit. Functions as a load in the
circuit. They are components that do not rely on an energy source to function.
Example of passive components: __________________________________________

10.1.1 Resistor
Function:
● limits the flow of current
Unit: ohm, Ω
Obeys Ohm’s Law; V = IR (V = voltage, I = current, R = resistance)

Symbol:

resistor variable resistor

resistor

variable resistor

No. 1st value 2nd value Multiplier (10colour Result (ohm, Ω)


value)
1 Red: 2 Violet: 7 Orange: 3 27×103=27000 Ω
2 Orange: 3 Orange: 3 Brown:1
3 Yellow: Violet: Red:
4 Red: Red: Black:

ROBOCON WORKSHOP © UTM ROBOCON


Page | 35

10.1.2 Capacitor
Function:
● Stores electricity or electrical energy
● Acts as a filter
● Passes alternating current (AC) and blocks direct current (DC)
● Stabilizes voltage level and eliminates bouncing effect of contact switch
Unit: Farad, F

Symbol:

Electrolytic capacitor Ceramic capacitor

Large capacitors have value printed on them


Capacitance of a small capacitor normally is read in pico-Farad (pF)

Multiplier
No. 1st 2nd Unit Result (Farad, F)
(x 103)
value value
1 4 7 3 pico 47×10-12×103=47 nF
2 3 3 0 pico
3 1 6 1 pico

ROBOCON WORKSHOP © UTM ROBOCON


Page | 36

10.2 Active components

Components that can deliver power to the circuit. Functions as a source of power in the
circuit. They are components that rely on an energy source to function or act as
amplifying components.
Example: ___________________________

10.2.1 Diode
Function:
● a semiconductor device which allows current to flow through in one
direction (from anode to cathode) aka forward bias.
Symbol:

Question: What happens when we connect it in reverse bias?

10.2.2 Light emitting diode (LED)


Function:
● used as an indicator
Symbol:

➢ Emits light when an electric current passes through.


➢ Same working principle as a diode.
➢ Available in different colors.
➢ Common colors are green, yellow and red.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 37

10.2.3 Transistor
Function: used as a signal-controlled switch or amplifier.
Symbol:

➢ Signal at base controls the operation of output (conducting or cut off)


➢ There are two types of standard transistors: NPN and PNP.
➢ The direction of the current flow differs between PNP and NPN type.
➢ Most transistors used is NPN type

10.2.4 Switch
Function: used to turn on and off circuits
Symbols:

Push button slide switch toggle switch


➢ Varies in model and size based on application.
➢ We have SPST, SPDT, DPDT types of switches.
➢ P means Poles and T means Throws. But what are they?
➢ ____________________________________

ROBOCON WORKSHOP © UTM ROBOCON


Page | 38

10.2.5 Voltage regulator


Function:
Maintains a constant voltage level all the time even
if there is an unstable voltage power source.

Symbol:

➢ Model used: 78xx or 79xx series.


➢ It is a linear regulator.
➢ Number 78 represents the positive voltage regulator and 79 represents negative voltage
regulator. Meanwhile, xx indicates the output voltage
➢ Example:
○ 5V DC Regulator name: LM7805 or MC7805
○ -5V DC Regulator name: LM7905 or MC7905
○ 6V DC Regulator name: LM7806 or MC 7806
○ -9V DC Regulator name: LM7909 or MC7909

➢ Applied with a basic application circuit. (Stated in later sections)

➢ Application hints:
o The input voltage should always be greater than the output voltage (at least by 2.5V).
o The input current and output current are almost identical. (Max at 1.5A)
o Must attach heat sink when use in high current applications.
o Why? ___________________________

ROBOCON WORKSHOP © UTM ROBOCON


Page | 39

10.2.6 Infrared Sensor


Function: Used for line following in autocar
Diagram:

➢ Transmitter will emit infrared wave while receiver receives it.


➢ Transmitter: IR Emitter LED
➢ Receiver: IR Detector NPN

10.3 Integrated Circuit (IC)


It is a miniaturized electronic circuit.
Also called chip or IC

Advantages:
● Saves cost
● High performance
● Saves space
● Power saving (consumes only little amount of energy)

Example: LM342 (comparator), L293D (motor driver), dspic30f4011(microcontroller) etc.

LM324 and L293D are both DIP (Dual in-line packages).

ROBOCON WORKSHOP © UTM ROBOCON


Page | 40

CHAPTER 11 ELECTRONIC TOOLS

11.1 Soldering iron


A hand tool that is commonly used in soldering.
Supplies heat to melt the solder so that it can flow into the joints.

11.2 Solder
A fusible metal alloy used to join metal pieces.
Have a melting point below of the subject piece.

11.3 Wire stripper


A small, hand-held device used to strip the insulator from electric wires.

11.4 Desoldering pump


Used to remove solder from a printed circuit board or doughnut board.

11.5 Diagonal cutter


Used to cut the components’ lead (leg) and wires.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 41

11.6 Crimping tools


Special type of pliers used to crimp terminals with electrical connectors.

11.7 Tweezers
Used for picking up objects too small to be handled by human hands.
Example: surface mount components, IC chips

11.8 IDC crimp tool


Used for crimping IDC type connectors.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 42

11.9 Long nose pliers (Needle nose pliers)


Used to grip small components and bending components’ leg

11.10 Multimeter
An electronic measuring instrument that combines several functions in one unit
Example: measuring voltage, resistance, capacitance, etc.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 43

CHAPTER 12 BASIC ELECTRONIC CIRCUIT

12.1 Power management

▪ It is not recommended to share one single battery for many applications


▪ Circuits’ power source should be separated from others such as motor.
▪ Ensure the circuit receives a stable power source and expand the battery life.

12.2 Common ground

▪ All the ground inside the circuit is connected


▪ However, the circuits’ ground is recommended to be separated from the motors’ ground
▪ Opto-isolators or relays are used to separate the ground

12.3 Microcontroller

▪ A circuit consisting of a microcontroller will work only if there are the elements below:
1. Power source: VDD (5V) and VSS (GND/ 0V)
2. Reset button: Resets the microcontroller back to the beginning of the program,
like a restart of a computer. It is an active low connection.

12.4 Linear Voltage Regulator

▪ Generates 5V from 7V – 12V


▪ Capacitor C1 & C2 is for stable voltage level supply
▪ Diode for reverse polarity protection

ROBOCON WORKSHOP © UTM ROBOCON


Page | 44

12.6 Input connections

12.6.1 Active low

When the switch is not pushed, the output voltage will be high (5V). The pull-up resistor (4.7kῼ) ensures
it is high
When the switch is pushed, the output voltage is shorted to the ground. Thus, the voltage is low (0V)

12.6.2 Active high

When the switch is not pushed, the output voltage will be low (0V)
When the switch is pushed, the output voltage is shorted to Vcc, thus the voltage is high (5V)

ROBOCON WORKSHOP © UTM ROBOCON


Page | 45

12.7 Output connections

12.7.1 Active low


- The output is ON the logic ‘0’ is given
- The resistor is to limit the current flow through the LED.
- The greater the resistor value, the dimmer the LED.

12.7.2 Active high


-The output is ON when logic ‘1’ is given

ROBOCON WORKSHOP © UTM ROBOCON


Page | 46

12.8 Communication (UART)

▪ UART stands for Universal asynchronous receiver/transmitter.


▪ A communication protocol that lets two devices ‘talk’ to each other.
▪ Needed to program the IC.

12.9 Sensor

▪ Gives feedback to the microcontroller about the environment


▪ There are several types of sensors with different prices, functions, accuracy etc.
▪ To sense line for line following, an IR sensor can be used
▪ The output of IR sensor:

 High: black trail detected 
 Low: white surface detected 



Using comparator to compare the feedback from sensor with the reference value

ROBOCON WORKSHOP © UTM ROBOCON


Page | 47

Vref
Vin

Schematic shows the connection of IR and phototransistor

Connection of preset
ROBOCON WORKSHOP © UTM ROBOCON
Page | 48

12.10 L293D (Quadruple Half H-Bridge drivers)


▪ Used to drive DC motor

EN Input1 Input2 Motor direction


(PIN 0) (PIN 1) (PIN 2) (M1)
H H L Clockwise / Forward
H L H Counter-clockwise / Backward
H H H Stop
H L L Stop
L X X Stop
Where H = high; L = low; X = don’t care

ROBOCON WORKSHOP © UTM ROBOCON


Page | 49

Clockwise Counter-clockwise

ROBOCON WORKSHOP © UTM ROBOCON


Page | 50

Hands-on activities

1. Breadboarding

2. Tinkercad

The only way to teach electronics is: Lighting up an LED!

- So, what do we need to light up an LED?


- An LED of course! But how do we connect it?
- An LED has Anode and Cathode, how to determine which
is which?
- Tip: we can get the answer using Tinkercad!

Steps:
a. Drag out an LED! (From the right section under basic
components)
b. Don’t forget about your power! Drag a 9v battery out.
c. Randomly connect the positive (red) end to the LED,
we will soon find out if it’s the correct way.
d. Press at the top right.
e. If your LED lights up, congratulations! If it does not, then you know it’s in the opposite way.

f. BUT…. the LED is blown! But why?

g. How do we solve it? We put a resistor in series! The resistor here functions as a current-
limiting resistor.
h. It is always a good practice to put a resistor in series with an LED.
i. Resistor + LED = 1 set. (That’s what my senior told me.)

j. Drag a resistor out. Double-click to change its value to 330 ohms.


k. You should have a circuit like this:

l. Next, let’s connect a 5v voltage regulator.


m. Does anyone remember the part number? Type 7805 in the search bar.
n. Try connecting it, look in your booklet for the pinout.
o. **A good practice to always keep your wires nice and tidy. Keep power
ROBOCON WORKSHOP © UTM ROBOCON
Page | 51

wires in RED and Ground wires in BLACK.

p. Next, anyone know what’s the function of a diode?


q. Try connecting a diode in series with the LED.
r. Connect the diode in FORWARD BIAS. Remember the symbol?
s. The white line represents the Cathode.

Quick question:
What happens if we connect it in REVERSE BIAS? Any guesses?
Try it in Tinkercad!

t. Next, we change the resistor to a preset variable resistor. Change the value to 1k ohms.
u. Observe the brightness of the LED.

v. Now we add a push button. But how to connect? There are 4 pins.
w. This push button is what we call a SPST (Single Pole Single Throw) switch.
x. In laymen terms, it means that the switch has one input and one output only.
y. Thus, two of the four pins are input and the other two are outputs.
But which is which? How to test it out?
z. Try randomly connecting the push button in series with the LED. (Along with power please!)

If the LED lights up without us pressing the


LED. There you have it!

Now reverse the push button.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 52

CHAPTER 13 C Programming
● C is a general-purpose, structured programming language.
● It is a high-level language(compared to assembly language) that allows the programmer to write a
program.
● The program using C language can be compiled to become executable machine code.
● The C language consists of 3 things:-
a. The Environment
b. The Language
c. The C Standard Library
● The Environment is to describe the method to write and implement the C program
● The Language is to emphasize on the rule of syntax
● The Library provides a
collection of existing functions
to perform operations
● There are four phases for a C
program to become an executable:
a. Pre-processing
b. Compilation
c. Assembly
d. Linking
● Standards of C: C89, C99, C11,
C18, and Embedded C.
● Make sure to read the compiler
documentation when writing a C program for a microcontroller.

13.1 Basic Structure of C Program

Example 1
Preprocessor directives #include <stdio.h>

main() int main() {

body printf(“hello, world\n”);

return }

Example 2
Preprocessor directive: stdio #include <stdio.h>
stands for standard input output.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 53

Comment: any character between /* print Fahrenheit-Celsius table


/* and */ are ignored by the For fhr = 0, 20, …, 300 */
compiler.

main() int main() {

Variable declaration: define fahr int fahr;


and celsius in single line is the int celsius;
same as define them in two lines. int lower, upper, step;
Assignment of values to the lower = 0; // lower limit of temp
variables. upper = 300; // upper limit
// also defines comment. Any step = 20; // step size
character after // is ignored by
the compiler. fahr = lower;

While loop. while (fahr <= upper) {


Arithmetic expression. celsius = 5*(fahr-32)/9;
printf, a function from stdio.h printf(“%d\t%d\n”, fahr, celsius);
fahr = fahr + step;
}
Return value for main() return 0; /* program exit with value 0
tells the operating system
that the program exits without problem.
Non-zero values are used to signal
different failures. */

Closing brace for main() }

13.2 Variable Names


● Names are made up of letters and digits
● Underscore ‘_’ counts as a letter
● Don’t begin variable names with underscore ‘_’ as library routines often use such names
● Traditional C practice use lowercase for variable names and uppercase for symbolic constants
● Reserved words are not allowed

13.3 Reserved Words


Since C89
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
Since C99
Bool _Complex _Imaginary inline restrict
Since C11
_Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local

ROBOCON WORKSHOP © UTM ROBOCON


Page | 54

13.4 Data Types


char : store a character
int : store an integer
float : store a decimal number with single precision (IEEE 754)
double : store a decimal number with double precision (IEEE 754)

Below shows ranges of data types with different modifiers, and format specifiers on 32-bit GCC compiler.
Data type Mem Precision Range of values Format
/Byte Specifier
unsigned char 1 1 0 to 255 %c
signed char 1 1 -128 to 127 %c
short int 2 1 -32,768 to 32,767 %hd
unsigned short int 2 1 0 to 65,535 %hu
unsigned int 4 1 0 to 4,294,967,295 %u
int 4 1 -2,147,483,648 to 2,147,483,647 %d
long int 8 1 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 8 1 0 to 4,294,967,295 %lu
long long int 8 1 -9,223,372,036,854,775,808 to %lld
9223372036854775807
unsigned long long int 8 1 0 to 18,446,744,073,709,551,615 %llu
float 4 6 decimal digits 1.2E-38 to 3.4E+38 %f
double 8 15 decimal digits 2.3E-308 to 1.7E+308 %lf
long double 16 19 decimal digits 3.4E-4932 to 1.1E+4932 %Lf
It is possible to determine the range of values a data type can present according to memory size and the
way it contains the information. For example, int have 4 byte = 4*4 = 16 bits, thus it has 2^16 possible
values. int without unsigned modifiers has negative values, thus its upper bound is [(2^14)/2] - 1
while its lower bound is -1*[(2^14)/2]. In contrast, unsigned int has no negative values, so it has
an upper bound of (2^14)-1 and a lower bound of 0.
Also, sometimes long and short will be used alone. long rat; means rat’s data-type is long
int while short pen; means pen’s data-type is short int.

13.5 Functions
A function is a set of statements that take parameters as input, do some specific computation and return
value as output. General form of function is as below:
return_type function_name([ arg1_type arg1_name, ... ]) { code }

ROBOCON WORKSHOP © UTM ROBOCON


Page | 55

Example 1
#include <stdio.h>

/* This function takes an int as input


and return int as output */
int fib(int n){
if ((n == 0) || (n == 1))
return n;
else
return (fib(n-1) + fib(n-2));
}
int main()
{
for (i = 0; i != 10; i++) {
printf("%d, ", fib(i)); /* fib(i) takes i as input,
* then return an int after it
* completes its operation.
* printf then takes the string and
* also int returned by fib(i) as
* input, and print them on stdout.
*/
}
printf(“\b\b \n”);
return 0;
}

Example 2
#include <stdio.h>

/* Function prototypes */

long combination (int n, int r);


long permutation (int n, int r);
long factorial (int n);
void info (void); /* void as return type means the function
return nothing, and void as parameter
means nothing needed to be passed as
input to the function
*/

int main()
{
long int result;
result = combination(5, 2); /* The return value is assigned
to result */
info(); /* info returns nothing */
printf(“5C2 = %ld\n”, result);
return 0;
}
/* Function Definitions */

ROBOCON WORKSHOP © UTM ROBOCON


Page | 56

long permutation(int n, int r){return factorial(n)-factorial(n-r);}

long
combination (int n, int r)
{
return permutation(n,r)/factorial(r);
}
void factorial (int n)
{
long i = 1;
while (n > 0) {
i = i * n;
n--;
}
return i;
}
void info (void) { printf(“This program is written by ME\n”); }
Remarks:
Function definition can be done in a single line or multiple line according to your preference. However, it
is best to always follow a neat formatting style to ease readability.

13.6 Scope Rule


#include <stdio.h>

void fried_rice (int num);


void fried_noodle (int num);

/* GLOBAL VARIABLES */
int energy = 60; // total energy available
int rice = 4; // energy needed for 1 fried rice
int noodle = 5; // energy needed for 1 fried noodle

int main (void)


{
/* LOCAL VARIABLE */
int rice_order = 5; /* other functions cannot directly */
int noodle_order = 7; /* access, but can pass as arguments */
/* to the functions */
fried_rice(rice_order);
fried_noodle(noodle_order);
printf(“energy left = %d\n”, energy);

return 0;
}
void fried_rice (int num) {
int i = num; /* local variable of this function, similarly, */
/* other functions cannot access this i */
energy -= rice*i;

ROBOCON WORKSHOP © UTM ROBOCON


Page | 57

void fried_noodle (int num) {


int i = num; /* this i is not the i in fried_rice, so do num */
/* they are specific to this function only. */
/* Also, global variables cannot be redefined */
/* inside functions because they are visible to */
/* these functions */
energy -= noodle*i;
}

13.7 Operators

Arithmetic Operators
+ addition int i = 5; // value of i is 5
i = i + 2; // value of i now is 7

- subtraction int i = 5; // value of i is 5


i = i - 2; // value of i now is 3

* multiplication int i = 5; // value of i is 5


i = i * 2; // value of i now is 2

/ division int i = 5; // value of i is 5 | No decimal or


i = i / 2; // value of i is 2 | round off when
float j = 5; // value of j is 5.0 | divide int
j = j / 2; // value of j is 2.5 |
% modulus int i = 5; // value of i is 5 | both operands should
(remainder) i = i % 2; // value of i is 1 | be int

Unary Operators
Unary operators are operators that act upon a single operand to produce a new value.
- unary minus int i = 5; // value of i is 5
int j = -i; // value of j is -5

++ increment int i = 5; // value of i is 5


i++; // value of i is 6

-- decrement int i = 5; // value of i is 5


i--; // value of i is 4

! not // to reverse the logical state of its operand

& address of int jar = 5;


int* ptr; // declare ptr as a pointer to int
ptr = &a; // now ptr has address to jar, or
// ptr is now points to jar

ROBOCON WORKSHOP © UTM ROBOCON


Page | 58

sizeof sizeof // returns the size of its operand, in bytes


Remarks:
Both ++ and -- can be used either as prefix operators (before the variable: ++n ) or postfix operators
(after the variable: n++ ). In both cases, the effect is to increment n . The expression ++n increments n
before its value is used, while n++ increments n after its value is used.

Relational Operators
== equal to Single ‘=’ is an assignment operator, which
assigns values. This has two ‘=’, which
compares the values.

!= Not equal to

> greater than

>= greater than or equal to

< smaller than

<= smaller than or equal to

Logical Operators
&& logical and ((5>3)&&(4>5)) means ((true)&&(false)) means (false)

|| logical or ((5>3)||(4>5)) means ((true)||(false)) means (true)

! logical not !((5>3)&&(4>5)) means not(false) means (true)

Bitwise Operators
Let char a = 0b01010101, b = 0b11001100, c = 0;
Operation Value of c Remarks

& Bitwise and c = a&b 0b01000100

| Bitwise or c = a|b 0b11011101

^ Bitwise c = a^b 0b10011001


exclusive or

~ Bitwise c = ~a; 0b10101010


complement c = ~b; 0b00110011

<< Shift left c = a<<3; 0b10101000 The left operand’s value is moved left by the
number of bits specified by the right operand,
the empty right bits are all filled with 0.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 59

>> Shift right C = a>>3; 0b00001010 The left operand’s value is moved right by
the number of bits specified by the right
operand, the empty left bits are all filled with
0.
Remarks:
Integer constants can be written as binary constants, consisting of a sequence of ‘0’ and ‘1’ digits,
prefixed by ‘0b’ or ‘0B’. Similarly, there are hexadecimal, which prefix is ‘0x’, and octal which is ‘0’.
For example, a decimal 27 can be represented by 0b11011, 0x1b, or 033.

Assignment Operators
= is the most basic assignment operator, which assigns value of right operand to left operand.
Below show how each following a <operator> b can be expanded.
+= a = a + b >>= a = a >> b

-= a = a - b <<= a = a << b

*= a = a * b &= a = a & b

/= a = a / b |= a = a | b

%= a = a % b ~= a = ~ b

Other Operators
, comma a binary operator that evaluates its first operand and discards the result, it
then evaluates the second operand and returns this value (and type).

int i = (5, 10); /* 10 is assigned to i */


int j = (f1(), f2()); /* f1() is called (evaluated) first */
/* followed by f2(). The returned value of */
/* f2() is assigned to j */

?: ternary/ It takes in a binary condition as input, which makes it similar to an 'if-else'


conditional control flow block. It also, however, returns a value, behaving similar to a
function.

int x = 5, y = 4;

x = (y>2)?6:7; /* y is 4 and greater than 2, thus x is now 6 */

/* Below is another equivalent code */


if (y>2) { x = 6; }
else { x = 7; }

ROBOCON WORKSHOP © UTM ROBOCON


Page | 60

Operator Precedence Chart


Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ -- (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

13.8 Selection Structures

If-Else
/* Basic single line */
if (x > 6) printf(“yes\n”); // {} can be omitted since printf
// is only one statement.
if (x > 6) { i = 5; b = 5; } // 2 statements, thus {} is needed
/* if-else */
if (x > 6) {
printf(“yes\n”);
} else {
printf(“no\n”);
}
/* if-else-if */
if (x > 6) printf(“no\n”);
else if (y > 9) { printf(“yes\n”); }

ROBOCON WORKSHOP © UTM ROBOCON


Page | 61

else if (t < 3) {
printf(“tt\n”);
} else if (j != 6) {
x = 0; y = 0; j = 0; t = 100;
} else if ((t-x)==6) printf(“joke\n”);
else printf(“end\n”);
/* this code is valid, showing different styles available */

Switch
int i = 1; /* assign a value to i here */
switch (i) { /* Check the value of i */
case 1:
printf(“One\n”);
break; /* Program will exit from switch */
case 4:
printf(“Four\n’); /* Program will continue to execute */
case 5: /* code for next case, which is 5 */
printf(“Five\n”);
break;
default:
printf(“Wrong\n’);
}
/* If i is 1, the switch will print One */
/* If i is 4, the switch will print Four then Five. */
/* If i is 5, the switch will print Five only. */
/* For other values of i, the code will print Wrong */

13.9 Repetitive Structure

Example 1
For While Do-while

int i; int i = 0; int i = 0;


for (i = 0; i != 10; i++) while (i != 10) do {
{ { printf(“%d\n”, i);
printf(“%d\n’, i); printf(“%d\n”, i); i++;
} i++; } while(i != 11);
}
Remarks: The above examples produce the same output.

Example 2 (break and continue)


int i = 99;
while (i != 10) {
if (i == 71) break; /* force exit from the while loop if i is 71 */
printf(“%d “, i);
if (i%4 == 0) { /* If i is even */
i--; /* decrement i */
continue; /* skip the rest of code and proceed to next loop */
}
printf(“\n”);

ROBOCON WORKSHOP © UTM ROBOCON


Page | 62

i--;

int i;
for (i = 99; i != 10; i--) {
if (i == 71) break; /* force exit from the for loop if i is 71 */
printf(“%d “, i);
if (i%4 == 0) continue; /* continue will skip the rest part and directly
evaluate (i != 10) and also run i--, entering
next loop */
printf(“\n”);

Remarks: The above examples produce the same output.

13.10 Preprocessor Directives


The C preprocessor modifies a source file before handing it over to the compiler, allowing conditional
compilation with #ifdef, defining constants with #define, including header files with #include, and using
built-in macros such as FILE .

#include instructs the preprocessor to paste the text of the given file into the current file

#define defines a symbolic constant or creates a macro

#undef undefines a constant or preprocessor macro defined previously using #define

#if checks whether the value is true (in the C sense of everything but 0) and if so,
includes the code between it and the closing #else or, if no #else is present,
#endif statement.

#ifndef checks whether the given token has been #defined earlier in the file or in an
included file; if not, it includes the code between it and the closing #else or, if
no #else is present, #endif statement.
FILE a preprocessor macro that expands to full path to the current file.

LINE a preprocessor macro that expands to current line number in the source file, as an
integer

DATE a preprocessor macro that expands to current date (at compile time) in the form
mmm dd yyyy (e.g. "Jan 14 2012"), as a string.

TIME a preprocessor macro that expands to current time (at compile time) in the form
hh::mm::ss in 24 hour time (e.g. "22:29:12"), as a string.

TIMESTAMP a preprocessor macro that expands to current time (at compile time) in the form
Ddd Mmm Date hh::mm::ss yyyy (e.g. "Wed Jan 18 22:29:12 2012"), as a string.

Example 1
1 /*
2 ** Runge-Kutta Method
3 ** dv/dt = 9.81 - 0.1v, where v=0 at t=0

ROBOCON WORKSHOP © UTM ROBOCON


Page | 63

4 */
5 #include <stdio.h>
6
7 #define END 1
8 #define FNVD(x) (9.81 - 0.1*(x))
9 #define DEBUG
10
11 int main() {
12 float t = 0.0, v = 0.0, h = 0.1;
13 float k1 = 0.0;
14 float k2 = 0.0;
15 float k3 = 0.0;
16 float k4 = 0.0;
17 #ifdef DEBUG
18 printf(“We’re at %d in %s\n”, LINE , FILE );
19 printf(" k1 k2 k3 k4 ");
20 #endif
21 printf(" T -- V\n");
22 while (t < END) {
23 #ifdef DEBUG
24 printf("%.5f %.5f %.5f %.5f :: ",k1, k2, k3, k4);
25 #endif
26 printf("%.1f -- %8.5f\n", t, v);
27 k1 = h*FNVD(v);
28 k2 = h*FNVD(v+0.5*k1);
29 k3 = h*FNVD(v+0.5*k2);
30 k4 = h*FNVD(v+k3);
31 v = v + (k1 + 2*(k2+k3) + k4)/6;
32 t = t + h;
33 }
34 return 0;
35 }
Remarks:
END is a symbolic constant. The compiler sees line 22 as while (t < 1) {.
FNVD(x) is a macro. The compiler sees line 27 as k1 = h*(9.81 - 0.1*(v)). Also, every (
and ) matters. If we use #define FNVD(x) 9.81 - 0.1*x , the compiler will sees line 27 as
k1 = h*9.81 - 0.1*v , since the compiler directly copy-paste macro, so the resulting arithmetic
expression is not what we wanted.

13.11 Some Important Topics


Array * Pointers * Structures * Unions * Type Casting
Concepts such as arrays and strings are easy to understand and very common, so please go back and
study. Pointers are hard to understand at first, but it is used everywhere in C, so if you want to use the C
language fully you have to have a very good understanding of pointers. Examples after this will not avoid
these topics.

ROBOCON WORKSHOP © UTM ROBOCON


Page | 64

13.12 Sample Codes

Example 1
/*
** Sieve of Eratosthene
** - an algorithm for finding prime numbers
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sieve (int n);

int main(void)
{
int input;
printf("List all primes number smaller than ");
scanf("%d", &input);
if (input > 100000 || input < 3) /* Limit the input range */
printf("Invalid range\n");
else
sieve(input);
return 0;
}

void sieve (int n) {


int p = 2, p2 = 4;
int i;
char* prime = malloc(sizeof(char)*n);
memset(prime, 1, sizeof(char)*n);
for (p = 2; p2 <= n; p++) {
p2 = p*p;
if (prime[p] == 1) /* If not changed, it is a prime */
for (i = p2; i <= n; i += p)
prime[i] = 0; /* Mark multiples of the prime */
}
for (p = 2; p <= n; p++)
if (prime[p])
printf("%d ", p);
printf("\n");
free(prime);
}
Remarks: malloc, free, scanf, memset.

Example 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define inp scanf(" %15s", buf); scanf("%*[^\n]");


#define ttl printf("Tic Tac Toe\n");
#define prt(x) printf(x)
#define chk if(ci(buf)){e=1;continue;}
#define dro bd[buf[0]-'1'] = 'o';
#define drx bd[buf[0]-'1'] = 'x';

ROBOCON WORKSHOP © UTM ROBOCON


Page | 65

#if defined(_WIN32)
#include <windows.h>
#define clr system("cls")
#define slp(x) Sleep(x*1000)
#elif defined( linux )
#include <unistd.h>
#define clr system("clear")
#define slp(x) sleep(x)
#else
#define clr
#define slp
#endif

char bd[9];
char ci (char*);
void pb (void);
char cb (void);

int main (void)


{
char buf[16];
char r=0, t=0, e=0, a=0;
memset(bd, ' ', 9);
srand(time(0));

clr;
ttl;
prt("Single or Multi (s/m): ");
inp;
if ((strlen(buf) == 1)&&(buf[0] == 's')) t = 0;
else if ((strlen(buf) == 1)&&(buf[0] == 'm')) t = 1;
else { prt("Undefined input.\n"); return 0; }

while(1) {
clr;
ttl;
if(e) { prt("Wrong Input!\n"); e = 0; } else prt("\n");
pb();
if (r != 9) {
if (t == 1) {
if ((r&1) == 0) {
prt("Player1's turn [0-9]: "); inp; chk; drx;
} else {
prt("Player2's turn [0-9]: "); inp; chk; dro;
}
} else {
if ((r&1) == 0) {
prt("Player's turn [0-9]: "); inp; chk; drx;
} else if (r!= 9){
prt("Computer's turn.");
fflush(stdout);
while(bd[(buf[0]=rand()%9)]!=' ');
buf[0]+='1';
dro;
slp(1);
}
}
} else { prt("Nobody wins!\n"); return 0; }
a = cb();

ROBOCON WORKSHOP © UTM ROBOCON


Page | 66

if (a != 0) break;
r++;
}

clr;
ttl;
if(a == 'x') {
if (t == 1) prt("Player1 wins!\n");
else prt("Player wins!\n");
} else if(a == 'o') {
if (t == 1) prt("Player2 wins!\n");
else prt("Computer wins!\n");
}
pb();
return 0;
}

/* Check Input */
char ci (char* buf)
{
if (buf[0] > 48 && buf[0] < 58 && buf[1] == 0)
if (bd[buf[0]-'1'] != ' ') return 1;
else return 0;
else return 1;
}
/* Print Board */
void pb (void)
{
int i,j;
for (i=0; i!=9; i+=3) {
for(j=0; j!=3; j++) printf("%d---",j+i+1);
prt("+\n");
for(j=0; j!=3; j++) printf("| %c ",bd[j+i]);
prt("|\n");
}
prt("+---+---+---+\n\n");
}
/* Check Board */
char cb (void)
{
int i;
for (i = 0; i != 9; i+=3)
if (bd[i]!=' ' && bd[i+1]!=' ' && bd[i+2]!=' ')
if (bd[i] == bd[i+1] && bd[i] == bd[i+2])
return bd[i];
for (i = 0; i != 3; i++ )
if (bd[i]!=' ' && bd[i+3]!=' ' && bd[i+6]!=' ')
if (bd[i] == bd[i+3] && bd[i] == bd[i+6])
return bd[i];
if (bd[0]!=' ' && bd[4]!=' ' && bd[8]!=' ')
if (bd[0] == bd[4] && bd[0] == bd[8]) return bd[0];
if (bd[2]!=' ' && bd[4]!=' ' && bd[6]!=' ')
if (bd[2] == bd[4] && bd[2] == bd[6]) return bd[2];
return 0;

ROBOCON WORKSHOP © UTM ROBOCON


Page | 67

CONTACT US:

utmrbc.com

UTM Robocon Team

utm.rbc

Assoc. Prof. Ir. Dr. Mohd Ridzuan Ahmad


(UTM Robocon Team Manager)

Muhammad Irfan Rahman B. ☏ 017-5672687


Mohd Khaidzir ✉ muhammadirfanrahman@graduate.utm.my
(UTM Robocon Team President)

Dickson Chong Yung Haw ☏ 019-8299168


(Vice President of Legalities) ✉ dickson@graduate.utm.my

Wong Pei Sen ☏ 012-2117563


(Vice President of Finance) ✉ wongsen@graduate.utm.my

Yu Jinx Xian ☏ 011-11634462


(Vice President of Talent ✉ yuxian@graduate.utm.my
Management)

ROBOCON WORKSHOP © UTM ROBOCON

You might also like