materi kuliah mikro_uts

250
Mikrokontroler P1 – PENDAHULUAN RATNA AISUWARYA, M.ENG

Upload: rizkifajri

Post on 19-Dec-2015

29 views

Category:

Documents


4 download

DESCRIPTION

silahkan

TRANSCRIPT

Page 1: Materi Kuliah Mikro_UTS

MikrokontrolerP1 – PENDAHULUAN

RATNA AISUWARYA, M.ENG

Page 2: Materi Kuliah Mikro_UTS

Materi Hari IniKontrak Perkuliahan

Pengenalan Mikrokontroler (Arduino, ATMega 328)

Page 3: Materi Kuliah Mikro_UTS

Penilaian, Aturan Kehadiran

Penilaian

Tugas

Plagiarisme

Praktikum

Partisipasi

Page 4: Materi Kuliah Mikro_UTS

Penilaian Tugas : 20 %

Tugas Besar : 10 %

Praktikum : 20%

UTS : 25%

UAS : 25%

Page 5: Materi Kuliah Mikro_UTS

Materi Kuliah Pengenalan Arduino – ATMega 328

Pemrograman Arduino

Komunikasi Serial

Analog Digital Conversion (ADC)

Sistem Interupsi

Sistem Timer

Aplikasi Antarmuka

Page 6: Materi Kuliah Mikro_UTS

Apa yang akan dipelajari ?

Page 7: Materi Kuliah Mikro_UTS

P1. Overview Konsep arduino sebagai hardware open source.

Layout diagram board Arduino.

Deskripsi fitur‐fitur yang ada bada board Arduino.

Fitur‐fitur dan fungsi ATmega328.

Varian board Arduino.

Pengembangan fitur hardware pada Arduino.

Download, konfigurasi, dan eksekusi program test menggunakan software Arduino.

Page 8: Materi Kuliah Mikro_UTS
Page 9: Materi Kuliah Mikro_UTS

Apa itu Arduino ?

Page 10: Materi Kuliah Mikro_UTS

Arduino

Page 11: Materi Kuliah Mikro_UTS

Arduino

Page 12: Materi Kuliah Mikro_UTS

Apa saja Komponennya ? Arduino‐based hardware processing platform Arduino Duemilanove board / Arduino Uno

Arduino compatible power supply Board Arduino dapat diaktifkan dengan power yang bersumber dari port USB komputer, atau dari power supply eksternal.

Arduino software Disediakan Arduino IDE (Intergrated Development Environment) yang dapat diunduh gratis di homepage Arduino (www.arduino.cc). 

Page 13: Materi Kuliah Mikro_UTS

Arduino Layout

Page 14: Materi Kuliah Mikro_UTS

ARDUINO HOST PROCESSOR — THE ATMEGA328 Prosesor Arduino adalah Atmel Atmega 328. 28 Pin. Mikrokontroler 8‐bit.

Arsitekturnya berbasis Reduced Instruction Set Computer (RISC), yang dapatmengeksekusi 20 Juta Instruksi per detik (MIPS) million instructions per second(MIPS) ketika bekerja dengan frekuensi 20 MHz!

Fitur‐fitur yang ada pada  Arduino Duemilanove :Memory system Port system Timer system Analog‐to‐digital converter (ADC) Interrupt system Komunikasi serial

Page 15: Materi Kuliah Mikro_UTS

Arduino systems

Page 16: Materi Kuliah Mikro_UTS

EXAMPLE: AUTONOMOUS MAZE NAVIGATING ROBOTSebelum membahas lebih jauh tentang arduino, kita lihat contoh penerapan arduino sebagaikontroler robot (Blinky 602A). Robot ini bekerja sebagai line following robot. Dengan komponensebagai berikut :

2 motor DC untuk roda kiri dan kanan. Roda ketiga untuk kestabilan robot.

3 sensor Infra Red Sharp GP12D yang akan mendeteksi dinding pada labirin.

Page 17: Materi Kuliah Mikro_UTS
Page 18: Materi Kuliah Mikro_UTS
Page 19: Materi Kuliah Mikro_UTS

STRUCTURE CHARTBlok diagram menggambarkan sistem secara visual. Tanda panah menunjukkanaliran data antara bagian‐bagian. Pada blok diagram robot ini terdapat 3 sistemutama :

sistem kontrol motor

sistem sensor

sistem input/output digital.

Ketiga sistem tsb saling berinteraksi dengan algoritma kontrol utama yang akanmengatur robot agar dapat bekerja secara otomatis melalui labirin by sensingand avoiding walls.

Page 20: Materi Kuliah Mikro_UTS
Page 21: Materi Kuliah Mikro_UTS

DIAGRAM UMLDiagram Unified Modeling Language (UML) atau flow chart,merupakan tool yang memvisualisasikan langkah‐langkah yang diperlukan untuk menjalankan algoritma. Pada flowchart robot ini, setelah inisialisasi sistem, kontrol robot berjalan secara continous loop. 

Page 22: Materi Kuliah Mikro_UTS

ARDUINO OPEN SOURCE SCHEMATICSemua produk Arduino memiliki konsep open source hardware dan software, yang berarti untuk pengembangannya terbuka bagi semua pengguna untuk menghasilkan konsep/ide baru. Sehingga team pengembang arduino secara terbuka membagi rangkaian skematik semua tipe board arduino.

Page 23: Materi Kuliah Mikro_UTS
Page 24: Materi Kuliah Mikro_UTS

Variasi Arduino

Page 25: Materi Kuliah Mikro_UTS

Arduino shield

Page 26: Materi Kuliah Mikro_UTS

ARDUINO SOF TWAREDisebut juga dengan Arduino Development Environment.  Program ini dapat didownload di homepage Arduino (www.arduino.cc)

Page 27: Materi Kuliah Mikro_UTS

ARDUINO /ATMEGA328 HARDWAREFEATURESArduino Duemilanove / Uno menggunakan Atmega 328 sebagai prosesornya. Berikut Diagram pin dan blok diagram Atmega328

Page 28: Materi Kuliah Mikro_UTS
Page 29: Materi Kuliah Mikro_UTS
Page 30: Materi Kuliah Mikro_UTS

MEMORYATmega328 memiliki 3 memori utama :

Flash electrically erasable pro‐grammable read only memory (EEPROM)

Static random access memory (SRAM)

byte‐addressable EEPROM untuk penyimpanan data. 

Page 31: Materi Kuliah Mikro_UTS

In-System Programmable Flash EEPROM programmable flash EEPROM digunakan untuk menyimpan program.

memori ini dapat dihapus dan diprogram sebagai single unit.

Flash EEPROM merupakan memori nonvolatile, isi memori tetap ada sampai catu daya dimatikan. 

ATmega328 memiliki 32K bytes reprogrammable flash memory. Komponen memory ini terdiri dari 16K lokasi yang dapat menyimpan 16 bit untuk setiap lokasi.

Page 32: Materi Kuliah Mikro_UTS

Byte-Addressable EEPROM Byte‐addressable memory digunakan untuk menyimpan secara permanen variabel‐variabel selama eksekusi program.

merupakan memori nonvolatile. Berguna untuk sistem logging jika terjadi kesalahan / malfunction saat eksekusi program, juga berguna untuk menyimpan data ketika kehilangan catu daya tapi bisa diganti‐ganti secara periodik. Contoh : kunci elektronik, pintu garasi otomatis.

ATmega328 memiliki EEPROM 1024 bytes.

Page 33: Materi Kuliah Mikro_UTS

Static Random Access Memory (SRAM)Memory Static RAM merupakan volatile, yang isinya akan terhapus jika catu daya dimatikan.

Memory dapat ditulis dan dibaca selama eksekusi program.

ATmega328 memiliki 2KBytes SRAM. Terdapat bagian kecil yang dialokasikan untuk  general purpose registers yang digunakan oleh prosesor dan sistem input/output peripheral.

Daftar register dan file headeryang ada pada ATmega328 dapat dilihat di lampiran A dan B.

Ketika eksekusi program, RAM digunakan untuk menyimpan variabel global, mendukung alokasi memory dynamic untuk variabel, dan menyediakan lokasi stack .

Page 34: Materi Kuliah Mikro_UTS

PORT SYSTEM Atmel ATmega328 memiliki 4 unit 8‐bit input/output (I/O) digital, yaitu : PORTA, PORTB, PORTC, and PORTD. 

Semua port ini memiliki fungsi alternatif. (akan dibahas nanti)

Page 35: Materi Kuliah Mikro_UTS
Page 36: Materi Kuliah Mikro_UTS

Terlihat pada gambar 1.13, setiap port memiliki tiga register , yaitu :

Data Register PORTx —‐ digunakan untuk menulis data output ke port. 

Data Direction Register DDRx —‐ digunakan untuk set pin tertentu pada port untuk output (1) atau input (0).

Input Pin Address PINx —‐ digunakan untuk membaca data input dari port. 

Gambar 1.13(b) menjelaskan pengaturan yang dibutuhkan untuk konfigurasi pin tertentu pada port untuk input atau output.

Jika input, pin dapat di set sebagai pin input atau untuk beoperasi dengan mode impedansi tinggi (Hi‐Z) mode. Ketika mode Hi‐Z , input pada pin tersebut berimpedansi tinggi.

Jika output, pin dapat diatur sebagai  logic low atau logic high.

Pin‐pin pada port dikonfigurasi di awal program, baik untuk input atau output dengan set nilai awal.  Biasanya 8 pin pada port dikonfigurasi sekaligus bersamaan.

Page 37: Materi Kuliah Mikro_UTS

ATmega328 block diagram

Page 38: Materi Kuliah Mikro_UTS

INTERNAL SYSTEMSBagian ini membahas fitur‐fitur internal yang ada pada ATmega328.fitur‐fitur tersebut telah built‐in pada chip mikrokontrolernya.Dengan ini tugas‐tugas cukup rumit dapat dilakukan olehmikrokontroler.

Page 39: Materi Kuliah Mikro_UTS

Time Base Mikrokontroler merupakan sebuah synchronous state machine yang kompleks. 

secara sekuensial merespon step‐step program seperti yang tertulis pada program yang dibuat oleh user dengan urutan fetch‐decode‐execute. 

setiap instruksi program bahasa assembler menghasilkan serangkaian sinyal kontrol ke hardware mikrokontroler untuk menghasilkan operasi‐operasi yang berkaitan dengan instruksi yang diberikan.

Page 40: Materi Kuliah Mikro_UTS

Time Base (con’t) Kecepatan urutan‐urutan setiap task pada mikrokontroler diaturdengan clock.  Sumber clock ini dijadikan sinyal pulsa bagi seluruhperangkat yang terhubung dengan mikrokontroler. 

ATmega328 memiliki clock internal atau clock eksternal. FrekuensiClock internal dapat diatur melalui program, dengan frekuensi 1, 2, 4 or 8 MHz.

Untuk variasi frekuensi selain itu dapat menggunakan eksternalclock (cth: oscillator crystal).

Page 41: Materi Kuliah Mikro_UTS

Timing Subsystem ATmega328 dilengkapi dengan timer tambahan yang dapatmenghasilkan sinyal output yang presisi, menghitung karakteristiksinyal digital (periode, duty cycle, frekuensi). 

ATmega328 dilengkapi dengan 2 unit timer/counter 8‐bit dan 1 unit counter 16‐bit. 

Page 42: Materi Kuliah Mikro_UTS

Pulse Width Modulation Channels Sinyal Pulse width modulated (PWM) memiliki frekuensi tetap dengan duty cycle yang bervariasi. 

Duty cycle adalah persentasi waktu sinyal dengan logika high selama periodesinyal berlangsung. Dapat dituliskan sebagai :

ATmega328 memiliki 4 unit channel (PWM). Channel PWM terhubung dengansumber clock yang dapat menghasilkan beberapa variasi lebar sinyal PWM (darifrekuensi tinggi dengan sinyal low duty cycle sampai dengan frekuensi rendahdengan sinyal high duty cycle)

Sinyal PWM digunakan dalam berbagai aplikasi, seperti dalam pengontrolanposisi motor servo, pengaturan kecepatan motor DCV, dll. 

Page 43: Materi Kuliah Mikro_UTS

Serial CommunicationsATmega328 dilengkapi dengan beberapa subsistem komunikasi serial : Universal Synchronous and Asynchronous Serial Receiver and Transmitter (USART) Serial peripheral interface (SPI) Two‐wire Serial Interface. Semua system tersebut menggunakan transmisi data secara serial, yaitu dengan mengirimkan data bit per bit dari transmitter kereceiver. 

Page 44: Materi Kuliah Mikro_UTS

Serial USART Serial USART menggunakan komunikasi full duplex (dua arah) antara receiver dan transmitter.  Pada Atmega328 dihubungkan dengan hardware terpisah untuk transmitter dan receiver. 

USART secara umum menggunakan komunikasi asynchronous. Yang artinya tidak ada clock yang tetap antara pengirim dan penerima. Untuk menyelaraskan antara keduanya, digunakanstart bit dan stop bit disetiap awal dan akhir data. 

USART pada ATmega328 USART cukup flexible. Kecepatan transmisi data (Baud (bits per second) dapat diset sesuai dengan keperluan, dengan lebar data 5 – 9 bit dengan satu atau duastop bit.

ATmega328 juga dilengkapi dengan bit parity (even atau odd) dan hardware yang akanmelakukan check parity pada receiver. Satu bit paritas dapat mendeteksi error bit dalam satubyte data. 

USART juga bias dikonfigurasi dalam mode synchronous. (akan dibahas nanti).

Page 45: Materi Kuliah Mikro_UTS

Serial Peripheral Interface—SPI Serial Peripheral Interface (SPI) menggunakan komunikasi serial dua arah antara transmitter dan receiver. 

Sistem SPI menggunakan sumber clock yang sama. Sehingga membutuhkan jalur clock tambahan antara receiver dan transmitter tapi juga meningkatkan kecepatan transmisi data dibandingkan USART. 

SPI  merupakan shift register synchronous dengan 8‐bit transmitter dan 8‐bit receiver. 

Transmitter di set sebagai master karena menyediakan sumber clock antara transmitter danreceiver. Sedangkan receiver di set sebagai slave.  (dibahas nanti)

Page 46: Materi Kuliah Mikro_UTS

Two-wire Serial Interface—TWI Dengan Sistem TWI beberapa perangkat bisa dihubungkan dalam satu jaringan(microcontrollers, transducers, displays, memory storage, etc.) denganmenggunakan skema interkoneksi two‐wire.

The TWI dapat menghubungkan maximum 128 perangkat sekaligus. Setiapperangkat memiliki alamat yang unik dengan frekuensi komunikasi data sampaidengan 400 KHz. This allows the device to freely exchange information with other devices in the network within a small area. 

Page 47: Materi Kuliah Mikro_UTS

Analog to Digital Converter—ADC ATmega328 dilengkapi dengan 8 channel ADC.

ADC mengkonversi sinyal analog dari lingkungan luar menjadi repesentasi biner untukdigunakan oleh mikrokontroler.

Atmega328 memiliki ADC dengan resolusi 10 bit, yang artinya tegangan analog antara 0 sampai dengan 5 Volt akan di encode menjadi satu dari representasi 1024 angka biner, yaituantara 000(16) dan 3FF (16).

Page 48: Materi Kuliah Mikro_UTS

Interrupts Eksekusi program secara umum mengikuti langkah‐langkah sesuai dengan urutan instruksiyang telah dibuat.

Tetapi, terkadang urutan instruksi ini perlu di interupsi untuk merespon kesalahan atau status  yang memiliki prioritas lebih tinggi pada internal atau eksternal mikrokontroler. 

Saat hal itu terjadi, mikrokontroler harus menghentikan operasi normal dan menjalankaninstruksi spesifik, yang disebut dengan Interrupt Service Routine (ISR). Setelah itu, mikrokontroler akan kembali menjalankan instruksi sesuai dengan urutan proses pada program.

ATmega328 dilengkapi dengan 26 sumber interrupt. 2 adalah interrupt yang bersumber dariluar (eksternal). 

Page 49: Materi Kuliah Mikro_UTS

REFERENCESSparkFun Electronics, 6175 Longbow Drive, Suite 200, Boulder, CO 80301

(www.sparkfun.com)

• Arduino homepage (www.arduino.cc)

Page 50: Materi Kuliah Mikro_UTS

MikrokontrolerARSITEKTUR ATMEGA328

RATNA AISUWARYA, M.ENG

Page 51: Materi Kuliah Mikro_UTS

ARDUINO /ATMEGA328 HARDWAREFEATURES

Page 52: Materi Kuliah Mikro_UTS
Page 53: Materi Kuliah Mikro_UTS

MEMORYATmega328 memiliki 3 memori utama :

Flash electrically erasable programmable read only memory (EEPROM)

Static random access memory (SRAM)

byte‐addressable EEPROM untuk penyimpanan data. 

Page 54: Materi Kuliah Mikro_UTS

In-System Programmable Flash EEPROM programmable flash EEPROM digunakan untuk menyimpan program.

memori ini dapat dihapus dan diprogram sebagai single unit.

Flash EEPROM merupakan memori nonvolatile, isi memori tetap ada sampai catu daya dimatikan. 

ATmega328 memiliki 32K bytes reprogrammable flash memory. Komponen memory ini terdiri dari 16K lokasi yang dapat menyimpan 16 bit untuk setiap lokasi.

Page 55: Materi Kuliah Mikro_UTS

Byte-Addressable EEPROM Byte‐addressable memory digunakan untuk menyimpan secara permanen variabel‐variabel selama eksekusi program.

merupakan memori nonvolatile. Berguna untuk sistem logging jika terjadi kesalahan / malfunction saat eksekusi program, juga berguna untuk menyimpan data ketika kehilangan catu daya tapi bisa diganti‐ganti secara periodik. Contoh : kunci elektronik, pintu garasi otomatis.

ATmega328 memiliki EEPROM 1024 bytes.

Page 56: Materi Kuliah Mikro_UTS

Static Random Access Memory (SRAM)Memory Static RAM merupakan volatile, yang isinya akan terhapus jika catu daya dimatikan.

Memory dapat ditulis dan dibaca selama eksekusi program.

ATmega328 memiliki 2KBytes SRAM. Terdapat bagian kecil yang dialokasikan untuk  general purpose registers yang digunakan oleh prosesor dan sistem input/output peripheral.

Ketika eksekusi program, RAM digunakan untuk menyimpan variabel global, mendukung alokasi memory dynamic untuk variabel, dan menyediakan lokasi stack .

Page 57: Materi Kuliah Mikro_UTS

PORT SYSTEM Atmel ATmega328 memiliki 3 unit 8‐bit input/output (I/O) digital, yaitu : PORTB, PORTC, and PORTD. 

Semua port ini memiliki fungsi alternatif. (akan dibahas nanti)

Page 58: Materi Kuliah Mikro_UTS
Page 59: Materi Kuliah Mikro_UTS

Terlihat pada gambar 1.13, setiap port memiliki tiga register , yaitu :

Data Register PORTx —‐ digunakan untuk menulis data output ke port. 

Data Direction Register DDRx —‐ digunakan untuk set pin tertentu pada port untuk output (1) atau input (0).

Input Pin Address PINx —‐ digunakan untuk membaca data input dari port. 

Gambar 1.13(b) menjelaskan pengaturan yang dibutuhkan untuk konfigurasi pin tertentu pada port untuk input atau output.

Jika input, pin dapat di set sebagai pin input atau untuk beoperasi dengan mode impedansi tinggi (Hi‐Z) mode. Ketika mode Hi‐Z , input pada pin tersebut berimpedansi tinggi.

Jika output, pin dapat diatur sebagai  logic low atau logic high.

Pin‐pin pada port dikonfigurasi di awal program, baik untuk input atau output dengan set nilai awal.  Biasanya 8 pin pada port dikonfigurasi sekaligus bersamaan.

Page 60: Materi Kuliah Mikro_UTS

INTERNAL SYSTEMSBagian ini membahas fitur‐fitur internal yang ada pada ATmega328.fitur‐fitur tersebut telah built‐in pada chip mikrokontrolernya.Dengan ini tugas‐tugas cukup rumit dapat dilakukan olehmikrokontroler.

Page 61: Materi Kuliah Mikro_UTS
Page 62: Materi Kuliah Mikro_UTS

Time Base Mikrokontroler merupakan sebuah synchronous state machine yang kompleks. 

secara sekuensial merespon step‐step program seperti yang tertulis pada program yang dibuat oleh user dengan urutan fetch‐decode‐execute. 

setiap instruksi program bahasa assembler menghasilkan serangkaian sinyal kontrol ke hardware mikrokontroler untuk menghasilkan operasi‐operasi yang berkaitan dengan instruksi yang diberikan.

Page 63: Materi Kuliah Mikro_UTS

Time Base (con’t) Kecepatan urutan‐urutan setiap task pada mikrokontroler diaturdengan clock.  Sumber clock ini dijadikan sinyal pulsa bagi seluruhperangkat yang terhubung dengan mikrokontroler. 

ATmega328 memiliki clock internal atau clock eksternal. FrekuensiClock internal dapat diatur melalui program, dengan frekuensi 1, 2, 4 or 8 MHz.

Untuk variasi frekuensi selain itu dapat menggunakan eksternalclock (cth: oscillator crystal).

Page 64: Materi Kuliah Mikro_UTS

Timing Subsystem ATmega328 dilengkapi dengan timer tambahan yang dapatmenghasilkan sinyal output yang presisi, menghitung karakteristiksinyal digital (periode, duty cycle, frekuensi). 

ATmega328 dilengkapi dengan 2 unit timer/counter 8‐bit dan 1 unit counter 16‐bit. 

Page 65: Materi Kuliah Mikro_UTS

Pulse Width Modulation Channels Sinyal Pulse width modulated (PWM) memiliki frekuensi tetap dengan duty cycle yang bervariasi. 

Duty cycle adalah persentasi waktu sinyal dengan logika high selama periodesinyal berlangsung. Dapat dituliskan sebagai :

ATmega328 memiliki 4 unit channel (PWM). Channel PWM terhubung dengansumber clock yang dapat menghasilkan beberapa variasi lebar sinyal PWM (darifrekuensi tinggi dengan sinyal low duty cycle sampai dengan frekuensi rendahdengan sinyal high duty cycle)

Sinyal PWM digunakan dalam berbagai aplikasi, seperti dalam pengontrolanposisi motor servo, pengaturan kecepatan motor DCV, dll. 

Page 66: Materi Kuliah Mikro_UTS

Serial CommunicationsAmega328 dilengkapi dengan beberapa subsistem komunikasi serial :

Universal Synchronous and Asynchronous Serial Receiver and Transmitter (USART)

Serial peripheral interface (SPI)

Two‐wire Serial Interface. 

Semua system tersebut menggunakan transmisi data secara serial, yaitu dengan mengirimkan data bit per bit dari transmitter kereceiver. 

Page 67: Materi Kuliah Mikro_UTS

Serial USART Serial USART menggunakan komunikasi full duplex (dua arah) antara receiver dan transmitter.  Pada Atmega328 dihubungkan dengan hardware terpisah untuk transmitter dan receiver. 

USART secara umum menggunakan komunikasi asynchronous. Yang artinya tidak ada clock yang tetap antara pengirim dan penerima. Untuk menyelaraskan antara keduanya, digunakanstart bit dan stop bit disetiap awal dan akhir data. 

USART pada ATmega328 USART cukup flexible. Kecepatan transmisi data (Baud (bits per second) dapat diset sesuai dengan keperluan, dengan lebar data 5 – 9 bit dengan satu atau duastop bit.

ATmega328 juga dilengkapi dengan bit parity (even atau odd) dan hardware yang akanmelakukan check parity pada receiver. Satu bit paritas dapat mendeteksi error bit dalam satubyte data. 

USART juga bias dikonfigurasi dalam mode synchronous. (akan dibahas nanti).

Page 68: Materi Kuliah Mikro_UTS

Serial Peripheral Interface—SPI Serial Peripheral Interface (SPI) menggunakan komunikasi serial dua arah antara transmitter dan receiver. 

Sistem SPI menggunakan sumber clock yang sama. Sehingga membutuhkan jalur clock tambahan antara receiver dan transmitter tapi juga meningkatkan kecepatan transmisi data dibandingkan USART. 

SPI  merupakan shift register synchronous dengan 8‐bit transmitter dan 8‐bit receiver. 

Transmitter di set sebagai master karena menyediakan sumber clock antara transmitter danreceiver. Sedangkan receiver di set sebagai slave.  (dibahas nanti)

Page 69: Materi Kuliah Mikro_UTS

Two-wire Serial Interface—TWI Dengan Sistem TWI beberapa perangkat bisa dihubungkan dalam satu jaringan(microcontrollers, transducers, displays, memory storage, etc.) denganmenggunakan skema interkoneksi two‐wire.

The TWI dapat menghubungkan maximum 128 perangkat sekaligus. Setiapperangkat memiliki alamat yang unik dengan frekuensi komunikasi data sampaidengan 400 KHz. This allows the device to freely exchange information with other devices in the network within a small area. 

Page 70: Materi Kuliah Mikro_UTS

Analog to Digital Converter—ADC ATmega328 dilengkapi dengan 8 channel Analog to digital converter (ADC).

ADC melakukan konversi sinyal analog yang diperoleh dari lingkungan luar menjadi representasi biner pada microcontroller.

ADC pada ATmega328 memiliki resolusi 10 bit, yang artinya tegangan analog antara 0 dan 5 V akan di encoded menjadi salah satu dari representasi biner (1024) antara (000)16 dan (3FF)16.

Tegangan resolusi pada Atmega328 berkisar 4.88 mV.

Page 71: Materi Kuliah Mikro_UTS

Interrupts Eksekusi program pada umumnya mengikuti urutan program yang telah dirancang. Tapi, terkadang urutan event tersebut harus diinterupsi akibat adanya fault (kesalahan) atau status yang terjadi pada mikrokontroler. 

Saat event dengan prioritas lebih tinggi terjadi, mikrokontroler akan menunda operasi normal dan melakukan eksekusi yang disebut dengan interrupt service routine. 

setelah event tersebut selesai, mikrokontroler akan kembali melanjutkan proses program sesuai dengan urutannya. 

ATmega328 dilengkapi dengan 26 sumber interrupt. 2 interrupt disediakan untuk sumber input eksternal.

Page 72: Materi Kuliah Mikro_UTS

Pemrograman Arduinopada umumnya mikrokontroler diprogram menggunakan beberapa variasi bahasa C. Bahasa Cmemberikan kemudahan bagi programmer untuk mengontrol hardware mikrokontroler sekaligusefisiensi waktu dalam penulisan program. Pada gambar terlihat software compiler terletak padakomputer sebagai host.

Tugas compiler  mengubah program (filename.c dan filename.h) menjadi code mesin (filename.hex) yang akan diloading ke processor.

Ada dua tahap yang dilakukan compiler untuk merender kode mesin.  Tahap pertama disebut denganproses kompilasi (file program source diubah menjadi kode assembly (filename.asm) 

Jika file program source memiliki error, compiler akan memberitahu user. Program assembly tidakakan digenerated sampai tidak ada error lagi.

File program assembly (filename.asm) kemudian dilanjutkan ke assembler. Assembler mengubah file bahasa program assembly menjadi kode mesin (filename.asm) yang akan diload ke arduino

Arduino Development Environment menyediakan user friendly interface yang membantu dalampemrograman. (program development, transformation to machine code, and loading into the Arduino

Page 73: Materi Kuliah Mikro_UTS
Page 74: Materi Kuliah Mikro_UTS

ANATOMY PROGRAM (dalam C)Program pada mikrokontroler memiliki struktur dan format yang sama. Beberapa variasi dibuatsesuai dengan kebutuhan programmer. 

Komentar dibuat sebagai log program yang dibuat. Sehingga memudahkan programmer untukmerevisi di kemudian hari, serta dapat digunakan sebagai pengingat detil‐detil program.

Page 75: Materi Kuliah Mikro_UTS
Page 76: Materi Kuliah Mikro_UTS

INCLUDE FILESOften you need to add extra files to your project besides the main program. For example, most compilers require a “personality file” on the specific microcontroller that you are using. This file is provided with the compiler and provides the name of each register used within the microcontroller.

It also provides the link between a specific register’s name within software and the actual register location within hardware. These files are typically called header files and their name ends with a “.h”.

Within the C compiler there will also be other header files to include in your program such as the “math.h” file when programming with advanced math functions.

To include header files within a program, the following syntax is used:◦ //include files◦ #include<file_name1.h>◦ #include<file_name2.h>

Page 77: Materi Kuliah Mikro_UTS

FUNCTIONSAt the highest level is the main program which calls functions that have a defined action

When a function is called, program control is released from the main program to the function. 

Once the function is complete, program control reverts back to the main program.

Functions may in turn call other functions as shown in Figure 2.2. This approach results in a collection of functions that may be reused over and over again in various projects. 

Most importantly, the program is now subdivided into doable pieces, each with a defined action. This makes writing the program easier but also makes it much easier to modify the program since every action is in a known location.

Page 78: Materi Kuliah Mikro_UTS
Page 79: Materi Kuliah Mikro_UTS

There are three different pieces of code required to properly configure and call the function:◦ the function prototype,◦ the function call, and◦ the function body.

Function prototypes are provided early in the program as previously shown in the program template. The function prototype provides the name of the function and any variables required by he function and any variable returned by the function.

The function prototype follows this format:◦ return_variable function_name(required_variable1, required_variable2);

Page 80: Materi Kuliah Mikro_UTS

If the function does not require variables or sends back a variable the word “void” is placed in the variable’s position.

Thefunction callis the code statement used within a program to execute the function. The function call consists of the function name and the actual arguments required by the function. If the

function does not require arguments to be delivered to it for processing, the parenthesis containing the variable list is left empty.

The function call follows this format:◦ function_name(required_variable1, required_variable2);

A function that requires no variables follows this format:◦ function_name( );

When the function call is executed by the program, program control is transferred to the function, the function is executed, and program control is then returned to the portion of the program that called it.

Page 81: Materi Kuliah Mikro_UTS

The function body is a self‐contained “mini‐program.” The first line of thefunction body contains the same information as the function prototype: thename of the function, any variables required by the function, and any variablereturned by the function. The last line of the function contains a “return”statement.

Here a variable may be sent back to the portion of the program that called thefunction. The processing action of the function is contained within the open ({)and close brackets (}).

If the function requires any variables within the confines of the function, theyare declared next. These variable are referred to as local variables. The actionsrequired by the function follow.

The function prototype follows this format:return_variable function_name(required_variable1, required_variable2){//local variables required by the functionunsigned int variable1;unsigned char variable2;//program statements required by the function//return variablereturn return_variable;}

Page 82: Materi Kuliah Mikro_UTS

Contoh

Page 83: Materi Kuliah Mikro_UTS

Example:In figure 2.3 example, we describe how to configure the ports of the microcontroller to act as input or output ports. 

Briefly, associated with each port is a register called the data direction register (DDR). Each bit in the DDR corresponds to a bit in the associated PORT. 

For example, PORTB has an associated data direction register DDRB. If DDRB[7] is set to a logic 1, the corresponding port pin PORTB[7] is configured as an output pin. Similarly, if DDRB[7] is set to logic 0, the corresponding port pin is configured as an input pin.

During some of the early steps of a program, a function is called to initialize the ports as input, output, or some combination of both. 

Page 84: Materi Kuliah Mikro_UTS

PROGRAM CONSTANTSThe #define statement is used to associate a constant name with a numerical value in a program. 

It can be used to define common constants such as pi. It may also be used to give terms used within a program a numerical value. This makes the code easier to read. For example, the following constants may be defined within a program://program constants#define TRUE 1#define FALSE 0#define ON 1#define OFF 0

Page 85: Materi Kuliah Mikro_UTS

VARIABLESThere are two types of variables used within a program: global variables and local variables. 

A global variable is available and accessible to all portions of the program. Whereas, a local variable is only known and accessible within the function where it is declared.

When declaring a variable in C, the number of bits used to store the operator is also specified.

In Figure2.4, we provide a list of common C variable sizes used with the ImageCraft ICC AVR

compiler. 

The size of other variables such as pointers, shorts, longs, etc. are contained in the compiler documentation [ImageCraft].

Page 86: Materi Kuliah Mikro_UTS

C Variables

Page 87: Materi Kuliah Mikro_UTS

When programming microcontrollers, it is important to know the number of bits used to store the variable and also where the variable will be assigned. For example, assigning the contents of an unsigned char variable, which is stored in8‐bits, to an 8‐bit output port will have a predictable result. 

However, assigning an unsigned int variable, which is stored in 16‐bits, to an 8‐bit output port does not provide predictable results. It is wise to insure your assignment statements are balanced for accurate and predictable results. 

The modifier “unsigned” indicates all bits will be used to specify the magnitude of the argument. Signed variables will use the left most bit to indicate the polarity (±) of the argument.

A global variable is declared using the following format provided below. The type of the variable is specified, followed by its name, and an initial value if desired.//global variablesunsigned int loop_iterations = 6;

Page 88: Materi Kuliah Mikro_UTS

MAIN PROGRAMThe main program is the hub of activity for the entire program. 

The main program typically consists of program steps and function calls to initialize the processor followed by program steps to collect data from the environment external to the microcontroller, process the data and make decisions, and provide external control signals back to the environment based on the data collected.

Page 89: Materi Kuliah Mikro_UTS

FUNDAMENTAL PROGRAMMING CONCEPTSIn the previous section, we covered many fundamental concepts. In this section we discussoperators, programming constructs, and decision processing constructs to complete ourfundamental overview of programming concepts.

OPERATORS◦ There are a wide variety of operators provided in the C language. An abbreviated list of commonoperators are provided in Figures2.5and 2.6. The operators have been grouped by general category.

Page 90: Materi Kuliah Mikro_UTS
Page 91: Materi Kuliah Mikro_UTS
Page 92: Materi Kuliah Mikro_UTS

Arithmetic operationsThe arithmetic operations provide for basic math operations using the various variablesdescribed in the previous section. As described in the previous section, the assignment operator(=) is used to assign the argument(s) on the right‐hand side of an equation to the left‐hand sidevariable.

Example: In this example, a function returns the sum of two unsigned int variables passed to thefunction.

unsigned int sum_two(unsigned int variable1, unsigned int variable2){unsigned int sum;sum = variable1 + variable2;return sum;

Page 93: Materi Kuliah Mikro_UTS

Logical operationsThe logical operators provide Boolean logic operations. They can be viewed as comparison operators.

One argument is compared against another using the logical operator provided. The result is returned as a logic value of one (1, true, high) or zero (0 false, low). 

The logical operators are used extensively in program constructs and decision processing operations. to be discussed in the next  several sections.

Page 94: Materi Kuliah Mikro_UTS

Bit manipulation operationsThere are two general types of operations in the bit manipulation category: shiftingoperations and bitwise operations. Let’s examine several examples:

Example : Given the following code segment, what will the value of variable2 be afterexecution?

unsigned char variable1 = 0x73;unsigned char variable2;variable2 = variable1 << 2;

Note that the left and right shift operation is equivalent to multiplying and dividing thevariable by a power of two. The bitwise operators perform the desired operation on a bit‐by‐bit basis. That is, the least significant bit of the first argument is bit‐wise operated withthe least significant bit of the second argument and so on.

Example:Given the following code segment, what will the value of variable3 be afterexecution?

unsigned char variable1 = 0x73;unsigned char variable2 = 0xfa;unsigned char variable3;variable3 = variable1 & variable2;

Page 95: Materi Kuliah Mikro_UTS

Unary operationsThe unary operators, as their name implies, require only a single argument.

For example, in the following code segment, the value of the variable “i” isincremented. This is a shorthand method of executing the operation “i =i +1;”

unsigned int i;

i++;

Example : It is not uncommon in embedded system design projects to haveevery pin on a microcontroller employed. Furthermore, it is not uncommonto have multiple inputs and outputs assigned to the same port but ondifferent port input/output pins. Some compilers support specific pinreference. Another technique that is not compiler specific is bit twiddling.Figure 2.7 provides bit twiddling examples on how individual bits may bemanipulated without affecting other bits using bitwise and unary operators.The information provided here was extracted from the ImageCraft ICC AVRcompiler documentation [ImageCraft].

Page 96: Materi Kuliah Mikro_UTS
Page 97: Materi Kuliah Mikro_UTS

PROGRAMMING CONSTRUCTSIn this section, we discuss several methods of looping through a piece of code. We willexamine the “for” and the “while” looping constructs. Thefore loop provides amechanism for looping through the same portion of code a fixed number of times. Thefor loop consists of three main parts:

◦ loop initiation,◦ loop termination testing, and◦ the loop increment.

In the following code fragment the for loop is executed ten times.unsigned int loop_ctr;for(loop_ctr = 0; loop_ctr < 10; loop_ctr++){//loop body}

The for loop begins with the variable “loop_ctr” equal to 0. During the first passthrough the loop, the variable retains this value. During the next pass through the loop,the variable “loop_ctr” is incremented by one. This action continues until the“loop_ctr” variable reaches the value of ten. Since the argument to continue the loop isno longer true, program execution continues after the close bracket for the for loop.

Page 98: Materi Kuliah Mikro_UTS

In the previous example, the for loop counter was incremented at the beginning of each loop pass. The“loop_ctr” variable can be updated by any amount. For example, in the following code fragment the“loop_ctr” variable is increased by three for every pass of the loop.

unsigned int loop_ctr;for(loop_ctr = 0; loop_ctr < 10; loop_ctr=loop_ctr+3){//loop body}The “loop_ctr” variable may also be initialized at a high value and then decremented at thebeginning of each pass of the loop.unsigned int loop_ctr;for(loop_ctr = 10; loop_ctr > 0; loop_ctr‐‐){//loop body}

Page 99: Materi Kuliah Mikro_UTS

As before, the “loop_ctr” variable may be decreased by any numerical value asappropriate for the application at hand.

The while loop is another programming construct that allows multiple passes through aportion of code. The while loop will continue to execute the statements within theopen and close brackets while the condition at the beginning of the loop remainslogically true. The code snapshot below will implement a ten iteration loop. Note howthe “loop_ctr” variable is initialized outside of the loop and incremented within thebody of the loop. As before, the variable may be initialized to a greater value and thendecremented within the loop body.

unsigned int loop_ctr;loop_ctr = 0;while(loop_ctr < 10){//loop bodyloop_ctr++;}

Frequently, within a microcontroller application, the program begins with systeminitialization actions. Once initialization activities are complete,the processor enters acontinuous loop. This may be accomplished using the following code fragment.

while(1){}

Page 100: Materi Kuliah Mikro_UTS

DECISION PROCESSINGThere are a variety of constructs that allow decision making. These include the following:

The if statement,

The if–else construct,

The if–else if–else construct, and the

Switch statement.

The if statement will execute the code between an open and close bracket set should the conditionwithin the if statement be logically true.

Example: To help develop the algorithm for steering the Blinky 602A robot through a maze, a lightemitting diode (LED) is connected to PORTB pin 1 on the ATmega328. The robot’s center IR sensor isconnected to an analog‐to‐digital converter at PORTC, pin 1. The IR sensor provides a voltage outputthat is inversely proportional to distance of the sensor from the maze wall. It is desired to illuminatethe LED if the robot is within 10 cm of the maze wall. The sensor provides an output voltage of 2.5 VDCat the 10 cm range. The followingifstatement construct will implement this LED indicator. We providethe actual code to do this later in the chapter.

Page 101: Materi Kuliah Mikro_UTS

if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC

{

PORTB = 0x02; //illuminate LED on PORTB[1]

}

In the example provided, there is no method to turn off the LED once it is turned on. This will require theelseportion of the construct as shown in the next code fragment.

if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC

{

PORTB = 0x02; //illuminate LED on PORTB[1]

}

else

{

PORTB = 0x00; //extinguish the LED on PORTB[1]

}

Theif–else if—elseconstruct may be used to implement a three LED system. In this exam‐ple, the left, center, and right IR sensors are connected to analog‐to‐digital converter channels on PORTC pins 2, 1, and 0, respectively. The LED indicators are connected to PORTB pins 2, 1, and 0. The following code fragment implements this LED system.

Page 102: Materi Kuliah Mikro_UTS

Theswitchstatement is used when multiple if‐else conditions exist. Each possible condition is specified by a case statement. When a match is found between the switchvariable and a specific case entry, the statements associated with the case are executed until abreakstatement is encountered.

Example:Suppose eight pushbutton switches are connected to PORTD. Each switch will implement a different action. A switch statement may be used to process the multiplepossible decisions as shown in the following code fragment.

void read_new_input(void)

{

new_PORTD = PIND;

if(new_PORTD != old_PORTD) //check for status change PORTD

switch(new_PORTD)

{ //process change in PORTD input

case 0x01: //PD0

//PD0 related actions

break;

case 0x02: //PD1

//PD1 related actions

break;

case 0x04: //PD2

//PD2 related actions

break;

case 0x08: //PD3

//PD3 related actions

break;

case 0x10: //PD4

//PD4 related actions

Page 103: Materi Kuliah Mikro_UTS

break;

case 0x20: //PD5

//PD5 related actions

break;

case 0x40: //PD6

//PD6 related actions

break;

case 0x80: //PD7

//PD7 related actions

break;

default:; //all other cases

} //end switch(new_PORTD)

} //end if new_PORTD

old_PORTD=new_PORTD; //update PORTD

}

That completes our brief overview of the C programming language. In the next section, we provide an overview of the Arduino development Environment. 

Page 104: Materi Kuliah Mikro_UTS

ARDUINO DEVELOPMENT ENVIRONMENTIn this section, we provide an overview of the Arduino Development Environment (ADE). We begin with some background information about the ADE and then review its user friendly features.

We then introduce the sketchbook concept and provide a brief overview of the built‐in software features withinthe ADE. Our goal is to provide a brief introduction to the features.

All Arduino related features are well documented on the Arduino homepage (www.arduino.cc).

The first version of the Arduino DevelopmentEnvironment was released in August 2005. It was developed at theInteraction Design Institute in Ivrea, Italy to allow students the ability to quickly put processing power to use in awide variety of projects. Since that time, newer versions incorporating new features, have been released on aregular basis [www.arduino.cc].

At its most fundamental level, the Arduino Development Environment is a user friendly interface to allow one toquickly write, load, and execute code on a microcontroller. A barebones program need only consist of a setup()and loop()function.

The Arduino Development Environment adds the other required pieces such as header files and the mainprogram construct. The ADE is written in Java and has its origins in the Processor programming language and theWiring Project [www.arduino.cc].

Page 105: Materi Kuliah Mikro_UTS

ARDUINO DEVELOPMENT ENVIRONMENT OVERVIEW

The Arduino Development Environment is illustrated in right Figure. The ADE contains : 

a text editor, 

a message area for displaying status, 

a text console, 

a tool bar of common functions, 

and an extensive menuing system. 

The ADE also provides a user friendly interface to the Arduino Duemilanovewhich allows for a quick upload of code. This is possible because the ArduinoDuemilanove is equipped with a bootloader program.

Page 106: Materi Kuliah Mikro_UTS

The toolbar provides single button access to the more commonly used menu features. Most of the features are self explanatory. 

The “Upload to I/O Board” button compiles your code and uploads it to the ArduinoDuemilanove.

The “Serial Monitor” button opens the serial monitor feature. The serial monitor feature allows text data to be sent to and received from the Arduino Duemilanove. 

The serial monitor feature is halted with the “Stop” button.

Page 107: Materi Kuliah Mikro_UTS

SKETCHBOOK CONCEPTARDUINO SOFTWARE, LIBRARIES, AND LANGUAGE REFERENCESIn keeping with a hardware and software platform for students of the arts, the Arduino environment employs the concept of a sketchbook. An artist maintains their works in progress in a sketchbook. Similarly, we maintain our programs within a sketchbook in the Arduino environment.  Furthermore, we refer to individual programs as sketches. An individual sketch within the sketchbook may be accessed via the Sketchbook entry under the file tab.

The Arduino Development Environment has a number of built in features. Some of the features may be directly accessed via the ArduinoDevelopment Environment drop down toolbar. Provided in Figure 2.10 is a handy reference to show all of the available features.

The toolbar provides a wide variety of features to compose, compile, load and execute a sketch. We illustrate how to use these features in the Application section later in the chapter. Aside from the toolbar accessible features, the Arduino Development Environment contains a number of built‐in functions that allow the user to quickly construct a sketch. These built‐in functions are summarized in Figure 2.11. 

Complete documentation for these built‐in features is available at the Arduino homepage [www.arduino.cc]. This documentation is easily accessible via the Help tab on the Arduino Development Environment toolbar. This documentation will not be repeated here. Instead, we refer to these features at appropriate places throughout the remainder of the book as we discuss related hardware systems.

Keep in mind the Arduino open source concept. Users throughout the world are constantly adding new built‐in features. As new features are added, they will be released in future Arduino development Environment versions. As an Arduino user, you too may add to this collection of useful tools. In the next section, we illustrate how to use the Arduino Duemilanova board in  everal applications.

Page 108: Materi Kuliah Mikro_UTS
Page 109: Materi Kuliah Mikro_UTS

APPLICATION 1: ROBOT IR SENSORTo demonstrate how to construct a sketch in the Arduino Development Environment, we revisit the robot IR sensor application provided earlier in the chapter. We also investigate the sketches’sinteraction with the Arduino Duemilanove processing board and external sensors and indicators.

We will use the robot project as an ongoing example throughout the remainder of the book. Recall from Chapter 1, the Blinky 602A kit contains the hardware and mechanical parts to construct a line following robot. In this example, we modify the robot platform by equipping it with three Sharp GP12D IR sensors as shown in Figure2.12. 

Page 110: Materi Kuliah Mikro_UTS
Page 111: Materi Kuliah Mikro_UTS

The sensors are mounted to a bracket constructed from thin aluminum. Dimensions for the bracket are provided in the figure. In later Application sections, we equip the robot with all three IR sensors. In this example, we equip the robot with a single sensor and test its function as a proof of concept.

The IR sensor provides a voltage output that is inversely proportional to the sensor distance from the maze wall. 

It is desired to illuminate the LED if the robot is within 10 cm of the maze wall. 

The sensor provides an output voltage of 2.5 VDC at the 10 cm range. 

The interface between the IR sensor and the Arduino Duemilanove board is provided in Figure 2.13.

Page 112: Materi Kuliah Mikro_UTS
Page 113: Materi Kuliah Mikro_UTS

The IR sensor’s power (red wire) and ground (black wire) connections are connected to the 5V and Gnd pins on the Arduino Duemilanoveboard, respectively. 

The IR sensor’s output connection (yellow wire) is connected to the ANALOG IN 5 pin on the Arduino Duemilanove board. 

The LED circuit shown in the top right corner of the diagram is connected to the DIGITAL 0 pin on the Arduino Duemilanove board. 

Page 114: Materi Kuliah Mikro_UTS

Earlier in the chapter, we provided a framework for writing the if‐else statement to turn the

LED on and off. Here is the actual sketch to accomplish this.

//*************************************************************************

#define LED_PIN 0 //digital pin ‐ LED connection

#define IR_sensor_pin 5 //analog pin ‐ IR sensor

int IR_sensor_value; //declare variable for IR sensor value

void setup()

{

pinMode(LED_PIN, OUTPUT); //configure pin 0 for digital output

}

void loop()

{

//read analog output from IR sensor

IR_sensor_value = analogRead(IR_sensor_pin);

if(IR_sensor_value > 512) //0 to 1023 maps to 0 to 5 VDC

{

digitalWrite(LED_PIN, HIGH); //turn LED on

}

else

{

digitalWrite(LED_PIN, LOW); //turn LED off

}

}

//************************************************************************

Page 115: Materi Kuliah Mikro_UTS

The “analogRead” function requires the pin for analog conversion variable passed to it and returns the analog signal read as an integer value (int) from 0 to 1023. 

So, for this example, we need to declare an integer value to receive the returned value. We have called this integer variable “IR_sensor_value.”

Following the declaration of required variables are the two required functions for an Arduino Duemilanoveprogram: setup and loop. The setup function calls an Arduino built‐in function, pin‐Mode, to set the “LED_PIN” as an output pin. 

The loop function calls several functions to read the current analog value on pin 5 (the IR sensor output) and then determine if the reading is above 512 (2.5 VDC). 

If the reading is above 2.5 VDC, the LED on DIGITAL pin 0 is illuminated, else it is turned off.

After completing writing the sketch with the Arduino Development Environment, it must be compiled and then uploaded to the Arduino Duemilanove board. 

These two steps are accomplished using the “Sketch – Verify/Compile” and the “File – Upload to I/O Board” pull down menu selections.

Page 116: Materi Kuliah Mikro_UTS

SUMMARYThe goal of this chapter was to provide a tutorial on how to begin programming. We used a top‐down design approach. We began with the “big picture” of the chapter followed by an overview of the major pieces of a program. 

We then discussed the basics of the C programming language.

Only the most fundamental concepts were covered. We then discussed the ArduinoDevelopment Environment and how it may be used to develop a program for the ArduinoDuemilanove processor.

Page 117: Materi Kuliah Mikro_UTS

P-3 PemrogramanRatna Aisuwarya, M.Eng

Page 118: Materi Kuliah Mikro_UTS

Describe the key components of a program. Specify the size of different variables within the C programming

language. Define the purpose of the main program. Explain the importance of using functions within a program. Write functions that pass parameters and return variables. Describe the function of a header file. Discuss different programming constructs used for program

control and decision processing. Describe the key features of the Arduino Development

Environment. Describe what features of the Arduino Development Environment

ease the program devel-opment process. List the programming support information available at the

Arduino home page. Write programs for use on the Arduino Duemilanove processing

board.

Page 119: Materi Kuliah Mikro_UTS

pada umumnya mikrokontroler diprogram menggunakan beberapa variasibahasa C. Bahasa C memberikan kemudahan bagi programmer untukmengontrol hardware mikrokontroler sekaligus efisiensi waktu dalampenulisan program. Pada gambar 2.1 terlihat software compiler terletakpada komputer sebagai host.

Tugas compiler mengubah program (filename.c dan filename.h) menjadicode mesin (filename.hex) yang akan diloading ke processor.

Ada dua tahap yang dilakukan compiler untuk merender kode mesin. Tahap pertama disebut dengan proses kompilasi (file program source diubah menjadi kode assembly (filename.asm)

Jika file program source memiliki error, compiler akan memberitahu user. Program assembly tidak akan digenerated sampai tidak ada error lagi.

File program assembly (filename.asm) kemudian dilanjutkan keassembler. Assembler mengubah file bahasa program assembly menjadikode mesin (filename.asm) yang akan diload ke arduino

Arduino Development Environment menyediakan user friendly interface yang membantu dalam pemrograman. (program development, transformation to machine code, and loading into the Arduino

Page 120: Materi Kuliah Mikro_UTS
Page 121: Materi Kuliah Mikro_UTS

Programs written for a microcontroller have a fairly repeatable format. Slight variations exist but many follow the format provided.

Page 122: Materi Kuliah Mikro_UTS
Page 123: Materi Kuliah Mikro_UTS

Comments are used throughout the program to document what and how things were accomplished within a program.

The comments help you reconstruct your work at a later time. Imagine that you wrote a program a year ago for a project. You now want to modify that program for a new project.

The comments will help you remember the key details of the program.

Comments are not compiled into machine code for loading into the microcontroller.Therefore, the comments will not fill up the memory of your microcontroller.

Page 124: Materi Kuliah Mikro_UTS

Comments are indicated using double slashes (//). Anything from the double slashes to the end of a line is then considered a comment.

A multi-line comment can be constructed using a /∗at the beginning of the comment and a ∗/ at the end of the comment.

At the beginning of the program, comments may be extensive. Comments may include some of the following information: file name program author revision history or a listing of the key changes made to

the program compiler setting information hardware connection description to microcontroller pins program description

Page 125: Materi Kuliah Mikro_UTS

Often you need to add extra files to your project besides the main program. For example, most compilers require a “personality file” on the specific microcontroller that you are using. This file is provided with the compiler and provides the name of each register used within the microcontroller.

It also provides the link between a specific register’s name within software and the actual register location within hardware. These files are typically called header files and their name ends with a “.h”.

Within the C compiler there will also be other header files to include in your program such as the “math.h” file when programming with advanced math functions.

To include header files within a program, the following syntax is used: //include files #include<file_name1.h> #include<file_name2.h>

Page 126: Materi Kuliah Mikro_UTS

At the highest level is the main program which calls functions that have a defined action

When a function is called, program control is released from the main program to the function.

Once the function is complete, program control reverts back to the main program.

Functions may in turn call other functions as shown in Figure 2.2. This approach results in a collection of functions that may be reused over and over again in various projects.

Most importantly, the program is now subdivided into doable pieces, each with a defined action. This makes writing the program easier but also makes it much easier to modify the program since every action is in a known location.

Page 127: Materi Kuliah Mikro_UTS
Page 128: Materi Kuliah Mikro_UTS

There are three different pieces of code required to properly configure and call the function: the function prototype, the function call, and the function body.

Function prototypes are provided early in the program as previously shown in the program template. The function prototype provides the name of the function and any variables required by he function and any variable returned by the function.

The function prototype follows this format: return_variable

function_name(required_variable1, required_variable2);

Page 129: Materi Kuliah Mikro_UTS

If the function does not require variables or sends back a variable the word “void” is placed in the variable’s position.

Thefunction callis the code statement used within a program to execute the function. The function call consists of the function name and the actual arguments required by the function. If the

function does not require arguments to be delivered to it for processing, the parenthesis containing the variable list is left empty.

The function call follows this format: function_name(required_variable1, required_variable2);

A function that requires no variables follows this format: function_name( );

When the function call is executed by the program, program control is transferred to the function, the function is executed, and program control is then returned to the portion of the program that called it.

Page 130: Materi Kuliah Mikro_UTS

The function body is a self-contained “mini-program.” The first lineof the function body contains the same information as the functionprototype: the name of the function, any variables required by thefunction, and any variable returned by the function. The last line ofthe function contains a “return” statement.

Here a variable may be sent back to the portion of the program thatcalled the function. The processing action of the function iscontained within the open ({) and close brackets (}).

If the function requires any variables within the confines of thefunction, they are declared next. These variable are referred to aslocal variables. The actions required by the function follow.

The function prototype follows this format:return_variable function_name(required_variable1, required_variable2){//local variables required by the functionunsigned int variable1;unsigned char variable2;//program statements required by the function//return variablereturn return_variable;}

Page 131: Materi Kuliah Mikro_UTS
Page 132: Materi Kuliah Mikro_UTS

Example:In figure 2.3 example, we describe how to configure the ports of the microcontroller to act as input or output ports. Briefly, associated with each port is a register

called the data direction register (DDR). Each bit in the DDR corresponds to a bit in the associated PORT.

For example, PORTB has an associated data direction register DDRB. If DDRB[7] is set to a logic 1, the corresponding port pin PORTB[7] is configured as an output pin. Similarly, if DDRB[7] is set to logic 0, the corresponding port pin is configured as an input pin.

During some of the early steps of a program, a function is called to initialize the ports as input, output, or some combination of both.

Page 133: Materi Kuliah Mikro_UTS

The #define statement is used to associate a constant name with a numerical value in a program.

It can be used to define common constants such as pi. It may also be used to give terms used within a program a numerical value. This makes the code easier to read. For example, the following constants may be defined within a program://program constants#define TRUE 1#define FALSE 0#define ON 1#define OFF 0

Page 134: Materi Kuliah Mikro_UTS

There are two types of variables used within a program: global variables and local variables.

A global variable is available and accessible to all portions of the program. Whereas, a local variable is only known and accessible within the function where it is declared.

When declaring a variable in C, the number of bits used to store the operator is also specified.

In Figure2.4, we provide a list of common C variable sizes used with the ImageCraft ICC AVR

compiler. The size of other variables such as pointers,

shorts, longs, etc. are contained in the compiler documentation [ImageCraft].

Page 135: Materi Kuliah Mikro_UTS
Page 136: Materi Kuliah Mikro_UTS

When programming microcontrollers, it is important to know the number of bits used to store the variable and also where the variable will be assigned. For example, assigning the contents of an unsigned char variable, which is stored in8-bits, to an 8-bit output port will have a predictable result.

However, assigning an unsigned int variable, which is stored in 16-bits, to an 8-bit output port does not provide predictable results. It is wise to insure your assignment statements are balanced for accurate and predictable results.

The modifier “unsigned” indicates all bits will be used to specify the magnitude of the argument. Signed variables will use the left most bit to indicate the polarity (±) of the argument.

A global variable is declared using the following format provided below. The type of the variable is specified, followed by its name, and an initial value if desired.//global variablesunsigned int loop_iterations = 6;

Page 137: Materi Kuliah Mikro_UTS

The main program is the hub of activity for the entire program.

The main program typically consists of program steps and function calls to initialize the processor followed by program steps to collect data from the environment external to the microcontroller, process the data and make decisions, and provide external control signals back to the environment based on the data collected.

Page 138: Materi Kuliah Mikro_UTS

In the previous section, we covered manyfundamental concepts. In this section wediscuss operators, programming constructs,and decision processing constructs to completeour fundamental overview of programmingconcepts.OPERATORS There are a wide variety of operators provided in

the C language. An abbreviated list of commonoperators are provided in Figures2.5and 2.6. Theoperators have been grouped by generalcategory.

Page 139: Materi Kuliah Mikro_UTS
Page 140: Materi Kuliah Mikro_UTS
Page 141: Materi Kuliah Mikro_UTS

The arithmetic operations provide for basic mathoperations using the various variables described inthe previous section. As described in the previoussection, the assignment operator (=) is used toassign the argument(s) on the right-hand side of anequation to the left-hand side variable.Example: In this example, a function returns thesum of two unsigned int variables passed to thefunction.

unsigned int sum_two(unsigned int variable1, unsignedint variable2){unsigned int sum;sum = variable1 + variable2;return sum;

Page 142: Materi Kuliah Mikro_UTS

The logical operators provide Boolean logic operations. They can be viewed as comparison operators.

One argument is compared against another using the logical operator provided. The result is returned as a logic value of one (1, true, high) or zero (0 false, low).

The logical operators are used extensively in program constructs and decision processing operations. to be discussed in the next several sections.

Page 143: Materi Kuliah Mikro_UTS

There are two general types of operations in the bit manipulation category:shifting operations and bitwise operations. Let’s examine several examples:

Example : Given the following code segment, what will the value of variable2be after execution?

unsigned char variable1 = 0x73;

unsigned char variable2;

variable2 = variable1 << 2;

Note that the left and right shift operation is equivalent to multiplying anddividing the variable by a power of two. The bitwise operators perform thedesired operation on a bit-by-bit basis. That is, the least significant bit of thefirst argument is bit-wise operated with the least significant bit of the secondargument and so on.

Example:Given the following code segment, what will the value of variable3 beafter execution?

unsigned char variable1 = 0x73;unsigned char variable2 = 0xfa;unsigned char variable3;

variable3 = variable1 & variable2;

Page 144: Materi Kuliah Mikro_UTS

The unary operators, as their name implies, require only asingle argument.

For example, in the following code segment, the value of thevariable “i” is incremented. This is a shorthand method ofexecuting the operation “i =i +1;”unsigned int i;i++;Example : It is not uncommon in embedded system designprojects to have every pin on a microcontroller employed.Furthermore, it is not uncommon to have multiple inputs andoutputs assigned to the same port but on different portinput/output pins. Some compilers support specific pinreference. Another technique that is not compiler specific is bittwiddling. Figure 2.7 provides bit twiddling examples on howindividual bits may be manipulated without affecting other bitsusing bitwise and unary operators. The information providedhere was extracted from the ImageCraft ICC AVR compilerdocumentation [ImageCraft].

Page 145: Materi Kuliah Mikro_UTS
Page 146: Materi Kuliah Mikro_UTS

In this section, we discuss several methods of looping through a piece ofcode. We will examine the “for” and the “while” looping constructs.Thefore loop provides a mechanism for looping through the same portion ofcode a fixed number of times. The for loop consists of three main parts:

loop initiation, loop termination testing, and the loop increment.

In the following code fragment the for loop is executed ten times.unsigned int loop_ctr;

for(loop_ctr = 0; loop_ctr < 10; loop_ctr++)

{

//loop body

}

The for loop begins with the variable “loop_ctr” equal to 0. During the firstpass through the loop, the variable retains this value. During the next passthrough the loop, the variable “loop_ctr” is incremented by one. This actioncontinues until the “loop_ctr” variable reaches the value of ten. Since theargument to continue the loop is no longer true, program executioncontinues after the close bracket for the for loop.

Page 147: Materi Kuliah Mikro_UTS

In the previous example, the for loop counter was incremented atthe beginning of each loop pass. The “loop_ctr” variable can beupdated by any amount. For example, in the following codefragment the “loop_ctr” variable is increased by three for everypass of the loop.

unsigned int loop_ctr;for(loop_ctr = 0; loop_ctr < 10; loop_ctr=loop_ctr+3){//loop body}The “loop_ctr” variable may also be initialized at a high value and thendecremented at thebeginning of each pass of the loop.unsigned int loop_ctr;for(loop_ctr = 10; loop_ctr > 0; loop_ctr--){//loop body}

Page 148: Materi Kuliah Mikro_UTS

As before, the “loop_ctr” variable may be decreased by any numerical valueas appropriate for the application at hand.

The while loop is another programming construct that allows multiple passesthrough a portion of code. The while loop will continue to execute thestatements within the open and close brackets while the condition at thebeginning of the loop remains logically true. The code snapshot below willimplement a ten iteration loop. Note how the “loop_ctr” variable isinitialized outside of the loop and incremented within the body of the loop.As before, the variable may be initialized to a greater value and thendecremented within the loop body.

unsigned int loop_ctr;

loop_ctr = 0;

while(loop_ctr < 10)

{

//loop body

loop_ctr++;

}

Frequently, within a microcontroller application, the program begins withsystem initialization actions. Once initialization activities are complete,theprocessor enters a continuous loop. This may be accomplished using thefollowing code fragment.

while(1)

{

}

Page 149: Materi Kuliah Mikro_UTS

There are a variety of constructs that allow decision making. Theseinclude the following: The if statement, The if–else construct, The if–else if–else construct, and the Switch statement.The if statement will execute the code between an open and closebracket set should the condition within the if statement be logicallytrue.Example: To help develop the algorithm for steering the Blinky 602Arobot through a maze, a light emitting diode (LED) is connected toPORTB pin 1 on the ATmega328. The robot’s center IR sensor isconnected to an analog-to-digital converter at PORTC, pin 1. The IRsensor provides a voltage output that is inversely proportional todistance of the sensor from the maze wall. It is desired toilluminate the LED if the robot is within 10 cm of the maze wall.The sensor provides an output voltage of 2.5 VDC at the 10 cmrange. The followingifstatement construct will implement this LEDindicator. We provide the actual code to do this later in the chapter.

Page 150: Materi Kuliah Mikro_UTS

if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC{PORTB = 0x02; //illuminate LED on PORTB[1]}In the example provided, there is no method to turn off the LED once it is turned on. This will require theelseportion of the construct as shown in the next code fragment.if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC{PORTB = 0x02; //illuminate LED on PORTB[1]}else{PORTB = 0x00; //extinguish the LED on PORTB[1]}Theif–else if—elseconstruct may be used to implement a three LED system. In this exam-ple, the left, center, and right IR sensors are connected to analog-to-digital converter channels on PORTC pins 2, 1, and 0, respectively. The LED indicators are connected to PORTB pins 2, 1, and 0. The following code fragment implements this LED system.

Page 151: Materi Kuliah Mikro_UTS

Theswitchstatement is used when multiple if-else conditions exist. Each possible condition is specifiedby a case statement. When a match is found between the switch variable and a specific case entry,the statements associated with the case are executed until abreakstatement is encountered.Example:Suppose eight pushbutton switches are connected to PORTD. Each switch will implement adifferent action. A switch statement may be used to process the multiple possible decisions as shownin the following code fragment.void read_new_input(void){new_PORTD = PIND;if(new_PORTD != old_PORTD) //check for status change PORTDswitch(new_PORTD){ //process change in PORTD inputcase 0x01: //PD0//PD0 related actionsbreak;case 0x02: //PD1//PD1 related actionsbreak;case 0x04: //PD2//PD2 related actionsbreak;case 0x08: //PD3//PD3 related actionsbreak;case 0x10: //PD4//PD4 related actions

Page 152: Materi Kuliah Mikro_UTS

break;case 0x20: //PD5//PD5 related actionsbreak;case 0x40: //PD6//PD6 related actionsbreak;case 0x80: //PD7//PD7 related actionsbreak;default:; //all other cases} //end switch(new_PORTD)} //end if new_PORTDold_PORTD=new_PORTD; //update PORTD}That completes our brief overview of the C programming language. In the next section, we provide an overview of the Arduino development Environment.

Page 153: Materi Kuliah Mikro_UTS

In this section, we provide an overview of the Arduino Development Environment (ADE). We begin with some background information about the ADE and then review its user friendly features.

We then introduce the sketchbook concept and provide a brief overviewof the built-in software features within the ADE. Our goal is to provide abrief introduction to the features.

All Arduino related features are well documented on the Arduinohomepage (www.arduino.cc).

The first version of the Arduino DevelopmentEnvironment was released inAugust 2005. It was developed at the Interaction Design Institute in Ivrea,Italy to allow students the ability to quickly put processing power to usein a wide variety of projects. Since that time, newer versionsincorporating new features, have been released on a regular basis[www.arduino.cc].

At its most fundamental level, the Arduino Development Environment is auser friendly interface to allow one to quickly write, load, and executecode on a microcontroller. A barebones program need only consist of asetup() and loop()function.

The Arduino Development Environment adds the other required piecessuch as header files and the main program construct. The ADE is writtenin Java and has its origins in the Processor programming language and theWiring Project [www.arduino.cc].

Page 154: Materi Kuliah Mikro_UTS

The Arduino Development Environment is illustrated in right Figure. The ADE contains : a text editor, a message area for displaying

status, a text console, a tool bar of common functions, and an extensive menuing

system. The ADE also provides a user friendly interface to the ArduinoDuemilanove which allows for a quick upload of code. This is possible because the ArduinoDuemilanove is equipped with a bootloader program.

Page 155: Materi Kuliah Mikro_UTS

The toolbar provides single button access to the more commonly used menu features. Most of the features are self explanatory.

The “Upload to I/O Board” button compiles your code and uploads it to the ArduinoDuemilanove.

The “Serial Monitor” button opens the serial monitor feature. The serial monitor feature allows text data to be sent to and received from the Arduino Duemilanove.

The serial monitor feature is halted with the “Stop” button.

Page 156: Materi Kuliah Mikro_UTS

In keeping with a hardware and software platform for students of the arts, the Arduino environment employs the concept of a sketchbook. An artist maintains their works in progress in a sketchbook. Similarly, we maintain our programs within a sketchbook in the Arduino environment. Furthermore, we refer to individual programs as sketches. An individual sketch within the sketchbook may be accessed via the Sketchbook entry under the file tab.

The Arduino Development Environment has a number of built in features. Some of the features may be directly accessed via the Arduino Development Environment drop down toolbar. Provided in Figure 2.10 is a handy reference to show all of the available features.

The toolbar provides a wide variety of features to compose, compile, load and execute a sketch. We illustrate how to use these features in the Application section later in the chapter. Aside from the toolbar accessible features, the ArduinoDevelopment Environment contains a number of built-in functions that allow the user to quickly construct a sketch. These built-in functions are summarized in Figure 2.11.

Complete documentation for these built-in features is available at the Arduinohomepage [www.arduino.cc]. This documentation is easily accessible via the Help tab on the Arduino Development Environment toolbar. This documentation will not be repeated here. Instead, we refer to these features at appropriate places throughout the remainder of the book as we discuss related hardware systems.

Keep in mind the Arduino open source concept. Users throughout the world are constantly adding new built-in features. As new features are added, they will be released in future Arduino development Environment versions. As an Arduino user, you too may add to this collection of useful tools. In the next section, we illustrate how to use the Arduino Duemilanova board in everal applications.

Page 157: Materi Kuliah Mikro_UTS
Page 158: Materi Kuliah Mikro_UTS

To demonstrate how to construct a sketch in the Arduino Development Environment, we revisit the robot IR sensor application provided earlier in the chapter. We also investigate the sketches’sinteraction with the Arduino Duemilanoveprocessing board and external sensors and indicators.

We will use the robot project as an ongoing example throughout the remainder of the book. Recall from Chapter 1, the Blinky 602A kit contains the hardware and mechanical parts to construct a line following robot. In this example, we modify the robot platform by equipping it with three Sharp GP12D IR sensors as shown in Figure2.12.

Page 159: Materi Kuliah Mikro_UTS
Page 160: Materi Kuliah Mikro_UTS

Dasar Pemrograman MikrokontrolerRatna Aisuwarya, M.Eng

Page 161: Materi Kuliah Mikro_UTS

pada umumnya mikrokontrolerdiprogram menggunakan beberapavariasi bahasa C. Bahasa C memberikankemudahan bagi programmer untukmengontrol hardware mikrokontrolersekaligus efisiensi waktu dalampenulisan program. Pada gambarterlihat software compiler terletakpada komputer sebagai host.

Page 162: Materi Kuliah Mikro_UTS

Tugas compiler mengubah program (filename.c danfilename.h) menjadi code mesin (filename.hex) yang akandiloading ke processor.

Ada dua tahap yang dilakukan compiler untuk merenderkode mesin. Tahap pertama disebut dengan proses kompilasi (file program source diubah menjadi kodeassembly (filename.asm)

Jika file program source memiliki error, compiler akanmemberitahu user. Program assembly tidak akandigenerated sampai tidak ada error lagi.

File program assembly (filename.asm) kemudiandilanjutkan ke assembler. Assembler mengubah file bahasaprogram assembly menjadi kode mesin (filename.asm) yang akan diload ke arduino

Arduino Development Environment menyediakan user friendly interface yang membantu dalam pemrograman. (program development, transformation to machine code, and loading into the Arduino

Page 163: Materi Kuliah Mikro_UTS

Program yang ditulis pada mikrokontrolermemiliki format umum, dengan beberapavariasi yang dibuat sesuai dengan kebutuhan.

1. Comments2. Include Files3. Functions4. Program Constants5. Variables 6. Main Program

Page 164: Materi Kuliah Mikro_UTS
Page 165: Materi Kuliah Mikro_UTS

Komentar digunakan dalam program untukmendokumentasikan apa dan bagaimanasebuah proses dalam program yang ditulis.

Komentar membantu programmer dalammerevisi program di kemudian hari.

Komentar membantu programmer dalammengingat detail penting dalam sebuahprogram.

Komentar tidak dikompilasi menjadi kodemesin yang akan diload ke mikrokontroler. Sehingga, komentar tidak akan memenihumemory mikrokontroler.

Page 166: Materi Kuliah Mikro_UTS

komentar dibuat dengan tanda (//). Semua yang ditulis setelah tanda (//) dianggap sebagai sebuahkomentar.

Komentar multi-baris dapat dibuat denganmenggunakan tanda /∗ di awal dan di akhir komentar.

Diawal program, komentar dapat dibuat sepertiparagraf. Komentar diawal program dapat berisiinformasi sebagai berikut : Nama file Penulis Program Riwayat revisi atau hal-hal penting yang diubah pada

program. revision history or a listing of the key changes made to the program

Informasi setting compiler Deskripsi koneksi hardware ke pin mikrokontroler Deskripsi program

Page 167: Materi Kuliah Mikro_UTS

Selain program utama, seringkali kita membutuhkan file ektra ke dalam project. Contoh, kebanyakan compiler membutuhkan “file khusus” pada mikrokontroler tertentu. File ini menyediakan setting register yang digunakan padacompiler untuk berhubungan dengan mikrokontroler.

Include file juga menyediakan link antara register tertentupada software dan lokasi register yang sebenarnya padahardware. File ini disebut dengan header file yang biasanya berakhiran “.h”.

Header file lainnya pada compiler C seperti “math.h”. File ini digunakan untuk fungsi matematika.

Untuk meng-include header files dalam program, digunakan sintaks berikut : //include files #include<file_name1.h> #include<file_name2.h>

Page 168: Materi Kuliah Mikro_UTS

Program utama akan memangil function yang memiliki aksi yang telahdidefinisikan.

Ketika function dipanggil, kontrol program berpindah dari program utamake function.

Setelah function selesai diproses, control program kembali ke program utama.

Function dapat memanggil function lainnya. Sehingga function dapatdipanggil kapan saja di dalam listing program.

Page 169: Materi Kuliah Mikro_UTS

There are three different pieces of code required to properly configure and call the function: the function prototype, the function call, and the function body.

Function prototypes are provided early in the program as previously shown in the program template. The function prototype provides the name of the function and any variables required by he function and any variable returned by the function.

The function prototype follows this format: return_variable

function_name(required_variable1, required_variable2);

Page 170: Materi Kuliah Mikro_UTS

If the function does not require variables or sends back a variable the word “void” is placed in the variable’s position.

Thefunction callis the code statement used within a program to execute the function. The function call consists of the function name and the actual arguments required by the function. If the

function does not require arguments to be delivered to it for processing, the parenthesis containing the variable list is left empty.

The function call follows this format: function_name(required_variable1, required_variable2);

A function that requires no variables follows this format: function_name( );

When the function call is executed by the program, program control is transferred to the function, the function is executed, and program control is then returned to the portion of the program that called it.

Page 171: Materi Kuliah Mikro_UTS

The function body is a self-contained “mini-program.” The first lineof the function body contains the same information as the functionprototype: the name of the function, any variables required by thefunction, and any variable returned by the function. The last line ofthe function contains a “return” statement.

Here a variable may be sent back to the portion of the program thatcalled the function. The processing action of the function iscontained within the open ({) and close brackets (}).

If the function requires any variables within the confines of thefunction, they are declared next. These variable are referred to aslocal variables. The actions required by the function follow.

The function prototype follows this format:return_variable function_name(required_variable1, required_variable2){//local variables required by the functionunsigned int variable1;unsigned char variable2;//program statements required by the function//return variablereturn return_variable;}

Page 172: Materi Kuliah Mikro_UTS
Page 173: Materi Kuliah Mikro_UTS

Example:In figure 2.3 example, we describe how to configure the ports of the microcontroller to act as input or output ports. Briefly, associated with each port is a register

called the data direction register (DDR). Each bit in the DDR corresponds to a bit in the associated PORT.

For example, PORTB has an associated data direction register DDRB. If DDRB[7] is set to a logic 1, the corresponding port pin PORTB[7] is configured as an output pin. Similarly, if DDRB[7] is set to logic 0, the corresponding port pin is configured as an input pin.

During some of the early steps of a program, a function is called to initialize the ports as input, output, or some combination of both.

Page 174: Materi Kuliah Mikro_UTS

The #define statement is used to associate a constant name with a numerical value in a program.

It can be used to define common constants such as pi. It may also be used to give terms used within a program a numerical value. This makes the code easier to read. For example, the following constants may be defined within a program://program constants#define TRUE 1#define FALSE 0#define ON 1#define OFF 0

Page 175: Materi Kuliah Mikro_UTS

There are two types of variables used within a program: global variables and local variables.

A global variable is available and accessible to all portions of the program. Whereas, a local variable is only known and accessible within the function where it is declared.

When declaring a variable in C, the number of bits used to store the operator is also specified.

In Figure2.4, we provide a list of common C variable sizes used with the ImageCraft ICC AVR

compiler. The size of other variables such as pointers,

shorts, longs, etc. are contained in the compiler documentation [ImageCraft].

Page 176: Materi Kuliah Mikro_UTS
Page 177: Materi Kuliah Mikro_UTS

When programming microcontrollers, it is important to know the number of bits used to store the variable and also where the variable will be assigned. For example, assigning the contents of an unsigned char variable, which is stored in8-bits, to an 8-bit output port will have a predictable result.

However, assigning an unsigned int variable, which is stored in 16-bits, to an 8-bit output port does not provide predictable results. It is wise to insure your assignment statements are balanced for accurate and predictable results.

The modifier “unsigned” indicates all bits will be used to specify the magnitude of the argument. Signed variables will use the left most bit to indicate the polarity (±) of the argument.

A global variable is declared using the following format provided below. The type of the variable is specified, followed by its name, and an initial value if desired.//global variablesunsigned int loop_iterations = 6;

Page 178: Materi Kuliah Mikro_UTS

The main program is the hub of activity for the entire program.

The main program typically consists of program steps and function calls to initialize the processor followed by program steps to collect data from the environment external to the microcontroller, process the data and make decisions, and provide external control signals back to the environment based on the data collected.

Page 179: Materi Kuliah Mikro_UTS

In the previous section, we covered manyfundamental concepts. In this section wediscuss operators, programming constructs,and decision processing constructs to completeour fundamental overview of programmingconcepts.OPERATORS There are a wide variety of operators provided in

the C language. An abbreviated list of commonoperators are provided in Figures2.5and 2.6. Theoperators have been grouped by generalcategory.

Page 180: Materi Kuliah Mikro_UTS
Page 181: Materi Kuliah Mikro_UTS
Page 182: Materi Kuliah Mikro_UTS

The arithmetic operations provide for basic mathoperations using the various variables described inthe previous section. As described in the previoussection, the assignment operator (=) is used toassign the argument(s) on the right-hand side of anequation to the left-hand side variable.Example: In this example, a function returns thesum of two unsigned int variables passed to thefunction.

unsigned int sum_two(unsigned int variable1, unsignedint variable2){unsigned int sum;sum = variable1 + variable2;return sum;

Page 183: Materi Kuliah Mikro_UTS

The logical operators provide Boolean logic operations. They can be viewed as comparison operators.

One argument is compared against another using the logical operator provided. The result is returned as a logic value of one (1, true, high) or zero (0 false, low).

The logical operators are used extensively in program constructs and decision processing operations. to be discussed in the next several sections.

Page 184: Materi Kuliah Mikro_UTS

There are two general types of operations in the bit manipulation category:shifting operations and bitwise operations. Let’s examine several examples:

Example : Given the following code segment, what will the value of variable2be after execution?

unsigned char variable1 = 0x73;

unsigned char variable2;

variable2 = variable1 << 2;

Note that the left and right shift operation is equivalent to multiplying anddividing the variable by a power of two. The bitwise operators perform thedesired operation on a bit-by-bit basis. That is, the least significant bit of thefirst argument is bit-wise operated with the least significant bit of the secondargument and so on.

Example:Given the following code segment, what will the value of variable3 beafter execution?

unsigned char variable1 = 0x73;unsigned char variable2 = 0xfa;unsigned char variable3;

variable3 = variable1 & variable2;

Page 185: Materi Kuliah Mikro_UTS

The unary operators, as their name implies, require only asingle argument.

For example, in the following code segment, the value of thevariable “i” is incremented. This is a shorthand method ofexecuting the operation “i =i +1;”unsigned int i;i++;Example : It is not uncommon in embedded system designprojects to have every pin on a microcontroller employed.Furthermore, it is not uncommon to have multiple inputs andoutputs assigned to the same port but on different portinput/output pins. Some compilers support specific pinreference. Another technique that is not compiler specific is bittwiddling. Figure 2.7 provides bit twiddling examples on howindividual bits may be manipulated without affecting other bitsusing bitwise and unary operators. The information providedhere was extracted from the ImageCraft ICC AVR compilerdocumentation [ImageCraft].

Page 186: Materi Kuliah Mikro_UTS
Page 187: Materi Kuliah Mikro_UTS

In this section, we discuss several methods of looping through a piece ofcode. We will examine the “for” and the “while” looping constructs.Thefore loop provides a mechanism for looping through the same portion ofcode a fixed number of times. The for loop consists of three main parts:

loop initiation, loop termination testing, and the loop increment.

In the following code fragment the for loop is executed ten times.unsigned int loop_ctr;

for(loop_ctr = 0; loop_ctr < 10; loop_ctr++)

{

//loop body

}

The for loop begins with the variable “loop_ctr” equal to 0. During the firstpass through the loop, the variable retains this value. During the next passthrough the loop, the variable “loop_ctr” is incremented by one. This actioncontinues until the “loop_ctr” variable reaches the value of ten. Since theargument to continue the loop is no longer true, program executioncontinues after the close bracket for the for loop.

Page 188: Materi Kuliah Mikro_UTS

In the previous example, the for loop counter was incremented atthe beginning of each loop pass. The “loop_ctr” variable can beupdated by any amount. For example, in the following codefragment the “loop_ctr” variable is increased by three for everypass of the loop.

unsigned int loop_ctr;for(loop_ctr = 0; loop_ctr < 10; loop_ctr=loop_ctr+3){//loop body}The “loop_ctr” variable may also be initialized at a high value and thendecremented at thebeginning of each pass of the loop.unsigned int loop_ctr;for(loop_ctr = 10; loop_ctr > 0; loop_ctr--){//loop body}

Page 189: Materi Kuliah Mikro_UTS

As before, the “loop_ctr” variable may be decreased by any numerical valueas appropriate for the application at hand.

The while loop is another programming construct that allows multiple passesthrough a portion of code. The while loop will continue to execute thestatements within the open and close brackets while the condition at thebeginning of the loop remains logically true. The code snapshot below willimplement a ten iteration loop. Note how the “loop_ctr” variable isinitialized outside of the loop and incremented within the body of the loop.As before, the variable may be initialized to a greater value and thendecremented within the loop body.

unsigned int loop_ctr;

loop_ctr = 0;

while(loop_ctr < 10)

{

//loop body

loop_ctr++;

}

Frequently, within a microcontroller application, the program begins withsystem initialization actions. Once initialization activities are complete,theprocessor enters a continuous loop. This may be accomplished using thefollowing code fragment.

while(1)

{

}

Page 190: Materi Kuliah Mikro_UTS

There are a variety of constructs that allow decision making. Theseinclude the following: The if statement, The if–else construct, The if–else if–else construct, and the Switch statement.The if statement will execute the code between an open and closebracket set should the condition within the if statement be logicallytrue.Example: To help develop the algorithm for steering the Blinky 602Arobot through a maze, a light emitting diode (LED) is connected toPORTB pin 1 on the ATmega328. The robot’s center IR sensor isconnected to an analog-to-digital converter at PORTC, pin 1. The IRsensor provides a voltage output that is inversely proportional todistance of the sensor from the maze wall. It is desired toilluminate the LED if the robot is within 10 cm of the maze wall.The sensor provides an output voltage of 2.5 VDC at the 10 cmrange. The followingifstatement construct will implement this LEDindicator. We provide the actual code to do this later in the chapter.

Page 191: Materi Kuliah Mikro_UTS

if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC{PORTB = 0x02; //illuminate LED on PORTB[1]}In the example provided, there is no method to turn off the LED once it is turned on. This will require theelseportion of the construct as shown in the next code fragment.if (PORTC[1] > 2.5) //Center IR sensor voltage greater than 2.5 VDC{PORTB = 0x02; //illuminate LED on PORTB[1]}else{PORTB = 0x00; //extinguish the LED on PORTB[1]}Theif–else if—elseconstruct may be used to implement a three LED system. In this exam-ple, the left, center, and right IR sensors are connected to analog-to-digital converter channels on PORTC pins 2, 1, and 0, respectively. The LED indicators are connected to PORTB pins 2, 1, and 0. The following code fragment implements this LED system.

Page 192: Materi Kuliah Mikro_UTS

Theswitchstatement is used when multiple if-else conditions exist. Each possible condition is specifiedby a case statement. When a match is found between the switch variable and a specific case entry,the statements associated with the case are executed until abreakstatement is encountered.Example:Suppose eight pushbutton switches are connected to PORTD. Each switch will implement adifferent action. A switch statement may be used to process the multiple possible decisions as shownin the following code fragment.void read_new_input(void){new_PORTD = PIND;if(new_PORTD != old_PORTD) //check for status change PORTDswitch(new_PORTD){ //process change in PORTD inputcase 0x01: //PD0//PD0 related actionsbreak;case 0x02: //PD1//PD1 related actionsbreak;case 0x04: //PD2//PD2 related actionsbreak;case 0x08: //PD3//PD3 related actionsbreak;case 0x10: //PD4//PD4 related actions

Page 193: Materi Kuliah Mikro_UTS

break;case 0x20: //PD5//PD5 related actionsbreak;case 0x40: //PD6//PD6 related actionsbreak;case 0x80: //PD7//PD7 related actionsbreak;default:; //all other cases} //end switch(new_PORTD)} //end if new_PORTDold_PORTD=new_PORTD; //update PORTD}That completes our brief overview of the C programming language. In the next section, we provide an overview of the Arduino development Environment.

Page 194: Materi Kuliah Mikro_UTS

In this section, we provide an overview of the Arduino Development Environment (ADE). We begin with some background information about the ADE and then review its user friendly features.

We then introduce the sketchbook concept and provide a brief overviewof the built-in software features within the ADE. Our goal is to provide abrief introduction to the features.

All Arduino related features are well documented on the Arduinohomepage (www.arduino.cc).

The first version of the Arduino DevelopmentEnvironment was released inAugust 2005. It was developed at the Interaction Design Institute in Ivrea,Italy to allow students the ability to quickly put processing power to usein a wide variety of projects. Since that time, newer versionsincorporating new features, have been released on a regular basis[www.arduino.cc].

At its most fundamental level, the Arduino Development Environment is auser friendly interface to allow one to quickly write, load, and executecode on a microcontroller. A barebones program need only consist of asetup() and loop()function.

The Arduino Development Environment adds the other required piecessuch as header files and the main program construct. The ADE is writtenin Java and has its origins in the Processor programming language and theWiring Project [www.arduino.cc].

Page 195: Materi Kuliah Mikro_UTS

The Arduino Development Environment is illustrated in right Figure. The ADE contains : a text editor, a message area for displaying

status, a text console, a tool bar of common functions, and an extensive menuing

system. The ADE also provides a user friendly interface to the ArduinoDuemilanove which allows for a quick upload of code. This is possible because the ArduinoDuemilanove is equipped with a bootloader program.

Page 196: Materi Kuliah Mikro_UTS

The toolbar provides single button access to the more commonly used menu features. Most of the features are self explanatory.

The “Upload to I/O Board” button compiles your code and uploads it to the ArduinoDuemilanove.

The “Serial Monitor” button opens the serial monitor feature. The serial monitor feature allows text data to be sent to and received from the Arduino Duemilanove.

The serial monitor feature is halted with the “Stop” button.

Page 197: Materi Kuliah Mikro_UTS

In keeping with a hardware and software platform for students of the arts, the Arduino environment employs the concept of a sketchbook. An artist maintains their works in progress in a sketchbook. Similarly, we maintain our programs within a sketchbook in the Arduino environment. Furthermore, we refer to individual programs as sketches. An individual sketch within the sketchbook may be accessed via the Sketchbook entry under the file tab.

The Arduino Development Environment has a number of built in features. Some of the features may be directly accessed via the Arduino Development Environment drop down toolbar. Provided in Figure 2.10 is a handy reference to show all of the available features.

The toolbar provides a wide variety of features to compose, compile, load and execute a sketch. We illustrate how to use these features in the Application section later in the chapter. Aside from the toolbar accessible features, the ArduinoDevelopment Environment contains a number of built-in functions that allow the user to quickly construct a sketch. These built-in functions are summarized in Figure 2.11.

Complete documentation for these built-in features is available at the Arduinohomepage [www.arduino.cc]. This documentation is easily accessible via the Help tab on the Arduino Development Environment toolbar. This documentation will not be repeated here. Instead, we refer to these features at appropriate places throughout the remainder of the book as we discuss related hardware systems.

Keep in mind the Arduino open source concept. Users throughout the world are constantly adding new built-in features. As new features are added, they will be released in future Arduino development Environment versions. As an Arduino user, you too may add to this collection of useful tools. In the next section, we illustrate how to use the Arduino Duemilanova board in everal applications.

Page 198: Materi Kuliah Mikro_UTS
Page 199: Materi Kuliah Mikro_UTS

Blinking LED Wave

Page 200: Materi Kuliah Mikro_UTS

Hidupkan LED 1 Tunggu 500 msMatikan LED 1Hidupkan LED 2 Tunggu 500 msMatikan LED 2 Lanjutkan sampai LED 5 Proses berbalik dari LED 5 ke 1Ulangi sampai tak hingga

Page 201: Materi Kuliah Mikro_UTS
Page 202: Materi Kuliah Mikro_UTS
Page 203: Materi Kuliah Mikro_UTS
Page 204: Materi Kuliah Mikro_UTS

Ratna Aisuwarya, M.Eng.

Page 205: Materi Kuliah Mikro_UTS

2

living with the lab

A digital system is a data technology that uses discrete (discontinuous) values. By contrast, analog (non‐digital) systems use a continuous range of values to represent information. Although digital representations are discrete, they can be used to carry either discrete information, such as numbers, letters or other individual symbols, or approximations of continuous information, such as sounds, images, and other measurements of continuous systems.

Page 206: Materi Kuliah Mikro_UTS

Analog Signals

• What is an analog signal and how does it differ from a digital signal?

1 1 1 1 1 000

Page 207: Materi Kuliah Mikro_UTS

• What is analog ?• It is continuous range of voltage values (not just 0 or 5V)

• Why convert to digital ?• Because our microcontroller only understands digital.

Analog to Digital Coversion

Page 208: Materi Kuliah Mikro_UTS

Converting Analog Value to Digital

Page 209: Materi Kuliah Mikro_UTS

ADC

• 3 proses penting yang berhubungan dengan ADC : – Sampling, process of taking ‘snapshots’ of a signal over time.

– Quantization, When a signal is sampled, digitalsystems need some means to represent the capturedsamples. The quantization of a sampled signal is howthe signal is represented as one of the quantizationlevels. given n bits, we have 2n unique numbers orlevels one can represent.

– Encoding, the encoding process involves converting aquantized signal into a digital binary number. theencoding process involves representingthequantization level with the available bits

Ratna Aisuwarya, M.Eng. 6

Page 210: Materi Kuliah Mikro_UTS

Quantanization the signal

Page 211: Materi Kuliah Mikro_UTS

ADC – Sampling, Quantization, Encoding

Ratna Aisuwarya, M.Eng. 8

Page 212: Materi Kuliah Mikro_UTS

ADC Devices• Analog‐to‐digital converters merupakan perangkatakuisisi data.

• Komputer menggunakan nilai binary (diskrit),sedangkan dalam implementasi nyata data yg didapatberupa analog (kontinu).

• Contohnya : temperatur, tekanan (angin, cairan),humidity, dll.

• Besaran fisik yang diperoleh dari sensor dikonversikankedalam bentuk tegangan listrik.

• Sehingga, diperlukan ADC untuk menterjemahkansinyal analog ke angka digital sehingga MC dapatmembaca dan memproses data tsb.

9Ratna Aisuwarya, M.Eng.

Page 213: Materi Kuliah Mikro_UTS

10Ratna Aisuwarya, M.Eng.

Page 214: Materi Kuliah Mikro_UTS

Karakteristik ADC• Resolution

– ADC memiliki n‐bit resolusi, n= 8, 12, 16 atau 24– Resolusi chip ADC telah ditentukan berdasarkandesain pabrikan. Cth: ATMega8535 memiliki 8 bit, ATMega 328 memiliki 10 bit.

11Ratna Aisuwarya, M.Eng.

Page 215: Materi Kuliah Mikro_UTS

VRef

• Merupakan tegangan input yang digunakansebagai tegangan referensi. Tegangan ini dapatdigunakan untuk mengatur steps pada ADC.

• Cth: untuk ADC 8‐bit, jumlah steps = 28=256,maka untuk Vref= 4V, dapat ditentukan jumlahsteps = 4V/256=15,62mV

12Ratna Aisuwarya, M.Eng.

Page 216: Materi Kuliah Mikro_UTS

VRef

13Ratna Aisuwarya, M.Eng.

Page 217: Materi Kuliah Mikro_UTS

VRef

14Ratna Aisuwarya, M.Eng.

Page 218: Materi Kuliah Mikro_UTS

Digital Data Output

• Pada ADC 8‐bit output data digital (D0‐D7),sedangkan ADC 10‐bit memiliki output (D0‐D9).

• Untuk menghitung Data output :• Dout : Digital data output (Desimal)

• Vin : analog input voltage• Step size : smallest change

15Ratna Aisuwarya, M.Eng.

Page 219: Materi Kuliah Mikro_UTS

Contoh

• Untuk ADC 8‐bit, Vref = 2,56V. Hitunglahoutput D0‐D7 jika analog input :– 1,7 V– 2,1 V

16Ratna Aisuwarya, M.Eng.

Page 220: Materi Kuliah Mikro_UTS

Analog Signals & Arduinos

• The Arduino can read an analog signal on one of the analog input pins.– analogRead

• The signal that can be read must be between 0 and 5 V.

• The Arduino converts the signal to a number between 0 and 1023.

• How many values are there for a digital signal?  How many values are there for an analog signal on the Arduino?

Page 221: Materi Kuliah Mikro_UTS

• digitalWrite(13, LOW); // Makes the output voltage on pin 13 , 0V

• digitalWrite(13, HIGH); // Makes the output voltage on pin 13 , 5V

• int buttonState = digitalRead(2); // reads the value of pin 2 in buttonState

Reading/writing digital values

Page 222: Materi Kuliah Mikro_UTS

• The Arduino Uno board contains 6 pins for ADC

• 10‐bit analog to digital converter

• This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023

ADC in Arduino

Page 223: Materi Kuliah Mikro_UTS

Analog and Digital Measurements

living with the lab

14 digital input / output pins

6 analog input pins© 2011 LWTL faculty team

Page 224: Materi Kuliah Mikro_UTS

• analogRead(A0); // used to read the analog value from the pin A0

• analogWrite(2,128);  

Reading/Writing Analog Values

Page 225: Materi Kuliah Mikro_UTS

Inputs and OutputsAn input “receives” information or senses a voltage in the external world.An output “delivers” information or makes something happen in the external world.

22

living with the lab

Below is an example from an earlier class where we made an LED flash on and off. 

Are we using digital pin 0 as an input or an output? 

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

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

digital output

Page 226: Materi Kuliah Mikro_UTS

23

living with the lab

Receiving Input from an Arduino

int val;

val = digitalRead(7);

int val;

val = analogRead(5);

digital input analog input

val is either 0 or 1

• 0 = voltage sensed at digital pin 7 is LOW  (0V)

• 1 = voltage senses at digital pin 7 is HIGH (5V)

val is an integer between 0 and 1023

• 0 = voltage sensed at analog pin 5 is zero volts

• 1023 = voltage senses at analog pin 5 is five volts

Guess what val would be if the voltage sensed at analog pin 5 was 2.5V?

511

Page 227: Materi Kuliah Mikro_UTS

24

living with the lab

Digital InputsThe Arduino reference indicates that digitalRead() will return . . .

• a value of HIGH if the voltage at the digital input pin is greater than 3 volts• a value of LOW if the voltage at the digital input pin is less than 2 volts. 

time (milliseconds)

volta

ge (V

)

0 1 2 3 4 5 6 7 8 9

5

4

3

2

1

0

digitalRead()returns LOW or 0

digitalRead()may return a value of HIGH or LOW

digitalRead()returns HIGH or 1

LOW or HIGH???

low

high

ambiguous

Page 228: Materi Kuliah Mikro_UTS

25

living with the lab

Analog InputsThe analog input pins on your Arduino have 10‐bit resolution and consequently measure in (2)10 or 1024 increments.

The analogRead() functions returns a value between 0 and 1023, where 0 is zero volts and 1023 is 5 volts.

analogRead ·51023

smallest increment of voltage that can be read = 0.00488 volts

2 1024

Page 229: Materi Kuliah Mikro_UTS

26

living with the lab

data point from plot above

If a digital pin  is usedto sample voltage

if an analog pin  is usedto sample voltage

output ofdigitalRead()

hypothetical analogRead()

output

voltage computed fromanalogRead() output

time (milliseconds)

volta

ge (V

)

0 1 2 3 4 5 6 7 8 9

5

4

3

2

1

0

digitalRead()returns LOW or 0

digitalRead()may return a value of HIGH or LOW

digitalRead()returns HIGH or 1

point 1 point 2 point 3

Examples

2 ambiguous 526 526 ·51023 2.571

1 0 217 217 ·51023 1.061

3 1 964 964 ·51023 4.712

Page 230: Materi Kuliah Mikro_UTS

Analog Input

Program Time!

• We’re going to write a program that will turn on the Arduino’s LED when “threshold” value is reached.

How:

Potentiometer

• Use a Voltage Divider to change the voltage on the analog input pin.  • Use the Arduino to detect when the voltage has reached a certain level.• Turn on the LED!

Page 231: Materi Kuliah Mikro_UTS

Analog Signal Detector• Step 1 – Declare Variables:

int inputPin = 0;  // select the input pin for the potentiometer // ( can be 0 through 5).

int ledPin = 13;  // select the pin for the Arduino’s LED int inputValue = 0; // variable to store the value coming from

// the voltage divider.• Step 2 – Setup:

void setup(){

pinMode(ledPin, OUTPUT);  //Declare the LED pin as an //output.

}• We do NOT have to declare the analog pin as an input.  Why?

Page 232: Materi Kuliah Mikro_UTS

Analog Signal Detector• Step 3 – The Loop:

void loop() {

inputValue = analogRead(inputPin);  // Read the analog //input, what are// the possible values.

if(inputValue > 511) // Check our threshold.{

digitalWrite(ledPin, HIGH); // Turn on the LED.}else{

digitalWrite(ledPin, LOW); // Turn off the LED.}

}

Page 233: Materi Kuliah Mikro_UTS

Your turn

• Challenges: Complete in order1. Design a program to make the LED flash at a 

speed dependent on the value on the analog input pin.

2. Turn on a number of LEDs that is proportional to the analog input value. 

Page 234: Materi Kuliah Mikro_UTS
Page 235: Materi Kuliah Mikro_UTS

Ratna Aisuwarya, M.Eng.

Page 236: Materi Kuliah Mikro_UTS

Sensor Interfacing and Signal Conditioning

• Bagian ini akan menjelaskan bagaimanainterfacing sensor dengan mikrokontroler.

• Sensor SuhuTranduser mengkonversikan data fisik seperti suhu,intensitas cahaya,, dll menjadi sinyal listrik.Outputnya dapat berupa tegangan, arus, resistansi, ataukapasitansi.Cth: suhu dikonversikan menjadi sinyal listrikmenggunakan sebuah tranduser yang dinamakantermistorTermistor bereaksi terhadap perubahan suhu denganmengubah nilai resistansi. Tetapi tidak linear.

2Ratna Aisuwarya, M.Eng.

Page 237: Materi Kuliah Mikro_UTS

• Karena kompleksitasyang ditimbulkan saatmenulis software padakomponen yang tidaklinear tersebut mendo‐rong pabrikan untuk membuat sensor suhu yangbersifat linear. Salah satunya adalah sensor suhubuatan National Semiconductor Corp. yaituLM34 dan LM35.

3Ratna Aisuwarya, M.Eng.

Page 238: Materi Kuliah Mikro_UTS

Sensor Suhu LM34 dan LM35• Sensor suhu LM34 adalah IC sensor suhudengan tegangan output yang linear dengansuhu dalam Fahrenheit. Setiap kenaikan satuderajat ditandai dengan kenaikan teganganoutput sebesar 10 mV.

4Ratna Aisuwarya, M.Eng.

Page 239: Materi Kuliah Mikro_UTS

Sensor Suhu LM35

5

• Sensor suhu LM35 adalah IC sensor suhudengan tegangan output yang linear dengansuhu dalam Celcius. Setiap kenaikan satuderajat ditandai dengan kenaikan teganganoutput sebesar 10 mV.

Ratna Aisuwarya, M.Eng.

Page 240: Materi Kuliah Mikro_UTS

Signal Conditioning• Pengkondisian sinyal secaraluas digunakan dalam akuisisidata. Sinyal output yang dihasilkan oleh tranduser(berupa tegangan, arus, kapasitansi, resistansi, dll) harus dikonversikan menjaditegangan, yang nantinya akandigunakan sebagai input ADC.

• Cth: perubahan resistansi padathermistor akan dikonversikanmenjadi tegangan.

6Ratna Aisuwarya, M.Eng.

Page 241: Materi Kuliah Mikro_UTS

Interfacing LM34 pada AVR

• Sebuah ADC dengan resolusi 10‐bit mempunyaisteps maximum 1024.

• LM34/Lm35 menghasilkan 10mV setiapperubahan satu derajat suhu.

• jika tegangan internal digunakan sebagaitegangan referensi (2,56V). Step size =2,56V/1024 = 2,5 mV.

• Karena sensor memiliki perubahan setiap 10 mV,maka untuk setiap derajat, step size = 10 mV/2,5mV = 4)

7Ratna Aisuwarya, M.Eng.

Page 242: Materi Kuliah Mikro_UTS

8Ratna Aisuwarya, M.Eng.

Page 243: Materi Kuliah Mikro_UTS

Konfigurasi Pin AVR dengan sensor LM34/35

9Ratna Aisuwarya, M.Eng.

Page 244: Materi Kuliah Mikro_UTS

Contoh

Pada tabel 13.11, coba tentukan nilai outputuntuk suhu 70 derajat. Tentukan nilai registerADC pada ADCH dan ADCL untuk opsi left‐justified.

10Ratna Aisuwarya, M.Eng.

Page 245: Materi Kuliah Mikro_UTS

• Step size : 2,56/1024 = 2,,5 mV (Vref = 2,56)• Untuk suhu 70 derajat, outputnya = 700 mV. Karena setiap kenaikan 1 derajat = 10 mV.

• Jumlah steps = 700 mV//2,5 mV = 280 (desimal)• 280 = 0100011000• ADCH = 01000110 dan ADCL = 00000000 untukopsi left‐justified.

• Untuk mendapatkan nilai yang sesuai, maka hasiltsb dibagi 4. (280/4=70).

• Langkah sederhananya adalah dengan membacaregister ADCH, yang berisi nilai 70 (01000110)

11Ratna Aisuwarya, M.Eng.

Page 246: Materi Kuliah Mikro_UTS

DAC Interfacing

• Digital‐to‐analog converter (DAC)Digunakan untuk mengkonversikan pulsa digitalmenjadi sinyal analog. DAC memiliki beberapa jenisresolusi (8, 10, dan 12 bit). 8 bit input DAC sptDAC0808 memiliki 256 level tegangan output.

12Ratna Aisuwarya, M.Eng.

Page 247: Materi Kuliah Mikro_UTS

DAC 0808

• Pada DAC ini input digital akan dikonversikanmenjadi arus (Iout), dengan menghubungkansebuah resistor pada pin Iout, hasilnya akandikonversi menjadi tegangan.

• Jumlah arus total dalam bentuk biner (inputD0‐D7) sbb :

13Ratna Aisuwarya, M.Eng.

Page 248: Materi Kuliah Mikro_UTS

Converting Iout to Voltage in DAC0808

14Ratna Aisuwarya, M.Eng.

Page 249: Materi Kuliah Mikro_UTS

Contoh

• Diasumsikan R = 5 Kohms dan Iref = 2mA. Hitunglah Vout untuk binary input :

a) 10011001 (99H)

b) 11001000 (C8H)

a). Iout = 2mA(153/256)= 1,195 mA

Vout = 1,195 mA x 5K = 5,975 V

15Ratna Aisuwarya, M.Eng.

Page 250: Materi Kuliah Mikro_UTS