Mikrokontroler P 1 – P E ND N D AH A H UL ULUA N RATNA RA TNA AISUW AISUWARY ARYA, A, M.ENG
Materi Hari Ini Kontrak Perkuliahan Pengenalan Mikrokontroler (Arduino, ATMega 328)
Penilai enilaian, an, Aturan Kehadiran Penilaian Tugas Plagiarisme Praktikum Partisipasi
Penilaian Tugas : 20 % Tugas Besar : 10 % Praktikum : 20% UTS : 25% UAS : 25%
Matter Ma erii Kul ulia iah h Pengenalan Arduino – ATMega 328 Pemrograman Arduino
Komunikasi asi Serial Komunik Analog Digital Conversion (ADC) Sistem Interupsi Sistem Timer Aplikasi Antarmuka
Apa yang akan dipelajari ?
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.
Apa itu Arduino ?
Arduino
Arduino
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).
Arduino Lay Layout out
ARDUINO ARDUIN O HOST PROCE PROCESSOR SSOR — THE ATMEG ATMEGA328 A328 Prosesor Arduino adalah Atmel Atmega 328. 28 Pin. Mikrokontroler 8‐bit. Arsitekturnya berbasis Reduced Instruction Set Computer (RISC), yang dapat
mengeksekusii 20 Juta Instruksi mengeksekus Instruksi per detik (MIPS) mill million ion instructi instructions ons 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
Ardu Ar duin ino o system emss
EXAMPLE: AUT AUTONOMOUS ONOMOUS MAZE MAZE NAVIGATING ROBOT Sebelum membahas Sebelum membahas lebi lebih h jau jauh h ten tentan tang g ar ardui duino no,, kit kita a liha lihatt con contoh toh penerapa penerapan n ar ardui duino no seba sebaga gaii kontroler robot (Blinky 602A). Robot ini bekerja sebagai line following robot. Dengan komponen sebagai 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.
STRUCTURE CHART Blok diagram menggambarkan sistem secara visual. Tanda panah menunjukkan aliran data antara bagian‐bagian. Pada blok diagram robot ini terdapat 3 sistem utama : sistem kontrol motor sistem sensor sistem input/output digital.
Ketiga sistem tsb saling berinteraksi dengan algoritma kontrol utama yang akan mengatur robot agar dapat bekerja secara otomatis melalui labirin by sensing and avoiding walls.
DIAGRAM UML Diagram 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.
ARDUINO OPEN SOURCE SCHEMATIC Semua 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.
Variasi Arduino
Arduino shield
ARDUINO SOF TW TWARE Disebut juga dengan Arduino Development Disebut juga Environment. Program ini dapat didownload di homepage Arduino (www.arduino.cc)
ARDUINO /ATMEGA328 HARDWARE FEATURES Arduino Duemilanove / Uno menggunakan Atmega 328 sebagai prosesornya. Berikut Diagram pin dan blok diagram Atmega328
MEMORY ATmega328 memiliki 3 memori utama : Flash electrically erasable pro‐grammable read only memory
(EEPROM)
Static random access memory (SRAM) byte‐addressable EEPROM untuk penyimpanan data.
In-System In-Sys tem Programmable 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.
Byte-Addressable EEPROM Byte‐addressable memory digunakan untuk menyimpan secara
permanen variabel‐variabel selama eksekusi program.
logging jika jika merupakan memori nonvolatile. Berguna untuk sistem logging terjadi kesalahan / malfunction saat eksekusi program, program, juga 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.
Static Random Access Memory (SRAM) terhapus jika jika Memory Static RAM merupakan volatile, yang isinya akan terhapus 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 .
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)
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.
ATmega328 block diagram
INTERNAL SYSTEMS Bagian ini membahas fitur ‐fitur internal yang ada pada ATmega328. fitur‐fitur tersebut telah built‐in pad ada a ch chip ip mik ikrrok okon ontr trol oler ern nya. Dengan ini tugas‐tugas cukup rumit dapat dilakukan oleh mikrokontroler.
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.
Time Base (con’t) Kecepatan tan urutan‐urutan setiap task pada mikrok mikrokontroler ontroler diatur Kecepa dengan clock. Sumber clock ini dijadikan sinyal pulsa bagi seluruh perangkat yang terhubung dengan mikrokontroler.
ATmega328 memiliki clock internal atau clock eksternal. Frekuensi
Clock internal dapat diatur melalui program, dengan frekuensi 1, 2, 4 or 8 MHz. Untuk variasi frekuensi selain itu dapat menggunakan eksternal
clock (cth: oscillator crystal).
Timing Subsy Subsyst stem em ATmega328 dilengkapi dengan timer tambahan yang dapat
menghasilkan sinyal output yang presisi, menghitung karakteristik sinyal digital (periode, duty cycle, frekuensi). ATmega328 dilengkapi dengan 2 unit timer/counter 8‐bit dan 1
unit counter 16‐bit.
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 periode
sinyal berlangsung. Dapat dituliskan sebagai :
memilikii 4 unit channel (PWM). Channel PWM terhubung dengan ATmega328 memilik sumber clock yang dapat menghasilkan beberapa variasi lebar sinyal PWM (dari frekuensi tinggi dengan sinyal low duty cycle sampai dengan frekuensi rendah dengan sinyal high duty cycle) Sinyal PWM digunakan dalam berbagai aplikasi, seperti dalam pengontrolan
posisi motor servo, pengaturan kecepatan motor DCV, dll.
Serial Communications ATmega328 dilengkapi dengan beberapa subsistem komunikasi serial : Universal Synchronous and Asynchronous Serial Receiver and
Transmitter (USART)
peripheral al interface (SPI) Serial peripher Two‐wire Serial Interface.
Semua system tersebut menggunakan transmisi data secara serial, yaitu dengan mengirimkan data bit per bit dari transmit transmitter ter ke receiver.
Serial USART Serial USART menggunakan komunikasi full duplex (dua arah) antar antara a 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 menyelar menyelaraskan askan antar antara a keduan keduanya, ya, digunakan start 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 dua stop bit. ATmega328 ATmega328 juga juga dilengkapi dengan bit parity (even atau odd) dan hardwar hardware e yang akan
melakukan check parity pada receiver. Satu bit paritas dapat mendeteksi error bit dalam satu byte data. USART juga juga bias dikonfigurasi dalam mode synchronous. (akan dibahas nanti). USART
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 juga meningkatkan meningkatkan kecepa kecepatan tan transmisi data 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 antar antara a transmitter dan
receiver. Sedangkan receiver di set sebagai slave. (dibahas nanti)
Two-wire Serial Interface—TWI Dengan Sistem TWI beberapa perangkat bisa dihubungkan dalam satu jaringan
(microcontrollers, transducers, displays, memory storage, etc.) dengan menggunakan skema interkoneksi two‐wire. The TWI dapat menghubungkan maximum 128 perangkat sekaligus. Setiap
perangkat memiliki alamat yang unik dengan frekuensi komunikasi data sampai dengan 400 KHz. This allows the device to freely exchange information with other devices in the network within a small area.
Analog to Digital Converter—ADC ATmega328 dilengkapi dengan 8 channel ADC. ADC mengkonversi sinyal analog dari lingkungan luar menjadi repesentasi biner untuk
digunakan 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, yaitu antara 000(16) dan 3FF (16).
Interrupts Eksekusi program secara umum mengikuti langkah‐langkah sesuai dengan urutan instruksi
yang telah dibuat.
Tetapi, terkadang urutan instruksi ini perlu di interupsi untuk merespon kesalahan atau status
yang memiliki prioritas prioritas lebih tinggi pada internal internal atau eksternal mikrokontroler. Saat hal itu terjadi, mikrokontroler harus menghentikan operasi normal dan menjalankan
instruksi 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 dari
luar (eksternal).
REFERENCES SparkFun Electronics, 6175 Longbow Drive, Suite 200, Boulder, CO 80301 (www.sparkfun.com) • Arduino homepage (www.arduino.cc) •
Mikrokontroler ARSITEKTUR ATMEGA328 A TMEGA328 RATNA RA TNA AISUW AISUWARY ARYA, A, M.ENG
ARDUINO /ATMEGA328 HARDWARE FEATURES
MEMORY ATmega328 memiliki 3 memori utama :
Flash electrically erasable programmable read only memory (EEPROM)
Static random access memory (SRAM)
byte addressable EEPROM untuk penyimpanan data. ‐
In-System In-Sys tem Programmable 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.
Byte-Addressable EEPROM
Byte addressable memory digunakan untuk menyimpan secara permanen variabel variabel selama eksekusi program. ‐
‐
merupakan memori nonvolatile. Berguna untuk sistem logging logging jika jika terjadi kesalahan / malfunction saat eksekusi program, program, juga 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.
Static Random Access Memory (SRAM)
Memory Static RAM merupakan volatile, yang isinya akan terhapus terhapus jika 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 .
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)
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. ‐
INTERNAL SYSTEMS Bagian ini membahas fitur fitur internal yang ada pada ATmega328. fitur fitur tersebut telah built in pad ada a ch chip ip mik ikrrok okon ontr trol oler ern nya. Dengan ini tugas tugas cukup rumit dapat dilakukan oleh mikrokontroler. ‐
‐
‐
‐
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. ‐
Time Base (con’t)
Kecepatan urutan urutan setiap task pada mikrok Kecepatan mikrokontroler ontroler diatur dengan clock. Sumber clock ini dijadikan sinyal pulsa bagi seluruh perangkat yang terhubung dengan mikrokontroler. ‐
ATmega328 memiliki clock internal atau clock eksternal. Frekuensi Clock internal dapat diatur melalui program, dengan frekuensi 1, 2, 4 or 8 MHz.
Untuk variasi frekuensi selain itu dapat menggunakan eksternal clock (cth: oscillator crystal).
Timing Subsy Subsyst stem em
ATmega328 dilengkapi dengan timer tambahan yang dapat menghasilkan sinyal output yang presisi, menghitung karakteristik sinyal digital (periode, duty cycle, frekuensi).
ATmega328 dilengkapi dengan 2 unit timer/counter 8 bit dan 1 unit counter 16 bit. ‐
‐
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 periode sinyal berlangsung. Dapat dituliskan sebagai :
memilikii 4 ATmega328 memilik
unit channel (PWM). Channel PWM terhubung dengan sumber clock yang dapat menghasilkan beberapa variasi lebar sinyal PWM (dari frekuensi tinggi dengan sinyal low duty cycle sampai dengan frekuensi rendah dengan sinyal high duty cycle)
Sinyal PWM
digunakan dalam berbagai aplikasi, seperti dalam pengontrolan posisi motor servo, pengaturan kecepatan motor DCV, dll.
Serial Communications Amega328 dilengkapi dengan beberapa subsistem komunikasi serial :
Universal Synchronous and Asynchronous Serial Receiver and Transmitter (USART)
Serial peripher peripheral al interface (SPI)
Two wire Serial Interface. ‐
Semua system tersebut menggunakan transmisi data secara serial, yaitu dengan mengirimkan data bit per bit dari transmit transmitter ter ke receiver.
Serial USART
Serial USART menggunakan komunikasi full duplex (dua arah) antar antara a 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 menyelar menyelaraskan askan antar antara a keduan keduanya, ya, digunakan start 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 dua stop bit.
ATmega328 juga dilengkapi dengan bit parity (even atau odd) dan hardwar ATmega328 juga hardware e yang akan melakukan check parity pada receiver. Satu bit paritas dapat mendeteksi error bit dalam satu byte data.
USART juga USART juga bias dikonfigurasi dalam mode synchronous. (akan dibahas nanti).
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 juga meningkatkan meningkatkan kecepa kecepatan tan transmisi data 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 antar antara a transmitter dan receiver. Sedangkan receiver di set sebagai slave. (dibahas nanti)
Two-wire Serial Interface—TWI Dengan Sistem TWI
beberapa perangkat bisa dihubungkan dalam satu jaringan (microcontrollers, transducers, displays, memory storage, etc.) dengan menggunakan skema interkoneksi two wire. ‐
The
TWI dapat menghubungkan maximum 128 perangkat sekaligus. Setiap perangkat memiliki alamat yang unik dengan frekuensi komunikasi data sampai dengan 400 KHz. This allows the device to freely exchange information with other devices in the network within a small area.
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 mV..
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.
Pemr emrogr ograma aman n Ar Ardui duino no pada um pada umum umny nya a mi mikr krok okon ontr trole olerr di dipr prog ogra ram m me mengg nggun unak akan an beb beber erap apa a va varia riasi si ba baha hasa sa C. Ba Baha hasa sa C member mem berika ikan n kemu emudah dahan an bag bagii pr progr ogramm ammer er un untuk tuk men mengon gontro troll har hardw dware are mikr mikrok okon ontro troler ler sek sekali aligus gus efisi ef isien ensi si wa waktu ktu da dala lam m pe penu nulis lisan an pr progr ogram am.. Pad ada a ga gamb mbar ar te terli rliha hatt sof softw twar are e co comp mpile ilerr te terle rleta tak k pa pada da komputer sebagai host. Tugas compiler mengubah program (filename.c dan filename.h) menjadi code mesin (filename.hex) yang akan diloading ke processor. 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 error,, compiler akan memberitahu me mberitahu user user.. Program assembly tidak akan digenerated sampai tidak ada error lagi. File program assembly (filename.asm) kemudian dilanjutkan ke assembler. 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 dalam pemrograman. (program development, transformation to machine code, and loading into the Arduino
ANAT ANA TOMY PRO PROGRAM GRAM (dalam C) Program pada mikrokontroler memiliki struktur dan format yang sama. Beberapa variasi dibuat sesuai dengan kebutuhan programmer.
Komentar dibuat sebagai log program yang dibuat. Sehingga memudahkan programmer untuk merevisi di kemudian hari, serta dapat digunakan sebagai pengingat detil detil program. ‐
INCLUDE FILES 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 of each 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 files #include #include
FUNCTIONS 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 of functions 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.
There are three different pieces of of code 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 of the 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, return_variable function_name(required_variable1, required_variable2);
If the function does not require variables or sends back a variable the word “void” is placed in the If the variable’s position. Thefunction callis the code statement used within a program to execute the function. The function call consists of of the the function name and the actual arguments required by the function. If If the 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 of the the program that called it.
The fu The func ncti tion on bo body dy is a se self lf cont containe ained d “mini pr prog ogrram am..” Th The e fi firs rstt li line ne of th the e function body contains the same information as the function prototype: the name of the function, any variables required by the function, and any variable retu re turn rned ed by th the e fu func ncti tion. on. Th The e la last st li line ne of th the e fu func ncti tion on co cont ntai ains ns a “r “ret etur urn” n” statement. ‐
‐
Here a variable may be sent back to the portion of the program that called the function. 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, they are declared next. These variable are referred to as local variables. The actions required by the function follow. The function prototype follows this format: return_variable return_variab le function_nam function_name(required_variab e(required_variable1, le1, required_variabl required_variable2) e2) { //local variables required by the function unsigned int variable1; unsigned char variable2; //program statements statements required by the function //return variable return return_varia return_variable; ble; }
Contoh
Example:In figure 2.3 example, we describe how to configure the ports of of the 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] If DDRB[7] is set to a logic 1, the corresponding port pin PORTB[7] is configured as an output pin. Similarly, if if DDRB[7] DDRB[7] is set to logic 0, the corresponding port pin is configured as an input pin. During some of of the the early steps of of a a program, a function is called to initialize the ports as input, output, or some combination of of both. both.
PROGRAM CONSTANTS 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 TRUE 1 1 #define FALSE FALSE 0 0 #define ON 1 #define OFF OFF 0 0
VARIABLES There are two types of of variables variables used within a program: global variables and local variables. A global variable is available and accessible to all portions of of the 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 of bits bits used to store the operator is also specified. In Figure2.4, we provide a list of of common common C variable sizes used with the ImageCraft ICC AVR compiler. The size of of other other variables such as pointers, shorts, longs, etc. are contained in the compiler documentation [ImageCraft].
C Variables
When programming microcontrollers, it is important to know the number of of bits bits used to store the variable and also where the variable will be assigned. For example, assigning the contents of of an 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 of the the argument. Signed variables will use the left most bit to indicate the polarity (±) of of the the argument. A global variable is declared using the following format provided below. The type of of the the variable is specified, followed by its name, and an initial value if if desired. desired. //global variables //global variables unsigned int loop_iterations = 6;
MAIN PROGRAM The main program is the hub of of activity activity for the entire program. The main program typically consists of of program 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.
FUNDAMENTAL PROGRAMMING CONCEPTS In the pr prev eviou iouss se secti ction on,, we co cove vere red d ma many ny fun funda damen menta tall co conce ncept pts. s. In thi thiss sec sectio tion n we di disc scus usss oper op era ato torrs, pr prog ogrram ammi ming ng co cons nstr truc ucts ts,, an and d de deci cisi sion on pr proc oces essi sing ng co cons nstr truc ucts ts to co comp mple lete te ou ourr fundamental overview of programming concepts. OPERATORS ◦
There are a wide variety of operators provided in the C language. An abbreviated list of common operators are provided in Figures2.5and 2.6. The operators have been grouped by general category.
Arithmetic operations The ar The arit ithm hmet etic ic op oper erat atio ions ns pr prov ovid ide e for ba basi sicc ma math th op oper era ati tion onss us usin ing g th the e var ario ious us var aria iabl bles es described in the previous section. As described in the previous section, the assignment operator (=) is (=) is used to assign the argument(s) on the right hand side of an equation to the left hand side variable. ‐
‐
Example: In this example, a function returns the sum of two unsigned int variables passed to the function. unsigned int sum_two(unsigned int variable1, unsigned int variable2) { unsigned int sum; sum = variable1 + variable2; return sum;
Logical operations 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 of one 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.
Bit manipulation operations There are two gen There gener eral al typ types es of ope opera ratio tions ns in the bit ma manip nipula ulati tion on ca cate tegory gory:: shi shifti fting ng operations and bitwise operations. Let’s examine several exampl examples: es: Example : Given the following code segment, what will the value of variable2 of variable2 be after execution? unsigned char variable1 = 0x73; unsigned char variable2; variable2 = variable1 << 2;
Note that the left and right shift operation is equivalent to multiplying and dividing the variable 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 with the least significant bit of the second argument and so on.
‐
‐
‐
Example: Examp le:Gi Given ven the fo follo llowi wing ng cod code e seg segmen ment, t, wh what at wi will ll the va value lue of of variable3 be aft after er execution? unsigned char variable1 = 0x73; unsigned char variable2 = 0xfa; unsigned char variable3; variable3 = variable1 & variable2;
Unary operations The unary operators, as their name implies, require only a single argument. For example, in the following code segment, the value of the variable “i” is incremented. 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 have every pin on a microcontroller employed. Furthermore, it is not uncommon to ha have ve mu mult ltip iple le in inpu puts ts an and d ou outp tput utss as assi sign gned ed to th the e sa same me po port rt bu butt on diff di ffer eren entt po port rt in inpu put/ t/ou outp tput ut pi pins ns.. So Some me co comp mpil iler erss su supp ppor ortt sp spec ecif ific ic pi pin n reference. Another technique that is not compiler specific is bit twiddling. Figure 2.7 provides bit twiddling examples on how individual bits may be manipulated without affecting other bits using bitwise and unary operators. The information provided here was extracted from the ImageCraft ICC AVR compiler documentation [ImageCraft].
PROGRAMMING CONSTRUCTS
In this section, we discuss several methods of looping through a piece of code. We will exam ex amine ine the “for” and and th the e “while” loopi looping ng co cons nstr truc ucts ts.. Th Thef efor ore e lo loop op pr prov ovid ides es a mechanism for looping through the same portion of code 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 lo The loop op be begi gins ns wi with th th the e va vari riab able le “loop_ctr” equal equal to 0. Du Duri ring ng th the e fi firs rstt pa pass ss through the loop, the variable retains this value. During the next pass through the loop, the var variab iable le “loop_ctr” is in incr crem emen entted by on one. e. Th This is ac acti tion on co cont ntin inue uess un unti till th the e “loop_ctr” variable “loop_ctr” variable reaches the value of ten. Since the argument to continue the loop is no longer true, program execution continues after the close bracket for the for loop.
In the previous example, the for loop counter was incremented at the beginning of each loop pass. The “loop_ctr” variable “loop_ctr” variable can be updated by any amount. For example, in the following code fragment the “loop_ctr” variable “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” “loop_ctr” varia variable ble may also be initialized initialized at a high value and then decremented decremented at the beginning of each pass of the loop. unsigned int loop_ctr; ‐‐ ) for(loop_ctr = 10; loop_ctr > 0; loop_ctr ‐‐ { //loop body }
As be beffor ore, e, th the e “loop_ctr” vari variab able le ma may y be de decr crea ease sed d by an any y nu nume meri rica call va valu lue e as appropriate for the application at hand. The while loop is another programming construct that allows multiple passes through a portion of code. The while loop will continue to execute the statements within the open and close brackets while the condition at the beginning of the loop remains logically true. The code snapshot below will implement a ten iteration loop. Note how the “loop_ctr” variable is initialized outside of the loop and incremented within the body of the loop. As before, the variable may be initialized to a greater value and then decremented within the loop body. unsigned int loop_ctr; loop_ctr = 0; while(loop_ctr < 10) { //loop body loop_ctr++; }
Frequentl Freque ntly y, wi withi thin n a mi micr croco ocontr ntroll oller er app applic licat ation ion,, the pr progr ogram am beg begins ins wi with th sy syst stem em initialization actions. Once initialization activities are complete,the processor enters a continuous loop. This may be accomplished using the following code fragment. while(1) { }
DECISION PROCESSING There are a variety of constructs that allow decision making. These include the following: The if sta statemen tement, t, 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 condition within the if statement be logically true. Example: To help develop the algorithm for steering the Blinky 602A robot through a maze, a light emitting diode (LED) is connected to PORTB pin 1 on the ATmega328. The robot’s center IR sensor is connected to an analog to digital converter at PORTC, pin 1. The IR sensor provides a voltage output that is inversely proportional to distance of the sensor 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 followingifstatement construct will implement this LED indicator. We provide the actual code to do this later in the chapter. ‐
‐
if (PORTC[1] if (PORTC[1] > 2.5) 2.5) //Center //Center IR IR sensor sensor voltage voltage greater greater than than 2.5 VDC { PORTB = 0x02; 0x02; //illuminate //illuminate LED on PORTB[1] } In the example example provided, provided, there is no method method to to turn off off the the LED once it it is is turned on. This will will require require theelseportion of the of the construct construct as as shown in the next next code code fragment. if (PORTC[1] if (PORTC[1] > 2.5) 2.5) //Center //Center IR IR sensor sensor voltage voltage greater greater than than 2.5 VDC { PORTB = 0x02; 0x02; //illuminate //illuminate LED on PORTB[1] } else { PORTB = 0x00; 0x00; //extinguish //extinguish the LED on PORTB[1] } Theif–else if—elseconstruct may be may be used used to to implement implement a a three LED system. In this exam‐ ple, the left, center, and and right right IR IR sensors are connected connected to to analog‐to‐digital converter channels converter channels on PORTC pins pins 2, 1, and and 0, 0, respectively. The LED indicators are connected to connected to PORTB PORTB pins pins 2, 1, and and 0. 0. The The following following code code fragment fragment implements implements this LED system.
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 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 a different action. A switch statement may be used to process the multiple possible 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 { //process
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
break; case 0x20: 0x20: //PD5 //PD5 //PD5 related related actions actions break; case 0x40: 0x40: //PD6 //PD6 //PD6 related related actions actions break; case 0x80: 0x80: //PD7 //PD7 //PD7 related //PD7 related actions actions break; default:; //all default:; //all other other cases cases } //end } //end switch(new_PORTD) switch(new_PORTD) } //end } //end if if new_PORTD new_PORTD old_PORTD=new_PORTD; //update old_PORTD=new_PORTD; //update PORTD } That completes our brief brief overview overview of of the the C programming language. In the next section, we provide an overview of of the the Arduino development Environment.
ARDUINO DEVELOPMENT ENVIRONMENT In this section, we provide an overview of of the 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 within the ADE. Our goal is to provide a brief introduction to the features. ‐
All Arduin Arduino o relat related ed featu features res are well documented on the Arduino homepage (www (www.arduino .arduino.cc). .cc). The first version of the Arduino DevelopmentEnvironment was released in August 2005. It was developed at the Interaction Design Institute in Ivrea, Italy to allow students the ability to quickly put processing power to use in a wide variety of projects. Since that time, newer versions incorporating new features, have been released on a regular basis [www.arduino.cc]. At its most fundamental level, the Arduino Development Environment is a user friendly interface to allow one to quickly write, load, and execute code on a microcontroller. A barebones program need only consist of a setup() and loop()functio loop()function. n. The Ar Ardu duino ino Dev Develo elopm pmen entt En Envir viron onme ment nt add addss the oth other er re requi quire red d pie pieces ces suc such h as hea heade derr fil files es and the mai main n program construct. The ADE is written in Java and has its origins in the Processor programming language and the Wiring Project [www.arduino.cc].
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 of common common functions, and an extensive menuing system. The ADE also provides a user friendly interface to the Arduino Duemilanove which allows for a quick upload of of code. code. This is possible because the Arduino Duemilanove is equipped with a bootloader program.
The toolbar provides single button access to the more commonly used menu features. Most of the features are self self explanatory. explanatory. The “Upload to I/O Board” button compiles your code and uploads it to the Arduino Duemilanove. 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.
SKETCHBOOK CONCEPT ARDUINO SOFTWARE, LIBRARIES, AND LANGUAGE REFERENCES In keeping with a hardware and software platform for students of of the the arts, the Arduino environment employs the concept of of a 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 of built built in features. Some of of the 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 of the the available features. The toolbar provides a wide variety of of features 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 of built 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 of the 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 of useful useful tools. In the next section, we illustrate how to use the Arduino Duemilanova board in everal applications. ‐
APPLICATION 1: ROBOT IR SENSOR 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’s interaction 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 of the 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.
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 proof of concept. 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 if the the robot is within 10 cm of of the the maze wall. The sensor provides an output voltage of of 2.5 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.
The IR sensor’s power (red wire) and ground (black wire) connections are connected to the 5V and Gnd pins on the Arduino Duemilanove board, 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 of the the diagram is connected to the DIGITAL 0 pin on the Arduino Duemilanove board.
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 pin ‐ LED connection #define IR_sensor_pin 5 //analog 5 //analog pin pin ‐ IR sensor int IR_sensor_value; //declare IR_sensor_value; //declare variable variable for for IR IR sensor sensor value value void setup() { pinMode(LED_PIN, OUTPUT); OUTPUT); //configure //configure pin pin 0 for for digital digital output output } void loop() { //read analog //read analog output from from IR sensor IR_sensor_value = analogRead(IR_sensor_pin); if(IR_sensor_value > 512) 512) //0 //0 to 1023 maps to 0 to 5 VDC { digitalWrite(LED_PIN, HIGH); HIGH); //turn //turn LED on } else { digitalWrite(LED_PIN, LOW); LOW); //turn //turn LED off } } //************************************************************************
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 of required required variables are the two required functions for an Arduino Duemilanove program: 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 if the the reading is above 512 (2.5 VDC). If the 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 “Sketch – – Verify/Compile” Verify/Compile” and the “File “File – – Upload to I/O Board” pull down menu selections.
SUMMARY The goal of of this 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 of the the chapter followed by an overview of the of the major pieces of of a a program. ‐
We then discussed the basics of of the the C programming language. Only the most fundamental concepts were covered. We then discussed the Arduino Development Environment and how it may be used to develop a program for the Arduino Duemilanove processor.
P-3 Pemrograman Ratna Rat na Ais Aisuwa uwarya rya,, M.Eng M.Eng
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 Describe the key features features of the Arduin Arduino o Developme Development nt Environment. Describe what features features of the Arduino Development Environment Environment ease the the program program devel-opm devel-opment ent process. process. List the programming support information available at the Arduin Arduino o home home page. page. Write program programss for use on the the Arduino Arduino Duemilano Duemilanove ve processin processing g board.
pada pada umum umumny nya a mikr mikrok okon ontr trol oler er dipr diprog ogra ram m meng menggu guna naka kan n bebe bebera rapa pa vari varias asii baha bahasa sa C. Baha Bahasa sa C memb member erik ikan an kemud kemudah ahan an bagi bagi progr program amme merr untuk untuk meng mengont ontro roll hard hardwa ware re mikro mikroko kontr ntrol oler er sekal sekalig igus us efis efisie iens nsii wakt waktu u dala dalam m penuli penulisan san progra program. m. Pada gambar gambar 2.1 terliha terlihatt softwar software e comp compile ilerr terl terleta etak k pada ada komp komput uter er seba sebaga gaii host host..
Tugas ugas compil compiler er mengub mengubah ah progra program m (filen (filename ame.c .c dan filena filename. me.h) h) menjad menjadii code code mesin mesin (fil (filen enam ame. e.he hex) x) yang yang akan dilo diload adin ing g ke proc proces essor sor..
Ada Ada dua dua taha tahap p yang yang dila dilaku kuka kan n comp compil iler er unt untuk uk mere merend nder er kode kode mesi mesin. n. Tahap ahap pert pertam ama a dise disebu butt deng dengan an pros proses es komp kompil ilas asii (fil (file e progra program m sourc source e diub diubah ah menja menjadi di kode kode asse assemb mbly ly (filen (filenam ame. e.as asm) m)
Jika Jika file file program program sourc source e memilik memilikii err error or,, compile compilerr akan member memberita itahu hu user. user. Progr rogram am asse assemb mbly ly tida tidak k akan akan dige digene nera rate ted d samp sampai ai tida tidak k ada ada erro errorr lagi lagi..
File program program assembly assembly (filename.a (filename.asm) sm) kemudian kemudian dilanjutkan dilanjutkan ke assembler assembler.. Assembler Assembler mengubah mengubah file bahasa bahasa program program assembly assembly menjadi kode kode mesi mesin n (fil (filen enam ame. e.as asm) m) yang yang akan akan dilo diload ad ke ardu arduin ino o
Arduino Arduino Development Development Environment Environment menyediakan menyediakan user friendly friendly interface interface yang membantu membantu dalam pemrograman. pemrograman. (program (program development, development, transformation to machine code, and loading into the Arduino
Programs written for a microcontroller have a fairly repeatable format. Slight variations exist but many follow the format provided.
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.
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
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 #include
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 o ver 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.
There are three different pieces of code required to properly configure and call the function:
the function prototype, the function call, and the functi function on body b ody..
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:
r et ur n_ v a r i a b l e function_name(required_variable1, required_variable2);
If the function does not require variables or sends back a variable the word “void” is placed in the variable’s position. position. Thefuncti Thefunction on callis the code statement statement used within within a program 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:
A function function that requires no variables follows this format:
function_name(required_variable1, function_name(required_var iable1, required_variable2); required_variable2); f u nc n c t i o n _ n a m e( e( ) ;
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.
The function body is a self-contained “mini-program.” The first line of the function body contains the same information as the function prototype: the name of the function, any variables required by the function, and any variable returned by the function. The last line of the the func functi tion on cont conta ains ins a “retu return rn” ” sta statem temen ent. t.
Here a variable may be sent back to the portion of the program that called the function. 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, they are declared next. These variable are referred to as local variables les. The actions required by the function follow.
The fun unct ctio ion n pro prototy totype pe follo llows this this form format at:: return_vari retur n_variable able funct function_na ion_name(re me(requir quired_va ed_variabl riable1, e1, requ required_ ired_varia variable2) ble2) { //lloc // ocal al va varria iabl bles es req equi uire red d by th the e fu func ncti tion on unsi un sign gned ed in intt va vari riab able le1; 1; unsig un signe ned d ch char ar va vari riab able le2; 2; //p // pro rogr gram am st sta ate tem men ents ts re req qui uire red d by th the e fun unct ctio ion n //retu //r eturn rn var variab iable le return ret urn ret return urn_va _varia riable ble;; }
Example: Example:In In figure figure 2.3 examp example, le, we descri describe be 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] 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.
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
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 variable sizes used with with the ImageCraft ImageCraft ICC AVR compiler. The size of other variables such as pointers, shorts, longs, etc. are contained in the compiler documentation [ImageCraft].
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, 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 yo ur 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 variables unsi un sign gned ed int int lo loop op_i _ite tera rati tion onss = 6;
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.
In the previous section, we covered many fundamental concepts. In this section we discuss operators, programming constructs, and decision processing constructs to complete our fundamental overview of programming concepts.
OPERATORS
There are a wide variety of operators provided in the C language. An abbreviated list of common operators are provided in Figures2.5and 2.6. The operators have been grouped by general category.
The arithmetic operations provide for basic math operations using the various variables described 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 side variable. Example: In this example, a function returns the sum of two unsigned int variables passed to the function. unsigned int sum_two(unsigned int variable1, unsigned intt va in vari riab able le2) 2) { unsigned int sum; sum = variable1 + variable2; retu re turn rn su sum; m;
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.
There are two general types of operations in the bit manipulation category: shif shifti ting ng oper operat atio ions ns and and bitw bitwis ise e oper operat atio ions ns.. Let’ Let’ss exam examin ine e seve severa rall exam exampl ples es:: Example : Given the following code segment, what will the value of variable2 f variable2 be afte afterr exec execut utio ion? n? unsi un sign gned ed cha harr va vari riab able le1 1 = 0x 0x7 73; unsi un sign gned ed ch char ar va vari riab able le2; 2; variable2 = variable1 << 2;
Note that the left and right shift operation is equivalent to multiplying and dividing the variable 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 with the least significant bit of the second argument and so on. Example:Given the following code segment, what will the value of variable3 f variable3 be afte afterr exec executi ution? on? unsi un sig gne ned d ch char ar va vari riab able le1 1 = 0x7 x73; 3; unsi un sig gne ned d ch char ar va vari riab able le2 2 = 0xf xfa; a; unsi un sign gned ed ch char ar va vari riab able le3; 3; vari va riab able le3 3 = va vari riab able le1 1 & va vari riab able le2; 2;
The unary operators, as their name implies, require only a sing single le argu argume ment nt.. For example, in the following code segment, the value of the variable “i” is incremented. This is a shorthand method of exec ex ecut utin ing g the the oper operat atio ion n “i =i +1;” unsigned int i; i++; Example : It is not uncommon in embedded system design projects to have every pin on a microcontroller employed. Furthermore, it is not uncommon to have multiple inputs and outputs assigned to the same port but on different port input/output pins. Some compilers support specific pin reference. Another technique that is not compiler specific is bit twiddling. Figure 2.7 provides bit twiddling examples on how individual bits may be manipulated without affecting other bits using bitwise and unary operators. The information provided here was extracted from the ImageCraft ICC AVR compiler documenta documentation tion [ImageCra [ImageCraft]. ft].
In this section, we discuss several methods of looping through a piece of code. We will examine the “for” and the “while” loop loopin ing g cons constr truc ucts ts.. Thefore loop provides a mechanism for looping through the same portion of code a fixed number of times. The for loop consists of three main parts:
loop loo p ini initia tiatio tion, n,
loop lo op te term rmin inat atio ion n te test stin ing, g, an and d
the th e lo loop op in incr crem emen ent. t.
In the following code fragment the for loop is executed ten times. unsi un sign gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 0; loop_ctr < 10; loop_ctr++) { //lo // loop op bo body dy }
The for loop begins with the variable “loop_ctr” equal to 0. During the first pass through the loop, the variable retains this value. During the next pass thro hrough the loop, op, the the varia riable “loop_ctr” is incremented by one. This action cont ontinues unti ntil the “loop_ctr” variable reaches the value of ten. Since the argument to continue the loop is no longer true, program execution continues after the close bracket for the for loop.
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. unsign unsi gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 0; loop_ctr < 10; loop_ctr=loop_ctr+3) { //lo // loop op bo body dy } The “loop_ctr” variable may also be initialized at a high value and then decr de crem emen ente ted d at th the e beginning of each pass of the loop. unsi un sign gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 10; loop_ctr > 0; loop_ctr--) { //lo // loop op bo body dy }
As before, the “loop_ctr” variable may be decreased by any numerical value as appropriate for the application at hand. The while loop is anot nother prog rogramming constr struct that allows multiple passes through a portion of code. The while loop will continue to execute the statements within the open and close brackets while the condition at the beginning of the loop remains logically true. The code snapshot below will implement a ten iteration loop. Note how the “loop_ctr” variable is initialized outside of the loop and incremented within the body of the loop. As before, the variable may be initialized to a greater value and then decr decrem emen ente ted d with within in the the loop loop body ody. unsi un sign gned ed in intt lo loop op_c _ctr tr;; loop_ctr = 0; whil wh ile( e(lo loop op_c _ctr tr < 10 10)) { //lo // loop op bo body dy loop_ctr++; }
Frequently, within a microcontroller application, the program begins with syst system em init initia iali liz zatio ation n acti action ons. s. Once Once initi nitia aliza lizati tion on acti activi viti ties es are are com complet plete, e,th the e processor enters a continuous loop. This may be accomplished using the foll follow owin ing g code code frag fragme ment nt.. while(1) { }
There are a variety of constructs that allow decision making. These incl includ ude e the the foll follow owin ing: g: The if state tatem ment, nt, Th The e if–e if–els lse e cons constr truc uct, t, The if–else if–el –else construct, and the Switch Switch statem statement ent.. The if statement will execute the code between an open and close bracket set should the condition within the if statement be logically true. Example: To help develop the algorithm for steering the Blinky 602A robot through a maze, a light emitting diode (LED) is connected to PORTB pin 1 on the ATmega328. The robot’s center IR sensor is connected to an analog-to-digital converter at PORTC, pin 1. The IR sensor provides a voltage output that is inversely proportional to distance of the sensor 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 followingifstatement construct will implement this LED indicator. We provide the actual code to do this later in the chapter.
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. on. This will require theelseportion 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 POR TB = 0x02; //illuminate LED on PORTB[1] } else { PORTB POR TB = 0x00; //extinguish the LED on PORTB[1] } Theif–else if—elseconstruct if—elseconstruct may be used to to implement 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 fragment implements implements this LED LED system.
Thes Theswi witc tchs hsta tate teme ment nt is used used when when mult multip iple le ifif-else else cond condit itio ions ns exis exist. t. Each Each poss possib ible le cond condit itio ion n is spec specif ifie ied d by a case statement. When a match is found between the switch variable and a specific case entry, the the stat statem emen ents ts asso associ ciat ated ed with with the the case case are are exec execut uted ed unti untill abre abreak akst stat atem emen entt is enco encoun unte tere red. d. Exa Example mple:S :Su uppos pose eight ight push ushbutto utton n switc witch hes are are con connect nected ed to POR PORTD. Each Each swit switch ch will ill impl imple ement ment a diff differ ere ent actio ction n. A swit switch ch stat state ement ent may be used used to proc proce ess the the multip ltiple le poss possib ible le decisi cision onss as show shown n in the the foll follow owin ing g code code frag fragme ment nt.. void re ad_new_inp ad_n ew_inp ut(voi d) { new _POR _PORT T D = PIND; PIND;
//chec eck k for for stat status us chan change ge POR PORTD i f (new _PO _POR RT D != ol d_ POR ORT T D) //ch
switch(new_PORTD) //proc oces esss chan change ge in POR PORTD inpu inputt { //pr case 0x 01: / / PD0
//PD //PD0 0 rela relate ted d acti action onss break; case 0x 02: //PD1
//PD //PD1 1 rela relate ted d acti action onss break; case 0x 04: //PD2
//PD //PD2 2 rela relate ted d acti action onss break; case 0x 08: //PD3
//PD //PD3 3 rela relate ted d acti action onss break; case 0x 10: //PD4
//PD //PD4 4 rela relate ted d acti action onss
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) 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 overview of the Arduino Arduino development development Environm Environment. ent.
In this section, section, we provide provide an overview of the Arduino Arduino Development Development Environment (ADE). We begin with some background information about the ADE and then review its user friendly fr iendly features. We then introduce the sketchbook concept and provide a brief overview of the built-in software features within the ADE. Our goal is to provide a brief rief intro ntrodu duct ctiion to the the feat featur ures es.. All Arduino related features are well documented on the Arduino homepage homepage (www.ardu (www.arduino.cc ino.cc). ). The first vers versiion of the Arduino Devel velopmentE ntEnvir vironmen nmentt was was rel released in August 2005. It was developed at the Interaction Design Institute in Ivrea, Italy to allow students the ability to quickly put processing power to use in a wide variety of projects. Since that time, newer versions incorporating new features, have been released on a regular basis [www.arduino.cc]. At its most ost funda ndament ental leve evel, the the Arduino Devel velopment Envi Enviro ron nment is a user friendly interface to allow one to quickly write, load, and execute code on a microcontroller. A barebones program need only consist of a setup setup() () and and loop loop() ()fu func ncti tion. on. The Arduino Development Environment adds the other required pieces such as header files and the main program construct. The ADE is written in Java and has its origins in the Processor programming language and the Wirin Wiring g Project roject [www [www.ardui .arduino. no.cc] cc]..
The Ardui Arduino no Develo Developme pment nt Environment is illustrated in right Figure. The ADE 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 Arduino Duemilano Duemilanove ve which allows allows for a quick upload of code. This is possible because the Arduino Duemilano Duemilanove ve is equip equipped ped with a bootlo bootloade aderr progra program. m.
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 Arduino Duemilanove. The “Serial Monitor” button opens the serial monitor feature. The serial monitor feature allows text data to be sent to and received from from the Arduin Arduino o Duemil Duemilano anove. ve. The serial monitor feature is halted with the “Stop” button.
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 maintains their works in progress in a sketchbook. Similarly, 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 Environment has a number of built in features. Some of the features may may be directly accessed accessed via the Arduino Development Environment drop down toolbar. 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 Application section later in the chapter. 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]. [www.arduino.cc]. This documentation is easily accessible via the Help tab on the Arduino Development Environment toolbar. toolbar. This documentation 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 world are constantly adding new built-in features. As new features are added, they will be released released in future Arduino Arduino developmen developmentt Environment Environment versions. As As an Arduino user, user, you too may add to this collection of useful tools. In the next section, we illustrate how to use use the the Arduin Arduino o Duemil Duemilano anova va board board in in everal everal applic applicati ations ons..
To demonstrate demonstrate how to construct a sketch in the Arduino Arduino Developm Development ent Environ Environmen ment, t, we revisi revisitt the robot IR sensor application provided earlier in the the chapter chapt er.. We also investigat investigate e the sketches’s sketches’s interactio interaction n with the Arduino Arduino Duemilan Duemilanove ove 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 from Chapter Chapter 1, the Blinky 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.
Dasa Da sarr Pem emro rogr gram aman an Mi Mikr kroko okont ntro role lerr Ratna Rat na Ais Aisuwa uwarya rya,, M.Eng M.Eng
pada pada umum umumny nya a mikr mikroko okont ntrol roler er dipr diprog ogra ram m meng menggu guna naka kan n bebe bebera rapa pa vari varias asii baha bahasa sa C. Baha Bahasa sa C memb member erik ikan an kemu kemuda daha han n bagi bagi prog progra ramm mmer er untuk untuk mengontrol mengontrol hardware hardware mikrokontroler mikrokontroler seka sekali ligu guss efis efisie iens nsii wakt waktu u dala dalam m penuli penulisan san progra program. m. Pada gambar gambar terlihat terlihat software software compile compilerr terletak terletak pada ada komp komput uter er seba sebaga gaii host host..
Tugas ugas compil compiler er mengub mengubah ah progra program m (filen (filename ame.c .c dan filena filename. me.h) h) menjad menjadii code code mesin mesin (filen (filename ame.he .hex) x) yang yang akan dilo diload adin ing g ke proc proces esso sorr. Ada Ada dua dua taha tahap p yang yang dil dilak akuk ukan an comp compil iler er unt untuk uk mere merend nder er kode mesi mesin n. Taha ahap pert pertam ama a dise isebut but den enga gan n pros proses es komp kompil ilas asii (fil (file e prog progra ram m sour source ce diu diuba bah h menj menjad adii kode kode assembly (filename.asm) Jika file program program sourc source e memilik memilikii error, error, compile compilerr akan akan memberita memberitahu hu user. user. Progra Program m assemb assembly ly tidak tidak akan digen igener era ated ted samp sampai ai tida tidak k ada er erro rorr la lagi. gi. File program assembly (filename.asm) kemudian dilanj dilanjutk utkan an ke assemb assembler ler.. Assem Assemble blerr menguba mengubah h file file bahasa bahasa prog progra ram m assem assembl bly y menjad menjadii kode kode mesi mesin n (fil (filen enam ame. e.as asm) m) yang ak akan diload ke arduino Arduin Arduino o Develo Developme pment nt Environ Environmen mentt menyedia menyediakan kan user user friend friendly ly interfa interface ce yang yang membantu membantu dalam dalam pemrog pemrogram raman. an. (program development, transformation to machine code, and loading into the Arduino
Progr rogram am yang yang dit ditul ulis is pada pada mikr mikrok okon ontr trol oler er memi memili liki ki form format at umum umum,, deng dengan an bebe bebera rapa pa variasi yan yang di dibuat sesuai dengan kebutuhan.
1.
Comments
2.
Include Files
3.
Functions
4.
Program Constants
5.
Variables
6.
Main Program
Komen mentar tar digu digun naka akan dala alam progr rogra am un untuk tuk mendok ndokum ume entas ntasik ika an apa apa dan dan baga bagaim ima ana sebu sebuah ah pros proses es dala dalam m prog progra ram m yang yang ditu dituli lis. s. Komen omenta tarr memb memban antu tu prog progra ramm mmer er dala dalam m mere merevi visi si prog progra ram m di kemu kemudi dian an hari hari.. Komen omenta tarr memb memban antu tu prog progra ramm mmer er dala dalam m meng ngin inga gatt deta detail il pent pentin ing g dalam lam sebu sebua ah program. Komentar tidak dikompilasi menjadi kode mesin yang akan diload ke mikrokontroler. Seh ehin ingg gga a, kom kome entar ntar tid tidak akan memen menihu ihu memory mikrokontroler.
komentar dibuat dengan tanda (//) (//).. Sem Semua ua yang yang ditu dituli liss setel etela ah tand tanda a (//) dia diang ngga gap p seba sebaga gaii sebua ebuah h komentar. Komen omenta tarr multi ulti-b -bar aris is dapa dapatt dibu dibuat at deng dengan an meng menggu guna naka kan n tand tanda a / di awa awall dan dan di akh akhiir kome koment ntar ar.. Diaw Diawal al prog progra ram, m, kom komen enta tarr dap dapat dibu dibuat at sepe sepert rtii para paragr graf af.. Komen omenta tarr diaw diawal al prog progra ram m dapa dapatt beri berisi si informasi sebagai berikut : ∗
Nama file Penu enulis lis Prog rogram ram Riwayat revi vissi atau hal-hal penting yang diu diub bah pada program. revision history or a listing of the key changes made to the program Inform Inf ormasi asi set settin ting g compile compilerr Desk De skri rips psii ko kone neks ksii ha hard rdwa ware re ke ke pi pin n mikr mikrok okon ontr trol oler er Desk De skri rips psii pr prog ogra ram m
Sela Selain in prog progra ram m utam utama, a, seri sering ngka kali li kita kita memb membut utuh uhka kan n file file ektr ek tra a ke dala dalam m proj projec ect. t. Cont Contoh oh,, keban kebanya yaka kan n comp compil iler er membut membutuhk uhkan an “file “file khusus khusus” ” pada pada mikrok mikrokont ontrol roler er terten tertentu. tu. File File ini menyed menyediak iakan an settin setting g regist register er yang yang diguna digunaka kan n pada pada compil compiler er untuk untuk berhub berhubung ungan an dengan dengan mikrok mikrokont ontrol roler er.. Includ Include e file file juga juga menyed menyediak iakan an link link anta antara ra regist register er terten tertentu tu pada pada soft softwa ware re dan dan loka lokasi si re regi gist ster er yan yang g sebe sebena narn rnya ya pada pada hard hardwa ware re.. File File ini ini dise disebu butt deng dengan an he head ader er file file yang yang bias iasanya anya bera berak khira hiran n “.h”. Head Header er file file lain lainny nya a pada pada comp compil iler er C sep seper erti ti “math.h”. File ini ini digun iguna akan un untu tuk k fun fungsi gsi mate atemati matik ka. Untuk Untuk meng-i meng-incl nclude ude head header er files files dala dalam m progra program, m, digunakan sintaks beriku ikut :
//include files #include #include
Progr rogram am utama utama akan akan mema memang ngil il func functi tion on yang yang memi memili liki ki aksi aksi yang yang telah telah didefinisikan.
Ketika etika functio function n dipa dipangg nggil, il, kontrol kontrol progra program m berpin berpindah dah dari dari progra program m utama utama ke func functi tion on..
Setela Setelah h functio function n selesa selesaii diprose diproses, s, control control progra program m kembal kembalii ke progra program m utama.
Functi Function on dapat dapat memang memanggil gil functio function n lainny lainnya. a. Sehingg Sehingga a functio function n dapat dapat dipa dipangg nggil il kapa kapan n saja saja di dala dalam m list listin ing g prog progra ram. m.
There are three different pieces of code required to properly configure and call the function:
the function prototype, the function call, and the functi function on body b ody..
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:
r et ur n_ v a r i a b l e function_name(required_variable1, required_variable2);
If the function does not require variables or sends back a variable the word “void” is placed in the variable’s position. position. Thefuncti Thefunction on callis the code statement statement used within within a program 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:
A function function that requires no variables follows this format:
function_name(required_variable1, function_name(required_var iable1, required_variable2); required_variable2); f u nc n c t i o n _ n a m e( e( ) ;
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.
The function body is a self-contained “mini-program.” The first line of the function body contains the same information as the function prototype: the name of the function, any variables required by the function, and any variable returned by the function. The last line of the the func functi tion on cont conta ains ins a “retu return rn” ” sta statem temen ent. t.
Here a variable may be sent back to the portion of the program that called the function. 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, they are declared next. These variable are referred to as local variables les. The actions required by the function follow.
The fun unct ctio ion n pro prototy totype pe follo llows this this form format at:: return_vari retur n_variable able funct function_na ion_name(re me(requir quired_va ed_variabl riable1, e1, requ required_ ired_varia variable2) ble2) { //lloc // ocal al va varria iabl bles es req equi uire red d by th the e fu func ncti tion on unsi un sign gned ed in intt va vari riab able le1; 1; unsig un signe ned d ch char ar va vari riab able le2; 2; //p // pro rogr gram am st sta ate tem men ents ts re req qui uire red d by th the e fun unct ctio ion n //retu //r eturn rn var variab iable le return ret urn ret return urn_va _varia riable ble;; }
Example: Example:In In figure figure 2.3 examp example, le, we descri describe be 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] 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.
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
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 variable sizes used with with the ImageCraft ImageCraft ICC AVR compiler. The size of other variables such as pointers, shorts, longs, etc. are contained in the compiler documentation [ImageCraft].
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, 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 yo ur 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 variables unsi un sign gned ed int int lo loop op_i _ite tera rati tion onss = 6;
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.
In the previous section, we covered many fundamental concepts. In this section we discuss operators, programming constructs, and decision processing constructs to complete our fundamental overview of programming concepts.
OPERATORS
There are a wide variety of operators provided in the C language. An abbreviated list of common operators are provided in Figures2.5and 2.6. The operators have been grouped by general category.
The arithmetic operations provide for basic math operations using the various variables described 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 side variable. Example: In this example, a function returns the sum of two unsigned int variables passed to the function. unsigned int sum_two(unsigned int variable1, unsigned intt va in vari riab able le2) 2) { unsigned int sum; sum = variable1 + variable2; retu re turn rn su sum; m;
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.
There are two general types of operations in the bit manipulation category: shif shifti ting ng oper operat atio ions ns and and bitw bitwis ise e oper operat atio ions ns.. Let’ Let’ss exam examin ine e seve severa rall exam exampl ples es:: Example : Given the following code segment, what will the value of variable2 f variable2 be afte afterr exec execut utio ion? n? unsi un sign gned ed cha harr va vari riab able le1 1 = 0x 0x7 73; unsi un sign gned ed ch char ar va vari riab able le2; 2; variable2 = variable1 << 2;
Note that the left and right shift operation is equivalent to multiplying and dividing the variable 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 with the least significant bit of the second argument and so on. Example:Given the following code segment, what will the value of variable3 f variable3 be afte afterr exec executi ution? on? unsi un sig gne ned d ch char ar va vari riab able le1 1 = 0x7 x73; 3; unsi un sig gne ned d ch char ar va vari riab able le2 2 = 0xf xfa; a; unsi un sign gned ed ch char ar va vari riab able le3; 3; vari va riab able le3 3 = va vari riab able le1 1 & va vari riab able le2; 2;
The unary operators, as their name implies, require only a sing single le argu argume ment nt.. For example, in the following code segment, the value of the variable “i” is incremented. This is a shorthand method of exec ex ecut utin ing g the the oper operat atio ion n “i =i +1;” unsigned int i; i++; Example : It is not uncommon in embedded system design projects to have every pin on a microcontroller employed. Furthermore, it is not uncommon to have multiple inputs and outputs assigned to the same port but on different port input/output pins. Some compilers support specific pin reference. Another technique that is not compiler specific is bit twiddling. Figure 2.7 provides bit twiddling examples on how individual bits may be manipulated without affecting other bits using bitwise and unary operators. The information provided here was extracted from the ImageCraft ICC AVR compiler documenta documentation tion [ImageCra [ImageCraft]. ft].
In this section, we discuss several methods of looping through a piece of code. We will examine the “for” and the “while” loop loopin ing g cons constr truc ucts ts.. Thefore loop provides a mechanism for looping through the same portion of code a fixed number of times. The for loop consists of three main parts:
loop loo p ini initia tiatio tion, n,
loop lo op te term rmin inat atio ion n te test stin ing, g, an and d
the th e lo loop op in incr crem emen ent. t.
In the following code fragment the for loop is executed ten times. unsi un sign gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 0; loop_ctr < 10; loop_ctr++) { //lo // loop op bo body dy }
The for loop begins with the variable “loop_ctr” equal to 0. During the first pass through the loop, the variable retains this value. During the next pass thro hrough the loop, op, the the varia riable “loop_ctr” is incremented by one. This action cont ontinues unti ntil the “loop_ctr” variable reaches the value of ten. Since the argument to continue the loop is no longer true, program execution continues after the close bracket for the for loop.
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. unsign unsi gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 0; loop_ctr < 10; loop_ctr=loop_ctr+3) { //lo // loop op bo body dy } The “loop_ctr” variable may also be initialized at a high value and then decr de crem emen ente ted d at th the e beginning of each pass of the loop. unsi un sign gned ed in intt lo loop op_c _ctr tr;; for(loop_ctr = 10; loop_ctr > 0; loop_ctr--) { //lo // loop op bo body dy }
As before, the “loop_ctr” variable may be decreased by any numerical value as appropriate for the application at hand. The while loop is anot nother prog rogramming constr struct that allows multiple passes through a portion of code. The while loop will continue to execute the statements within the open and close brackets while the condition at the beginning of the loop remains logically true. The code snapshot below will implement a ten iteration loop. Note how the “loop_ctr” variable is initialized outside of the loop and incremented within the body of the loop. As before, the variable may be initialized to a greater value and then decr decrem emen ente ted d with within in the the loop loop body ody. unsi un sign gned ed in intt lo loop op_c _ctr tr;; loop_ctr = 0; whil wh ile( e(lo loop op_c _ctr tr < 10 10)) { //lo // loop op bo body dy loop_ctr++; }
Frequently, within a microcontroller application, the program begins with syst system em init initia iali liz zatio ation n acti action ons. s. Once Once initi nitia aliza lizati tion on acti activi viti ties es are are com complet plete, e,th the e processor enters a continuous loop. This may be accomplished using the foll follow owin ing g code code frag fragme ment nt.. while(1) { }
There are a variety of constructs that allow decision making. These incl includ ude e the the foll follow owin ing: g: The if state tatem ment, nt, Th The e if–e if–els lse e cons constr truc uct, t, The if–else if–el –else construct, and the Switch Switch statem statement ent.. The if statement will execute the code between an open and close bracket set should the condition within the if statement be logically true. Example: To help develop the algorithm for steering the Blinky 602A robot through a maze, a light emitting diode (LED) is connected to PORTB pin 1 on the ATmega328. The robot’s center IR sensor is connected to an analog-to-digital converter at PORTC, pin 1. The IR sensor provides a voltage output that is inversely proportional to distance of the sensor 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 followingifstatement construct will implement this LED indicator. We provide the actual code to do this later in the chapter.
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. on. This will require theelseportion 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 POR TB = 0x02; //illuminate LED on PORTB[1] } else { PORTB POR TB = 0x00; //extinguish the LED on PORTB[1] } Theif–else if—elseconstruct if—elseconstruct may be used to to implement 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 fragment implements implements this LED LED system.
Thes Theswi witc tchs hsta tate teme ment nt is used used when when mult multip iple le ifif-else else cond condit itio ions ns exis exist. t. Each Each poss possib ible le cond condit itio ion n is spec specif ifie ied d by a case statement. When a match is found between the switch variable and a specific case entry, the the stat statem emen ents ts asso associ ciat ated ed with with the the case case are are exec execut uted ed unti untill abre abreak akst stat atem emen entt is enco encoun unte tere red. d. Exa Example mple:S :Su uppos pose eight ight push ushbutto utton n switc witch hes are are con connect nected ed to POR PORTD. Each Each swit switch ch will ill impl imple ement ment a diff differ ere ent actio ction n. A swit switch ch stat state ement ent may be used used to proc proce ess the the multip ltiple le poss possib ible le decisi cision onss as show shown n in the the foll follow owin ing g code code frag fragme ment nt.. void re ad_new_inp ad_n ew_inp ut(voi d) { new _POR _PORT T D = PIND; PIND;
//chec eck k for for stat status us chan change ge POR PORTD i f (new _PO _POR RT D != ol d_ POR ORT T D) //ch
switch(new_PORTD) //proc oces esss chan change ge in POR PORTD inpu inputt { //pr case 0x 01: / / PD0
//PD //PD0 0 rela relate ted d acti action onss break; case 0x 02: //PD1
//PD //PD1 1 rela relate ted d acti action onss break; case 0x 04: //PD2
//PD //PD2 2 rela relate ted d acti action onss break; case 0x 08: //PD3
//PD //PD3 3 rela relate ted d acti action onss break; case 0x 10: //PD4
//PD //PD4 4 rela relate ted d acti action onss
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) 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 overview of the Arduino Arduino development development Environm Environment. ent.
In this section, section, we provide provide an overview of the Arduino Arduino Development Development Environment (ADE). We begin with some background information about the ADE and then review its user friendly fr iendly features. We then introduce the sketchbook concept and provide a brief overview of the built-in software features within the ADE. Our goal is to provide a brief rief intro ntrodu duct ctiion to the the feat featur ures es.. All Arduino related features are well documented on the Arduino homepage homepage (www.ardu (www.arduino.cc ino.cc). ). The first vers versiion of the Arduino Devel velopmentE ntEnvir vironmen nmentt was was rel released in August 2005. It was developed at the Interaction Design Institute in Ivrea, Italy to allow students the ability to quickly put processing power to use in a wide variety of projects. Since that time, newer versions incorporating new features, have been released on a regular basis [www.arduino.cc]. At its most ost funda ndament ental leve evel, the the Arduino Devel velopment Envi Enviro ron nment is a user friendly interface to allow one to quickly write, load, and execute code on a microcontroller. A barebones program need only consist of a setup setup() () and and loop loop() ()fu func ncti tion. on. The Arduino Development Environment adds the other required pieces such as header files and the main program construct. The ADE is written in Java and has its origins in the Processor programming language and the Wirin Wiring g Project roject [www [www.ardui .arduino. no.cc] cc]..
The Ardui Arduino no Develo Developme pment nt Environment is illustrated in right Figure. The ADE 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 Arduino Duemilano Duemilanove ve which allows allows for a quick upload of code. This is possible because the Arduino Duemilano Duemilanove ve is equip equipped ped with a bootlo bootloade aderr progra program. m.
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 Arduino Duemilanove. The “Serial Monitor” button opens the serial monitor feature. The serial monitor feature allows text data to be sent to and received from from the Arduin Arduino o Duemil Duemilano anove. ve. The serial monitor feature is halted with the “Stop” button.
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 maintains their works in progress in a sketchbook. Similarly, 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 Environment has a number of built in features. Some of the features may may be directly accessed accessed via the Arduino Development Environment drop down toolbar. 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 Application section later in the chapter. 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]. [www.arduino.cc]. This documentation is easily accessible via the Help tab on the Arduino Development Environment toolbar. toolbar. This documentation 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 world are constantly adding new built-in features. As new features are added, they will be released released in future Arduino Arduino developmen developmentt Environment Environment versions. As As an Arduino user, user, you too may add to this collection of useful tools. In the next section, we illustrate how to use use the the Arduin Arduino o Duemil Duemilano anova va board board in in everal everal applic applicati ations ons..
Blinking LED Wave
Hidup idupk kan LED 1
Tun ungg ggu u 500 500 ms ms
Matikan LED 1
Hidup idupk kan LED 2
Tun ungg ggu u 500 500 ms ms
Matikan LED 2
Lanjutkan sampai LED 5
Proses be berbalik dari LED 5 ke 1
Ulangi sampai tak hingga
Ratna Aisuwarya, M.Eng.
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 of values 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 of continuous continuous information, such as sounds, images, and other measurements of of continuous continuous systems.
2
Analog Signals • What is an analog signal and how does it differ from a digital signal?
0
1
1
0
1
1
1
0
Analog to Digital Coversion • What is analog ? of voltage values (not • It is continuous range of voltage just 0 or 5V) Why convert to digital ? • Why
• Because our microcontroller only understands digital.
Converting Analog Value to Digital
ADC • 3 proses penting yang berhubungan dengan ADC : – Sampling, process of taking of taking ‘snapshots’ of a of a signal over time. – Quantization, When a signal is sampled, digital systems need some means to represent the captured samples. The quantization of a sampled signal is how the signal is represented as one of the quantization levels. given n bits, we have 2n uniq unique ue numb number erss or levels one can represent. – Encoding, the encoding process involves converting a quan quanti tizzed signa ignall int into a digit igital al bin binary ary num number ber. the the encoding process involves representingthe quantization level with the available bits Ratna Aisuwarya, M.Eng.
6
Quantanization the signal
ADC – ADC – Sampling, Quantization, Encoding
Ratna Aisuwarya, M.Eng.
8
ADC Devices • Analog‐to‐digi digittal convert erters ers meru erupakan akan pera erangk ngkat akuisisi data. data. • Komputer menggunakan nilai binary (diskrit), sedangkan dalam implementasi nyata data yg didapat berupa analog (kontinu). • Contohnya : temperatur, tekanan (angin gin, cairan), humidity, dll. • Besar Besaran fisik fisik yang yang dipero diperoleh leh dari sensor sensor dikon dikonver versik sikan an kedalam bentuk tegangan listrik. • Sehingga, gga, diperlukan ADC untuk menterjemahkan sinyal analog ke angka digital sehingga gga MC dapat membaca dan memproses data tsb. Ratna Aisuwarya, M.Eng.
9
Ratna Aisuwarya, M.Eng.
10
Karakteristik ADC • Resolution – ADC memiliki n‐bit resolusi, n= 8, 12, 16 atau 24 – Resolusi chip ADC telah ditentukan berdasarkan desain pabrikan. Cth: ATMega8535 memiliki 8 bit, ATMega 328 memiliki 10 bit.
Ratna Aisuwarya, M.Eng.
11
VRef Merup upak akan an tegan egang gan inp input yang ang digu igunak nakan • Mer sebagai tegangan referensi. Tegangan ini dapat digunakan untuk mengatur steps pada ADC.
• Cth: untuk ADC 8‐bit, jumlah steps = 28=256, maka untuk Vref= 4V, dapat ditentukan jumlah steps = 4V/256=15,62mV
Ratna Aisuwarya, M.Eng.
12
VRef
Ratna Aisuwarya, M.Eng.
13
VRef
Ratna Aisuwarya, M.Eng.
14
Digital Data Output gital (D0‐D7), • Pada ADC 8‐bit output data digit sed sedangk angkan an ADC 10‐bit memiliki output (D0‐ D9).
• Untuk menghitung Data output : • Dout : Digital data output (Desimal) • Vin : analog input voltage • Step size : smallest change
Ratna Aisuwarya, M.Eng.
15
Contoh • Untuk ADC 8‐bit, Vref = 2,56V. Hitunglah output D0‐D7 jika analog input : – 1,7 V – 2,1 V
Ratna Aisuwarya, M.Eng.
16
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?
Reading/writing digital values • 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 of pin 2 in buttonState
ADC in Arduino • 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
living with the lab
Analog and Digital Measurements 14 digital input / output pins
6 analog input pins © 2011 LWTL faculty team
Reading/Writing Analog Values • analogRead(A0); // used to read the analog value from the pin A0 • analogWrite(2,128);
living with the lab
Inputs and Outputs An input “receives” information or senses a voltage in the external world. An output “delivers” information or makes something happen in the external world. 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?
digital output
void setup setup() () { pinMode(0, pinMode (0, OUTPUT OUTPUT); ); } void loop loop() () { digitalWrite(0, digitalWrite (0, HIGH HIGH); ); delay(1000); delay (1000); digitalWrite(0, digitalWrite (0, LOW LOW); ); delay(500); delay (500); }
22
living with the lab
Receiving Input from an Arduino digital input
analog input
int val ;
int val ;
val
val
= digitalRead ( 7) ;
= analogRead ( 5) ;
val is either 0 or 1
val is an integer between 0 and 1023
•
0 = voltage sensed at digital pin 7 is LOW (0V)
•
•
1 = voltage senses at digital pin 7 is HIGH (5V)
1023 = voltage senses at analog pin 5 is five volts • 1023 =
0 = voltage sensed at analog pin 5 is zero volts
Guess what val would be if if the the voltage sensed at analog pin 5 was 2.5V? 511 23
living with the lab
Digital Inputs The Arduino reference indicates that digitalRead () will return . . . () • a value of HIGH if if the the voltage at the digital input pin is greater than 3 volts if the the voltage at the digital input pin is less than 2 volts. • a value of LOW if 5 ) V ( e g a t l o v
4
( ) returns HIGH or 1 digitalRead
high 3
ambiguous
( ) may return a value of digitalRead of HIGH HIGH or LOW
2
low
1
( ) returns LOW or 0 digitalRead
0 0
1
2
3
4
5
6
7
8
9
time (milliseconds)
LOW or HIGH???
24
living with the lab
Analog Inputs The analog input pins on your Arduino have 10‐bit resolution and consequently measure in (2)10 or 1024 increments. 2 1024 The analogRead () functions returns a value between 0 and 1023, where 0 is zero () volts and 1023 is 5 volts.
analogRead ·
5 1023 smallest increment of of voltage voltage that can be read = 0.00488 volts
25
living with the lab
Examples point 1
point 2
point 3
5 ) V ( e g a t l o v
4
( ) returns HIGH or 1 digitalRead
3
( ) may return a value of of HIGH HIGH or LOW digitalRead 2
( ) returns LOW or 0 digitalRead
1 0 0
1
2
3
4
5
6
7
8
9
time (milliseconds) If a If a digital pin is used data point from plot
output of
above
digitalRead()
1 2 3
if an analog pin is used
to sample voltage
to sample voltage
hypothetical analogRead()
output
0
217
ambiguous
526
1
964
voltage computed from analogRead() output
5 1.061 1023 5 526 · 2.571 1023 5 964 · 4.712 1023 217 ·
26
Program Time! • We’re going to write a program that will turn on the Arduino’s LED when “threshold” value is reached. How: • 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!
Analog Input
Potentiometer
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?
Analog Signal Detector • Step 3 – The Loop: void loop() { inputValue = analogRead(inputPin);
if(inputValue > 511) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } }
// Read the analog //input, what are // the possible values. // Check our threshold. // Turn on the LED.
// Turn off the off the LED.
Your turn • Challenges: Complete in order 1. 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 of LEDs that is proportional to the analog input value.
Ratna Aisuwarya, M.Eng.
Sensor Interfacing and Signal Conditioning •
•
Bagian ini akan menjelaskan bagaimana interfacing sensor dengan mikrokontroler. Sensor Suhu
Trandu anduse serr meng mengk konv onversi ersik kan dat data fisi fisik k sepe sepert rtii suhu suhu,, intensitas cahaya,, dll menjadi sinyal listrik. Outputnya dapat berupa tegangan, arus, resistansi, atau kapasitansi. Cth: suhu dikonversikan menjadi sinyal listrik menggunakan sebuah tranduser yang dinamakan termistor Termi ermisstor tor ber bereak eaksi terh terhad adap ap peru peruba baha han n suhu suhu deng dengan an mengubah nilai resistansi. Tetapi tidak linear. Ratna Aisuwarya, M.Eng.
2
•
Karena kompleksitas
yang ditimbulkan saat menulis software pada komponen yang tidak linear tersebut mendo‐ rong pabrikan untuk membuat sensor suhu yang bersifat linear. Salah satunya adalah sensor suhu buatan National Semiconductor Corp. yaitu LM34 dan LM35.
Ratna Aisuwarya, M.Eng.
3
Sensor Suhu LM34 dan LM35 •
Sensor suhu LM34 adalah IC sensor suhu deng dengan an tegan egang gan outp output ut yang ang line linear ar deng dengan an suhu dalam Fahrenheit. Setiap kenaikan satu deraj eraja at dit ditanda andaii den dengan kenai enaik kan tegan egang gan output sebesar 10 mV.
Ratna Aisuwarya, M.Eng.
4
Sensor Suhu LM35 •
Sensor suhu LM35 adalah IC sensor suhu deng dengan an tegan egang gan outp output ut yang ang line linear ar deng dengan an suhu dalam Celcius. Setiap kenaikan satu deraj eraja at dit ditanda andaii den dengan kenai enaik kan tegan egang gan output sebesar 10 mV.
Ratna Aisuwarya, M.Eng.
5
Signal Conditioning •
•
Pengkondisian Pengkondisian sinyal sinyal secara luas digunakan dalam akuisisi data. Sinyal output yang dihasilkan oleh tranduser (berupa tegangan, arus, kapasitansi, resistansi, dll) harus dikonversikan menjadi tegangan, yang nantinya akan digunakan sebagai input ADC. Cth: perubahan resistansi resistansi pada thermistor akan dikonversikan menjadi tegangan.
Ratna Aisuwarya, M.Eng.
6
Interfacing LM34 pada AVR •
•
•
•
Sebuah ADC dengan resolusi 10 ‐bit mempun mempuny yai steps maximum 1024. LM34/Lm35 menghasilkan 10mV setiap perubahan satu derajat suhu. jika tegangan internal digunakan sebagai tegangan 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,5 mV = 4) Ratna Aisuwarya, M.Eng.
7
Ratna Aisuwarya, M.Eng.
8
Konfigurasi Pin AVR dengan sensor LM34/35
Ratna Aisuwarya, M.Eng.
9
Contoh Pada ada tabe abel 13.11, 11, coba tentukan nilai output untuk suhu 70 derajat. Tentukan nilai register ADC pada ADCH dan ADCL untuk opsi left‐ justified. justified.
Ratna Aisuwarya, M.Eng.
10
•
•
•
•
•
•
•
Step size : 2,56/1024 = 2,,5 mV (Vref = 2,56) Untuk suhu 70 derajat, outputnya = 700 mV. mV. Karena setiap kenaikan 1 derajat = 10 mV. mV. Jumlah steps = 700 mV//2,5 mV = 280 (desimal) 280 = 0100011000 ADCH = 01000110 dan ADCL = 00000000 untuk opsi left‐ justified. Untuk mendapatkan mendapatkan nilai nilai yang yang sesuai, maka hasil tsb dibagi 4. (280/4=70). Langkah sederhananya sederhananya adalah adalah dengan dengan membaca membaca register ADCH, yang berisi nilai 70 (01000110) Ratna Aisuwarya, M.Eng.
11
DAC DAC Interfacing •
Digital‐to‐analog converter (DAC) Digu igunaka akan untu untuk k meng mengk konversik sikan pulsa ulsa digi igital menjadi sinyal analog. DAC memiliki beberapa jenis resolusi (8, 10, dan 12 bit). 8 bit input DAC spt DAC0808 DAC0808 memiliki memiliki 256 level level tegang tegangan an output. output.
Ratna Aisuwarya, M.Eng.
12
DAC DAC 0808 •
•
Pada DAC ini input digital akan dikonversikan menjadi arus (Iout), dengan menghubungkan sebuah resistor pada pin Iout, hasilnya akan dikonversi menjadi tegangan. Jumlah arus total dalam bentuk biner (input D0‐D7) sbb :
Ratna Aisuwarya, M.Eng.
13
Converting Iout to Voltage in DAC0808
Ratna Aisuwarya, M.Eng.
14
Contoh •
Diasumsikan R = 5 Kohms dan Iref = 2 mA. Hitunglah Vout untuk binar y input :
a) 10011001 (9 (99H) b) 11001000 (C8H) a). a). Iout Iout = 2mA(15 2mA(153/2 3/256) 56)= = 1,195 1,195 mA Vout out = 1,19 1,195 5 mA mA x 5K = 5,97 5,975 5V Ratna Aisuwarya, M.Eng.
15