Penggunaan rotary encoder di sistem Arduino

[ [ images, codes & links ] ]
[su_panel border=”3px solid #C852CE” radius=”10″]

A rotary encoder, also called a shaft encoder, is an electro-mechanical device that converts the angular position or motion of a shaft or axle to an analog or digital signal.

There are two main types: absolute and incremental (relative). The output of absolute encoders indicates the current position of the shaft, making them angle transducers. The output of incremental encoders provides information about the motion of the shaft, which is typically further processed elsewhere into information such as speed, distance and position.

Rotary encoders are used in many applications that require precise shaft unlimited rotation—including industrial controls, robotics, special purpose photographic lenses, computer input devices (such as optomechanical mice and trackballs), controlled stress rheometers, and rotating radar platforms.

~https://en.wikipedia.org/wiki/Rotary_encoder

A rotary encoder is a type of position sensor which is used for determining the angular position of a rotating shaft. It generates an electrical signal, either analog or digital, according to the rotational movement.

Gambar 1.

Gambar 2.

This rotary encoder is also known as quadrature encoder or relative rotary encoder and its output is a series of square wave pulses.

How Rotary Encoder Works  [click to read more]

~howtomechatronics.com

Incremental Encoder Quadrature Output Waveform

An incremental rotary encoder generates two output signals while its shaft is rotating which is also called quadrature ouptut. Depending on the direction, one of the signals leads the other. You can see the output signal waveforms of an incremental rotary encoder and the expected bit sequence below.

Gambar 3.

As you can see from the figure, both of the outputs stays HIGH at the initial state. When the encoder shaft starts to rotate in clockwise direction, Output A falls to LOW first and Output B follows it with a lag. In a counter-clockwise direction the operation turns opposite. Time intervals on the waveform depend on the rotation speed but the signal lagging is guaranteed in encoder operation. We will build the whole scenario on this characteristic of the incremental rotary encoder.

~How to Use a Rotary Encoder in an MCU-Based Project

[/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

Mengenal Keyes KY-04 dan mencoba kode program sederhana.

Contoh kode dari:

http://henrysbench.capnfatz.com

[code lang=”C”] int pinA = 6; // Connected to CLK on KY-040. Gantidari pin 2
int pinB = 7; // Connected to DT on KY-040. Ganti dari pin 3
int encoderPosCount = 0;
int pinALast;
int aVal;
boolean bCW;

void setup() {
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
/* Read Pin A
Whatever state it’s in will reflect the last position
*/
pinALast = digitalRead(pinA);
Serial.begin (9600);
}

void loop() {
aVal = digitalRead(pinA);
if (aVal != pinALast){ // Means the knob is rotating
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinB) != aVal) { // Means pin A Changed first – We’re Rotating Clockwise
encoderPosCount ++;
bCW = true;
} else {// Otherwise B changed first and we’re moving CCW
bCW = false;
encoderPosCount–;
}
Serial.print (“Rotated: “);
if (bCW){
Serial.println (“clockwise”);
}else{
Serial.println(“counterclockwise”);
}
Serial.print(“Encoder Position: “);
Serial.println(encoderPosCount);

}
pinALast = aVal;
}
[/code]

Contoh kode dari:

http://howtomechatronics.com/tutorials/arduino/rotary-encoder-works-use-arduino/

[code lang=”C”] /* Arduino Rotary Encoder Tutorial
*
* by Dejan Nedelkovski, www.HowToMechatronics.com
*
*/

#define outputA 6
#define outputB 7

int counter = 0;
int aState;
int aLastState;

void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);

Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}

void loop() {
aState = digitalRead(outputA); // Reads the “current” state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
} else {
counter –;
}
Serial.print(“Position: “);
Serial.println(counter);
}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
[/code]

Description of the code: So first we need to define the pins to which our encoder is connected and define some variables needed for the program. In the setup section we need to define the two pins as inputs, start the serial communication for printing the results on the serial monitor, as well as read the initial value of the output A and put the value into the variable aLastState.

Then in the loop section we read the output A again but now we put the value into the aState variable. So if we rotate the encoder and a pulse is generated, these two values will differ and the first “if” statement will become true. Right after that using the second “if” statement we determine the rotation direction. If the output B state differ from the output A state the counter will be increased by one, else it will be decreased. At the end, after printing the results on the serial monitor, we need to update the aLastState variable with aState variable.

That’s all we need for this example. If upload the code, start the Serial Monitor and start rotating the encoder we will start getting the values in the serial monitor. The particular module that I have makes 30 counts each full cycle.

[/su_panel] [su_panel border=”3px solid #FF6666″ radius=”20″] [/su_panel] [su_panel border=”3px solid #00C700″ radius=”10″]

Gambar 20.

Berikut contoh-contoh kode program, silakan membaca situs sumber aslinya untuk lebih memahami. Beberpa kode memerlukan pustaka/library yang dapat dicari melalui halaman sumber kode.

Contoh kode program dari https://github.com/PaulStoffregen/Encoder (Basic.pde)

[code lang=”C”] /*
* Dimodifikasi dari kode contoh:
* Encoder Library – Basic Example
* http://www.pjrc.com/teensy/td_libs_Encoder.html
*
* This example code is in the public domain.
*/

#include <Encoder.h>

// Change these two numbers to the pins connected to your encoder.
// Best Performance: both pins have interrupt capability.
// Pin 2 & pin 3 di Arduino Uno
// Good Performance: only the first pin has interrupt capability
// Low Performance: neither pin has interrupt capability
Encoder myEnc(6, 7);
// avoid using pins with LEDs attached

void setup()
{
Serial.begin(9600);
Serial.println(“Basic Encoder Test:”);
}

long oldPosition = -999;
//long oldPosition = 0;

void loop()
{
long newPosition = myEnc.read();
if (newPosition != oldPosition)
{
oldPosition = newPosition;
Serial.println(newPosition);
// Serial.println(newPosition/4);
}
}[/code]

Contoh kode program dari https://github.com/PaulStoffregen/Encoder (NoInterrupts.pde)

[code lang=”C”] /* Encoder Library – NoInterrupts Example
* http://www.pjrc.com/teensy/td_libs_Encoder.html
*
* This example code is in the public domain.
*/

// If you define ENCODER_DO_NOT_USE_INTERRUPTS *before* including
// Encoder, the library will never use interrupts. This is mainly
// useful to reduce the size of the library when you are using it
// with pins that do not support interrupts. Without interrupts,
// your program must call the read() function rapidly, or risk
// missing changes in position.
#define ENCODER_DO_NOT_USE_INTERRUPTS
#include <Encoder.h>

// Beware of Serial.print() speed. Without interrupts, if you
// transmit too much data with Serial.print() it can slow your
// reading from Encoder. Arduino 1.0 has improved transmit code.
// Using the fastest baud rate also helps. Teensy has USB packet
// buffering. But all boards can experience problems if you print
// too much and fill up buffers.

// Change these two numbers to the pins connected to your encoder.
// With ENCODER_DO_NOT_USE_INTERRUPTS, no interrupts are ever
// used, even if the pin has interrupt capability
Encoder myEnc(6, 7);
// avoid using pins with LEDs attached

void setup() {
Serial.begin(9600);
Serial.println(“Basic NoInterrupts Test:”);
}

long position = -999;

void loop() {
long newPos = myEnc.read();
if (newPos != position) {
position = newPos;
Serial.println(position);
}
// With any substantial delay added, Encoder can only track
// very slow motion. You may uncomment this line to see
// how badly a delay affects your encoder.
//delay(50);
}[/code]

Contoh kode program dari https://github.com/mathertel/RotaryEncoder (InterruptRotator.ino)

[code lang=”C”] // —–
// InterruptRotator.ino – Example for the RotaryEncoder library.
// This class is implemented for use with the Arduino environment.
// Copyright (c) by Matthias Hertel, http://www.mathertel.de
// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
// More information on: http://www.mathertel.de/Arduino
// —–
// 18.01.2014 created by Matthias Hertel
// —–

// This example checks the state of the rotary encoder in the loop() function.
// The current position is printed on output when changed.

// Hardware setup:
// Attach a rotary encoder with output pins to A2 and A3.
// The common contact should be attached to ground.

#include <RotaryEncoder.h>

// Setup a RoraryEncoder for pins A2 and A3:
RotaryEncoder encoder(A2, A3);

void setup()
{
// Serial.begin(57600);
Serial.begin(9600); //diubah

Serial.println(“SimplePollRotator example for the RotaryEncoder library.”);

// You may have to modify the next 2 lines if using other pins than A2 and A3
PCICR |= (1 << PCIE1); // This enables Pin Change Interrupt 1 that covers the Analog input pins or Port C.
PCMSK1 |= (1 << PCINT10) | (1 << PCINT11); // This enables the interrupt for pin 2 and 3 of Port C.
} // setup()

// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3: exactly where we need to check.
ISR(PCINT1_vect)
{
encoder.tick(); // just call tick() to check the state.
}

// Read the current position of the encoder and print out when changed.
void loop()
{
static int pos = 0;

int newPos = encoder.getPosition();
if (pos != newPos)
{
Serial.print(newPos);
Serial.println();
pos = newPos;

// Just to show, that long lasting procedures don’t break the rotary encoder:
// When newPos is 66 the ouput will freeze, but the turned positions will be recognized even when not polled.
// The interrupt still works.
// The output is correct 6.6 seconds later.
if (newPos == 66)
{
// delay(6600);
delay(3000); //diubah
} // if newPOS
} // if
} // loop ()

// The End
[/code]

[/su_panel] [su_panel border=”3px solid #97B1FF” radius=”10″]

[/su_panel] [su_panel border=”3px solid #FFA858″ radius=”10″]

[/su_panel] [su_panel border=”3px solid #990066″ radius=”10″] [/su_panel]

Penggunaan sensor ultrasonic

[ [ images & links ] ]
[su_panel border=”3px solid #F0F000″ radius=”10″]

Sensor ultrasonic (ultrasonik) seperti srf04 dan srf05 dipergunakan untuk mengukur jarak suatu obyek.

SRF04Gambar 1. [sumber]

Gambar 2. [sumber]

 

Gambar 5. [sumber]

Ultrasonic ConeGambar 6. [sumber]Ojbects SameGambar 7. [sumber] Ultasonic FailGambar 8. [sumber]

Gambar 9. [sumber]

Gambar 10. [sumber]

Gambar 11. [sumber]

Working of HC-SR04 Ultrasonic SensorGambar 12. [sumber]

Gambar 13. [sumber]

Hubungan ke pin pada Gambar 13 dapat diubah sesuai keperluan, tidak mutlak harus menggunakan pin 12 dan pin 13. Perhatikan perbedaan pin antara SR04/SRF04 dengan SR05/SRF05 seperti pada Gambar 14.

Gambar 14. [sumber] [/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

Sebelum melanjutkan ke tahap yang lebih detail, bisa dicoba kode program yang relatif sederhana sebagai bahan untuk memahami proses kerja sensor lebih lanjut. Kode untuk SRF05 (jika menudukung) dengan menggunakan satu pin bisa dilihat di qqtrading.com.my.

Pengaturan mengikuti Gambar 14 (dua pin sinyal), dengan kode sederhana sebagai berikut:

[code lang=”C”] #define TRIG_PIN 7
#define ECHO_PIN 6

const uint8_t BATAS_BAWAH = 4;
const uint16_t BATAS_ATAS = 300;

int sonar(void);

void setup()
{
Serial.begin(9600);
pinMode(ECHO_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
}

void loop()
{
int jarak = sonar();
Serial.print("Jarak dalam satuan cm: ");
// Serial.println( sonar() );
if(jarak<BATAS_BAWAH)
{
Serial.println("Obyek terlalu dekat");
}
else if(jarak>BATAS_ATAS)
{
Serial.println("Terlalu jauh");
}
else
{
Serial.println(jarak);
}

delay(1000);
}

int sonar(void)
{
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

int jarak = pulseIn(ECHO_PIN, HIGH);

return (jarak = jarak / 58);
}
[/code]

Gambar 15.

 

Gambar 16. Hasil pengukuran jarak

[/su_panel] [su_panel border=”3px solid #E79B0E” radius=”10″] SRF04 Specifications (eprolabs)

    • Operating Voltage:5V

 

    • Operating Frequency: 40Hz

 

    • Max Range: 4m

 

    • Min Range: 2cm

 

    • Measuring Angle: 15 degree

 

    • Trigger Input Signal: 10uS  TTL pulse

 

    • Echo Output Signal: TTL level signal, proportional to distance

 

The SRF04 Timing diagram is shown below. You only need to supply a short 10uS pulse to the trigger input to start the ranging. The SRF04 will send out an 8 cycle burst of ultrasound at 40khz and raise its echo line high. It then listens for an echo, and as soon as it detects one it lowers the echo line again. The echo line is therefore a pulse whose width is proportional to the distance to the object. By timing the pulse it is possible to calculate the range in inches/centimeters or anything else. If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

Gambar 17.

In operation, the processor waits for an active low trigger pulse to come in. It then generates just eight cycles of 40khz. The echo line is then raised to signal the host processor to start timing. The raising of the echo line also shuts of the MAX232. After a while – no more than 10-12mS normally, the returning echo will be detected and the PIC will lower the echo line. The width of this pulse represents the flight time of the sonic burst. If no echo is detected then it will automatically time out after about 30mS (Its two times the WDT period of the PIC). Because the MAX232 is shut down during echo detection, you must wait at least 10mS between measurement cycles for the +/- 10v to recharge. Performance of this design is, I think, quite good. It will reliably measure down to 3cm and will continue detecting down to 1cm or less but after 2-3cm the pulse width doesn’t get any smaller. Maximum range is a little over 3m. As and example of the sensitivity of this design, it will detect a 1inch thick plastic broom handle at 2.4m. Average current consumption is reasonable at less than 50mA and typically about 30mA. Calculating the Distance The SRF04 provides an echo pulse proportional to distance. If the width of the pulse is measured in uS, then dividing by 58 will give you the distance in cm, or dividing by 148 will give the distance in inches. uS/58=cm or uS/148=inches.

Changing beam pattern and beam width You can’t! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I’m aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.  The beam pattern of the transducers used on the SRF04, taken from the manufacturers data sheet, is shown below.

 

Gambar 18.

SRF04 - Ultra-Sonic Ranger Technical Specification
SRF05  
At a quick glance there are only small differences between these two (www.f15ijp.com):

[/su_panel] [su_panel border=”3px solid #A5B1C3″ radius=”10″] Untuk dapat lebih memahami dasar perhitungan, berikut ada beberapa sumber bacaan yang baik dan menarik. Dari beberapa artikel ini, misalnya, bisa diketahui dari mana angka (konstanta) 58 pada contoh kode sebelumnya didapat, dan apa maknanya.

Gambar 19. [sumber]

Gambar 20. [sumber]

Sebagai catatan, situs penyedia layanan (sengpielaudio.com) di halaman tersebut mencantumkan bahwa perhitungan hanya dijamin akurat sampai suhu 30° C saja. Nilai pada Gambar 20 hanya sebagai perbandingan. Jika suhu diturunkan menjadi 30° C maka berdasarkan perhitungan di halaman itu kecepatan suara menjadi 350.7 m/s.

Dari semua bahan di atas dapat disarikan beberapa perhitungan yang berguna untuk memahami dan mengerjakan sistem dengan sensor ultrasonik. Pertama, mencari pendekatan terhadap nilai kecepatan suara (speed of sound).  

   

c : Kecepatan suara (speed of sound) dalam satuan meter per second (m/S) 331.3 : Nilai speed of sound (dalam m/s) pada suhu 0° C dan 0% humidity T : Suhu (temperatur) dalam ° C H : % Humidity (relative humidity)

  Jika memiliki sensor suhu dan kelembapan di sistem/papan mikrokontroler maka nilai c ini dapat dihitung saat kode program dieksekusi.


Sebagai contoh untuk beberapa nilai suhu dan nilai persen kelembapan relatif, dibuat tabel berikut:

 

 


Berdasarkan tabel di atas jika nilai c diambil senilai   351.36 m/s   maka nilai ini sama artinya dengan

Untuk mencari berapa jarak yang ditempuh (menggunakan nilai c yang sama) selama 1 μS:

Untuk mencari berapa waktu yang diperlukan (menggunakan nilai c yang sama) untuk menempuh 1 cm:

 


Jika menggunakan nilai 28.46 uS/cm maka untuk jarak 100 cm  diperlukan waktu 2846 μS. Tetapi perlu diingat untuk penggunaan sensor ultrasonik, pengukuran dilakukan untuk waktu pengiriman dan waktu pantulan terdeteksi kembali. Jadi untuk obyek yang berjarak 100 cm, pengukuran dilakukan untuk 200 cm (100 cm untuk waktu pengiriman dan ditambah 100 cm untuk waktu pantulan). Perhitungannya menjadi:

 


Skenario berikutya adalah jika waktu tempuh yang diukur menggunakan sensor ultrasonik  diketahui. Misalnya terukur waktu tempuh sebesar 1138 μS, berapakah jarak obyek di depan sensor ultrasonik?

Waktu yang ditempuh adalah untuk jarak sekitar 40 cm, tetapi ini waktu untuk “berangkat + pulang” sinyal ultrasonik. Bisa dilihat dari perhitungan, jarak obyek adalah separuhnya yang artinya dalam hal ini adalah sekitar 20 cm.


Beberapa artikel dan kode menggunakan langkah yang nampak sedikit berbeda untuk menentukan jarak obyek di depan sensor ultrasonik, walaupun jika diperhatikan sebenarnya sama saja. Berikut keterangan untuk memudahkan:

 

 

 

 

Beberapa orang melakukan pembulatan untuk efisiensi perhitungan, misalnya:

  Jika menggunakan speed of sound yang berbeda, beberapa orang menuliskan persamaan sebagai berikut:

Untuk beberapa keperluan yang tidak membutuhkan nilai akurasi yang sangat tinggi (yang didukung oleh akurasi dan resolusi sensor dan mikrokontroler), pembulatan bisa dilakukan. Misalnya: (28.46 μS/cm x 2) = 56.92 μS/cm, dapat dibulatkan menjadi 29 μS/cm dan 57 μS/cm. Dengan cara yang sama di beberapa kode bisa ditemui pembulatan dengan nilai 29 μS/cm dan 58 μS/cm.
Jika diperhatikan umumnya perhitungan maupun kode program mempergunakan satuan microsecond, mengapa? Jawabannya adalah pada cara pengukuran waktu pada sensor ultrasonik. Sebagai contoh, pada sistem Arduino telah disediakan rutin pulseIn() yang mengukur dalam (dan mempergunakan) satuan microsecond. [/su_panel] [su_panel border=”3px solid #677090″ radius=”10″] Berikut ada beberapa contoh kode yang, untuk kemudahan dan cadangan, saya kumpulkan dari Internet. Silakan menuju situs asalnya untuk memperoleh keterangan lengkap dan untuk membaca kode pada bagian ini silakan klik pada kotak “tombol”. [/su_panel] [su_panel border=”3px solid #FF6666″ radius=”10″]

Ada beberapa keunggulan ekosistem Arduino. Antara lain jumlah shield yang cukup banyak yang memudahkan pengguna untuk melakukan implementasi program untuk komponen pada shield ke dalam sistem. Komponen dan shield pun banyak yang sudah dilengkapi dengan pustaka (library). Ini mempercepat proses pengerjaan kode program.

Pustaka seperti ini bukanlah hal yang unik atau aneh. Cara semacam ini sudah lama dikenal dan juga dipakan di ekosistem lain. Misalnya di ekosistem bahasa pemrograman Java, ekosistem Python, ekosistem Perl, ekosistem C++ dan bahkan di ekosistem bahasa C. Dengan adanya pustaka, pemrogram tidak perlu menghabiskan waktu untuk mengulangi membuat kode program yang sama. Sumber dayanya bisa dialihkan untuk mengerjakan hal yang lain dalam penyelesaian masalah.

Untuk pemrograman ekosistem Arduino yang mempergunakan sensor ultrasonik terdapat satu pustaka yang diberi nama NewPing.

newping2.jpgGambar 21. [sumber]

Berikut adalah contoh-contoh kode yang disalin langsung dari situs arduino-new-ping/wiki/.

Gambar 22. Pengujian kode [ps2id url=’#SimpleNewPingSketch’ offset=’300′]Simple NewPing Sketch[/ps2id]

Gambar 23.

Mengenai risiko akurasi dan kestabilan pembacaan untuk peletakan obyek pada Gambar 22, bisa kembali melihat [ps2id url=’#gambar7′ offset=’300′]Gambar 7[/ps2id].

Berikut ini beberapa Gambar proses pengujian beberapa cara untuk melakukan pengukuran jarak obyek dengan sensor ultrasonik.

Gambar 24. Percobaan membandingkan hasil pengukuran alat-alat ukur dan cara pengukuran

Gambar 25. Hasil pengukuran dengan pulseIn (float)

Pada Gambar 25 terlihat bahwa pengukuran jarak obyek dengan menggunakan pulseIn dan pembagian (float), tidak memberikan hasil yang mendekati dua alat ukur lainnya. Hasil dari pengukuran dari alat laser distance meter sama dengan penunjukkan pada tape rule. Jarak terukur 1.2 m (120.5 cm), sedangakan pembacaan sensor ultrasonik oleh program Arduino menunjukkan 153.90 cm.

Adadua kemungkinan, sumber kesalahan ada pada sensor atau ada pada Arduino. Pada sensor bisa jadi resolusi dan/atau akurasi, sedang pada Arduino bisa jadi ada pada hardware atau pada software. Pada software bisa jadi ada pada fungsi/pustaka dari perangkat lunak Arduino atau bisa jadi dari kode program oleh pengguna.

Pengujuan pertama dengan mengganti sensor (Gambar 24), hasilnya sama, nilai kesalahan masih pada kisaran yang sama. Percobaan berikutnya adalah dengan mengganti cara pembacaan dan pengolahan data dari sensor. Perhitungan dilakukan di dalam pustaka, pengguna mendapatkan hasil pengukuran dalam cm.

Gambar 26.

Dengan menggunakan library NewPing, akurasi hasil pengukuran bisa lebih dapat dicapai. Pengukuran dengan sensor ultrasonik menggunakan pustaka NewPing sama dengan hasil pengukuran dua alat lainnya pada setup percobaan yang sama.

Gambar 27. Percobaan pembandingan untuk jarak dekat

[/su_panel] [su_panel border=”3px solid #00C700″ radius=”10″] [intense_tabs direction=”right” active_tab_background_color=”#000000″ active_tab_font_color=”#ffff00″ trigger=”click”] [intense_tab title=”Video01″ border=”3px solid #e8e8e8″ link_target=”_self”  content_background_color=”#000000″ content_font_color=”#ffffff” icon_size=”1″ icon_position=”left”]

[/intense_tab] [intense_tab title=”Video02″ border=”3px solid #e8e8e8″ link_target=”_self” icon_size=”1″  content_background_color=”#000000″ content_font_color=”#ffffff” icon_position=”left”]

[/intense_tab] [intense_tab title=”Video03″ border=”3px solid #e8e8e8″ link_target=”_self” icon_size=”1″ content_background_color=”#000000″ content_font_color=”#ffffff” icon_position=”left”]

[/intense_tab] [intense_tab title=”Video04″ border=”3px solid #e8e8e8″ link_target=”_self” icon_size=”1″ content_background_color=”#000000″ content_font_color=”#ffffff” icon_position=”left”]

[/intense_tab] [intense_tab title=”Video05″ border=”3px solid #e8e8e8″ link_target=”_self” icon_size=”1″ content_background_color=”#000000″ content_font_color=”#ffffff” icon_position=”left”]

[/intense_tab] [/intense_tabs] [/su_panel] [su_panel border=”3px solid #990066″ radius=”10″] [/su_panel]

 

 

Penggunaan PIR (Passive Infrared Sensor) pada sistem Arduino

[ [ images & links ] ]
[su_panel border=”3px solid #F8F800″ radius=”10″]

PIR (Passive infRared) sensor, adalah sensor yang mengukur radiasi infra merah dari suatu obyek. Seperti yang terlihat dari namanya, PIR diketahui bekerja secara pasif, artinya hanya menerima radiasi saja dan tidak memancarkan radiasi. PIR memberikan sinyal saat ada perubahan dari tingkat radiasi infra merah, karenanya PIR dipakai sebagai sensor gerakan. Keterangan lebih jauh bisa dipelajari dari beberapa kutipan berikut:

PIR SensorGambar 3. [sumber]HC-SR501 PIR MOTION SENSORGambar 4. [sumber]proximity_PIRbackLabeled.jpgGambar 5. [sumber]

Gambar 6. [sumber]

Specifications:

  • Operating voltage range: DC 4.5-20V
  • Quiescent Current: <50uA
  • Level output: High 3.3 V /Low 0V
  • Trigger: L can not be repeated trigger/H can be repeated trigger (Default repeated trigger)
  • Delay time: 5-200S(adjustable) the range is (0.xx second to tens of second) 
  • Block time: 1S(default) Can be made a range(0.xx to tens of seconds 
  • Board Dimensions: 32mm*24mm
  • Angle Sensor: <100 ° cone angle
  • Operation Temp: -15℃-+70℃
  • Lens size sensor: Diameter:23mm(Default)

Features:

  • the automatic sensor: to enter the sensor output range is high, people leave the sensor range of the automatic delay off high, output low.
  • the photosensitive control (optional, factory is not set) may set the photosensitive control during the day or light intensity without induction.
  • the temperature compensation (optional, factory is not set): In the summer when the ambient temperature rises to 30 ~ 32 ℃, slightly shorter detection range, temperature compensation can be used as a performance compensation.
  • two trigger mode: (can be selected by jumpers) a, can not repeat the trigger: the sensor output high, the delay time is over, the output will automatically become low from high; b, repeatable trigger: the sensor output high after the delay period, if the human body in its sensing range activities, its output will remain high until after the delay will be left high to low (sensor module review Measured activities of each body will be automatically extended after a delay time, and the final event of the delay time Starting point of time).
  • with induction blocking time (the default setting: 2.5S block time): sensor module, after each sensor output (high change Into a low level),you can set up a blockade followed by time period, in this time period the sensor does not accept any sensor signal. This feature can have a “sensor output time” and “blocking time” the interval between the work produced can be applied to detect the interval Products; also inhibit this function during load switching for a variety of interference. (This time can be set at zero seconds – Tens of seconds).
  • the working voltage range: the default voltage DC4.5V-20V.
  • micro-power consumption: static current “50 microamps, especially for battery-powered automatic control products.
  • the output high level signals: types of circuits can be easily and docking.
  • the working voltage range: the default voltage DC4.5V-20V.
  • the working voltage range: the default voltage DC4.5V-20V.

Instructions:

  • Sensing module for about a minute after power initialization time, during the interval to the output module 0-3 times a minute in standby mode.
  • Should avoid direct lighting such as interference sources close the surface of the lens module so as to avoid the introduction of interference signal generator malfunction; use of the environment to avoid the flow of the wind, the wind sensor will also cause interference.<50uA
  • Sensor module using a dual probe, the probe’s window is rectangular, dual (A per B million) in the direction of the ends of long, when the body passed from left to right or right to left when the reach the dual IR time, distance difference, the greater the difference, more sensitive sensors, when the body from the front to the probe or from top to bottom or from bottom to top direction passing, dual IR not detected changes in the distance, no difference value, the sensor insensitive or does not work; so the sensors should be installed dual direction of the probe with human activities as much as possible parallel to the direction of maximum to ensure that the body has been passed by the dual sensor probe. To increase the sensing range of angles, the module using a circular lens, the probe also makes sense on all four sides, but still higher than the upper and lower left and right direction of sensing range, sensitivity and strong, still as far as possible by the above installation requirements.VCC, trig (control side), echo (receiving end), GND

Note:

  • The potentiometer clockwise to adjust the distance, sensing range increases (about 7 meters), on the contrary, sensing range decreases (about 3 meters).Delay adjustment potentiometer clockwise rotation, sensor delay longer (about 300S), the other hand, induction by the short delay (about 5S).
eBay
  • In the beginning you might notice some seemingly erratic behavior – this is perfectly normal. We need to understand a few things before we can tweak the settings.
  • When connecting the battery, the sensor will take up to 30 to 60 seconds to stabilize (warm up).
  • Place your setup in such a way that there will be no motion and wait until the LED remains OFF.
Testing and Playing with PIR sensors (motion sensor)
[/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

DELAY TIME

SENSITIVITY ADJUST/DETECTING RANGE

Gambar 9. [sumber]

RETRIGER/RETRIGGERING

 

[/su_panel] [su_panel border=”3px solid #FF6666″ radius=”10″]

Testing your PIR with a Battery, LED and a ResistorGambar 10. [sumber]

IMG_0669Gambar 11. [sumber]

Untuk pengujian alat, proses belajar awal dan bahkan untuk tuning, konfigurasi seperti pada Gambar 10 dan Gambar 11 adalah yang paling memudahkan. Tidak ada delay tambahan dari program dan proses lain pada mikrokontroler. Pengguna dapat lebih mudah untuk memperhatikan dan mempelajari respon modul PIR. Pengaturan delay time dan sensitivity menjadi lebih mudah dilakukan dengan cara ini.

Gambar 12.

Contoh pengujuan seperti pada Gambar 12, menggunakan dua indikator bantuan. LED memudahkan kita untuk mengetahui tingkat tegangan sebagai penunjuk langsung kondisi deteksi modul. Kondisi LED yang menyala atau tidak menyala membantu proses analisis program untuk mikrokontroler (dalam hal ini sistem papan Arduino). Seberapa cepat respon program yang kita buat bila dibandingkan dengan kondisi deteksi modul PIR.

Setelah proses pengaturan awal menggunakan cara pada Gambar 10 dan Gambar 11, pemrograman pada Gambar 12 menggunakan kode berikut. Tentu dapat dan perlu dilakukan coba-coba, proses trial & error, tinkering untuk hasil yang sesuai seperti yang dikehendaki.

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

  Mark Bramwell, July 2010

  This program will test the LCD panel and the buttons.When you push the button on the shield,
  the screen will show the corresponding one.
 
  Connection: Plug the LCD Keypad to the UNO(or other controllers)

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

#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel



#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5


const uint8_t INPUT_PIR = 12;

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;


int val = 0; 
uint8_t pirState = LOW;

int read_LCD_buttons()
{               // read the buttons
  adc_key_in = analogRead(0);       // read the value from the sensor 

  // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
  // we add approx 50 to those values and check to see if we are close
  // We make this the 1st option for speed reasons since it will be the most likely result

  if (adc_key_in > 1000) return btnNONE; 

  // For V1.1 us this threshold
  if (adc_key_in < 50)   return btnRIGHT;  
  if (adc_key_in < 250)  return btnUP; 
  if (adc_key_in < 450)  return btnDOWN; 
  if (adc_key_in < 650)  return btnLEFT; 
  if (adc_key_in < 850)  return btnSELECT;  

  // For V1.0 comment the other threshold and use the one below:
  /*
  if (adc_key_in < 50)   return btnRIGHT;  
  if (adc_key_in < 195)  return btnUP; 
  if (adc_key_in < 380)  return btnDOWN; 
  if (adc_key_in < 555)  return btnLEFT; 
  if (adc_key_in < 790)  return btnSELECT;   
  */

  return btnNONE;                // when all others fail, return this.
}


void lcdTest001(void)
{
  lcd.begin(16, 2);               // start the library
  lcd.setCursor(0,0);             // set the LCD cursor   position 
  lcd.print("Uji PIR >>");  // print a simple message on the LCD
}

void lcdShieldTest001(void)
{
  lcd.setCursor(9,1);             // move cursor to second line "1" and 9 spaces over
  lcd.print(millis()/1000);       // display seconds elapsed since power-up

  lcd.setCursor(0,1);             // move to the begining of the second line
  lcd_key = read_LCD_buttons();   // read the buttons

  switch (lcd_key)
  {               // depending on which button was pushed, we perform an action

    case btnRIGHT:
    {             //  push button "RIGHT" and show the word on the screen
      lcd.print("RIGHT ");
      break;
    }
    case btnLEFT:
    {
      lcd.print("LEFT   "); //  push button "LEFT" and show the word on the screen
      break;
    }    
    case btnUP:
    {
      lcd.print("UP    ");  //  push button "UP" and show the word on the screen
      break;
    }
    case btnDOWN:
    {
      lcd.print("DOWN  ");  //  push button "DOWN" and show the word on the screen
      break;
    }
    case btnSELECT:
    {
      lcd.print("SELECT");  //  push button "SELECT" and show the word on the screen
      break;
    }
    case btnNONE:
    {
      lcd.print("NONE  ");  //  No action  will show "None" on the screen
      break;
    }//EOF btnNONE
  }//EOF switch
}//EOF lcdShieldTest001


void pirinit(void)
{
  pinMode(INPUT_PIR, INPUT);     // declare sensor as input
}

/*
  Fungsi adapirtest disalin dari:
  https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor?view=all

*/
void adapirtest(void)
{

  val = digitalRead(INPUT_PIR);  // read input value
  if (val == HIGH) // check if the input is HIGH
  {            

    lcd.clear();
    // digitalWrite(ledPin, HIGH);  // turn LED ON
    lcd.setCursor(0,0);
    lcd.print("val = HIGH");
    if (pirState == LOW) 
    {
      // we have just turned on
      // Serial.println("Motion detected!");
      lcd.setCursor(0,1);
      lcd.print("Motion detected!");
      delay(3000);

      // We only want to print on the output change, not state
      pirState = HIGH;
    }
    delay(1000);
  } 
  else 
  {
    lcd.clear();
    // digitalWrite(ledPin, LOW); // turn LED OFF
    lcd.setCursor(0,0);
    lcd.print("val = LOW");
    if (pirState == HIGH)
    {
      // we have just turned of
      // Serial.println("Motion ended!");
      lcd.setCursor(0,1);
      lcd.print("Motion ended!");
      delay(3000);

      // We only want to print on the output change, not state
      pirState = LOW;
    }
    delay(1000);
  }


}


void setup()
{

  // Serial.begin(9600);

  lcd.begin(16, 2);               // start the library
  lcd.setCursor(0,0);             // set the LCD cursor   position 

  lcdTest001();
  delay(1000);
  lcd.clear();

  pirinit();
}

void loop()
{
  // lcdShieldTest001();
  adapirtest();
  // delay(1000);

}
[/su_panel] [su_panel border=”3px solid #FFD104″ radius=”10″]

[/su_panel] [su_panel border=”3px solid #990066″ radius=”10″] [/su_panel]

Thyristor AC Switch, 3.3V/5V logic, AC 220V/5A (peak 10A)

[ [ images & links ] ]
[su_panel border=”3px solid #66FF00″ radius=”10″]

Unit ketiga yang hendak dikemukakan yang bisa dengan mudah dipergunakan untuk mengendalikan daya adalah unit modul triac (thyristor). Sebelumnya sudah disampaikan penggunaan SSR, relay shield, dan modul dua relai. Modul yang akan dipergunakan adalah seperti yang terlihat di Gambar 1, Gambar 2 dan Gambar 3. Modul ini diproduksi oleh RobotDyn dan sudah bisa dibeli di toko online di lokal Indonesia.

Gambar 1. [sumber]

Gambar 2. [sumber]

Gambar 3. [sumber]

Di modul/papan ini sudah terdapat beberapa komponen pendukung selain komponen utama berupa triac BTA-16 600B, yang terpenting adalah MOC3042. Komponen ini adalah 6-Pin DIP Zero-Cross Optoisolators Triac Driver Output, artinya papan ini hanya bisa bekerja mengikuti pengaturan zero crossing. Salah satu diskusi mengenai mengapa fasilitas zero cross dipergunakan ada di electronics.stackexchange.com.

enter image description hereGambar 4. [sumber]enter image description hereGambar 5. [sumber]

 

Dikutip dari halaman RobotDyn:

If you need to control the AC power (lights, home equipment’s), a thyristor is what you need. This is a very common thyristor module with very low on-resistance and a control voltage, that is compatible with any 3.3V or 5V micro-controller or mechanical switch. This allows you to control high-power devices with very low-power control mechanisms.
This board has an optoisolator to protect your micro-controller from high AC currents.
We also left more space, if you need to install the heat sink for thyristor.

  • GND to GND
  • Signal (VCC) to Digital I/O, or 3.3V~5V

[/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

Pengujian dengan Arduino Uno.

Gambar 6.

const uint8_t IND_LED_PIN = LED_BUILTIN;
const uint16_t DELAY02 = 2000; 

#define BLINK_DELAY 500

#define TRIAC_ON HIGH
#define TRIAC_OFF LOW

#define LED_PORT PORTD
#define LED_ARRAY_GND 6
#define LED_ARRAY_LAST (LED_ARRAY_GND-6)
#define LD1 (LED_ARRAY_GND-1)
#define LD2 (LED_ARRAY_GND-2)
#define LD3 (LED_ARRAY_GND-3)
#define LD4 (LED_ARRAY_GND-4)
#define LD5 (LED_ARRAY_GND-5)
#define LD6 (LED_ARRAY_GND-6)

#define KY1 13
#define KY2 (LED_ARRAY_GND-1)
#define KY3 (LED_ARRAY_GND-2)
#define KY4 (LED_ARRAY_GND-3)

#define SIG A0


int buttonState = 0; // variable for reading the pushbutton status
uint8_t btn1, btn2, btn3, btn4; 


void buttonSafeInit(void)
{
  for (int i = KY1; i >= KY4; i--)
  {
    pinMode(i, INPUT);
    delay(1);
  }

  for (int i = KY1; i >= KY4; i--)
  {
    digitalWrite(i, HIGH);
    delay(1);
  }  
}

void ledArrayInit(void)
{
  // Urutan (eksekusi) kode dalam fungsi ini jangan ditukar;

  digitalWrite(LED_ARRAY_GND,HIGH);
  
  for (int i = LD1; i >= LD6; --i)
  {
    digitalWrite(i, LOW);
    delay(1);
  } 
   
  for (int i = LED_ARRAY_GND; i >= LED_ARRAY_LAST; --i)
  {
    pinMode(i, OUTPUT);
  } 

  // LOW yang kedua
  for (int i = LED_ARRAY_GND; i >= LED_ARRAY_LAST; --i)
  {
    digitalWrite(i, LOW);
  }  
}  

void ledBlinkTest(void)
{
  for (int i = LD1; i >= LED_ARRAY_LAST; --i)
  {
    digitalWrite(i, HIGH);
    delay(100);
  }  
  delay(500);
  for (int i = LD1; i >= LED_ARRAY_LAST; --i)
  {
    digitalWrite(i, LOW);
    delay(100);
  }  
}

void safeTRIACinit(void)
{
  digitalWrite(SIG, LOW);
  delay(100);
  pinMode(SIG, OUTPUT);
}

void triacTest001(void)
{
  digitalWrite(SIG, LOW);
  delay(2000);
  digitalWrite(SIG, HIGH);
  delay(2000);
}

void triacTest002(void)
{
  digitalWrite(SIG, TRIAC_ON);
  delay(DELAY02);
  digitalWrite(SIG, TRIAC_OFF);
  delay(DELAY02);
}

void triacTest003(void)
{
  digitalWrite(SIG, TRIAC_ON);
  LED_PORT |= (0b00111111);
  delay(DELAY02 * 2);
  digitalWrite(SIG, TRIAC_OFF);
  LED_PORT &= ~(0b00111111);
  delay(DELAY02);
}

void setup(void)
{
  safeTRIACinit();
  // delay(2);

  buttonSafeInit();
  // delay(2);

  ledArrayInit();
  // delay(2);

  pinMode(IND_LED_PIN, OUTPUT);
  digitalWrite(IND_LED_PIN, LOW);
  delay(200);
}


void loop(void)
{
  delay(1000);
  digitalWrite(IND_LED_PIN, HIGH);
  delay(1000);
  
  // ledBlinkTest();

  triacTest003();

  digitalWrite(IND_LED_PIN, LOW);
}
[/su_panel] [su_panel border=”3px solid #FF6666″ radius=”10″]

Gambar 7.

Gambar 8.

[/su_panel]
[su_panel color=”#010101″ border=”0px none #cccccc” shadow=”0px 0px 0px #ffffff” text_align=”center”]

BTA16 600B en.CD00002265 by Sunu Pradana on Scribd

[/su_panel] [su_panel border=”3px solid #990066″ radius=”10″]

[/su_panel]

Modul solid state relay

Mengenai EMR (Electromechanical Relay) telah dicatatkan di dua post terdahulu, di link ini dan di link ini. Dalam post ini akan diungkap mengenai penggunaan SSR (Solid State Relay).

Ada banyak tipe dan instalasi SSR, salah satu modul yang cukup mudah ditemui dalam bidang elektronika adalah seperti pada Gambar 1 dan Gambar 2.

Gambar 1.

http://artofcircuits.com/wp-content/uploads/2016/06/1-CH-2A-240VAC-SSR-Module-2.jpgGambar 2. [sumber]

Gambar 3. [sumber]

Pada tabel di Gambar 3 (screenshot dari datasheet) bisa dilihat bahwa tipe G3MB ini sudah discontinued, artinya secara resmi sebenarnya produksinya telah dihentikan oleh produsennya. Di sana tabel yang sama juga bisa dilihat bahwa ada dua jenis SSR tipe ini, yang menggunakan zero crossing dan yang tidak (disebut juga random turn-on). Jenis G2MB-202P adalah jenis yang di dalamnya terdapat zero cross.

Gambar 4. [sumber]

Sekadar sebagai gambaran untuk mempermudah membayangkan cara kerja SSR, dapat dilihat rangkaian pada Gambar 4. Prinsip/dasar kerjanya tidaklah rumit, triac berfungsi sebagai sakelar utama, dibantu oleh phototriac sebagai sakelar yang menghubungkan antara input dengan sakelar utama. Phototriac memberikan isolasi galvanis, artinya input (misalnya dari Arduino) tidak terhubung langsung secara elektrikal dengan triac.

Jika suatu saat diperlukan atau dikehendaki prinsip blok rangkaian pada Gambar 4 bisa diwujudkan dengan komponen-komponen distrik seperti pada Gambar 5. Namun untuk banyak keperluan modul SSR yang sudah dalam bentuk yang terintegrasi lebih memudahkan, seperti pada Gambar 6 yang merupakan komponen utama dari papan pada Gambar 1 dan Gambar 2.

Image result for omron g3mbGambar 5. [sumber]

Gambar 6. [sumber]

SSRGambar 7. [sumber]

Rangkaian papan SSR pada [ps2id url=’#gambar2′ offset=’300′]Gambar 2[/ps2id] dapat lebih mudah dipahami dengan melihat pada Gambar 7. Semua komponen terdapat di papan SSR (lihat Gambar 2), tidak diperlukan lagi komponen tambahan. Tiga masukan berasal dari pengendali digital, semisal papan Arduino M0 atau GPIO Raspberry Pi atau papan TI Launchpad. Polaritas catu daya jangan sampai terbalik meskipun di papan telah dipasang diode.

Gambar 8. Ringkasan spesifikasi papan SSR Omron G3MB [sumber]

Gambar-gambar berikut adalah contoh penerapan papan SSR.

Image result for arduino ssrGambar 9. [sumber]Image result for arduino ssr ACGambar 10. [sumber]Image result for arduino omron ssr wiring ACGambar 11. [sumber]

Gambar 11.

Uji coba untuk melakukan pemrograman pengujian awal bisa dilakukan dengan konfigurasi DC seperti pada Gambar 11. Meski harus tetap diingat bahwa SSR ini adalah untuk beban AC (lihat [ps2id url=’#gambar6′ offset=’300′]Gambar 6[/ps2id]), bukan beban DC. Sehingga meskipun SSR sudah dimatikan (off) tetap ada aliran arus DC ke beban.

const uint8_t IND_LED_PIN = LED_BUILTIN;
const uint16_t DELAY02 = 2000; 

#define BLINK_DELAY 500

#define SSR_ON HIGH
#define SSR_OFF LOW

#define LED_SRC 7

#define CH1 8
#define CH2 9




void safeSSRinit(void)
{
  digitalWrite(CH1, LOW);
  digitalWrite(CH2, LOW);
  delay(100);
  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
}


void ssrTest001(void)
{
  digitalWrite(CH1, LOW);
  delay(2000);
  digitalWrite(CH1, HIGH);
  delay(2000);

  digitalWrite(CH2, LOW);
  delay(2000);
  digitalWrite(CH2, HIGH);
  delay(2000);  
}

void ssrTest002(void)
{
  digitalWrite(CH1, SSR_ON);
  delay(DELAY02);
  digitalWrite(CH1, SSR_OFF);
  delay(DELAY02);
}

void testPola01(void)
{
  digitalWrite(LED_SRC, HIGH);
  ssrTest002();
  digitalWrite(LED_SRC, LOW);
}

void testPola02(void)
{
  digitalWrite(LED_SRC, HIGH);

  digitalWrite(CH1, SSR_ON);
  delay(DELAY02);
  digitalWrite(LED_SRC, LOW);
  delay(DELAY02);
  digitalWrite(CH1, SSR_OFF);
  delay(DELAY02);

  digitalWrite(LED_SRC, LOW);
}

void testPola03(void)
{
  delay(DELAY02);
  digitalWrite(IND_LED_PIN, HIGH);
  delay(DELAY02);
  digitalWrite(CH1, SSR_ON);
  delay(DELAY02);  
  digitalWrite(LED_SRC, HIGH);
  delay(DELAY02);
}

void testPola04(void)
{
  digitalWrite(LED_SRC, LOW);
  delay(DELAY02);
  digitalWrite(CH1, SSR_ON);
  delay(DELAY02);
  digitalWrite(LED_SRC, HIGH);
  delay(DELAY02);
  digitalWrite(CH1, SSR_OFF);
  delay(DELAY02);
  digitalWrite(LED_SRC, LOW);
}

void setup(void)
{
  safeSSRinit();
  delay(10);

  pinMode(LED_SRC, OUTPUT);
  digitalWrite(LED_SRC, LOW);

  pinMode(IND_LED_PIN, OUTPUT);
  digitalWrite(IND_LED_PIN, LOW);

  delay(1000);
  digitalWrite(IND_LED_PIN, HIGH);
  delay(1000);
  
  // ssrTest001();

  for (int i = 0; i < 3; ++i)
  {
    /* code */
    // ssrTest002();
    // testPola01();
    // testPola02();
    // testPola03();
    testPola04();
  } 
  digitalWrite(IND_LED_PIN, LOW);
}


void loop(void)
{

}

Dengan kode yang sama, bisa dilakukan pengujian untuk beban AC seperti pada Gambar 12 dengan daya AC, tegangan listrik sebesar kurang-lebih 220 V dari jala-jala PLN. Hasil unjuk kerja akan berbeda dengan percobaan pada Gambar 11 (beban DC). Pada pengendalian beban AC, pemutusan berlangsung seperti yang seharusnya sebab kondisi latching dan (terutama) holding akan terhenti saat nilai arus turun menuju crossing.

Gambar 12.

[su_panel color=”#010101″ border=”0px none #cccccc” shadow=”0px 0px 0px #ffffff” text_align=”center”]

Solid State Relay G3MB by Sunu Pradana on Scribd

[/su_panel]

Untuk mempelajari lebih lanjut tentang pengoperasian SSR, silakan membaca dokumen dan artikel berikut:

 

Modul dua relay

Sebelumnya saya sudah membuat catatan tentang Arduino shield yang berisi empat relay. Di pasaran lokal, pembeli perlu cermat karena rating relay bisa jadi tidak sesuai dengan aplikasi yang direncanakan.

Gambar 1.

Kali ini adalah catatan tentang papan relay (relai) seperti pada Gambar 1. Rating relai dapat dibaca di bagian atas masing-masing relai, untuk kemudian bisa dibandingkan dengan datasheet yang sesuai. Yang sangat penting diperhatikan adalah mengenai single-line header yang tampak sebagai selection jumper pada bagian kiri dari Gambar 1. Di sana tertulis JD-VCC, VCC dan GND. Lebih detail bisa dilihat pada Gambar 2.

Gambar 2. [sumber]

Posisi jumper secara default dari awal adalah terhubung antara JD-VCC dengan VCC. Konfigurasi ini berarti catu daya untuk optocoupler, transistor BJT dan relai berasal dari catu daya VCC yang sama untuk pemberian sinyal ke optocouler. Perlu berhati-hati VCC pada header ini secara elektris terhubung dengan header VCC untuk masukkan, bisa dilihat langsung pada bagian bawah PCB. Begitu pula GND pada header yang sama.

Gambar 3. [sumber]

Gambar 3 menyampaikan informasi yang sama dengan cara yang berbeda. Di sini bagian GND pada header dihilangkan sehingga jelas bahwa jumper itu bukanlah selector-jumper. Jangan menghubungkan antara VCC dengan GND! Fungsi pin GND pada header itu adalah untuk penyambungan ke sumber catu daya lain. Dua kabel yang perlu disambungkan adalah JD-VCC dan GND, sehingga GND dari catu daya ini akan terhubung dengan GND pada papan pengendali (mikrokontroler seperti ATmega328P atau sistem Arduino).

 

Dari situs http://howtomechatronics.com, bisa juga dilihat gambar yang memberi keterangan tentang sambungan daya.

Gambar 4. Menggunakan catu daya Arduino [sumber]

Gambar 5. Menggunakan catu daya terpisah (sambungkan juga GND) [sumber]

Gambar 6. Papan sistem menggunakan active-low [sumber]

Keterangan yang lebih baik bisa diperoleh langsung dari situs aslinya di link ini: howtomechatronics.com .

Berdasar pengetahuan yang diperoleh dari Gambar 6, kita bisa melakukan pengaturan pada kode progam sehingga penggunaan relai tidak terganggu dengan kode program yang janggal atau tidak natural.

const uint8_t IND_LED_PIN = 1;
#define BLINK_DELAY 500
#define RELAY_ON LOW
#define RELAY_OFF HIGH
#define IN1 3
#define IN2 4


void safeRelayInit(void)
{
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  delay(100);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}


void relayTest001(void)
{
  digitalWrite(IN1, LOW);
  delay(2000);
  digitalWrite(IN1, HIGH);
  delay(2000);

  digitalWrite(IN2, LOW);
  delay(2000);
  digitalWrite(IN2, HIGH);
  delay(2000);  
}

void relayTest002(void)
{
  digitalWrite(IN1, RELAY_ON);
  delay(1000);
  digitalWrite(IN1, RELAY_OFF);
  delay(1000);

  digitalWrite(IN2, RELAY_ON);
  delay(1000);
  digitalWrite(IN2, RELAY_OFF);
  delay(1000);  
}

void setup(void)
{
  safeRelayInit();
  delay(10);


  pinMode(IND_LED_PIN, OUTPUT);
  digitalWrite(IND_LED_PIN, LOW);

  

  delay(1000);
  digitalWrite(IND_LED_PIN, HIGH);
  delay(1000);
  
  // relayTest001();

  for (int i = 0; i < 2; ++i)
  {
    /* code */
    relayTest002();
  } 


  digitalWrite(IND_LED_PIN, LOW);

}


void loop(void)
{

}

Gambar 7. Papan SRD-05VDC-SL-C

Gambar 8.

[su_panel color=”#010101″ border=”0px none #cccccc” shadow=”0px 0px 0px #ffffff” text_align=”center”]

SONGLE SRD relay by Sunu Pradana on Scribd

[/su_panel]

Key button & LED

Untuk belajar maupun untuk pengujian program, secara berurutan yang sering secara sederhana diperlukan adalah LED, push-button/key, dan potensiometer. Selain perangkat lunak simulator dan komunikasi serial (via USB), indikator hardware sering mempermudah proses pembuatan program. Itulah gunanya LED. Berikutnya adalah push button/keys, yang berguna sebagai masukan (input) digital. Tombol-tombol/anak kunci itu sebenarnya bisa diganti dengan kabel, tetapi cara itu bisa jadi tidak praktis dan tidak rapi. Sedangkan yang terakhir, potensiometer, adalah pengganti yang cukup baik untuk banyak sensor dengan output berupa tegangan analog.

Sekarang, modul/papan LED dan push-button sudah banyak dijual dalam bentuk yang lebih praktis untuk dipergunakan. Salah satunya ditampilkan di halaman ini, lihat Gambar 1.

aeProduct.getSubject()Gambar 1. [sumber]

Modul seperti Gambar 1 sudah dijual di toko online lokal, jadi yang berminat tidak harus membelinya langsung Aliexpress.

aeProduct.getSubject()Gambar 2. [sumber]

Penggunaan modul LED tidak berisiko mendatangkan masalah yang fatal. Papan LED sudah dilengkapi dengan resistor pembatas arus sebesar 1 KOhm, seperti yang bisa dilihat pada Gambar 2.

Hal yang berbeda dengan push button/key. Bisa diperhatikan pada Gambar 3 dan [ps2id url=’#gambar4′ offset=’300′]Gambar 4[/ps2id], papan ini tidak memiliki bantuan perlindungan apapun, hanya berisi sakelar saja.

aeProduct.getSubject()Gambar 3. [sumber]

aeProduct.getSubject()Gambar 4. [sumber]

Untuk menjaga keselamatan alat (papan sistem Arduino), ada baiknya sebelum menggunakan papan sakelar, pengguna terlebih dahulu mempelajari hal-hal yang berisiko dapat merusak sistem papan Arduino. Beberapa tulisan yang berisi hal-hal yang harus dihindari saya kumpulkan sebagai berikut:

Dari membaca halaman-halaman pada tautan di atas ada beberapa pembahasan mengenai hal yang sama. Justru di situlah salah satu letak keutamaan belajar, melihat berbagai sudut pandang dan pengalaman orang lain mengenai suatu hal/permasalahan. Salah satu yang penting untuk diketahui adalah menghindari arus lebih pada pin, port dan sistem papan Arduino.

Penting untuk mengetahui bagaimana menjadikan suatu pin di papan Arduino sebagai INPUT (bukan OUTPUT) dan bagaimana menggunakan pull-up untuk pin itu.

Dari dua bagian kumpulan tautan di atas, kita bisa belajar tentang bahaya kesalahan penggunaan tombol/sakelar/push button/key pada sistem Arduino. Selanjutnya bagaimana memanfaatkan pin pada papan Arduino sebagai masukan dan bagaimana melakukan konfigurasi yang sesuai dengan pull-up. Juga disinggung bagaimana konsep internel pull-up di sistem mikrokontroler yang lain, sekadar sebagai pembanding.

Berikut, di bawah ini adalah kode dari halaman Aliexpress mengenai penggunaan papan LED dan keys. Dengan pemahaman sebelumnya tentang keamanan dan internel pull-up, kode ini menjadi lebih mudah dipahami.

	
/*
	Format ulang dari kode pada:
	Aliexpress https://goo.gl/wYK6mi

	Ardiuno_4key_6led
	 
	This example code is in the public domain.
*/
 
// Define key pin
int K1 = 13;
int K2 = 12;
int K3 = 11;
int K4 = 10;
// Define led pin
int GND = 6;
int D1 = 5;
int D2 = 4;
int D3 = 3;
int D4 = 2;
int D5 = 1;
int D6 = 0;
 
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
uint8_t btn1, btn2, btn3, btn4; 
 
// the setup routine runs once when you press reset:
void setup() 
{
	// initialize the keys pin as an input.	 
	// pinMode(K1, INPUT);
	// pinMode(K2, INPUT);
	// pinMode(K3, INPUT);
	// pinMode(K4, INPUT);

	for (int i = K1; i >= K4; i--)
	{
		pinMode(i, INPUT);
	}
	 
	// initialize the leds pin as an output.
	// pinMode(GND, OUTPUT);
	// pinMode(D1, OUTPUT);
	// pinMode(D2, OUTPUT);
	// pinMode(D3, OUTPUT);
	// pinMode(D4, OUTPUT);
	// pinMode(D5, OUTPUT);
	// pinMode(D6, OUTPUT);

	pinMode(GND, OUTPUT);
	for (int i = D1; i >= D6; i--)
	{
		pinMode(i, OUTPUT);
	}
	 
	/*
		PERHATIKAN BAGIAN KODE INI
	*/
	//Activate key pin internal pull-up resistors
	digitalWrite(K1, HIGH);
	digitalWrite(K2, HIGH);
	digitalWrite(K3, HIGH);
	digitalWrite(K4, HIGH);

	// for (int i = K1; i >= K4; i--)
	// {
	// 	pinMode(i, HIGH);
	// }	 
	 
	//as LED GND
	digitalWrite(GND, LOW);
}
 
// the loop routine runs over and over again forever:
void loop() 
{
 
	btn1 = digitalRead(K1);
	buttonState = btn1;
	digitalWrite(D1, buttonState); //
	 
	btn2 = digitalRead(K2);
	buttonState = btn2;
	digitalWrite(D2, buttonState); //
	 
	buttonState = btn3 =  digitalRead(K3);
	// buttonState
	digitalWrite(D3, buttonState); //
	 
	btn4 = buttonState = digitalRead(K4);
	// buttonState
	digitalWrite(D4, buttonState); //
	
	// delay(2000); 
	 
	// digitalWrite(D5, HIGH); // turn the LED on (HIGH is the voltage level)
	// digitalWrite(D6, HIGH); // turn the LED on (HIGH is the voltage level)
	digitalWrite(D5, buttonState); // turn the LED on (HIGH is the voltage level)
	digitalWrite(D6, btn2); // turn the LED on (HIGH is the voltage level)
	
	// delay(2000); 
}
 
    
 //******************************************************//

Sebagai bonus dan penutup, berikut adalah tautan ke tulisan-tulisan yang bagus mengenai bouncing, debounce/debouncing. Bisa dibaca jika diperlukan, bahan-bahan sudah diurutkan dari pemahaman dasar umum ke tingkat yang lebih advance.

 

nRF24L01

[ [ images, codes & links ] ]
[su_panel border=”3px solid #66FF00″ radius=”10″]

Ada banyak sumber belajar mengenai nRF24L01 di Internet, dalam berbagai format. Halaman ini hanya merangkum sebagian kecil di antaranya. Lebih lanjut silakan mengikuti link yang sudah disediakan.

Gambar 1. nRF24L01 [sumber]

RF24013.jpgGambar 2. nRF24L01 [sumber]

Gambar 3. nRF24L01 [sumber]

Gambar 4. nRF24L01 [sumber]

Gambar 5. [sumber]

Gambar 6. [sumber]

Gambar 7.

NRF24L01 2.4GHz wireless module with an ArduinoGambar 8. [sumber]

Gambar 9. [sumber]

Gambar 10. [sumber]

NOTE: These units VCC connection must go to 3.3V not 5.0V, although the Arduino itself may run at 5.0V and the signals will be OK. The NRF24L01+ IC is a 3.3V device, but its I/O pins are 5 V tolerant , which makes it easier to interface to Arduino/YourDuino.
Arduino UNO and earlier versions have a 3.3V output that can run the low-power version of these modules (See Power Problems at the top of this page!), but the high-power versions must have a separate 3.3V supply or use a Base Module with a 3.3V regulator. The YourDuino RoboRED has a higher power 3.3V regulator and can be used to run the high-power Power Amplifier type module without a separate 3.3V regulator. ~arduino-info.wikispaces.com

If you scroll through the RF24 library documentation, you will notice that there are many parameters that can be set.  Some key parameters are

  • Channel: the specific frequency channel that communication will occur on (frequencies are mapped to integers between 0 and 125
  • Reading pipe: the reading pipe is a unique 24, 32, or 40-bit address from which the module reads data
  • Writing pipe: the writing pipe is a unique address to which the module writes data
  • Power Amplifier (PA) level: the PA level sets the power draw of the chip and thereby the transmission power.  For the purposes of this tutorial (use with the Arduino) we will use the minimum power setting.  

The RF24 library documentation page provides some great example code for getting started with the library.  The example projects can be found here: http://tmrh20.github.io/RF24/examples.html  ~DevicePlus

[/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

Keseluruhan dari keterangan dalam kotak ini dikutip dari
https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo :

RF24 LIBRARIES: Commonly Used Commands (Methods):

NOTE: If you wish, see ALL the details HERE.
We will try to understand the commands to set up and operate an nRF24L01 radio and build a very simple working example.
First we will look at the minimum needed to set up and transmit or receive data. Later we will write more complete examples and get them working with real radios..

CREATE AND START UP A RADIO (For either transmit or receive):

RF24 (uint8_t _cepin, uint8_t _cspin) Create a radio and set the Arduino pins to be used for CE and CS)

EXAMPLE: (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (7,8); “myRadio” is the identifier you will use in the following examples

NOTE: The following pins are fixed and unchangeable. AND Vcc (supply voltage MUST be 3.3V)
SCK to Arduino pin 13
MOSI to Arduino pin 11
MISO to Arduino pin 12

NOTE: In all following commands, you must use the same identifying name you used in the RF24 statement that created the radio. (“myRadio” in the example above) You will use that identifier followed by (dot) followed by the method (command), followed by parameters. This is “object oriented programming”. The OBJECT in this case is the Radio, and there are many METHODS that can operate on the Object. A METHOD is much like a Function or a Subroutine.

EXAMPLE: myRadio.begin(); Start up the actual radio module with the “begin” method

NOTE: “PIPES” : This is often confusing. nRF24L01 uses “pipes” that connect from transmitter to receiver. Pipes have an address you need to set. The Transmitter pipe must have the same address as the Receiver pipe. Later it’s possible to use multiple “pipes” at once


EXAMPLE OF RECEIVING DATA:

myRadio.openReadingPipe (1, const uint8_t *address) Pipe number (usually 1), pipe address (which is usually 5 bytes in an array structure).

EXAMPLE:
byte addresses[][6] = {“1Node”}; Create address for 1 pipe.
myRadio.openReadingPipe(1, addresses[0]); Use the first entry in array ‘addresses’ (Only 1 right now)

myRadio.startListening (); Turn on the receiver and listen for received data. You MUST have opened a reading pipe FIRST.

if( myRadio.available()) Check for available incoming data from transmitter
{
while (myRadio.available()) While there is data ready
{
myRadio.read( &myData, sizeof(myData) ) ; Get the data payload (You must have defined that already!)
}
myRadio.stopListening(); stop listening


EXAMPLE OF TRANSMITTING DATA:
byte addresses[][6] = {“1Node”}; Create address for 1 pipe.
myRadio.openWritingPipe(1, addresses[0]); Use the first entry in array ‘addresses’ (Only 1 right now)

myRadio.write( &myData, sizeof(myData) )


We have written working examples of Transmit and Receive sketches using these methods. See them HERE


SET SOME OTHER OPERATING OPTIONS AND PARAMETERS:

NOTE: Many of these methods have default values you can usually use.

radio.printDetails();
Prints out a LOT of debugging information.


radio.setDataRate(RF24_250KBPS);
speed RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps. 250K Bits per second gives longest range.


radio.setPALevel(RF24_PA_MAX);
Set Power Amplifier (PA) level to one of four levels: RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX
The power levels correspond to the following output levels respectively: NRF24L01: -18dBm, -12dBm,-6dBM, and 0dBm
0 dBm is equal to 1 milliwatt. Each 3 dB is a 2:1 ratio. 6 dB is 4:1 10 dB is 10:1 So -18 dBm is 0.0000158489 watts !
To calculate all this dBm Stuff (Which us old Radio Engineers love) See THIS..
The “High Power” nRF24L01 modules like THIS have a gain of 100, so their output is +20 dBm (100 milliwatts)


radio.setChannel(108);

Which RF channel to communicate on, 0-124 Can operate on frequencies from 2.400GHz to 2.524GHz.
Programming resolution of channel frequency is 1Mhz
This is the same unlicensed band WiFi operates in (WiFi uses 2.400 to 2.500 gHz). Usually frequencies above channel 100 are best.
NOTE: In most countries the allowed frequencies are from 2.400GHz to 2.483.5GHz which you must not exceed. In USA it’s best to use channels from 70 to 80.

You can scan the channels in your environment to find a channel that is clear… See this Scanner sketch.


radio.enableDynamicPayloads();

Enable custom length payloads on the acknowledge packets. Ack payloads are a handy way to return data back to senders without manually changing the radio modes on both units.


radio.setRetries(15,15);

Set the number and delay of retries upon failed transmit. Parameters:
delay: How long to wait between each retry, in multiples of 250us, max is 15. 0 means 250us, 15 means 4000us.
count: How many retries before giving up, max 15


radio.setCRCLength(RF24_CRC_16);

length: RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit Cyclic Redundancy Check (Error checking)


[/su_panel] [su_panel border=”3px solid #FF6666″ radius=”10″]
[/su_panel] [su_panel border=”3px solid #00C700″ radius=”10″]

Gambar 11.

Gambar 12.

Gambar 13.

Gambar 14. [sumber]

http://www.pighixxx.com/test/wp-content/uploads/2014/11/nano.pngGambar 15.

Gambar 16.

Kode uji pengiriman sederhana #01. Sender :

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>



// uint8_t sVal = 0;

RF24 myRadio(9, 10);
byte addresses[][6] = {"1Nodx"}; // Create address for 1 pipe.
// const uint64_t pipe = 0xE8E8F0F0E1LL;

void setup(void) 
{
  delay(2000);
  myRadio.begin();
  myRadio.setChannel(108);  // Above most Wifi Channels
  myRadio.setPALevel(RF24_PA_MIN);
  
  myRadio.openWritingPipe( addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  // radio.openWritingPipe(pipe);
}

void loop(void)
{
  for(int i=0; i<100; i++)
  {
    // myRadio.write(&sVal, sizeof(sVal));
    myRadio.write(&i, sizeof(i));
    delay(400);   
      
  }
}

Kode uji pengiriman sederhana #01. Receiver :

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Addr, En, Rw, Rs, d4, d5, d6, d7, backlighpin, polarity

RF24 myRadio(9, 10);
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
// const uint64_t pipe = 0xE8E8F0F0E1LL;
int nilaiTerkirim;

void setup(void) 
{
  lcd.off();
  Serial.begin(115200);

  myRadio.begin();
  myRadio.setChannel(108);  // Above most Wifi Channels
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)  
  // radio.openReadingPipe(1, pipe);

  myRadio.startListening();

  lcd.on();
  lcd.begin(16, 2);
  lcd.backlight();
  lcd.clear();
  lcd.print("Uji nRF24L01 ...");
  delay(1000);
  lcd.clear();
  lcd.print("Starting ...");
  delay(2000);
  lcd.clear();
}

void loop(void)
{
  if ( myRadio.available() )
  {
    while (myRadio.available())
    {
      myRadio.read(&nilaiTerkirim, sizeof(nilaiTerkirim));
//      lcd.clear();
//      delay(500);
      lcd.setCursor(0, 0);
      lcd.print("Nilai: ");
      lcd.print(nilaiTerkirim);

      delay(400);
    }
  }
  else
  {
    lcd.setCursor(0, 0);
    lcd.print("No radio");
    delay(1000);
  }

//  delay(200);
  lcd.clear();
}

Kode dimodifikasi dari:

[/su_panel] [su_panel border=”3px solid #FFCC33″ radius=”10″]

Kode uji pengiriman sederhana #02. Sender :

/* 
	M O D I F I E D code

  Beberapa bagian kode di bawah ini telah diubah. 
  Untuk melihat kode aslinya silakan membuka situs asal.

	YourDuinoStarter Example: Simple nRF24L01 Transmit
  - WHAT IT DOES: Transmits simple fixed data with nRF24L01 radio
  - SEE the comments after "//" on each line below
   Start with radios about 4 feet apart.
  - SEE the comments after "//" on each line below
  - CONNECTIONS: nRF24L01 Modules See:
  http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
  Uses the RF24 Library by TMRH2o here:
  https://github.com/TMRh20/RF24
   1 - GND
   2 - VCC 3.3V !!! NOT 5V
   3 - CE to Arduino pin 9 //Telah diubah
   4 - CSN to Arduino pin 10 //Telah diubah
   5 - SCK to Arduino pin 13
   6 - MOSI to Arduino pin 11
   7 - MISO to Arduino pin 12
   8 - UNUSED

   V1.02 02/06/2016
   Questions: terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <SPI.h>   // Comes with Arduino IDE
#include "RF24.h"  // Download and Install (See above)



/*-----( Declare Constants and Pin Numbers )-----*/


/*-----( Declare objects )-----*/
// (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (9, 10); // "myRadio" is the identifier you will use in following methods
/*-----( Declare Variables )-----*/
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
int dataTransmitted;  // Data that will be Transmitted from the transmitter

void setup()   /****** SETUP: RUNS ONCE ******/
{
  // Use the serial Monitor (Symbol on far right). Set speed to 115200 (Bottom Right)
  Serial.begin(115200);
  delay(1000);
  Serial.println(F("RF24/Simple Transmit data Test"));
  // Serial.println(F("Questions: terry@yourduino.com"));
  Serial.println(F("Questions: RTFM"));

  dataTransmitted = 10; // Arbitrary known data to transmit. Change it to test...
  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MIN);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

  myRadio.openWritingPipe( addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  delay(1000);
}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  myRadio.write( &dataTransmitted, sizeof(dataTransmitted) ); //  Transmit the data

  Serial.print(F("Data Transmitted = "));
  Serial.print(dataTransmitted);
  Serial.println(F(" No Acknowledge expected"));
  dataTransmitted = dataTransmitted + 1;  // Send different data next time
  delay(500);

}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/



//*********( THE END )***********

Kode uji pengiriman sederhana #02. Receiver :

/* 

  Beberapa bagian kode di bawah ini telah diubah. 
  Untuk melihat kode aslinya silakan membuka situs asal.

  YourDuinoStarter Example: Simple nRF24L01 Receive
  - WHAT IT DOES: Receives simple fixed data with nRF24L01 radio
  - SEE the comments after "//" on each line below
   Start with radios about 4 feet apart.
  - SEE the comments after "//" on each line below
  - CONNECTIONS: nRF24L01 Modules See:
  http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
  Uses the RF24 Library by TMRH2o here:
  https://github.com/TMRh20/RF24
   1 - GND
   2 - VCC 3.3V !!! NOT 5V
   3 - CE to Arduino pin 9 //Telah diubah
   4 - CSN to Arduino pin 10 //Telah diubah
   5 - SCK to Arduino pin 13
   6 - MOSI to Arduino pin 11
   7 - MISO to Arduino pin 12
   8 - UNUSED

   V1.02 02/06/2016
   Questions: terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <SPI.h>   // Comes with Arduino IDE
#include "RF24.h"  // Download and Install (See above)
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants and Pin Numbers )-----*/
//None yet
/*-----( Declare objects )-----*/
// (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (9, 10); // "myRadio" is the identifier you will use in following methods
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Addr, En, Rw, Rs, d4, d5, d6, d7, backlighpin, polarity

/*-----( Declare Variables )-----*/
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
int dataReceived;  // Data that will be received from the transmitter

void setup()   /****** SETUP: RUNS ONCE ******/
{
  delay(100);
  // Use the serial Monitor (Symbol on far right). Set speed to 115200 (Bottom Right)
  Serial.begin(115200);
  delay(100);
  Serial.println(F("RF24/Simple Receive data Test"));
  Serial.println(F("Q: RTFM dude"));

  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MIN);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();

  delay(200);
  lcdInit();

}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
//  lcd.clear();

  if ( myRadio.available()) // Check for incoming data from transmitter
  {
    while (myRadio.available())  // While there is data ready
    {
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!)
    }
    // DO something with the data, like print it
    Serial.print("Data received = ");
    Serial.println(dataReceived);

    lcdDisp(dataReceived);

  } //END Radio available
  else
  {
    lcd.clear();
    // lcd.setCursor(0, 0);
    lcd.print("No radio");
    delay(1000);
    lcd.clear();
  }

}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/
void lcdInit()
{
  lcd.begin(16, 2);

  lcd.backlight();
  lcd.clear();

  lcd.print("Uji nRF24L01 ...");
  delay(1000);
  lcd.clear();
  lcd.print("Mulai ...");
  delay(2000);

  lcd.clear();

}

void lcdDisp(int dataIN)
{

  lcd.setCursor(0, 0);
  lcd.print("Nilai: ");
  lcd.print(dataIN);
  delay(500);
}


//None yet
//*********( THE END )***********

Gambar 17.

Kode dimodifikasi dari:

[/su_panel] [su_panel border=”3px solid #990066″ radius=”10″]
Sumber belajar:
[/su_panel]

 

I²C LCD

[ [ images & links ] ]
[su_panel border=”3px solid #D34EE4″ radius=”10″]

Gambar 1.

Gambar 2.

Image result for i2c pcf8574 lcdGambar 3. [sumber]

[/su_panel] [su_panel border=”3px solid #30C0F0″ radius=”10″]

Untuk lebih mudah mendeteksi alamat dari modul LCD pada sistem i2c, kita menggunakan i2c  scanner. Bagian berikut dikutip dari
https://playground.arduino.cc/Main/I2cScanner.

Last Modified: March 05, 2017, at 02:02 PM
By: Frode Grimstad Bang

 // --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
// 
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>


void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("nI2C Scanner");
}


void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4) 
    {
      Serial.print("Unknown error at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found");
  else
    Serial.println("done");

  delay(5000);           // wait 5 seconds for next scan
}

Gambar 4.

[/su_panel] [su_panel border=”3px solid #FF6666″ radius=”10″]

Bagian berikut diadaptasi dari: 
http://www.carobot.cc/how-to/lcd-16×2-or-20×4-usage-guide/
Library: fdebrabander/Arduino-LiquidCrystal-I2C-library

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,16,2);

void setup()
{
  lcd.begin();
  lcd.backlight();
  lcd.print("tinker.");
  lcd.setCursor(0,1);
  lcd.print("sunupradana.info");
}

void loop()
{
}

Gambar 5.


[/su_panel] [su_panel border=”3px solid #00C700″ radius=”10″]

Kode pengujian berikut terinspirasi dari komenter user bernama “turbiny” di halaman Instructables. Kode ini memanfaatkan pustaka dari Francisco Malpartida.

#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

// Set the pins on the I2C chip used for LCD connections:
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

Kode lengkap hasil modifikasi:

/* 

Dimodifikasi dari : 

YourDuino.com Example Software Sketch

20 character 4 line I2C Display

Backpack Interface labelled "LCM1602 IIC A0 A1 A2"

terry@yourduino.com 
*/

/*
Contoh kode tambahan: 
https://www.arduino.cc/en/Tutorial/
*/

/*-----( Import needed libraries )-----*/

#include <Wire.h> // Comes with Arduino IDE

// Get the LCD I2C Library here:

// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads/

// Move any other LCD libraries to another folder or delete them

// See Library "Docs" folder for possible commands etc.

#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/

//none

/*-----( Declare objects )-----*/

// set the LCD address to LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); for a 16 chars 2 line display

// Set the pins on the I2C chip used for LCD connections:

// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

/*-----( Declare Variables )-----*/

//none

void setup() /*----( SETUP: RUNS ONCE )----*/

{

	Serial.begin(9600); // Used to type in characters

	lcd.begin(16,2); // initialize the lcd for 16 chars 2 lines and turn on backlight

	//-------- Write characters on the display ----------------

	// NOTE: Cursor Position: CHAR, LINE) start at 0


	backLampu();

	posNol();
	delay(1000);
	lcd.clear();

	lcd.off();
	delay(1000);
	lcd.on();
	delay(1000);

	aturKursor();
	delay(1000);
	lcd.clear();

	noDis();
	delay(1000);
	lcd.clear();	
	
	geserKanan();
	delay(1000);
	
	autoGeserDemo();
	delay(500);

	kananKiri();
	delay(1000);
	

}/*--(end setup )---*/

void loop() /*----( LOOP: RUNS CONSTANTLY )----*/

{	
	// when characters arrive over the serial port...

	if (Serial.available()) 
	{
		uint8_t iCur = 0;

		// wait a bit for the entire message to arrive
		delay(100);
		// clear the screen
		lcd.clear();

		// read all the available characters
		while (Serial.available() > 0) 
		{

			// display each character to the LCD
			lcd.write(Serial.read());

			iCur++;
			if(iCur > 15)
			{
				iCur = 0;
				lcd.setCursor(0,1);
			}

		} //EOF while	
	} //EOF if
}/* --(end main loop )-- */

void backLampu()
{
	// ------- Quick 2 blinks of backlight -------------
	for(int i = 0; i< 2; i++)
	{
		lcd.noBacklight();
		delay(300);
		lcd.backlight();
		delay(200);		
	}

	// lcd.backlight(); // finish with backlight on
}

void posNol()
{
	lcd.setCursor(0,0); //Start at character 0 on line 0
	delay(1000);
	lcd.print("Kolom 0 Baris 0");
	delay(1000);
	lcd.setCursor(0,1);
	lcd.print("Kolom 0 Baris 1");
	delay(1000);
}


void aturKursor()
{
	lcd.setCursor(0,0); //Start at character 0 on line 0
	lcd.print("iic lcd");
	delay(1000);
	lcd.setCursor(6,1);
	lcd.print("6:1");
	delay(2000);
}

void noDis()
{
	lcd.noDisplay();
	delay(2000);
	lcd.display();
	delay(1000);		
}


void geserKanan()
{
	/* Arduino tutorial */

	lcd.setCursor(0,0);
	lcd.print("0");
	delay(1000);

	// scroll 29 positions (string length + display length) to the right
	// to move it offscreen right:
	for (int positionCounter = 0; positionCounter < 16; positionCounter++) 
	{
		// scroll one position right:
		lcd.scrollDisplayRight();
		// wait a bit:
		delay(200);
	}

	delay(400);

	lcd.clear();
	lcd.setCursor(0,1);
	lcd.print("0");
	delay(200);

	for (int positionCounter = 0; positionCounter < 16; positionCounter++) 
	{
		// scroll one position right:
		lcd.scrollDisplayRight();
		// wait a bit:
		delay(200);
	}

	delay(1000);
	lcd.clear();
}

void autoGeserDemo()
{
	/* Arduino tutorial */

	// set the cursor to (0,0):
	lcd.setCursor(0, 0);
	// print from 0 to 9:
	for (int thisChar = 0; thisChar < 10; thisChar++) 
	{
		lcd.print(thisChar);
		delay(500);
	}

	// set the cursor to (16,1):
	lcd.setCursor(16, 1);
	// set the display to automatically scroll:
	lcd.autoscroll();
	// print from 0 to 9:
	for (int thisChar = 0; thisChar < 10; thisChar++) 
	{
		lcd.print(thisChar);
		delay(500);
	}
	// turn off automatic scrolling
	lcd.noAutoscroll();

	// clear screen for the next loop:
	lcd.clear();
}


/* 
	Fungsi kananKiri dimodifikasi dari:
	https://www.arduino.cc/en/Tutorial/LiquidCrystalTextDirection 
*/
void kananKiri()
{

	int thisChar = 'a';

	lcd.clear();

	for(int i=0; i<26; i++)
	{
		// reverse directions at 'm':
		if (thisChar == 'm') 
		{
			lcd.clear();
			lcd.setCursor(12,0);
			// go right for the next letter
			lcd.rightToLeft();
		}
		// reverse again at 's':
		if (thisChar == 's') 
		{
			lcd.clear();
			lcd.setCursor(5,0);
			// go left for the next letter
			lcd.leftToRight();
		}
		// reset at 'z':
		if (thisChar > 'z') 
		{
			// go to (0,0):
			lcd.home();
			// start again at 0
			thisChar = 'a';
		}

		// print the character
		lcd.write(thisChar);
		// wait a second:
		delay(500);
		// increment the letter:
		thisChar++;	    
	}

	delay(800);
	lcd.clear();
}
/* ( THE END ) */
[/su_panel] [su_panel border=”3px solid #f1c112″ radius=”10″]
i2c lcd display pinout
Gambar 6. https://lastminuteengineers.com/i2c-lcd-arduino-tutorial/
Gambar 7. https://lastminuteengineers.com/i2c-lcd-arduino-tutorial/
Gambar 8.
[/su_panel] [su_panel border=”3px solid #990066″ radius=”10″] [/su_panel]

 

DT COMBO AVR 51

Pada post sebelumnya, saya sudah membuat catatan mengenai sistem papan DST-51. Sedang pada post ini saya membuat catatan mengenai DT-COMBO AVR-51. Papan ini juga merupakan papan lama yang saya miliki saat belajar beralih dari arsitektur MCS-51 (seperti AT89C52/AT89S52) ke arsitektur Atmel AVR. Sebelum papan Arduino banyak tersedia dengan harga yang relatif terjangkau seperti sekarang ini, papan yang disebut minimum sistem adalah papan mikrokontroler yang tersedia untuk belajar. Peningkatan dari minimum sistem dengan beberapa pelengkap seperti DT-COMBO AVR-51, lebih memudahkan bagi mereka yang belajar.

Catatan ini saya buat karena sistem ini sudah semakin tua, dikhawatirkan manual akan semakin sulit ditemukan. Selain itu ada hack kecil hasil tinkering yang semakin memudahkan penggunaan sistem ini.

http://www.innovativeelectronics.com/innovative_electronics/images/DT-COMBO/DT-COMBO%20AVR-51.gifGambar 1. Penampakan asli [sumber]

Salah satu keunggulan papan seperti ini untuk belajar adalah sudah tersedianya komponen-komponen tambahan yang memudahkan proses belajar. Bahkan di tahap lanjutan juga akan mempermudah proses prototyping. Misalnya adalah keberadaan push-button dan LED, seperti yang terlihat di Gambar 1.

Gambar 2.

Papan DT-COMBO milik saya terlihat di Gambar 2. Ada dua hal yang saya kombinasikan di sistem itu, yang pertama adalah soket ZIF seperti yang juga terlihat di Gambar 3. Soket ini memudahkan proses untuk mengganti-ganti IC yang dipakai pada papan sistem, juga mengurangi kemungkinan (kaki) IC rusak pada saat bongkar-pasang di papan.

Gambar 3.

Gambar 4.

Pada Gambar 2, dan lebih jelas lagi pada Gambar 4, terlihat bahwa saya mempergunakan USBasp untuk melakukan pemrograman di papan sistem DT-COMBO (menggunakan header yang tersedia). USBasp bisa dibuat sendiri karena rancangannya telah sengaja disebarluaskan di Internet.

Gambar-gambar berikut saya kutip dari manual yang juga saya cantumkan link-nya di bagian bawah post ini.

Gambar 5. Port

Gambar 6.

 

Gambar 7.

Gambar 8.

 

Manual dan file-file untuk DT-COMBO AVR-51: