You are on page 1of 153

Arduino

0
1
1.1
IDE , 1.2
1.3
1.4
1.5
1.6
( ) 1.7
( ) 1.8
(ADC) 1.9
2
LCD ( ) 2.1
2.2
3
Qt Arduino 3.1
Python , PyQt4
3.2

1
Arduino

howtocode.com.bd
9.9

| HowToCode | |

Arduino



Microcontroller Programmable Platform ,

,

, ,

2
Arduino

?

,

, ,

,
- Schematic design ,
Datasheet Datasheet

,


IDE ,



(ADC)


LCD
Keypad
L293D
Relay
LCD, Keypad, LED, Motor

Java, C#, QtC++, Processing


Line Follower Robot
Wall Follower/Avoider Robot
PID LFR
Bluetooth Controlled Robot
Wifi Controlled Robot

3
Arduino

Like 37 Share

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives


4.0 International License.

4
Arduino

5
Arduino

:
:

,
Proteus 8.X SPY Design Suite [X & Y for version number]

Arduino UNO R3 or Arduino Mega 2560

Half Size Breadboard

Resistor

Capacitor

LED

Variable Resistor

DMM (Digital Multimeter)

?
Arduino

,

Arduino Intuitive Programming Language


IDE Sensor, actuator, light, speaker,
add-on module ( Arduino Shield ) IC
Programmable Brain

Arduino ,

,

6
Arduino


!
,
,

, ,
.

Chinese
900 (UNO)-1200 (MEGA) Arduino
Freeduino, pcDuino, ODOO

:
Arduino UNO R3 (R stands for Revision):

Arduino Leonardo:

7
Arduino

Arduino DUE:

Arduino Mega 2560:

8
Arduino

Arduino Mega ADK [Android Development Kit]:

Arduino LilyPad:

Arduino Yun:

9
Arduino

IDE

10
Arduino

IDE ,

[
]
100MB [ IDE
]
Arduino UNO R3 Arduino Mega 2560 [ Arduino Mega 2560 ,
]
USB A B Cable [ ]

: ,
(32 bit, 64 bit) IDE
gksudo arduino

Arduino IDE :
, IDE
IDE IDE
Sublime Text Editor IDE
:

Run As Administrator :

IDE , 11
Arduino

I Agree:

Next:

IDE , 12
Arduino

Install:

IDE , 13
Arduino

Install :

Close :

IDE , 14
Arduino

Arduino Board :
Device Manager :

Ports Arduino :

Other devices Unknown Device


:P
Unknown Device Update Driver Software :

IDE , 15
Arduino

Browse my computer for driver software :

IDE , 16
Arduino

Browse :

Arduino Folder Driver OK :

IDE , 17
Arduino

Next:

, This driver software is incompatible


for the device Unknown Device Driver

Arduino Configure Program :


?
COM Port

IDE , 18
Arduino

Arduino IDE , :

Tools > Serial Port > COMX [Device Manager Port


Port ]

Tools > Board > Arduino . [ , UNO


Mega ]

IDE , 19
Arduino

? , IDE Example ,
Arduino
Blink Example Arduino UNO, Mega 13 LED
External Led Led Blinking

Example File > Examples > Basics > Blink , :

IDE , 20
Arduino

Arduino Blink , Blink


delay 1000 , delay(100)
delay(50)

[ : delay(int)
, 1000 1 second]

Upload :

IDE , 21
Arduino

Arduino IDE
Upload Completed !

Arduino IDE :
IDE ,
,
, Heavy Customization

, File > Preferences:

IDE , 22
Arduino

preferences.txt , ,
editor.font Monospaced [
Monospaced font Consolas ], plain

IDE , 23
Arduino

Ctrl+S Save !

IDE Restart

IDE , 24
Arduino

[F.A.Q / Troubleshooting]
: UNO ,
/ . /

/. :

Shift Choose an option


, Troubleshoot > Advanced options > Startup settings > Restart
, 7

IDE , 25
Arduino

Device Manager > Unknown Device [ ] > Update driver software >
Browse My computer for driver software > Let me pick from a list of device drivers from my
computer > Modems > Compaq Models Richochet Wireless
USB Model [ ] > Yes > Installing
Baud Rate 9600 COM COM 50-60

: : avrdude: stk500_getsync(): not in sync:


resp=0x00

COM Device Manager > Ports > Arduino [Right


Click] > Properties > Port setting > Advanced > Com Port Number >
( unused)

manashmndl[ ]gmail[ ]

IDE , 26
Arduino

:
[Arduino Uno / Mega 2560]

/ 22AWG Solid Wires
LED
[220Ohm / 330 Ohm / 1k]
Proteus 8.0 SP1 or Latest Version

[Top-View]

USB Connector: -- USB


Connector , USB A-B A Arduino
Arduino 5V

External Power Connector: -- DC


9-12V AC :P

27
Arduino

Digital Operation Pin-outs: 17 Digital


Operation

0, 1 : Serial Communication 0 RX [Receive/ Receiver /


Reception] 1 TX [Transmit/ Transmitter/ Transmission] [
]

2-13 : 5V 3V~5V
~ , PWM [Pulse Width Modulation]

GND : Digital Ground , Ground


Digital Ground

AREF : Analog Reference Pin , Analog Signal


Reset Button: [Revision] ,


Mega , UNO R2 R3
MCU :P

In-Circuit Serial Programmer ICSP Header Pin [ ]:


Atmega MCU
, MCU Board Specific :
MOSI {Master Out Slave In}, MISO {Master In Slave Out}, SCK {Serial Clock}, RESET,

VCC {+5V}, GND {Ground}


Atmega 328P-PU MCU: Atmel Co. AVR


ATmega
Leg

ATmega 16u2 / ATmega8u2 MCU: USB ,


, Arduino Computer
Serial Communication

ICSP Header for ATmega 16u2 MCU: ICSP


ATmega 16u2

A0-A5 Analog In (pins): UNO


6 ADC [Analog
to Digital Conversion] 14, 15 19

Voltage in (Vin): External Power 7-12V DC


28
Arduino

GND: Ground

3.3V: 5V
, 3.3V DC

Reset: Reset :P

, 12V , , 16Mhz , 3.3V , RX-TX


Led , 13-pin LED, Power LED

:
Blink
, .ino .pde

int ledPin = 13; // Putting integer value in a variable [A single line comment]

/* This is a Multiline
comment */

void setup()
{
pinMode(ledPin, OUTPUT);
}

void loop()
{
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}

/ / ++

Line 1:
int ledPin = 13 int integer [ ]
Variable ledPin

13

29
Arduino

, toy KhelnarBaksho = gari;


toy (thing) KhelnarBaksho = gari
( toy ,
:P )

toy khelnarBaksho = jeep;


khelnarBaksho = remoteControlledCar;

? khelnarBaksho
jeep
remote_Controlled_Car

, khelnarBaksho = remoteControlledCar
jeep replaced
:P , toy
toy
toy type

jeep remoteControlledCar :

toy jeepBox, remoteControllledCarBox;


jeepBox = jeep;
remoteControlledCarBox = remoteControlledCar;

, , .. ,
:P

// Comment , ,
; Comment
// Comment //

Line 3:
/ / // / /
:P

Line 6:

30
Arduino

void setup() , ; void setup() {}


void loop() {} y = f(x) = x^2
f(x) * x^2
/++, , {}
(Curly Braces)

void setup()
,
void
setup() void *

Line 8:
pinMode(ledPin, OUTPUT); pinMode(arg1, arg2)
,
Call** INPUT
OUTPUT INPUT ,
, OUTPUT Led, Motor

pinMode int mode pinMode(int,


mode) mode INPUT
OUTPUT Led OUTPUT

void setup() Call Simple as that.

Line 11:
void loop() {} , [
] infinity loop
, void setup void loop
void setup void loop

Line 13:
digitalWrite(ledPin, HIGH); Call

digitalWrite(int, bool) Pin 5V 0V


, int boolean bool ,
boolean / HIGH Synonym true, 1, yes
LOW Synonym false, 0, no

, __ /

31
Arduino

Line 14:
delay(1000) , - delay(int)
1000 1s delay
[
thread.sleep(int) ]

delay
-

* ledPin 13
* { ledPin } [void setup ]
* {
* ledPin
*
* ledPin
*
}

led

32
Arduino

(gif)
ISIS :

33
Arduino

34
Arduino

35
Arduino

y = f(x) y = f(x)
= 2 x 2 * x f(x)

** , z = f(r, x) = r^2 + x^2, , z = f(2,3) =


2^2 + 3^2 = 4 + 9 = 13 digitalWrite
integer bool ,

*
[return] , washClothes,
; ?

- ( ),
cloth washClothes(cloth);
void
washClothes(cloth) !
:P , void
null ,

** Call, , , f(x)
= 5x, g(y) = 10y f(2), g(2)
Call
loop user defined function
Call

: (F. A. Q)
:
blinking ledPin , digitalWrite(13,
HIGH) ?

36
Arduino

digitalWrite(13, HIGH) ,
Led, Sensor ,
,
ledPin = 13 , 13 1
ledPin

(constant)
const , const int ledPin = 13;
ledPin = 14 ,
ledPin ledPin

:
Proteus .ino blinking.cpp.hex ? .hex
?

:
.hex ,
.hex .ino Arduino
IDE Verify .hex

:
.hex ?

:
Everything

37
Arduino

, Loop If
Else

:
Arduino Board

Breadboard

Jumper Wire

10KOhm Resistor

220Ohm Resistor

USB Cable -

Pushbutton -

Single-Color LED -

Loop () :
Led
For loop

int ledPin = 13;

void setup()
{
pinMode(ledPin, OUTPUT);
}

void loop()
{
for (int i = 100; i

Line 1, 3, 5, 8

Line 10:

38
Arduino

for (int i = 100; i <= 1000; i = i + 100){


// Statements goes here
}


C ,

printf("Electroscholars"); // 1st one


printf("Electroscholars");
.................
.................
printf("Electroscholars"); // The 100th one

int i;
for (i = 0; i < 100; i = i + 1)
{
printf("Electroscholars");
}

For :
for First Bracket , First Bracket
;

; Initialization , ; ;
Condition ; Increment

first bracket Second Bracket Curly Braces Second


Bracket / Loop

For :
(Initialization) [ , i = 0
, C++, Java, Arduino - ,
for (int i = 0; i < 100; i = i + 1) Java, C++ C

39
Arduino

[Condition]

Increment Curly Braces


Walkthrough!:
ledPin 13
void setup() : ledPin
void loop() ( Infinite Loop ):
i 100 , i 1000 ?
( )

!
ledPin
100
ledPin
100
i (= )
i ? ,
ledPin
200
ledPin
200
i (= )

. . . i ,
void loop for
i

for void
loop

Proteus :

40
Arduino

Input Reading :

, , led

Pull Down*
Push Button 5V
5V Short 5V
5V ,

, Pull Down ?
5V
, 5V
[ Unpressed ] Unexpected Noise
Fluctuate

, 5V Supply Rail 5V ,
5V 5V ,
5V Push Button
Led 13

41
Arduino

, ,
?
Pull Down

Pull Down ,

Ohm :P
Resistance
Digital Reading 5V :)

42
Arduino

43
Arduino

int led = 13;


int button = 3;

void setup()
{
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}

void loop()
{
if (digitalRead(button) == HIGH)
{
digitalWrite(led, HIGH);
}
else
{
digitalWrite(led, LOW);
}
}

Walkthrough:

Line 7:
,
Input

Line 12:
if else ,
True , False
if else

if (booleanCheck == True)
{
doThis();
} else {
doThat();
}

, :

44
Arduino

if (6 < 7)
{
printf("This is Electroscholars!");
} else {
printf("Program will NEVER print this!");
}

6 7 , 6 < 7 == True This is


Electroscholars

if digitalRead digitalRead
/
, 1/0, HIGH, LOW

button Read LOW led


led

else if (digitalRead(button) == LOW) , if else


if , HIGH led

led
, ,

:
Pull Up Resistor, Pull Down Resistor

45
Arduino

Pull Down Resistor


VCC

46
Arduino


47
Arduino

48
Arduino

49
Arduino

PWM (Pulse Width Modulation)

:
Arduino [Predictable! Isnt it? :P]

Breadboard

Jumper

Led

Resistor [Recommended 100Ohm, but 220/330 Will work too]

PWM :
,
digitalWrite()
5V 5V ,
I/O Led ,
Led , ? 5V
Led

, PWM ,
PWM ! PWM DAC
[Digital to Analog Conversion] , DAC PWM PWM
,

PWM analogWrite(int pin, int value) ,


analogWrite pin value
PWM , value 8-bit
0 2^8 1 0 255 ,

, PWM Signal , UNO ~


PWM Signal , 3, 5, 6, 9, 10, 11
UNO PWM Led
/

50
Arduino

, 3 Led

51
Arduino

const int led = 3;


void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
for (int i = 0; i < 256; i++){
analogWrite(led, i);
delay(10);
}

for (int i = 255; i >= 0; i--){


analogWrite(led, i);
delay(10);
}
}

Walkthrough:
* led 3
* led
* , * i Initialize 0 ; i, 256
* led i analogWrite analog
*
* i 1 , i 256 ? ;
* i 255 ; i ? ,
* led i analogWrite analog
*
* . . void loop()

52
Arduino

:
:

i , i led
,
i
, i
i i


,
i :

int i;
... ... ....
void loop()
{
for (i = 0; i < 256; i++){ /* code */ }
for (i = 255; i >= 0; i--) { /* code */ }
}

53
Arduino

Duty Cycle:

Wikipedia ?
A duty cycle is the percentage of one period in which a signal is active. A period is the
time it takes for a signal to complete an on-and-off cycle.

, Duty Cycle , Duty Cycle


On
Off DC On 5V Off
0V :

PWM ?
PWM Duty Cycle analogWrite(pin, 255)
100% duty cycle
, digitalWrite(led, HIGH) == analogWrite(led, 255) ? Confusing ?
, , %
% analogWrite Value ?
, 127

, 2 millisecond
, ..

[F. A. Q]:
:
PWM - ?
?

54
Arduino

:
PWM Low Duty Cycle Dim Light Dim Light
PWM , ! , Arduino Square Wave 490Hz
, 490 5V 0V , T = 1 / f ,
0.002 Second duty cycle dim

led led

55
Arduino

( )

:
Codeblocks/Codelite/Eclipse IDE C++ , Text Editor Syntax
Highlighter

Arduino OOP Object Oriented Programming


OOP C++ C++ , ,
OOP , OOP
OOP OOP
OOP
Informative Implementation

[Programming Paradigm]:

Java
OOP Java
C++ Procedural/Functional/OOP

Procedural:
Imperative Programming C
Procedural
( )
Top To Bottom Approach

Procedural
BASIC, Pascal C Procedural Programming
C Procedural Programming :

56
Arduino

int add(int a, int b);

int main(){
int firstNum = 6;
int secondNum = 15;
int sum;
sum = add(firstNum,secondNum);
printf("sum= ",sum);
return 0;
}

int add(int a,int b){


int result;
result = a + b;
return result;
}

Object Oriented:
C++ :

#include <iostream>

class addNumbers
{
public:
int sum;
addNumbers(int, int); // Constructor, Constructor ,
};

addNumbers::addNumbers(int num1, int num2)


{
sum = num1 + num2;
}

int main()
{
addNumbers object(1,2);
std::cout << "Sum: " << object.sum;
}

Object Oriented Programming


OOP
OOP :

57
Arduino

Class, Object

Encapsulation

Inheritance

Polymorphism

: Constructor, Destructor

Class, Object:
Object Object
Object Class
, Pet C++ Pet
class* Pet , Pet ?
, Feedback Feedback,
Pet Object
Common ('Properties') , , ,
Pet Object Name, age
Attributes , , Method
Function Method Member Function

class Pet
{
public:
string name;
void eat();
void utter();
};

public: **

name string , Method


class Pet { // blablabla }; <-

Method
Method

[Inside of Class]
[Outside of Class]

58
Arduino

class Pet
{
public:
string name;
void eat()
{
cout << "Gulp gulp gulp..... ... .." << endl;
}
void utter()
{
cout << "meaw .... meaw ..." << endl;
}
};

class Pet
{
public:
string name;
void eat();
void utter();
};

void Pet::eat()
{
cout << "Gulp ... gulp... gulp.." << endl;
}

void Pet::utter()
{
cout << "Meaw..... meaw.... " << endl;
}

, Method
, C++ Method :

//[returnType] [ClassName] :: [methodName(argument)]


//Here-> '::' is called Scope Resolution Operator

void Pet :: eat()


{
// Code goes Here
}

::
:)

59
Arduino

:

Attribute Method
Method

:
Object
Object Variable Attribute Value

Object Method Call

object Argument Pass


Class, object

? ,
Comment

Object :

class Pet {}; // Assume it is the class

int main()
{
Pet dog; // Object Created!
}
// className objectName /* To create an object */

Object :

60
Arduino

#include <iostream>
using namespace std;
class Pet
{
public:
string name;
};

int main()
{
Pet dog, cat;
dog.name = "Tommy";
cat.name = "Tom";
cout << "Name of the cat is: " << cat.name << endl;
cout << "Name of the dog is: " << dog.name << endl;
}

Pet , Dog
Cat dog Tommy cat Tom
, dot operator objectName.variable =
Value Scope Resolution Operator Member Function Class

Dot operator Object Member Function Variable

Access name string Pet Pet

Object`

, variable = cat.name , cat.name = Tom , variable = Tom , Tom


( cat variable )

Name of the cat is: Tom


Name of the dog is: Tommy

Pet UML* (Unified Modeling Language)


Diagram:

61
Arduino

Object Method Call :


, object.functionName(argument) Method Call

62
Arduino

#include <iostream>
using namespace std;
class Pet
{
public:
string name;
void sayName()
{
cout << "My name is " << name << endl;
}
};

int main()
{
Pet cat;
cat.name = "Thomas";
cat.sayName();
}

cat Object sayName()


Call

My name is Thomas

Object Argument :

63
Arduino

#include <iostream>
using namespace std;
class Pet
{
public:
string name;
};

void sayName(Pet petObject, string petName) // This is NOT A MEMBER FUNCTION, it is just a function i
{
petObject.name = petName; // Name has been assigned by taking the name from the argument
cout << "Name of the pet is: " << petObject.name << endl;
}

int main()
{
Pet cat;
sayName(cat, "Thomas"); // This will print "Name of the pet is: Thomas"
cout << cat.name << endl; // This will print nothing!!!
}

, , Pass by reference Pass by value


Pass by Value void sayName ,
, Attribute name string
,

Name of the pet is: Thomas

[int main() ] , sayName cat


cat cat.name cout
? Pass by value

, (URL) ,

Pass by reference

URL Pass by value , URL




Pass by value

64
Arduino

Pass by reference :

......
void sayName(Pet &petObject, string petName) // I just put an & before the object!
{
petObject.name = petName;
cout << "Name of the pet is: " << petObject.name << endl;
}

int main()
{
Pet cat;
sayName(cat, "Thomas"); // This will print "Name of the pet is: Thomas"
cout << cat.name << endl; // This will print "Thomas"
}

Name of the pet is: Thomas


Thomas

Pass by reference cat & cat


(
) cat name Pass by
Value , petObject != cat [Not equal] Pass by reference
petObject == cat cat
petObject name cat name
!

: [Led Blinking in Console using OOP!]


Led blinking ,
led ,

65
Arduino

#include <iostream>
#include <Windows.h>
using namespace std;

class Led
{
public:
int ledPin;
Led(int pinNumber);
void pinMode(int);
void blinkLed(int delay);
};

Led::Led(int pinNumber)
{
ledPin = pinNumber;
pinMode(pinNumber);
}

void Led::pinMode(int pin)


{
cout << pin << " is set as output" << endl;
}

void Led::blinkLed(int delay)


{
cout << "Led at " << ledPin << " is on" << endl;
Sleep(delay);
cout << "Led at " << ledPin << " is off" << endl;
Sleep(delay);
}

int main()
{
int usDelay, pinNumber, turn;
cout << "Enter Delay, Pin number and Turns [sequentially, example: 1000 13 2]: ";
cin >> usDelay, cin >> pinNumber, cin >> turn;
Led led(pinNumber);
while (turn > 0){
led.blinkLed(usDelay);
turn--;
}
}

66
Arduino

Enter Delay, Pin number and Turns [sequentially, example: 1000 13 2]: 1000 13 2
13 is set as output
Led at 13 is on
Led at 13 is off
Led at 13 is on
Led at 13 is off

:
Access Modifiers:

C++ Access Modifiers , public, private protected Encapsulation

Data Hiding

UML Diagram:
UML Diagram Class [Class Diagram]
( ):

Class Name , Capitalized


Attributes Variable Left aligned Lowercase
Method Left aligned
Attributes Method [Access Modifier -> +, -, #;
Package -> ~, Derived-> / ]

, OOP

67
Arduino

68
Arduino

( )
, , ,
Call
:

Encapsulation
Constructor
Inheritance
Polymorphism

Encapsulation:
Data hiding Data protection OOP

( ) Encapsulation
Attribute Encapsulated
Object Attribute , Person Class Attribute
name (string type) age (int type) Person object
:

#include <iostream>
using namespace std;

class Person
{
public:
string name;
int age;
};

int main()
{
Person idiot;
idiot.age = 0;
idiot.name = "Idiot";
cout << idiot.age << endl;
cout << idiot.name << endl;
}

? public private
:)

( ) 69
Arduino

#include <iostream>
using namespace std;

class Person
{
private:
string name;
int age;
};

int main()
{
Person idiot;
idiot.age = 0;
idiot.name = "Idiot";
cout << idiot.age << endl;
cout << idiot.name << endl;
}

Class Encapsulated !
Attribute

, Attribute
? OOP C++ Private Protected
, public private !
, Attribute
Deal Private/Protected Attribute
:

( ) 70
Arduino

#include <iostream>
using namespace std;

class Person
{
public:
void setNameAndAge(string n, int a);
void showNameAndAge();
private:
string name;
int age;
};

int main()
{
Person A;
A.setNameAndAge("My Name", 20);
A.showNameAndAge();
}

void Person::setNameAndAge(string n, int a)


{
name = n;
age = a;
}

void Person::showNameAndAge()
{
cout << "The name: " << name << endl;
cout << "The age: " << age << endl;
}

setNameAndAge showNameAndAge Object



Private/Public/Protected Attribute
,
(setNameAndAge showNameAndAge) :D

, Encapsulation
? Encapsulation Public Data Public
Class Object Access

( ) 71
Arduino

#include <iostream>
using namespace std;

class Person
{
public:
string name;
int age;
};

class dataChanger
{
public:
dataChanger(Person &p)
{
p.name = "I Changed it";
p.age = 10;
}
};

int main()
{
Person person;
person.name = "The Name has been set";
person.age = 99;
cout << person.name << endl;
cout << person.age << endl;
dataChanger danger(person);
cout << person.name << endl;
cout << person.age << endl;
}

The Name has been set


99
I Changed it
10

, , Person
dataChanger dataChanger *
dataChanger Person Class Object Attribute
public Public
Method Accessible!

Access :

( ) 72
Arduino

class Person
{
private:
string name;
int age;
};

Encapsulated Access Modifier Modify


C++ Modifier Modifier private
Encapsulation Constructor

Constructor:
Constructor Constructor
Call Object
Execute
, Return Constructor
:

Call ,
Argument
Return
Constructor

( ) 73
Arduino

#include <iostream>
using namespace std;

class Person
{
public:
string name;
int age;
Person(string string_as_argument, int int_as_argument)
{
name = string_as_argument;
age = int_as_argument;
}
};

int main()
{
Person A("Mr. A", 5);
cout << "My name is: " << A.name << endl;
cout << "My age: " << A.age << endl;
}

My name is: Mr. A


My age: 5

? ,
Return Type
Person Person string
int !

Person ?
main Object
Mr. A 5 Constructor
name age A.name A.age

, Constructor
Declare !

( ) 74
Arduino

class Person
{
public:
string name;
int age;
Person(string, int);
};

Person::Person(string n, int a)
{
name = n;
age = a;
}

! ?

Constructor :
Initial ,
Initial Value

Arduino LiquidCrystal
Order Liquid Crystal
Display - Arduino
Order
LiquidCrystal ! LCD ReadWrite mode ,

Inheritance:

Common
OOP Inheritance!
Method Attribute
Inheritance

Animal Animal ? , , ,
Animal Class
:

( ) 75
Arduino

class Animal
{
public:
void eat() { cout << "eating" << endl;}
void sleep() {cout << "sleeping" << endl;}
void hunt() {cout << "hunting" << endl;}
};

, Animal , Bird

Bird Animal eat, sleep hunt


Bird
Method Fly :)

class Bird
{
public:
void eat() {cout << "eating" << endl;}
void sleep() {cout << "sleeping" << endl;}
void hunt() {cout << "hunting" << endl;}
void fly() {cout << "flying" << endl;}
};

? ,
! :P

? Inheritance Apply :)

Bird inherits Animal Animal class eat, sleep hunt


`

Inheritance Apply :

( ) 76
Arduino

#include <iostream>
using namespace std;

class Animal
{
public:
void eat() { cout << "Eating" << endl;}
void sleep() {cout << "Sleeping" << endl;}
void hunt() {cout << "Hunting" << endl;}
};

class Bird : public Animal


{
public:
void fly() { cout << "Flying" << endl; }

// Calling the functions


void activities()
{
eat();
sleep();
hunt();
fly();
}
};

int main()
{
Bird b; // Creating an object
b.eat();
b.sleep(); // Calling the functions individually
b.hunt();
b.fly();
cout << "----------" << endl;
b.activities(); // Calling the 'activities' function which calls other functio
}

Eating
Sleeping
Hunting
Flying
----------
Eating
Sleeping
Hunting
Flying

( ) 77
Arduino

Bird eat(), sleep(), hunt() Definition


Call Animal
Animal Inherit
,

?
class derivedClass : public baseClass { /* Put your attributes and methods here!*/ };
// derivedClass is the inherited one
// class[keyword] your_class_Name :[colon] public/private/protected[access modifier] base_Class

Polymorphism:
Poly Polymorphism
OOP :P

, Function Overloading, operator


overloading Polymorphism Function/Method
overloading
Function Overloading Polymorphism
, Function overloading Polymorphism

( ) 78
Arduino

#include<iostream>

using namespace std;

class Shape
{
public:
float calcArea(int height, int width); // Calculate area for Rectangular shape
float calcArea(double base, double height); // Calculate area for Triangular Shape
float calcArea(int side); // Calculate area for Square shape
};

float Shape::calcArea(int height, int width)


{
return height * width;
}

float Shape::calcArea(double base, double height)


{
return 0.5 * base * height;
}

float Shape::calcArea(int side)


{
return side * side;
}

int main()
{
Shape rectangle, triangle, square;
cout << "Area of rectangle is: " << rectangle.calcArea(5,3) << endl;
cout << "Area of triangle is: " << rectangle.calcArea(2.0,5.0) << endl;
cout << "Area of square is: " << square.calcArea(5) << endl;
}

Area of rectangle is: 15


Area of triangle is: 5
Area of square is: 25

Shape calcArea

, int
double

( ) 79
Arduino


Call ? C++
Call
Function / Method overloading

OOP
OOP


Header
, OOP Readable Organized

( ) 80
Arduino

:
Arduino Board (Uno / Mega 2560)

Arduino IDE (-_-)

Usb Cable

Computer (duh!)

(Serial Communication):


? ,

0 1

, ;

,

COM Port ,
COM3, COM14
, , ? , ,

( ) 81
Arduino

.hex
ATmega16u2 ATmega8u2

Serial ! ?

Hardware
,
UART (Universal Asynchronous Receiver Transmitter)

UART 8-bit ,

UART ,
3.3V 5V MCU
, ,
Transmission speed *

UART :

, UART Protocol hello Boka MCU


Start Bit

, , ?

( ) 82
Arduino

UART/USART Serial
Communication Establishment
, PC Boka PC
Boka vice versa PC
Boka (Clock) PC Synchronized
Boka MCU Clock hello
B| String char
Null Terminated Array String
, ?

Synchronized
(!) PC Boka MCU
Accurate

>:( , Start bit


, Boka MCU Clock PC
LSB (Least
Significant Bit) ,
Boka MCU
PC

, PC Boka MCU , PC

hello PC hello
Parity Bit [may but not will] Parity Bit Stop Bit ,
Error checking Bit Receiver [Boka MCU] Error
Parity Bit Stop Bit

Parity Bit Transmitter Parity Bit ,


PC Boka MCU word
Boka MCU Stop Bit Boka MCU ( ?)
Framing Error *

UART Protocol UART


, Sender Receiver Identically configure
Start, Stop Parity Bit

hello , world , ?
, , PC Start Bit
Stop Bit

( ) 83
Arduino

Transmission line USART


USART

:
, ,
ATmega8u2 ATmega16u2 Arduino.h B|


Arduino IDE
, ; , :P

const int led = 13;


char command;

void setup() {
Serial.begin(9600);
Serial.println("Ready for command\nEnter A/a to turn on\nEnter other keys to turn off");
pinMode(led, OUTPUT);
}

void ledOn()
{
Serial.println("Led On!");
digitalWrite(led, HIGH);
}

void ledOff()
{
Serial.println("Led Off!");
digitalWrite(led, LOW);
}

void loop() {
if (Serial.available()){
command = Serial.read();
if (command == 'a' || command == 'A') ledOn();
else ledOff();
}
}

( ) 84
Arduino

Walkthru:
,

Line 5:

Serial.begin(9600);

( ) 85
Arduino

OOP , Serial Definition Arduino.h


begin Serial OOP ,
objectName.methodName(parameter) ,
begin Serial communication establish

begin 9600 ! Baud Rate


? UART
Serial Monitor ;)

Line 6:

Serial.println("Ready for command\nEnter A/a to turn on\nEnter other keys to turn off");

println -> printf(Hello


world) Serial comm B| print println
Enter

println("blablabla") print("blablabla\n")

Line 11:

void ledOn()
{
Serial.println("Led On!");
digitalWrite(led, HIGH);
}


( ) :P

Line 24:

if (Serial.available()){

available , ?
, available() boolean
bool

Line 25:

( ) 86
Arduino

command = Serial.read();

, command
read() char ( )

Line 26 Line 27:

if (command == 'a' || command == 'A') ledOn();


else ledOff();

a A :D

:
led
command
Serial communication 9600 bits per sec
led
ledOn
ledOff

:
, command
command a A ledOn()
ledOff()

, ADC

:
Baud Rate:
Arduino Baud Rate 9600 bits
per second Baud Rate 115200 bits per second

Framing Error:
PC MCU Interrupted

( ) 87
Arduino

[F. A. Q]
Serial Monitor ? ?
Serial B| , ,

Serial Monitor , -
-

Serial Communication ?
:P Sensor checking ,
wireless/wired data transmission , interfacing !

( ) ??
Serial communication , -


, ADC !

( ) 88
Arduino


,
, , Environment Interaction
ADC
:

10K / 20K Potentiometer (AKA Variable Resistor)

Premium Jumper Wires [22AWG Solid would work too]

(ADC) 89
Arduino

IR Sensor pair [RX/TX] [ IR , -


IR IR
IR , IR
IR ]

(ADC) 90
Arduino

IR Alternative LDR-LED Pair [Light Dependent Resistor]

Resistors [1k, 330, 10k]

ADC :

(ADC) 91
Arduino

?

? State
? ,
, , , . , , , . , ., ., ., . . ..

? , !
,
, ? , , ., ., . ?
?

ADC

, sin(theta) vs theta sin()


, 90 0

sin(0) 90 90
sin(theta) (
)

( )

(ADC) 92
Arduino

x = 0:90:720;
plot(x, sind(x));

* =
! ,

, Sawtooth !

(ADC) 93
Arduino

:
,
;
( ) - -


0V OFF 0 5V Reference
Voltage ON

, ADC ?
, ADC


:

(ADC) 94
Arduino

theta = 0:.1:90;
plot (theta, sind(theta));
axis([0 90 0 1]);

sine -
3-bit ADC Channel Pass :

(ADC) 95
Arduino

syms x;
sqr = floor(x);
ezplot(sqr, [0, 8]);

8 ! 3-bit ADC Channel = 2^3 = 8


, Peak Value 5V
5/8 = 0.625V 2.5V ADC Value 4
5V ADC Value 8

ADC Value Accuracy ADC Resolution ,




ADC ? ADC 1024 5V
1023 ( ) 2.5V 512..
Arduino ADC Channel 10-bit [2^10 = 1024]

ADC [ ]:
UNO Mega A0-A5 (UNO) A0-
A15(Mega)

(ADC) 96
Arduino

ADC Arduino Function :

int sensorValue = analogRead(int sensorPin);

analogRead

:
5V GND

,
IR, LDR Photosensitive / Photo reflective sensor

:
,
:

:
- ,

(ADC) 97
Arduino

const int potPin = 14; //Change 14 to 53 If you use Arduino Mega

void setup()
{
Serial.begin(9600);
pinMode(potPin, INPUT); //Sensors are always set as INPUT
}

void loop()
{
int value = analogRead(potPin);
Serial.println(value);
delay(200);
}

(ADC) 98
Arduino

IR Sensor :

IR : IR Led IR
Led IR Ray IR TX IR RX IR
IR RX
IR

:
330 Ohm IR TX 10K IR RX
IR Pair LDR
IR LED LED

(ADC) 99
Arduino

(ADC) 100
Arduino

:
ADC PWM ?

:
, 0-255
0-1023

IR ?

:
IR Led 330Ohm Receiver
1/10K

? ?

MATLAB ,

(ADC) 101
Arduino

102
Arduino

LCD (Liquid Crystal Display) (


)
LCD ,
Alphanumerical Graphical LCD
LCD
LCD Hookup

( IDE)
USB Cable (A to B)

16x2 / 16x4 / 20x4 /.. Alphanumeric Liquid Crystal Display (LCD)

LCD ( ) 103
Arduino

10k Ohm Pot

Jumper Wires (22AWG or Premium)

Breadboard

LCD Header Pin Soldered

Soldering Iron


Header Pin

LCD ( ) 104
Arduino

Proteus ISIS
Arduino IDE

LCD :
Alphanumeric LCD , Backlight
+ LCD

? LCD ,

: LCD , 16x4, 16x2 20x2


20x4, LCD

LCD wiring LCD module wiring


4-pin 8-pin mode 4-pin
LCD :

LCD :

LCD ( ) 105
Arduino

LCD ,

LCD

LCD ( ) 106
Arduino

Pin no. Pin Name Pin Purpose

1 VSS GND Connection


2 VDD +5V Connection
3 V0 Contrast Adjustment

4 RS Register selection (Character vs Command)


5 RW Read/Write
6 EN Enable
7 D0 Data Line 0 (Unused)

8 D1 Data Line 1 (Unused)


9 D2 Data Line 2 (Unused)
10 D3 Data Line 3 (Unused)
11 D4 Data Line 4
12 D5 Data Line 5
13 D6 Data Line 6

14 D7 Data Line 7
15 A Backlight Anode (+5V Connection)
16 K Backlight Cathode (GND Connection)


V0 [3rd Pin]:

V0 LCD Contrast 10KOhm Pot


V0 LCD

V0

RS [4th Pin]:

LCD Command Character mode LCD


Data Line Data set
?

RW [5th Pin]:

LCD Write

LCD ( ) 107
Arduino

EN [6th Pin]:

EN LCD Data Line

Backlight Anode & Cathode [15th & 16th Pin]:

LCD 15 +5V
16 GND


LCD :

LCD Pin Arduino Pin Number


RS Pin 2
EN Pin 3
D4 Pin 4
D5 Pin 5
D6 Pin 6
D7 Pin 7


Arduino LCD

LCD ( ) 108
Arduino


LCD ,
LCD "Electroscholars"

LCD ( ) 109
Arduino

//Importing LiquidCrystal Library for driving the LCD

#include <LiquidCrystal.h>

//LCD Dimension
#define COLS 16
#define ROWS 4

//Creating global LCD Object


LiquidCrystal my_lcd(2, 3, 4, 5, 6, 7);

void setup()
{
//Setting up the LCD
my_lcd.begin(COLS, ROWS);

//Setting the cursor at the beginning


my_lcd.setCursor(0, 0);

//Printing a string on the lcd


my_lcd.print("Electroscholars");
}

//Nothing To Loop
void loop() {}

( ):

LCD ( ) 110
Arduino


#import <LiquidCrystal.h>
LCD LiquidCrystal

LiquidCrystal , ,
, (left to right / right to left)

, - ;

LCD

#define ROWS, #define COLS


LCD LCD
#define , LCD
variable
:

LCD ( ) 111
Arduino

const int rows = 4;


const int cols = 16;

my_lcd.begin(16, 4);

LiquidCrystal my_lcd(....)

?

LiquidCrystal #LiquidCrystal.h
:

//Without constructor arguments


the_class objectName;

//If the constructor takes arguments


the_class objectName(1, 2, 3);

LiquidCrystal Constructor
LCD I/O

Constructor

LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);

my_lcd.begin(COLS, ROWS);
LCD LiquidCrystal::begin(const
uint8_t, const uint8_t) LCD

LCD
LiquidCrystal::print(char* str) LiquidCrystal::setCursor(uint8_t x, uint8_t y)

my_lcd.setCursor(x, y)

LCD ( ) 112
Arduino

Cursor LCD
my_lcd.setCursor(1, 2); //1 for second
column, 2 for 3rd row [zero indexing]

my_lcd.print(..)
LiquidCrystal::print(char *str) LCD

void loop()

LCD LCD
, LCD

LCD Header

LCD ( ) 113
Arduino

:
C/C++ IDE [Code::blocks, Codelite, Qt Creator, Visual Studio..] Text
Editor [Notepad++, Sublime Text Editor, Atom, Brackets ...]

Official Arduino IDE

(Proteus)

LCD Module ( )

:
, digitalWrite(size_t, MODE)
analogRead(size_t) LED
Serial.read()
Arduino Arduino Avr
Communication Atmega8U2 / Atmega16U2
- * Atmega328p-PU
AVR AVR-C
Arduino Library
,

- ,
Code Reusability

, PIC MikroC
Pay /

114
Arduino

,
,

, , ,

,


, ;
,

SoftwareSerial
LiquidCrystal
Wifi
NewPing
SPI


MyLibrary

MyLibrary :
examples [MyLibrary/examples/MyExample/MyExample.ino] :
, .ino

changelog.txt [MyLibrary/changelog.txt] : ,
(optional)
keywords.txt [MyLibrary/keywords.txt] : Class, method, properties
Syntax Highlighting , Class, method
IDE Keyword (optional)
MyLibrary.h [MyLibrary/MyLibrary.h] : ,

115
Arduino


,
Header

MyLibrary.cpp [MyLibrary/MyLibrary.cpp] : Header
,
.h .cpp [MyLibrary/Others.h, MyLibrary/Others.cpp]:
/

:
LiquidCrystal , /
, :

(
)


MyLiquidCrystal.h

MyLiquidCrystal.cpp

116
Arduino

keywords.txt

changelog.txt

examples\ScrollText\ScrollText.ino

MyLiquidCrystal LiquidCrystal Arduino.h


LiquidCrystal ( LiquidCrystal.h LiquidCrystal.cpp )
Arduino.h


, Buggy
,

:
LiquidCrystal ,
LCD LiquidCrystal
Buggy code

117
Arduino

LCD (maxCol)
:

(x,y)
del
LCD
x
:
y
x
y LCD maxRow :

x
y

118
Arduino

119
Arduino

MyLiquidCrystal.h MyLiquidCrystal
LiquidCrystal
Header
, #ifndef
: #ifndef MyLiquidCrystal_h
#define : #define MyLiquidCrystal_h
#endif

//Header File Name: MyLiquidCrystal.h


#ifndef MyLiquidCrystal_h
#define MyLiquidCrystal_h

//Logic Goes here

#endif

#include
LiquidCrystal Arduino.h #include

120
Arduino

#ifndef MyLiquidCrystal_h
#define MyLiquidCrystal_h

//Naming unsigned 8 bit integer as "byte"


typedef uint8_t byte;

//Adding Necessary Header Files


#include "Arduino.h"
#include "LiquidCrystal.h"

#endif

, :

i) Inheritance
LiquidCrystal Header
: LiquidCrystal
LiquidCrystal ,

#ifndef MyLiquidCrystal_h
#define MyLiquidCrystal_h

//Naming unsigned 8 bit integer as "byte"


typedef uint8_t byte;

//Adding Necessary Header Files


#include "Arduino.h"
#include "LiquidCrystal.h"

//Added Class
class MyLiquidCrystal : public LiquidCrystal {
//Methods And Properties go here
};

#endif

ii) Properties

( )
private
public get set

121
Arduino

class MyLiquidCrystal : public LiquidCrystal {


private:

//Initial Position Variable


byte x;
byte y;

//Scroll Delay
byte scrollDelay;

//Storing LCD Row and Column


byte lcdRows;
byte lcdCols;

//Getting the string length for out of bound calculation


byte wordLength;

//Distance from first character to the last boundary of lcd


byte distance;
};

iii) Method
,
Access Modifier public

122
Arduino

class MyLiquidCrystal : public LiquidCrystal {


public:

//Function for scrolling


void word_scroll(char *str, byte del);

//Setting LCD Dimension


void set_lcd(byte col, byte row);

//Get LCD Dimension


byte get_row(void);
byte get_col(void);

//Using Constructor from LiquidCrystal, and setting initial position to 0, 0 (or at the top left
MyLiquidCrystal(byte rs, byte en, byte d4, byte d5, byte d6, byte d7) : LiquidCrystal (rs, en, d4
{
x = 0;
y = 0;
}

//Getting the distance of word


byte get_distance(void);
};

: MyLiquidCrystal LiquidCrystal
derived_class(int arg1, int arg2) : base_class(arg1,
arg2) {}

[MyLiquidCrystal.cpp]

, MyLiquidCrystal OOP , Out
of Class : return_type className ::
(scope_resolution_operator) functionName(argument)

#include "MyLiquidCrystal.h"

//Initialize LCD
void MyLiquidCrystal::set_lcd(byte col, byte row)
{
lcdRows = row;
lcdCols = col;
begin(col, row);

123
Arduino

//Getting Rows and Columns


byte MyLiquidCrystal::get_col(void)
{
return lcdCols;
}

byte MyLiquidCrystal::get_row(void)
{
return lcdRows;
}

//Getting Current Distance


//It is measured from the first character of the string upto the boundary

byte MyLiquidCrystal::get_distance(void)
{

return get_col() + 1 - x;
}

//Function that actually does the scrolling


void MyLiquidCrystal::word_scroll(char *str, byte del)
{
//Getting the string length
wordLength = strlen(str);
scrollDelay = del;

//Getting row and column


byte maxCol = get_col();
byte maxRow = get_row();

//Infinite Loop [You have to customize and solve it]


//Buggy code
while (true){
if (get_distance() >= wordLength){

/* Algorithm
* -> Check if the distance is greater or equal to the wordlength
* -> set Cursor at a coordinate
* -> Print the string
* -> wait about delay time
* -> clear the lcd
* -> Increase x one character
* -> Check if the word is at boundary
* -> if it's in the boundary then increase y and set x = 0
* -> follow the algorithm from beginning
* */
setCursor(x, y);
print(str);
delay(scrollDelay);
clear();

124
Arduino

x++;
if (get_distance() == wordLength)
{
x = 0;
y++;
}
}
//If the cursor is at the bottom then setting the cursor at the beginning
if(y == maxRow) {x = 0; y = 0;}
}
}

Syntax Highlighting keywords.txt

Arduino IDE
,
keywords.txt (TAB) [ TAB ,
; / ,
]

Class KEYWORD1 Method KEYWORD2


keywords.txt

#########################################
# Syntax Coloring Map For MyLiquidCrystal
#########################################

###################################
# Datatypes (KEYWORD1)
###################################

MyLiquidCrystal KEYWORD1

###################################
# Methods and Functions (KEYWORD2)
###################################

word_scroll KEYWORD2
set_lcd KEYWORD2
get_row KEYWORD2
get_col KEYWORD2
get_distance KEYWORD2

, Example

125
Arduino

examples

examples examples
ScrollText

.ino ScrollText.ino

ScrollText.ino MyLiquidCrystal

#include <MyLiquidCrystal.h>

//Creating MyLiquidCrystal Object, constructor same as LiquidCrystal


MyLiquidCrystal myLcd(2, 3, 4, 5, 6, 7);

void setup()
{
//Initializing the lcd module, set_lcd calls begin method so don't need to call lcd.begin

myLcd.set_lcd(20, 4);

//String scroll method


myLcd.word_scroll("Manash", 100);
}

void loop() {}


Arduino IDE

: Arduino IDE
C:\Users\user_name\Documents\Arduino\libraries\

: (.zip)

126
Arduino

Arduino IDE Sketch > Import Library > your_library.zip


Arduino IDE
keywords.txt , TAB Space
Space

:
,
ScrollText.ino

127
Arduino

:
,

word_scroll while(true) Infinite loop


word_scroll , infinite loop
Button, Serial

, word_scroll LCD

128
Arduino

129
Arduino

Qt Arduino

:
Qt 4 5 [ ]
C++ ( ,
]
Arduino Board (
)
Usb A to B Cable
Arduino IDE

Qt ?
Qt ( "" "-" ())

C++ GUI Based Qt Framework



Qt Framework
signal slot Arduino

Qt First Run
-> New Project -> Application -> Qt Widgets Application ->
Choose -> Name -> Next -> Next -> Next -> Finish MainWindow.cpp

Qt Arduino 130
Arduino

main.cpp --
, Ctrl+R
MainWindow

Qt

Qt

Qt Arduino 131
Arduino

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])


{
QApplication a(argc, argv);
QLabel label("Electroscholars");
label.show();
return a.exec();
}

? "Hello World"
Minimum Qt GUI GUI
, "Electroscholars"

Walkthru
#include "mainwindow.h"

Qt Arduino 132
Arduino

main.cpp

#include <QApplication>
Qt Header

#include <QLabel>
Qt , Header Class
Q Label Label
Qt Variant QLabel Header

QApplication a(argc, argv);


QApplication
a (argc,
argv) QApplication
QApplication Event Loop
window

QLabel label("....");
QLabel
Invisible Visible
label.show()

return a.exec()
Event Loop Event
User Action
LED Event Loop
QApplication quit


Qt

Qt Arduino 133
Arduino

The Book of Qt 4 - The Art of Building Qt Application


C++ GUI Programming in Qt - Summerfield
Official Qt Documentation


VoidRealms +
Qt BootCamp

Qt Designer Event Driven GUI



, Led
On Led Off


Forms mainwindow.ui
,

Qt Arduino 134
Arduino

: ,
:

,
go to slot -> clicked() IDE

Qt Arduino 135
Arduino

: qDebug() cout
#include <QDebug>

led off

ledStatus QLabel ,
ui_mainwindow.h
Qt IDE
,
,
ledStatus QLabel setText
ledStatus ?
MainWindow / Widget / Dialog Ui
private *ui
, ui
ui->object->objectMethod()
ledStatus ui->ledStatus-
>setText("Some text")

Qt Arduino 136
Arduino

Qt Arduino 137
Arduino


led off on

QSerialPort Arduino
QSerialPort
.pro serialport

Qt Arduino 138
Arduino

QSerialPort mainwindow.h Header


#include <QSerialPort> Header
QSerialPort private access
modifier public

Qt Arduino 139
Arduino

: Arduino Qt
An optional
second argument configures the data, parity, and stop bits. The default is 8 data

bits, no parity, one stop bit. , dataBits ,


Parity one stop

Serial.begin baudRate

Qt QSerialPort
arduino, Connect
Connection Established

( ) :

arduino->setPortName("COM12"); //yours maybe different, please check by connecting it to your pc


arduino->setBaudRate(QSerialPort::Baud9600);
arduino->setDataBits(QSerialPort::Data8);
arduino->setParity(QSerialPort::NoParity);
arduino->setStopBits(QSerialPort::OneStop);
// Skipping hw/sw control
arduino->setFlowControl(QSerialPort::NoFlowControl);

Connect (mainwindow.cpp ) QSerialPort



COM12

arduino = new QSerialPort(this);


arduino->setPortName("COM12");

Qt Arduino 140
Arduino

mainwindow.ui QPushButton
ObjectName connectArduino Text
Connect go to slot

Qt Arduino 141
Arduino

QSerialPort
Establish
ReadWrite Mode
:

Qt Arduino 142
Arduino

QMessageBox
Qt Docs

, LED ON
Led LED OFF
LED Arduino write()

Qt Arduino 143
Arduino

LED , Serial
Qt
:

//Arduino Side
// Baud Rate 9600
int led = 13;
char command;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}

void loop() {
if (Serial.available()){
command = Serial.read();
if (command == 'a') digitalWrite(led, HIGH);
else digitalWrite(led, LOW);
}
}

Qt Arduino 144
Arduino

, Led

Qt Arduino 145
Arduino

,

Arduino LCD Qt Desktop App Wirelessly
F.A.Q
one way duplex

Qt Arduino 146
Arduino



PySerial

:
-
. -

PySerial
PyQt4 [optional]

pip pip

( ) ( )

pip install pyserial

Python , PyQt4
147
Arduino

#define led 13
#define baud 9600

void setup() {
pinMode(led, OUTPUT);
Serial.begin(baud);
}

void loop() { /*Nothing to do*/ }

void serialEvent(){
if (Serial.available() > 0){
//Reading string until '\n' is encountered
String command = Serial.readStringUntil('\n');

//Sending a reply after executing the function


if (command.equals("on")) { digitalWrite(led, HIGH); Serial.println("LED ON"); }
else if (command.equals("off")) { digitalWrite(led, LOW); Serial.println("LED OFF"); }
}
}

- void loop() {}
serialEvent()

- void serialEvent(){
/

,
Call ,

Interrupt Signal
Interrupt Function

,
serialEvent()

Python , PyQt4
148
Arduino

- String command =
Serial.readStringUntil('\n')
\n ,
command String

- if (command.equals("on")) ...
equals String command String
command.equals(another_string)

equals , equals
boolean , equals true
false

digitalWrite ... ; Serial.println ...


on 13 no LED LED

off .... :P

Python , PyQt4
149
Arduino

# Importing the pyserial library


import serial

# My arduino is connected to COM3, check device manager for yours


arduino = serial.Serial("COM3")

# Closing the arduino serialport just in case


arduino.close()

# Setting baudrate to 9600


arduino.baudrate = 9600

# If not open then try to open it


if not arduino.is_open:
arduino.open()

# While the port is opened, play with it by sending string commands


while True:
command = raw_input('Enter command: ')
arduino.write(command + '\n')
print arduino.readline()

- import serial

- arduino = serial.Serial(com_port)
Serial
Arduino COM3 ,
IDE , Device manager > Ports
( )

Python , PyQt4
150
Arduino

- arduino.close()
, ,
Safety check

- arduino.baudrate = 9600
, 9600 ,

- - if not ...
( )

- while True:

- command = raw_input('Enter command: ')

Python , PyQt4
151
Arduino

, ,

- arduino.write(command + '\n')
write

+ \n ,
readStringUntil('\n') , ' ' \n
;, -, + ,
readStringUntil(delimiter)

- print arduino.readline()

Python , PyQt4
152
Arduino

PyQt4
PyQt4

PySerial

Python , PyQt4
153

You might also like