Category Archives: Dasar-3

Pengetahuan Dasar Input Data Arduino dengan Remote TV

Software

-Arduino

Library IRRemote

Hardware

-Remote TV ( NEC, SONY, PANASONIC, SANYO atau yg lainya) pada contoh ini menggunakan remote dgn data kode  NEC  spt pd gb ke-2

-Sensor TV /IR senor

-Arduino board

PINIRREMOTE.jpg

 

Rangkai spt gambar berikut.  pin data untuk contoh ini no 8

irremote.jpg

Code Program

#include <IRremote.h>

int RECV_PIN = 8;
int y=0,data;
IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
displayUtama();
pilihMenuUtama();

}
void displayUtama(){
Serial.println(“Display Utama”);
}

//==========================================
void pilihMenuUtama(void)
{ int y=0;
int Loop0=1; // loop1 baca menu,loop2 input data.

Serial.println(“pilihMenuUtama”);
while(Loop0) //loop baca #
{
y = key();
if( y == 1) // pilih menu #
{
menuUtama(); //tampilkan menu utama lalu menuju loop 2 baca keypad ke-2
Loop0=0;
}
if( y == 2) // pilih menu #
{
menuUtama1(); //tampilkan menu utama lalu menuju loop 2 baca keypad ke-2
Loop0=0;
}
} // end while(Loop0)

}
//=============================
int bacaRemotedanEnter(){
//input data integer dan tekan #
int y=0;
int Loop0=1; // loop1 baca menu,loop2 input data.
int data=0;
Serial.println(“baca remote dan enter”);
while(Loop0) //loop baca #
{
y = key();
if( y <10 ) // pilih menu 1-9
{
if(y==0 && results.value !=0xFF6897) continue;
data =data*10+y;
Serial.println(data);

}
if( y == ‘#’) // pilih menu #
{
Loop0=0;
return data;
}

delay(300); // Do not get immediate repeat
} // end while(Loop0)
}
//=============================
void menuUtama(){
Serial.println(“input plan:”);
int datahasil = bacaRemotedanEnter();
Serial.print(“hasil baca remote dan enter : “);
Serial.println(datahasil);
return;
}
void menuUtama1(){
Serial.println(“input cycle:”);
int datahasil = bacaRemotedanEnter();
Serial.print(“hasil baca remote dan enter : “);
Serial.println(datahasil);
return;
}
//=========================================
int key(void)
{

char KEY = 1 ;
while(KEY){
if (irrecv.decode(&results))
{
// Serial.println(results.value, HEX);
if(results.value != 0xFFFFFFFF)
{

y= translateIR();

KEY=0;
irrecv.resume(); // Receive the next value
return y;
}
delay(100); // Do not get immediate repeat
irrecv.resume(); // Receive the next value
}
}
}

//========================================================

int translateIR() // data tergantung kode masing2 merk remote
{
if(results.value== 0xFF30CF) return 1;
if(results.value== 0xFF18E7) return 2;
if(results.value== 0xFF7A85) return 3;
if(results.value== 0xFF10EF) return 4;
if(results.value== 0xFF38C7) return 5;
if(results.value== 0xFF5AA5) return 6;
if(results.value== 0xFF42BD) return 7;
if(results.value== 0xFF4AB5) return 8;
if(results.value== 0xFF52AD) return 9;
if(results.value== 0xFF6897) return 0;
if(results.value== 16769055) return ‘#’;

}
//======================================

hasilbacairremoteTV

Pengetahuan Dasar Input Data Arduino menggunakan Keypad 4×4 di tampilkan pada LCD

Hardware

pada percobaan ini sy menggunakan arduino mega2560

ketikKeypad.jpg

#include <LiquidCrystal.h>
//LiquidCrystal(rs, en,d0, d1, d2, d3);
LiquidCrystal lcd( 22, 23, 24, 25, 26,27);

#define kolom1 2 //pin 2
#define kolom2 3
#define kolom3 4
#define kolom4 5

#define baris1 6
#define baris2 7
#define baris3 8
#define baris4 9
int key(void);
void bacaKeypad();
int y=0;

void setup()
{
lcd.begin(16, 4);
// put your setup code here, to run once:

Serial.begin(9600);
pinMode(kolom1, OUTPUT);
pinMode(kolom2, OUTPUT);
pinMode(kolom3, OUTPUT);
pinMode(kolom4, OUTPUT);

pinMode(baris1, INPUT);
pinMode(baris2, INPUT);
pinMode(baris3, INPUT);
pinMode(baris4, INPUT);
digitalWrite(baris1, HIGH);
digitalWrite(baris2, HIGH);
digitalWrite(baris3, HIGH);
digitalWrite(baris4, HIGH);

Serial.println(“test”);
lcd.setCursor(0, 0);
lcd.print(“ketik keypad :”);   // akhiri dengan ketik tanda #
}

void loop()
{
bacaKeypad();

}

int key(void)
{
unsigned char delaykeypad=700;
char KEY = 1 ;
while(KEY){

digitalWrite(kolom1, LOW);
digitalWrite(kolom2, HIGH);
digitalWrite(kolom3, HIGH);
digitalWrite(kolom4, HIGH);

if(digitalRead(baris1) == 0){delay(delaykeypad);KEY = 0; return 13 ; }
if(digitalRead(baris2) == 0){delay(delaykeypad);KEY = 0; return ‘#’ ; }
if(digitalRead(baris3) == 0){delay(delaykeypad);KEY = 0; return 0 ; }
if(digitalRead(baris4) == 0){delay(delaykeypad);KEY = 0; return ‘*’ ; }

//==========================================
digitalWrite(kolom1, HIGH);
digitalWrite(kolom2, LOW);
digitalWrite(kolom3, HIGH);
digitalWrite(kolom4, HIGH);

if(digitalRead(baris1) == 0){delay(delaykeypad);KEY = 0; return 12 ; }
if(digitalRead(baris2) == 0){delay(delaykeypad);KEY = 0; return 9 ; }
if(digitalRead(baris3) == 0){delay(delaykeypad);KEY = 0; return 8 ; }
if(digitalRead(baris4) == 0){delay(delaykeypad);KEY = 0; return 7 ; }
//==========================================

digitalWrite(kolom1, HIGH);
digitalWrite(kolom2, HIGH);
digitalWrite(kolom3, LOW);
digitalWrite(kolom4, HIGH);
if(digitalRead(baris1) == 0){delay(delaykeypad);KEY = 0; return 11 ; }
if(digitalRead(baris2) == 0){delay(delaykeypad);KEY = 0; return 6 ; }
if(digitalRead(baris3) == 0){delay(delaykeypad);KEY = 0; return 5 ; }
if(digitalRead(baris4) == 0){delay(delaykeypad);KEY = 0; return 4 ; }
//==========================================
//==========================================

digitalWrite(kolom1, HIGH);
digitalWrite(kolom2, HIGH);
digitalWrite(kolom3, HIGH);
digitalWrite(kolom4, LOW);

if(digitalRead(baris1) == 0){delay(delaykeypad);KEY = 0; return 10 ; }
if(digitalRead(baris2) == 0){delay(delaykeypad);KEY = 0; return 3 ; }
if(digitalRead(baris3) == 0){delay(delaykeypad);KEY = 0; return 2 ; }
if(digitalRead(baris4) == 0){delay(delaykeypad);KEY = 0; return 1; }
//==========================================

KEY = 1 ;
}
}

//================

void bacaKeypad()
{
int Loop = 1 ;
int inputData=0;
inputData=0;
lcd.setCursor(0, 1);
while(Loop)
{
y = key();
if( y < 10 ) // ambil data 0~9 simpan di inputData
{
inputData = (inputData*10)+y ;
Serial.print(y);
lcd.print(y);
delay(300);
}
else if(y == ‘*’)
{ lcd.setCursor(0, 0);
lcd.clear();

y = 0 ;
Loop = 0 ; //keluar loop2
delay(300);
return ;
}
else if(y == ‘#’) //jika ditekan tanda “#”
{ lcd.setCursor(0, 2);
lcd.print(“anda ketik:”);
lcd.setCursor(0, 3);
lcd.print(inputData);

y = 0 ;
Loop = 0 ; //keluar loop2
delay(300);
return ;
}
} //end while loop
}

Pengetahuan Dasar Simpan Data Char Integer dan Array di EEPROM

Contoh Code -1

void writeInteger(int addr, int dataeeprom)
{
writeeeprom(addr+1, dataeeprom & 0xff);
writeeeprom(addr, (dataeeprom>>8) & 0xff);
}

int ReadInteger(int addr)
{ char value=0,value2=0;
value = readeeprom(addr);
value2 = readeeprom(++addr);
value = (value <<8) & 0xff00;
value = value | value2;
return value;
}

void writeeeprom(unsigned int alamat, unsigned char datana)
{
while(EECR & (1<<1));
EEAR = alamat;
EEDR = datana;
EECR |= (1<<2);
EECR |= (1<<1);
delay_ms(10);
}
unsigned char readeeprom(unsigned int alamat)
{
unsigned char dataeeprom;
while(EECR & (1<<1));
EEAR = alamat;
EECR |= (1<<0);
dataeeprom=EEDR;
return dataeeprom;
delay_ms(10);
}

void simpanArrayKeEEPROM( int array[],int alamat)
{ char i=0;

for(i=0;i<13;i++)
{
writeInteger(alamat, array[i]) ;
alamat=alamat+2;
}
}

 

Contoh Kode -2 dgn menggunakan library EEPROM

#include <EEPROM.h>

void writeEepromInteger(int addr, unsigned int dataeeprom)
{
EEPROM.write(addr+1, dataeeprom & 0xff);
EEPROM.write(addr, (dataeeprom>>8) & 0xff);
delay(50);
}

int readEepromInteger(int addr)
{
int value = EEPROM.read(addr);
int value2 = EEPROM.read(++addr);
value = (value <<8) & 0xff00;
value = value | value2;
return value;
}

//contoh penggunaan fungsi writeEepromInteger()  diatas

writeEepromInteger(1,1500);   // write intger 1500 ke alamat 1 dan 2 dimemori eeprom
writeEepromInteger(4,6789);   // write intger 6789 ke alamat 4 dan 5 dimemori eeprom

//contoh penggunaan fungsi readeepromInteger()  diatas

int dataku =readEepromInteger(1);   //baca Eeprom alamat 1 dan 2 simpan sebagai integer di variable dataku

int datamu =readEepromInteger(4);

Pengetahun Dasar dan Contoh code Timer pada Arduino

Pengetahun Dasar dan Contoh code Timer pada Arduino

Pendahuluan

Cara kerja Timer Arduino sama dengan Cara kerja Timer pada timer mikrokontroller AVR yg sudah dibahas pada artikel disini.  Hal ini dikarenakan Arduino menggunakan mikrokontroler AVR sebagai chip utamanya yaitu atmega 328, atmega 1260 atmeg2560 dll.

Pada Arduino telah disediakan(ada yg membuatkan) library untuk penggunaan timer seingga kita tak perlu menetahui detail register yg dipakai.  sedang untuk menggunakan timer pada compiler lain (misal avr-gcc atau codevision) kita sendiri yg harus menseting nilai register yg mengatur timer .

pada Arduino Timer0 sebaiknya tdk kita gunakan karena timer0 dipakai oleh fungsi delay() dan milis()

 Memakai Timer dgn bantuan Library yg sdh tersedia 

berikut ini beberapa library siap pakai  sdh sy test pada Arduino Uno (CPU atmega 328) dan Arduino Mega (CPU ATmega 2560)

1.TimerLib

2.TimerOne

3.MsTimer2

Contoh :

Memakai Timer tanpa menggunakan Library 

#include <TimerOne.h>

void setup()
{
pinMode(13, OUTPUT);   

Timer1.initialize(100000); // 100.000 ms ( 0.1 sec )
Timer1.attachInterrupt( LedBlink);
}

void loop()
{

}

/// --------------------------
/// ISR Timer Routine  , nama fungsi bisa custom
/// --------------------------
void LedBlink()
{
digitalWrite( 13, digitalRead( 13 ) ^ 1 );
}

Memakai Timer tanpa menggunakan Library 

void setup()
{
  pinMode(13, OUTPUT);

  // initialize timer1 
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;

  TCNT1 = 34286;            // preload timer 65536-16MHz/256/2Hz
  TCCR1B |= (1 << CS12);    // 256 prescaler 
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
}

ISR(TIMER1_OVF_vect)        //nama fungsi harus "ISR(nama vector) 
{
  TCNT1 = 34286;            // preload timer
  digitalWrite(13, digitalRead(13) ^ 1);
}

void loop()
{
 
}

Cara kerjanya spt ini:

-Set durasi/periode  timer overflow  misal kita set 2 detik

-tiap 2 detik  terjadi overflow yg akan menimbulkan interupsi  (interupsi overflow)

-interupsi akan menjalankan fungsi ISR

-paramater fungsi ISR adalah nama vector atau vector name dari tiap jenis penyebab interupsi.  berikut vector name untuk tiap interupsi  timer yg lainya :

TIMER0_OVF_vect   adalah vector name  untuk interupsi overflow timer 0

TIMER1_OVF_vect    untuk timer 1

TIMER2_OVF_vect    untuk timer 2

TIMER3_OVF_vect    untuk timer 3   dst…..

Pengetahuan Dasar Komunikasi (network) VB.Net dengan Arduino Ethernet

Untuk pemula daripada nanti bingung sebaiknya baca dulu teori dasar pemrograman jaringan dan  dasar network arduino 


[Draft]

Pengetahuan Dasar Komunikasi VB.Net  dengan Arduino Ethernet

 

Pendahuluan

bla bla bla hehehuhu  sabar dulu yah

Setup Hardware :

arduinoethernet0
arduino + ethernet shield

 

arduinoethernet1

Memasang ethernet shield di atas Arduino Uno dibawah

arduinoethernet1a

Pasang  kable utp  dan usb

kalau blm punya kable UTP  pergilah ke toko komputer katakan sama mba nya ” mba beli kabel UTP semeter,  dikrimping ya ke dua ujungnya”  kalau ditanya buat apa ,katakan padanya : buat mengikat hatimu hehehe.

Set Alamat IP komputer yg akan dihubungkan dgn Arduino

sy  menggunakan win 7 ,untuk set alamat IP nya sbb:

setLANpc.jpg

alamat IP PC harus dlm grup yg sama dgn Arduino konkritnya spt ini

jika alamat Arduino 192.168.1.xxx (192.168.1 adalah alamat grup, xxx adalah alamat host )

maka IP komputer  harus sama dgn yg diatas kecuali xxx harus ,nilai xxx  1 s/d 255

contoh alamat IP ethernet shield  192.168.1.177   xxx disini kita set =177.

alamat IP komputer anda  192.168.1. 9.      xxx disini kita set= 9 ( yg penting jgn 0 atau 177)

Koneksi kabel LAN  PC dan Arduino ethernet shield sbb:

arduinoethernet3

 

Program VB.Net sbg client

contoh client VB.net mengirim string :  1234#

vbclient

Program Arduino sbg server

serverarduino

#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 177);
int i=0;
String inString = “”;
EthernetServer server(5000);
boolean alreadyConnected = false;

void setup()

{
Ethernet.begin(mac, ip);
// menunggu client
server.begin();
Serial.begin(9600);
Serial.print(“aku arduino pelayan yg sedang nunggu kerjaan”);
}
void loop() {
EthernetClient client = server.available();
if (client) {
if (!alreadyConnected) {
client.flush();   // clear bufer
Serial.println(“Wow ada tamu yg datang”);
client.println(“Hello, VB.Net ada yg bisa sy  bantu?”);
alreadyConnected = true;
}

if (client.available() > 0) {
char thisChar = client.read();     // Vb.net mengirim data angka diakhiri #
if(thisChar !=’#’)
{
inString += thisChar;
}
else
{
client.println(“hai VB.Net request sdh  kuterima tunggu sebentar ya..”);
Serial.print(“string:”);
Serial.println(inString);
Serial.print(“Nilai:”);
Serial.println(inString.toInt());
client.println(“nih aku kembalikan angkanya  aku tambah 10 ya “);
client.println(inString.toInt()+10);
client.println(“sama aku kasih bonus deh dgn hasil baca pin analog 0 : “);
int hasilPin_A0 = analogRead(A0);
client.println(hasilPin_A0);
i=0;
inString=””;
}

}
}
}

promoarduinovbnet

 

 

Pengetahuan Dasar Membuat Grafik Real Time VB.Net Data Serial Port Arduino

Pengetahuan Dasar Membuat Grafik Real Time Data Serial Port

Aplikasi yg dibutuhkan
VB.Net
Codevision atau Arduino

ARDUINO_MODUL

Hardware yg dibutuhkan
Usb to Serial
Mikrocontroller board AVR atau Arduino board

Tahapan Pembuatan aplikasi VB.Net

-Buka project baru

-pada form tambahkan komponen Chart,timer, textbox,listbox  dan button

-Atur tata letak komponen chart,textbox,buton pada form

graph

Kode ProgramVB.Net 2010
Imports System
Imports System.IO.Ports
Imports System.Threading
Imports System.Threading.Thread
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim data As String
Dim frek As String
Dim RXArray(2047) As Char
Dim RXCnt As Integer ‘
Dim time As String
Dim frekwensi As String
Dim engChart As New Series

Dim WithEvents COMPort As New SerialPort

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

End Sub
Private Sub ClosePort()
If COMPort.IsOpen Then
COMPort.Close()
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If COMPort.IsOpen Then
COMPort.Close()
Label3.Text = “koneksi berhasil ditutup”

End If
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each COMString As String In My.Computer.Ports.SerialPortNames
ComboBox1.Items.Add(COMString)
Next
Chart1.Series.Clear()
Chart1.Titles.Add(“data serial real time”)
engChart.Name = “analog in”
engChart.ChartType = SeriesChartType.Line
Chart1.Series.Add(engChart)
Chart1.ForeColor = Color.Cyan
ComboBox1.Focus()
RXCnt = 0

End Sub

‘=================================================================

‘=================================================================
Private Sub Receiver(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles COMPort.DataReceived
Dim RXByte As Byte

Do
RXByte = COMPort.ReadByte
RXArray(RXCnt) = Chr(RXByte)

If Chr(RXByte) = Chr(13) Then
Me.Invoke(New MethodInvoker(AddressOf Display))
RXCnt = 0
End If
RXCnt = RXCnt + 1

Loop Until (COMPort.BytesToRead = 0)
End Sub

Private Sub Display()
data = (New String(RXArray, 1, RXCnt))

TextBox1.Text = data

DoUpdate()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
time = TimeOfDay
End Sub
Public Sub DoUpdate()

Try
engChart.Points.AddXY(time, data)
Catch ex As Exception

Label3.Text = ex.Message
Finally

End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If COMPort.IsOpen Then
COMPort.RtsEnable = False
COMPort.DtrEnable = False
ClosePort()

Application.DoEvents()
Sleep(200)
End If
COMPort.PortName = ComboBox1.Text
COMPort.BaudRate = 9600
COMPort.WriteTimeout = 2000
Try
COMPort.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try

If COMPort.IsOpen Then
COMPort.RtsEnable = True
COMPort.DtrEnable = True

Label3.Text = “koneksi berhasil dibuka”
End If
End Sub
End Class

kode program Arduino
void setup() {
Serial.begin(9600);
}
void loop() {
// baca  analog pin 0:
int sensorValue = analogRead(A0);
// kirim hasil ke serial
Serial.println(sensorValue);
delay(1000);
}

Kode progrtam AVR codevision

/*****************************************************
Date : 13/08/2016
Chip type : ATmega16
Clock frequency : 11,059200 MHz
kontinyu kirim data :50987<0D>60734<0D>dst..
*****************************************************/

#include <mega16.h>
#include <stdio.h>
#include <delay.h>

unsigned int i;
void main(void)
{
// 8 Data, 1 Stop, No Parity
// Baud rate: 9600
UCSRA=0x00;
UCSRB=0x08;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x47;

while (1)
{
i++;
putchar(i/1000 %10 + 0x30);
putchar( i/100 %10 + 0x30);
putchar(i/10 %10 + 0x30);
putchar(‘.’);
putchar(i % 10 + 0x30);
putchar(‘\r’) ;
delay_ms(600);

};
}

promoarduinovbnet

Contoh kode Arduino Menulis String data ke Mifare RFID Tag

contoh string yg akan ditulis  “tgl 20/07/2016 NO ST:001/ST/SDI-SYM/VII/2016 Rp.50.000,-#” .
string diatas dikirim dari serial port dan di simpan kedalam array buffer[64].
krn tiap 1 blok tag rfid cuma ada 16 byte maka string diatas ditulis ke dalam 4 blok yaitu blok 1,2 4 dan 5
blok 3,7,11, 15, 19… dst tdk boleh untuk menyimpan data krn berisi data untuk authentifikasi

/*
*menulis string ke MIFARE RFID card menggunakan RFID-RC522 reader
—————————————————————————–
* Pin layout should be as follows:
* Signal Pin Pin Pin
* Arduino Uno Arduino Mega MFRC522 board
* ————————————————————
* Reset 9 5 RST
* SPI SS 10 53 SDA
* SPI MOSI 11 52 MOSI
* SPI MISO 12 51 MISO
* SPI SCK 13 50 SCK
*————————————————————–

*/

#include  SPI.h
#include  MFRC522.h
//atur kembali konfigurasi pin sesuai modul arduino anda
#define SS_PIN 10 //Arduino Uno
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

void setup() {
Serial.begin(9600);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(“Write string data on a MIFARE PICC “);
}

void loop() {

// Prepare key – all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
MFRC522::MIFARE_Key key;
for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) return;

Serial.print(“Card UID:”); //kirim UID ke serial port
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? ” 0″ : ” “);
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print(” PICC type: “); // kirim PICC type ke serial port
byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));

byte buffer[64]; //untuk menampung string dari serial port
byte block;
byte status, len;

Serial.setTimeout(20000L) ; // time out serial port 20 detik
// input string
Serial.println(“masukan data string akhiri dgn #”);
len=Serial.readBytesUntil(‘#’, (char *) buffer, 64) ; // terima data string dari serial
for (byte i = len; i < 64; i++) buffer[i] = ‘\s’; // sisa bufer disi kode spasi

block = 1;
//Serial.println(“Authenticating using key A…”);
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(“PCD_Authenticate() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}

// Write block
status = mfrc522.MIFARE_Write(block, buffer, 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(“MIFARE_Write() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else Serial.println(“MIFARE_Write() success: “);

block = 2;
//Serial.println(“Authenticating using key A…”);
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(“PCD_Authenticate() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}

// Write block
status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(“MIFARE_Write() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else Serial.println(“MIFARE_Write() success: “);
block = 4;
//Serial.println(“Authenticating using key A…”);
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(“PCD_Authenticate() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}

// Write block
status = mfrc522.MIFARE_Write(block, &buffer[32], 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(“MIFARE_Write() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else Serial.println(“MIFARE_Write() success: “);

block = 5;
//Serial.println(“Authenticating using key A…”);
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(“PCD_Authenticate() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}

// Write block
status = mfrc522.MIFARE_Write(block, &buffer[48], 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(“MIFARE_Write() failed: “);
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else Serial.println(“MIFARE_Write() success: “);

Serial.println(” “);
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD

}

 

Contoh Kode Arduino Akses Pintu dengan RFID

Untuk Teori dasar RFID  mifare bisa dibaca disini
#include <SPI.h>
#include <MFRC522.h>

#define selenoid 4
#define RST_PIN 9
#define SS_PIN 10
#define jumlahdatabaseTAG 5

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

MFRC522::MIFARE_Key key; // prepare struct key for authentification

/**
* Initialize.
*/

char* databaseTAG[] =
{
“123456789ABCDE1”,// Tag 0
“123456789ABCDE2”,// Tag 1
“123456789ABCDE3”, // Tag 2
“123456789ABCDE4”, // Tag 3
“123456789ABCDE5”, // Tag 4
“123456789ABCDE6”, // Tag 5
“123456789ABCDE7”, // Tag 6
“123456789ABCDE8”, // Tag 7
“123456789ABCDE9”, // Tag 8
“123456789ABCDEF”, // Tag 9
};

char* Name[] =
{
“abdullah”, // Tag 1
“dodi”, // Tag 2
“uus”,
“yudi”,
“mario”,
“usman”,
“fatih”,
“fayiz”,
“herman”,
“dede”,

// Tag 3
};

int led1 = 5;
int led2= 6;
int pintu = 7;
int buzzer = 8;

void setup() {

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(pintu, OUTPUT);
pinMode(buzzer, OUTPUT);

Serial.begin(9600);
SPI.begin();
mfrc522.PCD_Init();

// Prepare the key: 0xff 0xff 0xff 0xff 0xff 0xff
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}

}

//===============================================
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
Serial.print(“Card UID:”);
kirimkePC(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
int tagNo =0;
byte sector = 1;
byte blockAddr = 4;
byte trailerBlock = 7;
byte status;
byte buffer[18];
byte size = sizeof(buffer);

char bufferchar[16];
byte sizechar = sizeof(bufferchar);

status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(“Authenticate failed: “);
return;
}

// Read block
Serial.print(“hasil baca blok = “); Serial.print(blockAddr);
Serial.println();

status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
if (status != MFRC522::STATUS_OK)
{
Serial.print(“Read failed”);
return;
}

kirimkePC(buffer, 16); Serial.println();

//konversi buffer dari byte ke string
for(byte j=0;j<16;j++)
{
bufferchar[j]=buffer[j];
}

bufferchar[15]=0x00; // string adalah array char yg diakhiri NULL (0x00)

Serial.print(bufferchar);
Serial.println();

//compare string hasil baca dengan string di database
tagNo=0xff;
for(byte i=0;i<10;i++)
{
if(strcmp(bufferchar, databaseTAG[i]) == 0)
{
tagNo=i;
}
}

if(tagNo !=0xff) // TAG cocok
{
Serial.print(“kunci terbuka”);Serial.println();
Serial.print(“selamat datang : “);
Serial.print(Name[tagNo]);
Serial.println();
digitalWrite(led1, HIGH);
delay(100);
digitalWrite(pintu, HIGH);
delay(2000);
digitalWrite(led1, LOW);

}
else // TAG tdk cocok
{
digitalWrite(led2, HIGH);
delay(100);
digitalWrite(buzzer, HIGH);
delay(100);
Serial.print(“anda tak berhak masuk”);
Serial.println();
}

mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
} // end of main loop
//========================================================

void kirimkePC(byte *buffer, byte bufferSize)
{
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? ” 0″ : ” “);
Serial.print(buffer[i], HEX);
}
}

Membuat Display 4 baris 7 segment menggunakan MAX7221

Teory dasar bisa dibaca di https://pccontrol.wordpress.com/2011/09/15/pemrograman-display-7-segment-dengan-spi-max7221-max7219/

pada contoh ini menggunakan 7 segment  kecil < 1 inch dgn tegangan 5v.jika Anda ingin menggunakan 7 segmen dgn tegangan lebih dari 5 v ( 7 segment ukuran yg besar i inch,2 inch 3 inch dst) maka tinggalditambahkan penguat daya misal dgn transistor atau ic ULN2083 atau lainnya.

4baris7segment

koneksi

max7221serial

Kode program C dengan codevision

 

/*****************************************************
CodeWizardAVR V1.24.
Chip type : ATmega16
Clock frequency : 11.059200 MHz
*****************************************************/
// Standard Input/Output functions
#include <stdio.h>
#include <delay.h>
#include <spi.h>
#include <mega16.h>
//=========================

// SPI
#define PIN_SCK PORTB.7
#define PIN_MOSI PORTB.5
#define PIN_SS PORTB.4

#define ON 1
#define OFF 0

#define MAX7219_LOADa1 PORTB.4=1 //chip enable 1
#define MAX7219_LOADa0 PORTB.4=0 //chip enable 0
#define MAX7219_LOADb1 PORTB.3=1 //chip enable 1
#define MAX7219_LOADb0 PORTB.3=0 //chip enable 0
#define MAX7219_LOADc1 PORTB.2=1 //chip enable 1
#define MAX7219_LOADc0 PORTB.2=0 //chip enable 0
#define MAX7219_LOADd1 PORTB.1=1 //chip enable 1
#define MAX7219_LOADd0 PORTB.1=0 //chip enable 0

#define MAX7219_MODE_DECODE 0x09
#define MAX7219_MODE_INTENSITY 0x0A
#define MAX7219_MODE_SCAN_LIMIT 0x0B
#define MAX7219_MODE_POWER 0x0C
#define MAX7219_MODE_TEST 0x0F
#define MAX7219_MODE_NOOP 0x00

#define MAX7219_DIGIT0 0x01
#define MAX7219_DIGIT1 0x02
#define MAX7219_DIGIT2 0x03
#define MAX7219_DIGIT3 0x04
#define MAX7219_DIGIT4 0x05
#define MAX7219_CHAR_BLANK 0xF
#define MAX7219_CHAR_NEGATIVE 0xA
//================================
#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

//void MAX7219_displayNumber(volatile long number);
void MAX7219_displayNumber(long number,char baris);
void MAX7219_clearDisplay(char baris);
//void MAX7219_writeData(char data_register, char data);
void MAX7219_writeData(char data_register, char data, char baris);
void spiSendByte (char databyte);

// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];

#if RX_BUFFER_SIZE<256
unsigned char rx_wr_index,rx_rd_index,rx_counter;
#else
unsigned int rx_wr_index,rx_rd_index,rx_counter;
#endif

// This flag is set on USART Receiver buffer overflow
bit rx_buffer_overflow;

// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
{
rx_buffer[rx_wr_index]=data;
if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
if (++rx_counter == RX_BUFFER_SIZE)
{
rx_counter=0;
rx_buffer_overflow=1;
};
};
}

#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer
#define _ALTERNATE_GETCHAR_
#pragma used+
char getchar(void)
{
char data;
while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
#asm(“cli”)
–rx_counter;
#asm(“sei”)
return data;
}
#pragma used-
#endif

// Declare your global variables here
char digitsInUse = 5;
void main(void)
{
// Declare your local variables here

int a,b,c,d,i;
// Input/Output Ports initialization
// Port A initialization
PORTA=0x00;
DDRA=0x00;

// Port B initialization
PORTB=0x00;
DDRB=0xff; // SCK MOSI CS/LOAD/SS

// Port C initialization
PORTC=0x00;
DDRC=0x00;

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0x00;

// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: Off
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0x90;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x47;

// SPI initialization
// SPI Type: Master
// SPI Clock Rate: 86.400 kHz
// SPI Clock Phase: Cycle Half
// SPI Clock Polarity: Low
// SPI Data Order: MSB First
//SPCR=0x53;
//SPSR=0x00;
// SPI Enable, Master mode
SPCR =0x53;
for(i=1;i<5;i++)
{
// Decode mode to “Font Code-B”
MAX7219_writeData(MAX7219_MODE_DECODE, 0xFF,i);
// Scan limit runs from 0.
MAX7219_writeData(MAX7219_MODE_SCAN_LIMIT, digitsInUse – 1,i);
MAX7219_writeData(MAX7219_MODE_INTENSITY, 8,i);
MAX7219_writeData(MAX7219_MODE_POWER, ON,i);
delay_ms(50);
}
//

// Global enable interrupts
#asm(“sei”)

a=12305;
b=11300;
c=11612;
d=b-c;
MAX7219_displayNumber(a,1);
MAX7219_displayNumber(b,2);
MAX7219_displayNumber(c,3);
MAX7219_displayNumber(d,4);

while (1)
{

i=i+1;

if(i==999)i=0;
};

}

//===============================================================================
//=========================
void spiSendByte (char databyte)
{
SPDR = databyte;
// Wait until transfer is complete
while (!(SPSR & (1 << 7)));
}

void MAX7219_writeData(char data_register, char data, char baris)
{
if(baris==1)
{
MAX7219_LOADa0;
// Send the register where the data will be stored
spiSendByte(data_register);
// Send the data to be stored
spiSendByte(data);
MAX7219_LOADa1;
}
if(baris==2)
{
MAX7219_LOADb0;
// Send the register where the data will be stored
spiSendByte(data_register);
// Send the data to be stored
spiSendByte(data);
MAX7219_LOADb1;
}
if(baris==3)
{
MAX7219_LOADc0;
// Send the register where the data will be stored
spiSendByte(data_register);
// Send the data to be stored
spiSendByte(data);
MAX7219_LOADc1;
}
if(baris==4)
{
MAX7219_LOADd0;
// Send the register where the data will be stored
spiSendByte(data_register);
// Send the data to be stored
spiSendByte(data);
MAX7219_LOADd1;
}

}

void MAX7219_clearDisplay(char baris)
{
char i;
i = digitsInUse;
// Loop until 0, but don’t run for zero
do {
// Set each display in use to blank
MAX7219_writeData(i, MAX7219_CHAR_BLANK,baris);
} while (–i);

}

void MAX7219_displayNumber(long number,char baris)
{
char negative = 0;
char i = 0;
if (number < 0) {
negative = 1;
number =number * -1; //rubah ke +
}
MAX7219_clearDisplay(baris);
// If number = 0, only show one zero then exit
if (number == 0) {
MAX7219_writeData(1, 0,baris);
return;
}
// Initialization to 0 required in this case,
// does not work without it. Not sure why.
// Loop until number is 0.
do {
MAX7219_writeData(++i, number % 10,baris);
// Actually divide by 10 now.
number /= 10;
} while (number);

// display the sign.
if (negative) {
MAX7219_writeData(i+1, MAX7219_CHAR_NEGATIVE,baris);
}
}

Pengetahuan Dasar Pemrograman Modul Led/Dot Matrik Display (DMD) P10 dengan Arduino

Pendahuluan

Modul Display Led Matrik yg populer saat ini antara lain P10 .Kita dapat dengan mudah memprogram modul tersebut dengan Arduno karena telah tersedia library untuk itu.  library  tsb  dibuatkan oleh salah satu pembuat P10 yaitu Freetronic.

Dimensi modul  P10: 16 led x 32 Led

freetronic

Hardware

modulp10kearduino

konektor antara Arduino dan modul P10

soket_p10

penjelasan pin pada konektor

  • OE: Output Enable untuk on/off semua LED
  • A dan B: memilih kolom yg aktif.
  • CLK: SPI clock
  • SCLK: Latch data register
  • Data: SERIAL DATA SPI

 

 Circuit modul P10circuitep10

 

Penjelasan :

Data akan dikirm dari arduino  secara  serial melalui soket HUB1.2 kemudian diterima oleh IC serial to paralel 74595.  jika ada tambahan modul akan diambil dari keluaran 74595 yg terakhir yg dihubungkan ke soket X2-OUT. Untuk suply arus diberikan oleh ic driver penguat daya VT1,VT2..dst. Untuk memilih kolom mana yg menyala diaktifkan oleh IC multiplexer.

 

Rangkain Modul P10lebih dari 1 (Cascade )

Jika   module P10 lebih dari 1  , maka rangkaian dibentuk cascade  spt gambar berikut:

modulp10cascade

Gambar  dilihat dari arah  belakang modul P10

untuk konfigurasi panel diatas maka inisialisasi DMD  :

DMD dmd(2,2);  // 2 modul P10 ke samping , 2 modul P10 ke bawah.

software

 

Step by step install library untuk menjalankan DMD P10

Header file yg digunakan :

#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include “SystemFont5x7.h”
#include “Arial_Black_16_ISO_8859_1.h”


Fungsi fungsi  yg ada di library DMD yang digunakan  antara lain:

//Instantiate the DMD
DMD(byte panelsWide, byte panelsHigh);

//Set or clear a pixel at the x and y location (0,0 is the top left corner)
void writePixel( unsigned int bX, unsigned int bY, byte bGraphicsMode, byte bPixel );

//Draw a string
void drawString( int bX, int bY, const char* bChars, byte length, byte bGraphicsMode);

//Select a text font
void selectFont(const uint8_t* font);

//Draw a single character
int drawChar(const int bX, const int bY, const unsigned char letter, byte bGraphicsMode);

//Find the width of a character
int charWidth(const unsigned char letter);

//Draw a scrolling string
void drawMarquee( const char* bChars, byte length, int left, int top);

//Move the maquee accross by amount
boolean stepMarquee( int amountX, int amountY);

//Clear the screen in DMD RAM
void clearScreen( byte bNormal );

//Draw or clear a line from x1,y1 to x2,y2
void drawLine( int x1, int y1, int x2, int y2, byte bGraphicsMode );

//Draw or clear a circle of radius r at x,y centre
void drawCircle( int xCenter, int yCenter, int radius, byte bGraphicsMode );

//Draw or clear a box(rectangle) with a single pixel border
void drawBox( int x1, int y1, int x2, int y2, byte bGraphicsMode );

//Draw or clear a filled box(rectangle) with a single pixel border
void drawFilledBox( int x1, int y1, int x2, int y2, byte bGraphicsMode );

//Draw the selected test pattern
void drawTestPattern( byte bPattern );

//Scan the dot matrix LED panel display, from the RAM mirror out to the display hardware.
//Call 4 times to scan the whole display which is made up of 4 interleaved rows within the 16 total rows.
//Insert the calls to this function into the main loop for the highest call rate, or from a timer interrupt
void scanDisplayBySPI();

kordinat_p10


Contoh Kode program:

/*–Includes——-*/
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include “SystemFont5x7.h”
#include “Arial_Black_16_ISO_8859_1.h”

//Fire up the DMD library as dmd
#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

/*
Interrupt handler for Timer1 (TimerOne) driven DMD refresh scanning, this gets
called at the period set in Timer1.initialize();
*/
void ScanDMD()
{
dmd.scanDisplayBySPI();
}

/*————————————————————————-
setup
Called by the Arduino architecture before the main loop begins
————————————————————————-*/
void setup(void)
{

//initialize TimerOne’s interrupt/CPU usage used to scan and refresh the display
Timer1.initialize( 3000 ); //period in microseconds to call ScanDMD. Anything longer than 5000 (5ms) and you can see flicker.
Timer1.attachInterrupt( ScanDMD ); //attach the Timer1 interrupt to ScanDMD which goes to dmd.scanDisplayBySPI()

//clear/init the DMD pixels held in RAM
dmd.clearScreen( true ); //true is normal (all pixels off), false is negative (all pixels on)
Serial.begin(115200);
}

/*————————————————————————-
loop
Arduino architecture main loop
————————————————————————-*/
void loop(void)
{
dmd.clearScreen( true );
dmd.selectFont(Arial_Black_16_ISO_8859_1);

const char *MSG = “apa  kabar”;
dmd.drawMarquee(MSG,strlen(MSG),(32*DISPLAYS_ACROSS)-1,0);
long start=millis();
long timer=start;
while(1){
if ((timer+30) < millis()) {
dmd.stepMarquee(-1,0);
timer=millis();
}
}
}


referensi:

http://cdn.shopify.com/s/files/1/0045/8932/files/DMD_Getting_Started.pdf?100647

http://www.freetronics.com.au/pages/using-your-freetronics-dmd#.VyRQANSLTI

https://github.com/freetronics/DMD

https://forum.arduino.cc/index.php?topic=260320.0